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(team-helpers): 新增 /debug 指令和流式追踪能力
alan_cheng10479b826916
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex 76b8b7b0b0..6f738902c2 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -1602,7 +1602,7 @@ def _jiuwenbox_configs_dir() -> Path | None:def resolve_sandbox_policy_path(value: str | None) -> Path | None:- """把 ``sandbox.policy_file`` 的取值解析为宿主机绝对路径。+ r"""把 ``sandbox.policy_file`` 的取值解析为宿主机绝对路径。- ``None`` / 空字符串 → 返回 None, 由调用方决定是否落到 jiuwenbox 自身默认 policy;- 仅文件名 (不含路径分隔符) → 在 ``jiuwenbox/configs/`` 下拼接;diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex c45daa1d99..c51889496c 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -6,11 +6,14 @@ from __future__ import annotationsimport asyncioimport logging+import osimport timefrom typing import Any, AsyncIterator+from openjiuwen.agent_teams.paths import get_agent_teams_homefrom openjiuwen.agent_teams.runtime import RunActionKindfrom openjiuwen.agent_teams.schema.team import TeamRole+from openjiuwen.agent_teams.monitor import TeamStreamLoggerfrom openjiuwen.core.runner import Runnerfrom openjiuwen.harness import DeepAgent@@ -59,22 +62,34 @@ _TEAM_CREATE_KINDS = {RunActionKind.NEW_TEAM_IN_SESSION.value,}_HIDE_DM_PREFIX = "/hide_dm"+_STREAM_TRACE_ENV_KEY = "JIUWENSWARM_TEAM_STREAM_TRACE"+_DEBUG_PREFIX = "/debug"-def _extract_hide_dm_directive(query: str) -> tuple[str, bool]:- """Strip a leading ``/hide_dm`` directive from the first team query.+def _strip_directive(query: str, prefix: str) -> tuple[str, bool]:+ """Strip a leading slash directive from a query string.Returns the cleaned query and whether the directive was present."""stripped = query.lstrip()- if not stripped.startswith(_HIDE_DM_PREFIX):+ if not stripped.startswith(prefix):return query, False- remainder = stripped[len(_HIDE_DM_PREFIX):]+ remainder = stripped[len(prefix):]if remainder and not remainder[0].isspace():return query, Falsereturn remainder.lstrip(), True+def _extract_query_directives(query: str) -> tuple[str, bool, bool]:+ """Strip all leading slash directives from the first team query.++ Returns (cleaned_query, hide_dm, debug).+ """+ query, hide_dm = _strip_directive(query, _HIDE_DM_PREFIX)+ query, debug = _strip_directive(query, _DEBUG_PREFIX)+ return query, hide_dm, debug++def sync_team_identity_metadata(*,channel_id: str | None,@@ -604,14 +619,17 @@ async def process_team_message_stream(request_queue: asyncio.Queue | None = Nonehide_dm = False+ debug = Falseif is_first_request:- query, hide_dm = _extract_hide_dm_directive(str(query or ""))- if hide_dm:+ query, hide_dm, debug = _extract_query_directives(str(query or ""))+ if hide_dm or debug:logger.info(- "[TeamHelpers] hide_dm directive captured for first team request: "- "channel_id=%s session_id=%s",+ "[TeamHelpers] query directives captured for first team request: "+ "channel_id=%s session_id=%s hide_dm=%s debug=%s",_resolve_channel_id(channel_id),session_id,+ hide_dm,+ debug,)slash_result = await _handle_team_slash_command(@@ -725,6 +743,11 @@ async def process_team_message_stream(session_id,)+ stream_envs: dict[str, Any] = {}+ if hide_dm:+ stream_envs["hide_dm"] = True+ if debug:+ stream_envs[_STREAM_TRACE_ENV_KEY] = "1"round_id = increment_session_round_count(session_id)stream_task = asyncio.create_task(_consume_stream_with_query(@@ -733,7 +756,7 @@ async def process_team_message_stream(team_spec,query,round_id=round_id,- hide_dm=hide_dm,+ envs=stream_envs or None,))team_manager.register_stream_task(session_id, stream_task)@@ -849,9 +872,11 @@ async def _consume_stream_with_query(initial_query: str,*,round_id: int,- hide_dm: bool = False,+ envs: dict[str, Any] | None = None,) -> None:"""Consume the team stream in the background and broadcast parsed events."""+ _envs = envs or {}+ hide_dm: bool = bool(_envs.get("hide_dm", False))received_chunks = 0try:logger.info(@@ -874,10 +899,20 @@ async def _consume_stream_with_query("is_complete": False,},)+ stream_trace_enabled = bool(+ _envs.get(_STREAM_TRACE_ENV_KEY) or os.environ.get(_STREAM_TRACE_ENV_KEY)+ )+ lg: TeamStreamLogger | None = None+ if stream_trace_enabled:+ traces_dir = get_agent_teams_home() / "traces"+ traces_dir.mkdir(parents=True, exist_ok=True)+ lg = TeamStreamLogger(file_path=str(traces_dir / f"dump-team-{session_id}.txt"))async for chunk in Runner.run_agent_team_streaming(agent_team=team_spec,inputs={"query": initial_query},session=session_id,+ envs=envs,+ stream_logger=lg,):received_chunks += 1is_leader = _is_leader_output(chunk)diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.pyindex 6fc97caa72..a912d0b4ac 100644--- a/tests/unit_tests/agentserver/test_team_helpers.py+++ b/tests/unit_tests/agentserver/test_team_helpers.py@@ -1224,25 +1224,28 @@ async def test_consume_stream_with_query_broadcasts_leader_and_teammate_outputs(assert broadcasted[3]["member_name"] == "analyst"-def test_extract_hide_dm_directive_strips_prefix_and_flags():- cleaned, hide_dm = team_helpers._extract_hide_dm_directive( # pylint: disable=protected-access+def test_extract_query_directives_strips_hide_dm_prefix_and_flags():+ cleaned, hide_dm, debug = team_helpers._extract_query_directives( # pylint: disable=protected-access"/hide_dm please summarize")assert hide_dm is True+ assert debug is Falseassert cleaned == "please summarize"-def test_extract_hide_dm_directive_ignores_non_prefix():- cleaned, hide_dm = team_helpers._extract_hide_dm_directive( # pylint: disable=protected-access+def test_extract_query_directives_ignores_non_prefix():+ cleaned, hide_dm, debug = team_helpers._extract_query_directives( # pylint: disable=protected-access"/hide_dmsomething else")assert hide_dm is False+ assert debug is Falseassert cleaned == "/hide_dmsomething else"-def test_extract_hide_dm_directive_handles_bare_directive():- cleaned, hide_dm = team_helpers._extract_hide_dm_directive("/hide_dm") # pylint: disable=protected-access+def test_extract_query_directives_handles_bare_hide_dm():+ cleaned, hide_dm, debug = team_helpers._extract_query_directives("/hide_dm") # pylint: disable=protected-accessassert hide_dm is True+ assert debug is Falseassert cleaned == ""@@ -1308,7 +1311,7 @@ async def test_consume_stream_with_query_propagates_hide_dm_to_monitor(monkeypatSimpleNamespace(team_name="demo-team"),"hello",round_id=1,- hide_dm=True,+ envs={"hide_dm": True},)assert captured == {