Skip to content

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

feat: support trace & dump subagent data flow

huanggawaebb680bafe07
diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.py
index 7afa2b8fc0..2e68ba01cb 100644
--- a/jiuwenswarm/server/app_agentserver.py
+++ b/jiuwenswarm/server/app_agentserver.py
@@ -129,6 +129,14 @@ from jiuwenswarm.llm_sse_patch import apply_openai_sse_invoke_patch
apply_openai_sse_invoke_patch()
+# /debug 模式下捕获 builtin TaskTool 分发的 subagent 流(reasoning/tool_call/usage),
+# 内联写入主 dump。非 debug 或 include_subagent_flow 关闭时走原始 invoke,零回归。
+from jiuwenswarm.server.runtime.debug_trace.task_tool_patch import (
+ apply_task_tool_debug_patch,
+)
+
+apply_task_tool_debug_patch()
+
async def _run(host: str, port: int) -> None:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
index b9038541d9..4a6379369d 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
@@ -20,6 +20,8 @@ from openjiuwen.harness.rails.base import DeepAgentRail
from openjiuwen.harness.tools.base_tool import ToolOutput
from openjiuwen.harness.workspace.workspace import Workspace
+from jiuwenswarm.server.runtime.debug_trace import invoke_subagent_with_trace
+
if TYPE_CHECKING:
from openjiuwen.core.session.agent import Session
from openjiuwen.harness.deep_agent import DeepAgent
@@ -313,9 +315,11 @@ class AgentTool(Tool):
)
else:
try:
- result = await subagent.invoke(
- {"query": prompt, "conversation_id": sub_session_id},
+ result = await invoke_subagent_with_trace(
+ subagent,
+ inputs={"query": prompt, "conversation_id": sub_session_id},
session=parent_session,
+ source_label=f"subagent:custom:{subagent_type}",
)
output = result.get("output", "")
return ToolOutput(
@@ -334,9 +338,11 @@ class AgentTool(Tool):
subagent_type: str, parent_session: Session,
) -> None:
try:
- await subagent.invoke(
- {"query": prompt, "conversation_id": sub_session_id},
+ await invoke_subagent_with_trace(
+ subagent,
+ inputs={"query": prompt, "conversation_id": sub_session_id},
session=parent_session,
+ source_label=f"subagent:custom:{subagent_type}",
)
except Exception as exc:
logger.error(
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 6bd193a9c1..18b8951eb7 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -7267,6 +7267,7 @@ class JiuWenSwarmDeepAdapter:
image_files_token = None
_run_span: Any = None
_debug_logger = None
+ _debug_trace_token = None # reset token for the ContextVar-bound logger
interaction_stream = None
interaction_stream_abort = True
try:
@@ -7346,6 +7347,9 @@ class JiuWenSwarmDeepAdapter:
except Exception:
pass
try:
+ from jiuwenswarm.server.runtime.debug_trace.context import (
+ set_debug_trace_logger,
+ )
from jiuwenswarm.server.runtime.debug_trace.paths import debug_trace_file
from jiuwenswarm.server.runtime.debug_trace.stream_logger import (
DebugTraceLogger,
@@ -7363,6 +7367,11 @@ class JiuWenSwarmDeepAdapter:
otel_trace_id=_otel_trace_id,
otel_span_id=_otel_span_id,
)
+ # Publish the logger so subagent dispatch sites (TaskTool in
+ # the SDK, AgentTool in jiuwenswarm) can capture subagent
+ # streams into this same dump. asyncio.create_task copies the
+ # current ContextVar, so background subagents inherit it too.
+ _debug_trace_token = set_debug_trace_logger(_debug_logger)
except Exception as _dbg_exc:
logger.warning("[JiuWenSwarmDeepAdapter] debug trace init failed: %s", _dbg_exc)
_debug_logger = None
@@ -7746,6 +7755,11 @@ class JiuWenSwarmDeepAdapter:
close_agent_run_span(_run_span)
if _debug_logger is not None:
_debug_logger.flush()
+ if _debug_trace_token is not None:
+ from jiuwenswarm.server.runtime.debug_trace.context import (
+ reset_debug_trace_logger,
+ )
+ reset_debug_trace_logger(_debug_trace_token)
if image_files_token is not None:
from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
reset_current_multimodal_image_files,
diff --git a/jiuwenswarm/server/runtime/debug_trace/__init__.py b/jiuwenswarm/server/runtime/debug_trace/__init__.py
index d83bea074c..241f799a4a 100644
--- a/jiuwenswarm/server/runtime/debug_trace/__init__.py
+++ b/jiuwenswarm/server/runtime/debug_trace/__init__.py
@@ -13,18 +13,30 @@ from jiuwenswarm.server.runtime.debug_trace.config import (
DebugTraceSettings,
resolve_debug_trace_settings,
)
+from jiuwenswarm.server.runtime.debug_trace.context import (
+ get_debug_trace_logger,
+ reset_debug_trace_logger,
+ set_debug_trace_logger,
+)
from jiuwenswarm.server.runtime.debug_trace.directives import strip_debug_directive
from jiuwenswarm.server.runtime.debug_trace.paths import (
debug_trace_dir,
debug_trace_file,
)
from jiuwenswarm.server.runtime.debug_trace.stream_logger import DebugTraceLogger
+from jiuwenswarm.server.runtime.debug_trace.subagent_capture import (
+ invoke_subagent_with_trace,
+)
__all__ = [
"DebugTraceLogger",
"DebugTraceSettings",
"debug_trace_dir",
"debug_trace_file",
+ "get_debug_trace_logger",
+ "invoke_subagent_with_trace",
+ "reset_debug_trace_logger",
"resolve_debug_trace_settings",
+ "set_debug_trace_logger",
"strip_debug_directive",
]
diff --git a/jiuwenswarm/server/runtime/debug_trace/config.py b/jiuwenswarm/server/runtime/debug_trace/config.py
index a8b7ea6028..9753b56f02 100644
--- a/jiuwenswarm/server/runtime/debug_trace/config.py
+++ b/jiuwenswarm/server/runtime/debug_trace/config.py
@@ -31,6 +31,9 @@ class DebugTraceSettings:
include_reasoning: bool = True
include_tool_args: bool = True
include_tool_result: bool = True
+ # When False, subagent streams fall back to plain invoke() (no subagent
+ # section in the dump). See invoke_subagent_with_trace.
+ include_subagent_flow: bool = True
# Payload caps (chars).
tool_args_max_chars: int = 2000
tool_result_max_chars: int = 8000
@@ -110,6 +113,7 @@ def resolve_debug_trace_settings(*, mode: str, request_debug: bool) -> DebugTrac
include_reasoning=bool(mode_cfg.get("include_reasoning", True)),
include_tool_args=bool(mode_cfg.get("include_tool_args", True)),
include_tool_result=bool(mode_cfg.get("include_tool_result", True)),
+ include_subagent_flow=bool(mode_cfg.get("include_subagent_flow", True)),
tool_args_max_chars=_as_int(limits.get("tool_args_max_chars"), 2000),
tool_result_max_chars=_as_int(limits.get("tool_result_max_chars"), 8000),
generic_payload_max_chars=_as_int(limits.get("generic_payload_max_chars"), 4000),
diff --git a/jiuwenswarm/server/runtime/debug_trace/context.py b/jiuwenswarm/server/runtime/debug_trace/context.py
new file mode 100644
index 0000000000..74a62e3016
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/context.py
@@ -0,0 +1,49 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Process-wide ContextVar bridging a run's :class:`DebugTraceLogger` to the
+subagent dispatch sites (``TaskTool`` in the SDK, ``AgentTool`` in jiuwenswarm).
+
+The logger is created per-run as a local in
+``interface_deep.JiuWenSwarmDeepAdapter._run_agent_streaming_internal`` and is
+otherwise unreachable from the dispatch code paths. A ContextVar lets the
+adapter publish it for the duration of a run; ``invoke_subagent_with_trace``
+reads it (never writes) to decide whether to capture the subagent's stream.
+
+``asyncio.create_task`` copies the current ContextVar snapshot, so background
+subagents (``AgentTool`` ``background=True``) inherit the active logger too.
+"""
+
+from __future__ import annotations
+
+from contextvars import ContextVar, Token
+from typing import TYPE_CHECKING, Optional
+
+if TYPE_CHECKING:
+ from jiuwenswarm.server.runtime.debug_trace.stream_logger import DebugTraceLogger
+
+_DEBUG_TRACE_LOGGER: ContextVar[Optional["DebugTraceLogger"]] = ContextVar(
+ "debug_trace_logger",
+ default=None,
+)
+
+
+def get_debug_trace_logger() -> Optional["DebugTraceLogger"]:
+ """Return the active run's logger, or ``None`` when not in a debug run."""
+ return _DEBUG_TRACE_LOGGER.get()
+
+
+def set_debug_trace_logger(logger: Optional["DebugTraceLogger"]) -> Token:
+ """Publish *logger* as the active run's logger; returns a reset token."""
+ return _DEBUG_TRACE_LOGGER.set(logger)
+
+
+def reset_debug_trace_logger(token: Token) -> None:
+ """Restore the previous logger binding using the token from :func:`set`."""
+ _DEBUG_TRACE_LOGGER.reset(token)
+
+
+__all__ = [
+ "get_debug_trace_logger",
+ "set_debug_trace_logger",
+ "reset_debug_trace_logger",
+]
diff --git a/jiuwenswarm/server/runtime/debug_trace/stream_logger.py b/jiuwenswarm/server/runtime/debug_trace/stream_logger.py
index 14f4b860ff..689a02b2a6 100644
--- a/jiuwenswarm/server/runtime/debug_trace/stream_logger.py
+++ b/jiuwenswarm/server/runtime/debug_trace/stream_logger.py
@@ -160,11 +160,16 @@ def _classify(ctype: str, payload: Any) -> str:
class _Run:
"""A pending accumulation of token-streamed chunks (single source)."""
- __slots__ = ("category", "buf")
+ __slots__ = ("category", "source", "buf", "llm_output_seen")
- def __init__(self, category: str) -> None:
+ def __init__(self, category: str, source: str = "main") -> None:
self.category = category
+ self.source = source
self.buf: list[str] = []
+ # Per-run dedup flag: drop a trailing `answer` chunk that just repeats
+ # already-streamed llm_output. Kept per-_Run so main and subagent
+ # streams don't interfere.
+ self.llm_output_seen = False
class DebugTraceLogger:
@@ -199,9 +204,11 @@ class DebugTraceLogger:
self._start_monotonic: float | None = None
self._chunk_count = 0
- # Single-source accumulation (Phase 1: no subagent source metadata).
+ # Current accumulator. source is tracked per-_Run so the main run and
+ # any in-flight subagent stream coexist in one dump; begin_subagent /
+ # end_subagent bracket subagent sections, feed_subagent tags their
+ # chunks. See invoke_subagent_with_trace for the dispatch wiring.
self._run: _Run | None = None
- self._llm_output_seen = False
try:
self._path.parent.mkdir(parents=True, exist_ok=True)
@@ -248,11 +255,55 @@ class DebugTraceLogger:
except Exception as exc:
self._safe_warn(f"start_run error: {exc!r}")
+ def captures_subagent_flow(self) -> bool:
+ """True if this run should capture subagent streams into the dump."""
+ return not self._disabled and self._settings.include_subagent_flow
+
def feed(self, chunk: Any) -> None:
+ self._feed_safe(chunk, "main")
+
+ def feed_subagent(self, *, source: str, chunk: Any) -> None:
+ """Feed a chunk from an in-flight subagent stream.
+
+ Tags the chunk with *source* (e.g. ``subagent:builtin:explore_agent``)
+ so it appears in the dump under that source rather than ``main``.
+ No-op when disabled or when ``include_subagent_flow`` is off.
+ """
+ if self._disabled or not self._settings.include_subagent_flow:
+ return
+ self._feed_safe(chunk, source)
+
+ def begin_subagent(self, *, source: str, prompt: str = "") -> None:
+ if self._disabled:
+ return
+ try:
+ self._flush_run()
+ self._write_raw("\n".join([
+ "========== subagent start ==========",
+ f"timestamp={_now_ts()}",
+ f"source={source}",
+ f"prompt={_truncate(prompt or '', self._settings.generic_payload_max_chars)}",
+ ]))
+ except Exception as exc:
+ self._safe_warn(f"begin_subagent error: {exc!r}")
+
+ def end_subagent(self, *, source: str, status: str = "ok") -> None:
+ if self._disabled:
+ return
+ try:
+ self._flush_run()
+ self._write_raw(
+ "========== subagent end ==========\n"
+ f"timestamp={_now_ts()}\nsource={source}\nstatus={status}"
+ )
+ except Exception as exc:
+ self._safe_warn(f"end_subagent error: {exc!r}")
+
+ def _feed_safe(self, chunk: Any, source: str) -> None:
if self._disabled:
return
try:
- self._feed(chunk)
+ self._feed_chunk(chunk, source)
except Exception as exc: # never break the stream
self._safe_warn(f"feed error: {exc!r}")
@@ -299,20 +350,21 @@ class DebugTraceLogger:
self._file = None
# ── internals ────────────────────────────────────────────────────────
- def _feed(self, chunk: Any) -> None:
+ def _feed_chunk(self, chunk: Any, source: str) -> None:
self._chunk_count += 1
ctype, payload = self._unpack(chunk)
if ctype is None:
# Dict / untyped chunk: record as 'other' for visibility.
self._flush_run()
- self._emit("other", "main", _truncate(_safe_str(chunk), self._settings.generic_payload_max_chars))
+ self._emit("other", source, _truncate(_safe_str(chunk), self._settings.generic_payload_max_chars))
return
category = _classify(ctype, payload)
+ run = self._run
# `answer` duplicates already-streamed llm_output — drop if seen.
- if ctype == _CHUNK_ANSWER and self._llm_output_seen:
+ if ctype == _CHUNK_ANSWER and run is not None and run.llm_output_seen:
return
if ctype in _ACCUMULATING_TYPES:
@@ -323,20 +375,24 @@ class DebugTraceLogger:
content = _extract_content(payload)
if not content:
return
- if self._run is not None and self._run.category != category:
+ # Flush if the pending run is for a different category OR a different
+ # source (main vs a subagent) so streams never bleed into each other.
+ if run is not None and (run.category != category or run.source != source):
self._flush_run()
- if self._run is None:
- self._run = _Run(category)
- self._run.buf.append(content)
+ run = self._run
+ if run is None:
+ run = _Run(category, source)
+ self._run = run
+ run.buf.append(content)
if ctype == _CHUNK_LLM_OUTPUT:
- self._llm_output_seen = True
+ run.llm_output_seen = True
return
# Discrete chunk: flush pending text, then emit a summary now.
self._flush_run()
summary = self._discrete_summary(ctype, category, payload)
if summary:
- self._emit(category, "main", summary)
+ self._emit(category, source, summary)
@staticmethod
def _unpack(chunk: Any) -> tuple[str | None, Any]:
@@ -433,7 +489,7 @@ class DebugTraceLogger:
return
text = "".join(run.buf)
limit = self._settings.max_model_output_chars if run.category == "text" else None
- self._emit(run.category, "main", _truncate(text, limit))
+ self._emit(run.category, run.source, _truncate(text, limit))
def _emit(self, category: str, source: str, content: str) -> None:
if not content:
diff --git a/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
new file mode 100644
index 0000000000..788899cf64
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
@@ -0,0 +1,155 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Capture a subagent's stream into the active run's debug dump.
+
+Both subagent dispatch sites — the SDK's builtin ``TaskTool`` and jiuwenswarm's
+custom ``AgentTool`` — historically call ``await subagent.invoke(...)`` and keep
+only the final output string. The subagent's internal reasoning / tool calls /
+token usage never reach the parent run's :class:`DebugTraceLogger`, so a
+``/debug`` dump shows a multi-minute gap where the subagent worked invisibly.
+
+This module wraps that dispatch: when a debug run is active (and subagent
+capture is enabled) the subagent is driven through ``stream()`` instead, every
+chunk is fed to the active logger under a ``source=subagent:...`` label, and the
+chunks are reduced back into an invoke-style result via the SDK's own
+``DeepAgent._result_from_stream_chunk``. When no debug run is active, behaviour
+is identical to a plain ``invoke`` (zero regression for normal runs).
+
+Only ever reads the ContextVar (never set/reset) — the adapter owns the binding
+lifetime, see ``interface_deep.JiuWenSwarmDeepAdapter``.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+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:
+ # Never break the subagent run over tracing instrumentation.
+ pass
+
+
+async def invoke_subagent_with_trace(
+ subagent: Any,
+ *,
+ inputs: dict,
+ session: Any,
+ source_label: str,
+) -> dict:
+ """Run *subagent*, capturing its stream into the active run's debug dump.
+
+ Args:
+ subagent: A ``DeepAgent`` instance (has ``invoke`` / ``stream``).
+ inputs: The inputs dict (``{"query": ..., "conversation_id": ...}``).
+ session: The parent session, forwarded to the subagent.
+ source_label: Dump source tag, e.g. ``subagent:builtin:explore_agent``.
+
+ Returns:
+ 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)
+
+ from jiuwenswarm.server.runtime.debug_trace.context import get_debug_trace_logger
+
+ dbg = get_debug_trace_logger()
+ if dbg is None or not dbg.captures_subagent_flow():
+ # No debug run, or capture disabled — original path, unchanged.
+ return await subagent.invoke(inputs, session=session)
+
+ output_parts: list[str] = []
+ result: dict | None = None
+ dbg.begin_subagent(source=source_label, prompt=inputs.get("query", "") or "")
+ try:
+ # Drain the subagent's stream from an ISOLATED session (session=None ->
+ # ReActAgent.stream auto-creates one from inputs.conversation_id). Passing
+ # parent_session here would make BOTH the parent run and this helper drain
+ # parent_session.stream_iterator() — ReActAgent._inner_stream routes chunks
+ # through a shared per-session stream queue, so two drainers split the
+ # subagent's tokens round-robin between source=main and source=subagent.
+ # The isolated session is drained only by this loop, so tagging is clean
+ # and nothing leaks into the parent (TUI) stream.
+ async for chunk in subagent.stream(inputs, session=None):
+ dbg.feed_subagent(source=source_label, chunk=chunk)
+ reduced = _reduce_stream_chunk(chunk, output_parts)
+ if reduced is not None:
+ result = reduced
+ finally:
+ dbg.end_subagent(source=source_label)
+
+ if result is None:
+ result = {"output": "".join(output_parts), "result_type": "answer"}
+ return result
+
+
+def _reduce_stream_chunk(chunk: Any, output_parts: list[str]) -> dict | None:
+ """Reduce a stream chunk to an invoke-style result dict (or ``None``).
+
+ Mirrors the SDK's ``DeepAgent._result_from_stream_chunk`` reduction so the
+ result matches what ``subagent.invoke`` would have returned: accumulate
+ ``llm_output`` content and finalise on an ``answer`` chunk. Inlined (rather
+ than calling the SDK staticmethod) to avoid protected-member access.
+ """
+ chunk_type = getattr(chunk, "type", None)
+ payload = getattr(chunk, "payload", None)
+ if isinstance(chunk, dict):
+ chunk_type = chunk.get("type", chunk_type)
+ payload = chunk.get("payload", payload)
+ if not isinstance(payload, dict):
+ return None
+ result: dict | None = None
+ if chunk_type == "llm_output":
+ content = payload.get("content")
+ if isinstance(content, str):
+ output_parts.append(content)
+ elif chunk_type == "answer":
+ result = dict(payload)
+ result.setdefault("result_type", "answer")
+ if "output" not in result:
+ content = result.get("content")
+ if isinstance(content, str):
+ output_parts.append(content)
+ result["output"] = content
+ else:
+ result = None
+ return result
+
+
+__all__ = ["invoke_subagent_with_trace"]
diff --git a/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py b/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
new file mode 100644
index 0000000000..551f550918
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
@@ -0,0 +1,144 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Monkeypatch the SDK's builtin ``TaskTool.invoke`` to capture subagent streams.
+
+The builtin TaskTool (``openjiuwen.harness.tools.subagent.task_tool``) drives
+subagents via ``await subagent.invoke(...)``, which returns only the final
+output string — its internal reasoning / tool calls / token usage never reach
+the parent run's :class:`DebugTraceLogger`. This patch wraps ``invoke`` so that,
+when a debug run is actively capturing subagent flow, the subagent is instead
+driven through ``stream()`` via :func:`invoke_subagent_with_trace` and its
+chunks land in the dump under ``source=subagent:builtin:<type>``.
+
+Any run that is NOT capturing (no debug run, or ``include_subagent_flow`` off)
+short-circuits to the pristine original ``invoke`` (``_orig_invoke``) for zero
+behaviour change — the re-implemented parse/create/invoke path runs only while
+a dump is actually being written. Safe to apply unconditionally at startup.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+_PATCH_APPLIED = False
+
+
+def _build_sub_session_id(parent_session_id: str, subagent_type: str) -> str:
+ """Mirror of ``TaskTool._build_sub_session_id``.
+
+ Inlined here (rather than calling the SDK's protected staticmethod) so the
+ patch stays self-contained. ``browser_agent`` / ``verification_agent`` get a
+ deterministic id so their sessions can be resumed on a retry loop, matching
+ the SDK convention.
+ """
+ normalized = str(subagent_type or "").strip()
+ if normalized in ("browser_agent", "verification_agent"):
+ return f"{parent_session_id}_sub_{normalized}"
+ return f"{parent_session_id}_sub_{normalized}_{uuid.uuid4().hex[:8]}"
+
+
+def apply_task_tool_debug_patch() -> None:
+ """Patch ``TaskTool.invoke`` to capture subagent streams under ``/debug``.
+
+ Idempotent: a module flag plus a class-attribute guard make repeat calls
+ no-ops.
+ """
+ global _PATCH_APPLIED
+ if _PATCH_APPLIED:
+ return
+
+ from openjiuwen.harness.tools.subagent.task_tool import TaskTool
+
+ if getattr(TaskTool, "debug_trace_patch_applied", False):
+ _PATCH_APPLIED = True
+ return
+
+ _orig_invoke = TaskTool.invoke
+
+ async def _invoke_with_trace(self, inputs, **kwargs): # type: ignore[no-untyped-def]
+ from openjiuwen.core.common.exception.codes import StatusCode
+ from openjiuwen.core.common.exception.errors import build_error
+ from openjiuwen.core.common.logging import logger
+ from openjiuwen.core.session.agent import Session
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+
+ from jiuwenswarm.server.runtime.debug_trace import (
+ get_debug_trace_logger,
+ invoke_subagent_with_trace,
+ )
+
+ # Not capturing -> pristine original SDK path, unchanged.
+ dbg = get_debug_trace_logger()
+ if dbg is None or not dbg.captures_subagent_flow():
+ return await _orig_invoke(self, inputs, **kwargs)
+
+ parent_session = kwargs.get("session", None)
+ if not isinstance(parent_session, Session):
+ raise build_error(
+ StatusCode.TOOL_TASK_TOOL_INVOKED,
+ reason="TaskTool requires a valid session in kwargs",
+ )
+
+ if isinstance(inputs, dict):
+ subagent_type = inputs.get("subagent_type")
+ task_description = inputs.get("task_description")
+ else:
+ raise build_error(
+ StatusCode.TOOL_TASK_TOOL_INVOKED,
+ reason=f"Invalid inputs type: {type(inputs)}",
+ )
+
+ if not subagent_type or not task_description:
+ raise build_error(
+ StatusCode.TOOL_TASK_TOOL_INVOKED,
+ reason="Both 'subagent_type' and 'task' are required",
+ )
+
+ parent_session_id = parent_session.get_session_id()
+ sub_session_id = _build_sub_session_id(parent_session_id, str(subagent_type))
+ logger.info(
+ "[TaskTool] (debug) Creating subagent: %s, parent_session=%s, sub_session=%s",
+ subagent_type, parent_session_id, sub_session_id,
+ )
+
+ try:
+ subagent = self.parent_agent.create_subagent(subagent_type, sub_session_id)
+ except Exception as exc:
+ logger.error(
+ "[TaskTool] Subagent creation failed: type=%s, error=%s",
+ subagent_type, exc,
+ )
+ raise build_error(
+ StatusCode.TOOL_TASK_TOOL_INVOKED,
+ reason=f"Subagent {subagent_type} creation failed: {exc}",
+ ) from exc
+
+ try:
+ result = await invoke_subagent_with_trace(
+ subagent,
+ inputs={"query": task_description, "conversation_id": sub_session_id},
+ session=parent_session,
+ source_label=f"subagent:builtin:{subagent_type}",
+ )
+ output = result.get("output", "")
+ return ToolOutput(
+ success=True,
+ data={"output": output, "agent_id": subagent.card.id},
+ error=None,
+ )
+ except Exception as exc:
+ logger.error(
+ "[TaskTool] Subagent: %s execution failed, error=%s",
+ subagent_type, exc,
+ )
+ raise build_error(
+ StatusCode.TOOL_TASK_TOOL_INVOKED,
+ reason=f"Subagent {subagent_type} execution failed: {exc}",
+ ) from exc
+
+ TaskTool.invoke = _invoke_with_trace # type: ignore[assignment]
+ TaskTool.debug_trace_patch_applied = True
+ _PATCH_APPLIED = True
+
+
+__all__ = ["apply_task_tool_debug_patch"]
diff --git a/tests/unit_tests/agentserver/test_debug_trace.py b/tests/unit_tests/agentserver/test_debug_trace.py
index ffc7f67fa6..cbe7f5d131 100644
--- a/tests/unit_tests/agentserver/test_debug_trace.py
+++ b/tests/unit_tests/agentserver/test_debug_trace.py
@@ -4,6 +4,8 @@
from __future__ import annotations
+import asyncio
+import dataclasses
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -442,3 +444,355 @@ class TestAgentObservabilityForce:
assert calls["shutdown"] == 1
assert ao._force_ever_enabled is False
+
+# ── subagent capture (Phase 2: record subagent streams inline) ──────────────
+class TestSubagentCapture:
+ """begin/feed/end_subagent + source tagging + helper + patch."""
+
+ def _settings(self, **over: Any) -> Any:
+ base = resolve_debug_trace_settings(mode="code.normal", request_debug=True)
+ return dataclasses.replace(base, **over)
+
+ def test_config_include_subagent_flow_default_and_override(self, monkeypatch):
+ from jiuwenswarm.server.runtime.debug_trace import config as debug_config
+
+ monkeypatch.setattr(debug_config, "_load_debug_trace_config", lambda: {})
+ s = resolve_debug_trace_settings(mode="code.normal", request_debug=True)
+ assert s.include_subagent_flow is True # default on
+ monkeypatch.setattr(
+ debug_config, "_load_debug_trace_config", lambda: {"code": {"include_subagent_flow": False}}
+ )
+ assert resolve_debug_trace_settings(mode="code.normal", request_debug=True).include_subagent_flow is False
+
+ def test_captures_subagent_flow_flag(self, tmp_path):
+ lg_on = DebugTraceLogger(
+ file_path=tmp_path / "a.txt", mode="code.normal", session_id="s",
+ request_id="r", settings=self._settings(include_subagent_flow=True),
+ )
+ lg_off = DebugTraceLogger(
+ file_path=tmp_path / "b.txt", mode="code.normal", session_id="s",
+ request_id="r", settings=self._settings(include_subagent_flow=False),
+ )
+ assert lg_on.captures_subagent_flow() is True
+ assert lg_off.captures_subagent_flow() is False
+ lg_on.flush()
+ lg_off.flush()
+
+ def test_begin_end_subagent_write_boundaries(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.begin_subagent(source="subagent:builtin:explore_agent", prompt="find foo")
+ lg.end_subagent(source="subagent:builtin:explore_agent", status="ok")
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "subagent start" in out and "subagent end" in out
+ assert "source=subagent:builtin:explore_agent" in out
+ assert "prompt=find foo" in out
+ assert "status=ok" in out
+
+ def test_feed_subagent_tags_source_not_main(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.begin_subagent(source="subagent:custom:x")
+ lg.feed_subagent(
+ source="subagent:custom:x",
+ chunk=_chunk("llm_output", {"content": "sub text"}),
+ )
+ lg.end_subagent(source="subagent:custom:x")
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "source=subagent:custom:x category=text" in out
+ assert "sub text" in out
+
+ def test_main_and_subagent_streams_do_not_bleed(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.feed(_chunk("llm_output", {"content": "main text"}))
+ lg.begin_subagent(source="subagent:custom:x")
+ lg.feed_subagent(
+ source="subagent:custom:x",
+ chunk=_chunk("llm_output", {"content": "sub text"}),
+ )
+ lg.end_subagent(source="subagent:custom:x")
+ lg.feed(_chunk("llm_output", {"content": "main text 2"}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "source=main category=text" in out
+ assert "source=subagent:custom:x category=text" in out
+ assert "main text" in out and "sub text" in out and "main text 2" in out
+
+ def test_end_subagent_flushes_pending_accumulation(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.begin_subagent(source="subagent:custom:x")
+ lg.feed_subagent(
+ source="subagent:custom:x",
+ chunk=_chunk("llm_output", {"content": "buffered"}),
+ )
+ lg.end_subagent(source="subagent:custom:x") # must flush the buffered text
+ lg.end_run(status="ok")
+ assert "buffered" in _read(lg)
+
+ def test_feed_subagent_noop_when_flag_off(self, tmp_path):
+ lg = DebugTraceLogger(
+ file_path=tmp_path / "off.txt", mode="code.normal", session_id="s",
+ request_id="r", settings=self._settings(include_subagent_flow=False),
+ )
+ lg.start_run()
+ lg.begin_subagent(source="subagent:custom:x")
+ lg.feed_subagent(
+ source="subagent:custom:x",
+ chunk=_chunk("llm_output", {"content": "secret"}),
+ )
+ lg.end_subagent(source="subagent:custom:x")
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "secret" not in out # feed_subagent was a no-op
+
+ def test_invoke_subagent_with_trace_no_debug_calls_invoke(self):
+ from jiuwenswarm.server.runtime.debug_trace import invoke_subagent_with_trace
+ from jiuwenswarm.server.runtime.debug_trace.context import _DEBUG_TRACE_LOGGER
+
+ assert _DEBUG_TRACE_LOGGER.get() is None # clean baseline
+ calls = {"invoke": 0, "stream": 0}
+
+ class FakeSub:
+ async def invoke(self, inputs, session=None):
+ calls["invoke"] += 1
+ return {"output": "from-invoke", "result_type": "answer"}
+
+ async def stream(self, inputs, session=None):
+ calls["stream"] += 1
+ if False: # pragma: no cover - never entered in no-debug path
+ yield None
+
+ result = asyncio.run(invoke_subagent_with_trace(
+ FakeSub(), inputs={"query": "q"}, session=None,
+ source_label="subagent:builtin:explore_agent",
+ ))
+ assert calls == {"invoke": 1, "stream": 0}
+ assert result["output"] == "from-invoke"
+
+ def test_invoke_subagent_with_trace_debug_drives_stream(self, tmp_path):
+ from jiuwenswarm.server.runtime.debug_trace import (
+ invoke_subagent_with_trace,
+ reset_debug_trace_logger,
+ set_debug_trace_logger,
+ )
+
+ lg = _logger(tmp_path)
+ lg.start_run()
+ token = set_debug_trace_logger(lg)
+ try:
+
+ class FakeSub:
+ async def invoke(self, inputs, session=None): # pragma: no cover
+ return {"output": "should-not-happen"}
+
+ async def stream(self, inputs, session=None):
+ yield _chunk("llm_output", {"content": "hello "})
+ yield _chunk("llm_output", {"content": "world"})
+
+ result = asyncio.run(invoke_subagent_with_trace(
+ FakeSub(), inputs={"query": "do thing"}, session=None,
+ source_label="subagent:builtin:explore_agent",
+ ))
+ finally:
+ reset_debug_trace_logger(token)
+ assert result["output"] == "hello world" # chunks reduced via SDK helper
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "subagent start" in out and "subagent end" in out
+ assert "source=subagent:builtin:explore_agent" in out
+ assert "hello world" in out
+
+ def test_invoke_subagent_with_trace_uses_isolated_session(self, tmp_path):
+ # Fix D: the helper MUST pass session=None to subagent.stream() so the
+ # subagent drains an isolated session queue, not the parent session
+ # (which the parent run also drains — round-robin token split, see
+ # ReActAgent._inner_stream). Guards against regression.
+ from jiuwenswarm.server.runtime.debug_trace import (
+ invoke_subagent_with_trace,
+ reset_debug_trace_logger,
+ set_debug_trace_logger,
+ )
+
+ lg = _logger(tmp_path)
+ lg.start_run()
+ token = set_debug_trace_logger(lg)
+ try:
+ captured: dict[str, Any] = {}
+
+ class FakeSub:
+ async def invoke(self, inputs, session=None): # pragma: no cover
+ return {"output": "x"}
+
+ async def stream(self, inputs, session=None):
+ captured["session"] = session
+ yield _chunk("llm_output", {"content": "hi"})
+
+ asyncio.run(invoke_subagent_with_trace(
+ FakeSub(), inputs={"query": "q"}, session="PARENT_SESSION",
+ source_label="subagent:builtin:browser_agent",
+ ))
+ finally:
+ reset_debug_trace_logger(token)
+ assert captured.get("session") is None # isolated, NOT parent_session
+ lg.end_run(status="ok")
+ lg.flush()
+
+ def test_invoke_subagent_with_trace_flag_off_falls_back_to_invoke(self, tmp_path):
+ from jiuwenswarm.server.runtime.debug_trace import (
+ invoke_subagent_with_trace,
+ reset_debug_trace_logger,
+ set_debug_trace_logger,
+ )
+
+ lg = DebugTraceLogger(
+ file_path=tmp_path / "off.txt", mode="code.normal", session_id="s",
+ request_id="r", settings=self._settings(include_subagent_flow=False),
+ )
+ lg.start_run()
+ token = set_debug_trace_logger(lg)
+ try:
+ calls = {"invoke": 0, "stream": 0}
+
+ class FakeSub:
+ async def invoke(self, inputs, session=None):
+ calls["invoke"] += 1
+ return {"output": "ok"}
+
+ async def stream(self, inputs, session=None): # pragma: no cover
+ yield None
+
+ result = asyncio.run(invoke_subagent_with_trace(
+ FakeSub(), inputs={"query": "q"}, session=None,
+ source_label="subagent:custom:x",
+ ))
+ finally:
+ reset_debug_trace_logger(token)
+ assert calls == {"invoke": 1, "stream": 0}
+ assert result["output"] == "ok"
+ lg.end_run(status="ok")
+ assert "subagent start" not in _read(lg) # no capture section written
+
+ def test_background_task_inherits_contextvar(self, tmp_path):
+ # asyncio.create_task copies the current ContextVar snapshot, so a
+ # background subagent (AgentTool background=True) inherits the logger.
+ from jiuwenswarm.server.runtime.debug_trace import (
+ get_debug_trace_logger,
+ reset_debug_trace_logger,
+ set_debug_trace_logger,
+ )
+
+ lg = _logger(tmp_path)
+ token = set_debug_trace_logger(lg)
+ seen: dict[str, Any] = {}
+ try:
+
+ async def child():
+ seen["child_sees_logger"] = get_debug_trace_logger() is lg
+
+ async def main():
+ task = asyncio.create_task(child())
+ await task
+
+ asyncio.run(main())
+ finally:
+ reset_debug_trace_logger(token)
+ lg.flush() # close the dump file handle (avoid ResourceWarning)
+ assert seen.get("child_sees_logger") is True
+
+ def test_task_tool_patch_idempotent(self):
+ from openjiuwen.harness.tools.subagent.task_tool import TaskTool
+
+ from jiuwenswarm.server.runtime.debug_trace.task_tool_patch import (
+ apply_task_tool_debug_patch,
+ )
+
+ apply_task_tool_debug_patch()
+ apply_task_tool_debug_patch() # second call must be a no-op
+ assert getattr(TaskTool, "debug_trace_patch_applied", False) is True
+
+ def test_ensure_observability_rail_attaches_when_obs_up(self, monkeypatch):
+ # When observability is initialized, _ensure_observability_rail must
+ # add_rail() an ObservabilityRail onto the subagent (run-time attachment,
+ # since build-time is unreliable when obs isn't up yet).
+ import types
+
+ from jiuwenswarm.server.runtime.debug_trace import subagent_capture
+
+ sentinel = types.SimpleNamespace(name="OBS_RAIL")
+
+ class FakeObsRail:
+ pass
+
+ # Point the module-level symbols the helper imports at fakes.
+ import sys
+
+ fake_mod = types.ModuleType("fake_obs_rail")
+ fake_mod.ObservabilityRail = FakeObsRail
+ fake_mod.maybe_observability_rail = lambda: sentinel
+ monkeypatch.setitem(sys.modules, "openjiuwen.agent_teams.observability.rail", fake_mod)
+
+ added: list[Any] = []
+
+ class FakeSub:
+ def configured_rails(self):
+ return [] # none yet
+
+ def add_rail(self, rail):
+ added.append(rail)
+
+ subagent_capture._ensure_observability_rail(FakeSub())
+ assert added == [sentinel]
+
+ def test_ensure_observability_rail_skips_when_already_attached(self, monkeypatch):
+ import types, sys
+
+ from jiuwenswarm.server.runtime.debug_trace import subagent_capture
+
+ class FakeObsRail:
+ pass
+
+ sentinel = types.SimpleNamespace(name="OBS_RAIL")
+
+ fake_mod = types.ModuleType("fake_obs_rail")
+ fake_mod.ObservabilityRail = FakeObsRail
+ fake_mod.maybe_observability_rail = lambda: sentinel
+ monkeypatch.setitem(sys.modules, "openjiuwen.agent_teams.observability.rail", fake_mod)
+
+ added: list[Any] = []
+
+ class FakeSub:
+ def configured_rails(self):
+ return [FakeObsRail()] # already has an ObservabilityRail
+
+ def add_rail(self, rail):
+ added.append(rail)
+
+ subagent_capture._ensure_observability_rail(FakeSub())
+ assert added == [] # idempotent: not re-added
+
+ def test_ensure_observability_rail_noop_when_obs_off(self, monkeypatch):
+ import types, sys
+
+ from jiuwenswarm.server.runtime.debug_trace import subagent_capture
+
+ fake_mod = types.ModuleType("fake_obs_rail")
+ fake_mod.ObservabilityRail = type("ObservabilityRail", (), {})
+ fake_mod.maybe_observability_rail = lambda: None # obs not initialized
+ monkeypatch.setitem(sys.modules, "openjiuwen.agent_teams.observability.rail", fake_mod)
+
+ added: list[Any] = []
+
+ class FakeSub:
+ def configured_rails(self):
+ return []
+
+ def add_rail(self, rail):
+ added.append(rail)
+
+ subagent_capture._ensure_observability_rail(FakeSub())
+ assert added == [] # no-op when observability is off
+