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(runtime): mirror subagent reasoning and tool frames onto the parent stream

n993577028ccb85a81511d
diff --git a/jiuwenswarm/agents/harness/common/tools/subagent_compat.py b/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
index 2ca5ac1b47..bf50f7132c 100644
--- a/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
+++ b/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
@@ -4,8 +4,13 @@
from __future__ import annotations
+import logging
from dataclasses import replace
+from typing import Any
+from openjiuwen.core.session.stream.base import (
+ OutputSchema, # type: ignore[import-untyped]
+)
from openjiuwen.harness.subagent_runtime.control import ( # type: ignore[import-untyped]
SubagentControl,
)
@@ -14,7 +19,20 @@ from openjiuwen.harness.subagent_runtime.models import ( # type: ignore[import-
SubagentStatus,
SubagentStatusKind,
)
-from openjiuwen.harness.tools.subagent import _control_registry # type: ignore[import-untyped]
+from openjiuwen.harness.tools.subagent import (
+ _control_registry, # type: ignore[import-untyped]
+)
+
+logger = logging.getLogger(__name__)
+
+# Child chunks safe to replay onto the parent session stream. ``answer``
+# becomes chat.final, ``content_chunk`` becomes chat.delta and flips the
+# parent's streamed-content flag, ``error`` fails the whole parent turn, and
+# the child's own task.* / todo.updated frames would pollute the parent task
+# list — all of those stay on the child session.
+_MIRROR_CHUNK_TYPES = frozenset({"llm_reasoning", "tool_call", "tool_update", "tool_result"})
+# A child task_id would open a phantom task segment on the parent stream.
+_MIRROR_STRIP_KEYS = ("task_id", "parent_request_id")
class CompatibleSubagentControl(SubagentControl):
@@ -42,9 +60,45 @@ class CompatibleSubagentControl(SubagentControl):
await instance.status.set(idle)
return replace(result, status=idle)
+ # Toggled by ``install_subagent_control_compat_patch`` from
+ # ``react.subagent_runtime.mirror_child_stream``. Class-level because the
+ # control registry constructs instances itself.
+ mirror_child_stream: bool = False
+
+ async def _on_child_chunk(self, subagent_id: str, chunk: Any) -> None:
+ """Replay a child stream chunk onto the parent session stream.
+
+ The mirrored frame carries ``stream_source_id = subagent_id`` so hosts
+ that route by source (RelayClaw) nest it under the child instead of
+ mixing it into the parent bubble. A mirror failure must never break
+ the child turn, so write errors are logged and swallowed.
+ """
+ if not self.mirror_child_stream or self._parent_session is None:
+ return
+ chunk_type = getattr(chunk, "type", None)
+ if chunk_type not in _MIRROR_CHUNK_TYPES:
+ return
+ raw = getattr(chunk, "payload", None)
+ payload = dict(raw) if isinstance(raw, dict) else {"content": str(raw or "")}
+ for key in _MIRROR_STRIP_KEYS:
+ payload.pop(key, None)
+ payload["stream_source_id"] = subagent_id
+ try:
+ await self._parent_session.write_stream(
+ OutputSchema(type=chunk_type, index=0, payload=payload)
+ )
+ except Exception as exc: # noqa: BLE001 — mirror must not break the child turn
+ logger.warning(
+ "[subagent_mirror] write failed subagent=%s type=%s: %s",
+ subagent_id,
+ chunk_type,
+ exc,
+ )
+
-def install_subagent_control_compat_patch() -> None:
+def install_subagent_control_compat_patch(*, mirror_child_stream: bool = False) -> None:
"""Use the compatible control for newly created parent-session runtimes."""
+ CompatibleSubagentControl.mirror_child_stream = bool(mirror_child_stream)
_control_registry.SubagentControl = CompatibleSubagentControl
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index e60739c4e4..336888afc6 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -617,6 +617,22 @@ def is_subagent_runtime_enabled(config: dict[str, Any] | None = None) -> bool:
return bool(runtime_cfg.get("enabled")) if isinstance(runtime_cfg, dict) else False
+def is_subagent_mirror_child_stream_enabled(config: dict[str, Any] | None = None) -> bool:
+ """Return ``react.subagent_runtime.mirror_child_stream``.
+
+ When true, raw child stream chunks (reasoning and tool frames) are
+ replayed onto the parent session stream with ``stream_source_id`` set to
+ the subagent id, so hosts that route by source render them like any other
+ stream. Missing key is False: Swarm Web keeps its roster projection.
+ """
+ cfg = config if config is not None else get_config()
+ react = cfg.get("react") if isinstance(cfg, dict) else None
+ runtime_cfg = react.get("subagent_runtime") if isinstance(react, dict) else None
+ if not isinstance(runtime_cfg, dict):
+ return False
+ return bool(runtime_cfg.get("mirror_child_stream"))
+
+
def get_ttse_embedding_config(config: dict[str, Any] | None) -> dict[str, str]:
"""Return normalized ``react.ttse.embedding`` fields for TTSE retrieval.
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 1b0ce5256a..6ed8ad5c26 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -627,6 +627,10 @@ react:
# send_input/close/resume 六个工具替换(两者互斥)。默认开启。
subagent_runtime:
enabled: true
+ # 把子代理的思考/工具帧原样镜像到父会话流,并带 stream_source_id=子代理 id,
+ # 供按 source 路由的宿主(RelayClaw)渲染成嵌套子代理行。进程级开关:
+ # 打开后同一进程服务的所有 channel 都会收到这些帧,默认关闭。
+ mirror_child_stream: false
# ProgressiveToolRail: 工具延迟加载,固定 eager_tools schema,deferred 工具通过
# tools_search → invoke_tool 间接调用,最大化 prefix cache 命中率。
tool_lazy_load:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 09a73cb4cd..1b3a5f4b7b 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -446,6 +446,19 @@ def _should_defer_a2ui_processing_status(
)
+def _is_foreign_stream_source(payload: Any) -> bool:
+ """True for frames mirrored from a nested stream (subagent / skill node).
+
+ Such frames carry a non-empty ``stream_source_id`` other than the ``main``
+ sentinel the gateway fills in. They must not move parent-turn bookkeeping
+ or land in the parent history.
+ """
+ if not isinstance(payload, dict):
+ return False
+ source_id = payload.get("stream_source_id")
+ return isinstance(source_id, str) and bool(source_id) and source_id != "main"
+
+
def _is_duplicate_full_body_delta(pending_chunks: list[str], content: str) -> bool:
"""True when ``content`` is an exact replay of the already-buffered answer body.
@@ -3769,14 +3782,21 @@ class JiuWenSwarm:
durable_pending_final_chunks.append(payload_content)
should_record = False
elif et == "chat.reasoning":
- durable_pending_reasoning_chunks.append(payload_content)
+ # Reasoning mirrored from a nested stream stays
+ # out of the parent's reasoning buffer.
+ if not _is_foreign_stream_source(data.payload):
+ durable_pending_reasoning_chunks.append(payload_content)
should_record = False
elif et == "chat.tool_call":
- _persist_pending_final_text()
- # Post-tool LLM rounds must not inherit pre-tool
- # delta visibility; otherwise reasoning-only
- # follow-ups skip the empty-final rescue.
- final_answer_chunks = []
+ # A child tool call must not close the parent's
+ # in-flight answer segment or reset its delta
+ # visibility.
+ if not _is_foreign_stream_source(data.payload):
+ _persist_pending_final_text()
+ # Post-tool LLM rounds must not inherit pre-tool
+ # delta visibility; otherwise reasoning-only
+ # follow-ups skip the empty-final rescue.
+ final_answer_chunks = []
elif et == "chat.final":
if isinstance(data.payload, dict):
ensure_final_mode_inplace(data.payload)
@@ -3860,7 +3880,7 @@ class JiuWenSwarm:
)
durable_pending_final_chunks = []
- if should_record:
+ if should_record and not _is_foreign_stream_source(data.payload):
payload_dict = dict(data.payload)
extra_fields = {k: v for k, v in payload_dict.items() if
k not in ("event_type", "content", "task_id")}
@@ -3972,11 +3992,13 @@ class JiuWenSwarm:
durable_pending_final_chunks.append(payload_content)
should_record = False
elif et == "chat.reasoning":
- durable_pending_reasoning_chunks.append(payload_content)
+ if not _is_foreign_stream_source(data):
+ durable_pending_reasoning_chunks.append(payload_content)
should_record = False
elif et == "chat.tool_call":
- _persist_pending_final_text()
- final_answer_chunks = []
+ if not _is_foreign_stream_source(data):
+ _persist_pending_final_text()
+ final_answer_chunks = []
elif et == "chat.final":
if suppress_a2ui_stream or a2ui_split is not None:
first_a2ui_suppression = not suppress_a2ui_stream
@@ -4040,7 +4062,7 @@ class JiuWenSwarm:
)
durable_pending_final_chunks = []
- if should_record:
+ if should_record and not _is_foreign_stream_source(data):
extra_fields = {
k: v
for k, v in data.items()
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index db6f16edfd..05e7a82b56 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -175,6 +175,19 @@ _SKILL_TURBO_TOOL_ID_SUFFIX = "_skill_turbo"
_RESUME_SIGNAL_CHUNK_TYPE = "__resume_signal__"
+def _is_foreign_stream_source(payload: Any) -> bool:
+ """True when the frame was mirrored from a nested stream (subagent / skill node).
+
+ The gateway fills a missing source with the ``"main"`` sentinel, so only a
+ non-empty, non-``main`` id marks a frame that must not touch parent-turn
+ bookkeeping.
+ """
+ if not isinstance(payload, dict):
+ return False
+ source_id = payload.get(STREAM_SOURCE_ID_FIELD)
+ return isinstance(source_id, str) and bool(source_id) and source_id != "main"
+
+
def _propagate_stream_source_id(
src_payload: Any, result: dict[str, Any] | None
) -> dict[str, Any] | None:
@@ -543,6 +556,7 @@ from jiuwenswarm.common.config import (
_get_ttse_config,
get_ttse_embedding_config,
get_ttse_enabled,
+ is_subagent_mirror_child_stream_enabled,
is_subagent_runtime_enabled,
resolve_env_vars,
resolve_string_or_list_config,
@@ -9363,7 +9377,9 @@ class JiuWenSwarmDeepAdapter:
install_subagent_control_compat_patch,
)
- install_subagent_control_compat_patch()
+ install_subagent_control_compat_patch(
+ mirror_child_stream=is_subagent_mirror_child_stream_enabled(config_base),
+ )
except Exception as exc:
logger.warning(
"[JiuWenSwarmDeepAdapter] subagent control compat skipped: %s",
@@ -19996,6 +20012,11 @@ class JiuWenSwarmDeepAdapter:
nonlocal saw_approved_plan_exit_result, had_reasoning_output
nonlocal visible_text_since_last_final, segment_streamed_text
nonlocal has_streamed_content, had_visible_text_ever
+ # Frames mirrored from a child stream (subagent / skill node) must
+ # not reset the parent's streamed-content flags or stamp the
+ # parent's first-byte / first-answer marks.
+ if _is_foreign_stream_source(payload):
+ return payload
event_type = payload.get("event_type")
if event_type == "chat.reasoning":
had_reasoning_output = True
@@ -20580,7 +20601,11 @@ class JiuWenSwarmDeepAdapter:
getattr(chunk, "type", None) or type(chunk).__name__,
)
if _debug_logger is not None:
- _debug_logger.feed(chunk)
+ # Chunks mirrored from a child stream are captured under
+ # their own source; feeding them here would duplicate them
+ # in the parent run's "main" section.
+ if not _is_foreign_stream_source(getattr(chunk, "payload", None)):
+ _debug_logger.feed(chunk)
# Surface run-level terminal failures (model/task_failed,
# error answer) on the /debug run-end status instead of a
# blanket "ok"; recoverable tool_result errors stay "ok".
@@ -21948,7 +21973,14 @@ class JiuWenSwarmDeepAdapter:
tool_info = (
payload.get("tool_call", payload) if isinstance(payload, dict) else payload
)
- return {"event_type": "chat.tool_call", "tool_call": tool_info}
+ # 只透传 stream_source_id:tool 帧带 task_id 会让 RelayClaw
+ # 按它开一个假的 taskRuns 段,且 reasoning 帧与 tool 帧被拆开。
+ return _propagate_stream_source_id(
+ {STREAM_SOURCE_ID_FIELD: payload.get(STREAM_SOURCE_ID_FIELD)}
+ if isinstance(payload, dict)
+ else {},
+ {"event_type": "chat.tool_call", "tool_call": tool_info},
+ )
if chunk_type == "tool_update":
if isinstance(payload, dict):
@@ -21960,10 +21992,12 @@ class JiuWenSwarmDeepAdapter:
)
else:
update_payload = {"content": str(payload)}
- return {
- "event_type": "chat.tool_update",
- **update_payload,
- }
+ return _propagate_stream_source_id(
+ {STREAM_SOURCE_ID_FIELD: payload.get(STREAM_SOURCE_ID_FIELD)}
+ if isinstance(payload, dict)
+ else {},
+ {"event_type": "chat.tool_update", **update_payload},
+ )
if chunk_type == "tool_result":
if isinstance(payload, dict):
@@ -21971,10 +22005,12 @@ class JiuWenSwarmDeepAdapter:
result_payload = build_tool_result_payload(result_info)
else:
result_payload = {"result": str(payload)}
- return {
- "event_type": "chat.tool_result",
- **result_payload,
- }
+ return _propagate_stream_source_id(
+ {STREAM_SOURCE_ID_FIELD: payload.get(STREAM_SOURCE_ID_FIELD)}
+ if isinstance(payload, dict)
+ else {},
+ {"event_type": "chat.tool_result", **result_payload},
+ )
if chunk_type == "error":
error_msg = (
diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.py
index 8a156eb5e2..c1241b01a9 100644
--- a/jiuwenswarm/server/utils/stream_utils.py
+++ b/jiuwenswarm/server/utils/stream_utils.py
@@ -481,7 +481,11 @@ def _parse_typed_chunk(
if isinstance(payload, dict)
else payload
)
- return {"event_type": "chat.tool_call", "tool_call": tool_info}
+ return {
+ "event_type": "chat.tool_call",
+ "tool_call": tool_info,
+ **_propagate_stream_source_id(payload),
+ }
if chunk_type == "tool_update":
if isinstance(payload, dict):
@@ -492,6 +496,7 @@ def _parse_typed_chunk(
return {
"event_type": "chat.tool_update",
**update_payload,
+ **_propagate_stream_source_id(payload),
}
if chunk_type == "tool_result":
@@ -503,6 +508,7 @@ def _parse_typed_chunk(
return {
"event_type": "chat.tool_result",
**result_payload,
+ **_propagate_stream_source_id(payload),
}
if chunk_type == "error":
diff --git a/tests/unit_tests/agents/harness/test_subagent_compat.py b/tests/unit_tests/agents/harness/test_subagent_compat.py
index 343e5de358..98801809f8 100644
--- a/tests/unit_tests/agents/harness/test_subagent_compat.py
+++ b/tests/unit_tests/agents/harness/test_subagent_compat.py
@@ -76,7 +76,76 @@ def test_install_patch_rebinds_control_factory(monkeypatch: pytest.MonkeyPatch)
from openjiuwen.harness.tools.subagent import _control_registry
monkeypatch.setattr(_control_registry, "SubagentControl", SubagentControl)
+ previous = CompatibleSubagentControl.mirror_child_stream
+ CompatibleSubagentControl.mirror_child_stream = False
- install_subagent_control_compat_patch()
+ install_subagent_control_compat_patch(mirror_child_stream=True)
assert _control_registry.SubagentControl is CompatibleSubagentControl
+ assert CompatibleSubagentControl.mirror_child_stream is True
+ CompatibleSubagentControl.mirror_child_stream = previous
+
+
+class _Chunk:
+ def __init__(self, chunk_type: str, payload: object) -> None:
+ self.type = chunk_type
+ self.payload = payload
+
+
+class _ParentSession:
+ def __init__(self, *, fail: bool = False) -> None:
+ self.written: list[tuple[str, dict]] = []
+ self._fail = fail
+
+ async def write_stream(self, schema: object) -> None:
+ if self._fail:
+ raise RuntimeError("stream closed")
+ self.written.append((schema.type, schema.payload))
+
+
+def _mirror_control(session: _ParentSession) -> CompatibleSubagentControl:
+ control = object.__new__(CompatibleSubagentControl)
+ control._parent_session = session # pylint: disable=protected-access
+ control.mirror_child_stream = True
+ return control
+
+
+async def test_mirror_replays_allowed_chunks_with_source_id() -> None:
+ session = _ParentSession()
+ control = _mirror_control(session)
+
+ await control._on_child_chunk("sub-1", _Chunk("llm_reasoning", {"content": "先看一下"}))
+ await control._on_child_chunk(
+ "sub-1",
+ _Chunk("tool_call", {"tool_call": {"id": "c1", "name": "web_search"}, "task_id": "t-child"}),
+ )
+ await control._on_child_chunk("sub-1", _Chunk("answer", {"output": "结论"}))
+ await control._on_child_chunk("sub-1", _Chunk("content_chunk", {"content": "正文"}))
+ await control._on_child_chunk("sub-1", _Chunk("error", {"error": "boom"}))
+ await control._on_child_chunk("sub-1", _Chunk("task.start", {"task_id": "t-child"}))
+
+ assert [item[0] for item in session.written] == ["llm_reasoning", "tool_call"]
+ reasoning, tool = (item[1] for item in session.written)
+ assert reasoning == {"content": "先看一下", "stream_source_id": "sub-1"}
+ assert tool["stream_source_id"] == "sub-1"
+ assert "task_id" not in tool
+ assert tool["tool_call"]["name"] == "web_search"
+
+
+async def test_mirror_disabled_writes_nothing() -> None:
+ session = _ParentSession()
+ control = _mirror_control(session)
+ control.mirror_child_stream = False
+
+ await control._on_child_chunk("sub-1", _Chunk("llm_reasoning", {"content": "x"}))
+
+ assert session.written == []
+
+
+async def test_mirror_write_failure_is_swallowed() -> None:
+ control = _mirror_control(_ParentSession(fail=True))
+
+ await control._on_child_chunk("sub-1", _Chunk("tool_result", {"result": "ok"}))
diff --git a/tests/unit_tests/agentserver/test_foreign_stream_source.py b/tests/unit_tests/agentserver/test_foreign_stream_source.py
new file mode 100644
index 0000000000..e1c8799996
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_foreign_stream_source.py
@@ -0,0 +1,83 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Parent-turn bookkeeping ignores frames mirrored from a nested stream."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jiuwenswarm.server.runtime.agent_adapter.interface import (
+ _is_foreign_stream_source as facade_is_foreign,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ _is_foreign_stream_source as adapter_is_foreign,
+)
+
+
[email protected]("predicate", [facade_is_foreign, adapter_is_foreign])
+def test_foreign_source_detection(predicate) -> None:
+ assert predicate({"stream_source_id": "sub-1"}) is True
+ assert predicate({"stream_source_id": "main"}) is False
+ assert predicate({"stream_source_id": ""}) is False
+ assert predicate({}) is False
+ assert predicate(None) is False
+
+
+class _Logger:
+ def __init__(self) -> None:
+ self.sources: list[str] = []
+
+ def feed(self, chunk: object) -> None:
+ self.sources.append("main")
+
+
+def test_note_chat_payload_skips_foreign_tool_call() -> None:
+ """A mirrored child tool_call must not clear the parent's streamed flags."""
+ state = {"has_streamed_content": True, "segment_streamed_text": "父正文"}
+
+ def note(payload: dict) -> dict:
+ if adapter_is_foreign(payload):
+ return payload
+ if payload.get("event_type") == "chat.tool_call":
+ state["segment_streamed_text"] = ""
+ state["has_streamed_content"] = False
+ return payload
+
+ note({"event_type": "chat.tool_call", "stream_source_id": "sub-1", "tool_call": {}})
+
+ assert state == {"has_streamed_content": True, "segment_streamed_text": "父正文"}
+
+
+def test_debug_feed_skips_mirrored_chunk() -> None:
+ """The parent run dump must not re-record chunks mirrored from a child."""
+ debug_logger = _Logger()
+ chunk = SimpleNamespace(type="tool_call", payload={"stream_source_id": "sub-1"})
+
+ if not adapter_is_foreign(getattr(chunk, "payload", None)):
+ debug_logger.feed(chunk)
+
+ assert debug_logger.sources == []
+
+
+def test_adapter_parser_propagates_source_id_on_tool_call(caplog) -> None:
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ chunk = SimpleNamespace(
+ type="tool_call",
+ payload={
+ "tool_call": {"id": "c1", "name": "web_search"},
+ "stream_source_id": "sub-1",
+ "task_id": "t-child",
+ },
+ )
+
+ parsed = adapter._parse_stream_chunk(chunk)
+
+ assert parsed is not None, caplog.text
+ assert parsed["event_type"] == "chat.tool_call"
+ assert parsed["stream_source_id"] == "sub-1"
+ assert "task_id" not in parsed
diff --git a/tests/unit_tests/server/test_stream_utils_tool_source_id.py b/tests/unit_tests/server/test_stream_utils_tool_source_id.py
new file mode 100644
index 0000000000..c35592329e
--- /dev/null
+++ b/tests/unit_tests/server/test_stream_utils_tool_source_id.py
@@ -0,0 +1,68 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""stream_source_id propagation for tool frames parsed by stream_utils."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jiuwenswarm.server.utils.stream_utils import _parse_typed_chunk
+
+
+def _chunk(chunk_type: str, payload: dict) -> SimpleNamespace:
+ return SimpleNamespace(type=chunk_type, payload=payload)
+
+
+def test_tool_call_propagates_source_id_without_task_id() -> None:
+ parsed = _parse_typed_chunk(
+ _chunk(
+ "tool_call",
+ {
+ "tool_call": {"id": "c1", "name": "web_search", "arguments": {"q": "x"}},
+ "stream_source_id": "sub-1",
+ "task_id": "t-child",
+ },
+ ),
+ False,
+ )
+
+ assert parsed["event_type"] == "chat.tool_call"
+ assert parsed["stream_source_id"] == "sub-1"
+ assert "task_id" not in parsed
+ assert parsed["tool_call"]["name"] == "web_search"
+
+
+def test_tool_result_propagates_source_id() -> None:
+ parsed = _parse_typed_chunk(
+ _chunk(
+ "tool_result",
+ {
+ "tool_result": {"tool_call_id": "c1", "tool_name": "web_search", "result": "ok"},
+ "stream_source_id": "sub-1",
+ },
+ ),
+ False,
+ )
+
+ assert parsed["event_type"] == "chat.tool_result"
+ assert parsed["stream_source_id"] == "sub-1"
+ assert parsed["tool_call_id"] == "c1"
+
+
+def test_tool_update_propagates_source_id() -> None:
+ parsed = _parse_typed_chunk(
+ _chunk("tool_update", {"content": "working", "stream_source_id": "sub-1"}),
+ False,
+ )
+
+ assert parsed["event_type"] == "chat.tool_update"
+ assert parsed["stream_source_id"] == "sub-1"
+
+
+def test_tool_frames_without_source_id_stay_unchanged() -> None:
+ parsed = _parse_typed_chunk(
+ _chunk("tool_call", {"tool_call": {"id": "c1", "name": "web_search"}}),
+ False,
+ )
+
+ assert "stream_source_id" not in parsed