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): wire persistent subagent runtime into the server

n99357702898a4a12fa844
diff --git a/jiuwenswarm/agents/harness/common/browser_defaults.py b/jiuwenswarm/agents/harness/common/browser_defaults.py
new file mode 100644
index 0000000000..56ecce86e4
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/browser_defaults.py
@@ -0,0 +1,5 @@
+"""Shared jiuwenswarm defaults for the browser sub-agent."""
+
+DEFAULT_BROWSER_AGENT_MAX_ITERATIONS = 100
+
+__all__ = ["DEFAULT_BROWSER_AGENT_MAX_ITERATIONS"]
diff --git a/jiuwenswarm/agents/harness/common/prompt/browser_task_prompt.py b/jiuwenswarm/agents/harness/common/prompt/browser_task_prompt.py
new file mode 100644
index 0000000000..8a2799247e
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/prompt/browser_task_prompt.py
@@ -0,0 +1,65 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Browser guidance appended to agent-core's subagent tool section."""
+
+from __future__ import annotations
+
+
+_BROWSER_TASK_PROMPT = {
+ "cn": (
+ "## 浏览器能力路由规则(高优先级)\n\n"
+ "- 当用户明确要求使用浏览器,或任务需要打开/跳转真实页面、点击、输入、登录、"
+ "购物车操作、截图、检查页面显示内容、读取指定站点搜索结果时,立即调用同步 "
+ "`task_tool`,将 `subagent_type` 设为 `\"browser_agent\"`,并在 "
+ "`task_description` 中写明完整目标。不要使用 `subagent_spawn` 启动 browser_agent。\n"
+ "- Browser Agent 是同步的专用浏览器能力,不是可选的并行委派。即使用户没有明确说"
+ "“子代理”,即使主流程必须等待浏览器结果,也应遵循本节规则;本节覆盖通用子代理"
+ "规则中“未明确要求委派时不要调用”和“关键路径不要等待子代理”的限制。\n"
+ "- 对上述浏览器意图,不要先调用 paid_search、web_search、fetch 或类似搜索/抓取工具"
+ "做预检。只有用户仅要求一般资料检索且不关心指定页面交互时,才优先使用搜索/抓取;"
+ "或 Browser Agent 已返回明确 blocker/partial,用户要求确实尚未回答,且替代来源仍能满足目标时再降级。"
+ "已取得带来源的答案时直接汇报,不因 partial 标签或字段未结构化而重跑浏览器或交叉验证。\n"
+ "- `task_description` 必须保留用户的完整动作目标,不得把“加入购物车”等操作擅自缩减为"
+ "搜索或候选列表。加入购物车属于可逆操作,可按用户明确要求完成;进入结算、提交订单或"
+ "支付前仍须遵守最终确认要求。\n"
+ "- 不要通过 Bash、代码执行、子进程、Shell 命令或直接启动 Chrome/Edge "
+ "来执行浏览器自动化。\n"
+ "- `task_tool` 或 `browser_agent` 不可用时,明确说明不可用,不要改用命令行启动浏览器。"
+ ),
+ "en": (
+ "## Browser Capability Routing Rules (High Priority)\n\n"
+ "- When the user explicitly requests a browser, or the task requires opening or "
+ "navigating a real page, clicking, typing, logging in, changing a cart, taking a "
+ "screenshot, inspecting rendered content, or reading search results on a specified "
+ "site, immediately call the synchronous `task_tool`, set `subagent_type` to "
+ '`"browser_agent"`, and put the complete objective in `task_description`. Do not use '
+ "`subagent_spawn` for browser_agent.\n"
+ "- Browser Agent is a synchronous browser capability, not optional parallel delegation. "
+ "Apply this rule even when the user did not explicitly request a subagent and even when "
+ "the main path must wait for the result. This section overrides generic subagent rules "
+ "that prohibit unrequested delegation or waiting on critical-path subagents.\n"
+ "- For browser intent, do not preflight with paid_search, web_search, fetch, or similar "
+ "search/fetch tools. Prefer those tools only for general information research that does "
+ "not depend on a specified site's UI, or after Browser Agent returns an explicit "
+ "blocker/partial result with genuinely unanswered requirements that an alternate source can satisfy. "
+ "Report sourced answers directly; a partial label or unmapped field alone does not justify another "
+ "browser run or cross-check.\n"
+ "- Preserve the user's complete action objective in `task_description`; do not narrow actions such as "
+ "adding an item to the cart into search or a shortlist. Adding to a cart is reversible and may be "
+ "completed when explicitly requested; checkout, order submission, and payment still require final "
+ "confirmation.\n"
+ "- Do not use Bash, code execution, subprocesses, shell commands, or direct Chrome/Edge launches "
+ "for browser automation.\n"
+ "- If `task_tool` or `browser_agent` is unavailable, state that clearly; "
+ "do not fall back to launching a browser from the command line."
+ ),
+}
+
+
+def build_browser_task_prompt(language: str = "cn") -> str:
+ """Return localized browser guidance for the subagent tool section."""
+
+ return _BROWSER_TASK_PROMPT.get(language, _BROWSER_TASK_PROMPT["cn"])
+
+
+__all__ = ["build_browser_task_prompt"]
diff --git a/jiuwenswarm/agents/harness/common/rails/browser_task_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/browser_task_prompt_rail.py
new file mode 100644
index 0000000000..ba7014e4cd
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/browser_task_prompt_rail.py
@@ -0,0 +1,76 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Load-aware subagent prompt extension for browser delegation."""
+
+from __future__ import annotations
+
+from inspect import signature
+from typing import Any
+
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.rails.subagent import SubagentRail
+
+from jiuwenswarm.agents.harness.common.prompt.browser_task_prompt import (
+ build_browser_task_prompt,
+)
+
+
+def _subagent_rail_init_kwargs(
+ *,
+ enable_async_subagent: bool,
+ enable_subagent_runtime: bool,
+ task_prompt_extension: Any,
+ synchronous_subagent_types: set[str],
+) -> dict[str, Any]:
+ """Pass only kwargs the installed SDK SubagentRail actually accepts."""
+ params = signature(SubagentRail.__init__).parameters
+ kwargs: dict[str, Any] = {}
+ if "enable_async_subagent" in params:
+ kwargs["enable_async_subagent"] = enable_async_subagent
+ if "enable_subagent_runtime" in params:
+ kwargs["enable_subagent_runtime"] = enable_subagent_runtime
+ if "task_prompt_extension" in params:
+ kwargs["task_prompt_extension"] = task_prompt_extension
+ if "synchronous_subagent_types" in params:
+ kwargs["synchronous_subagent_types"] = synchronous_subagent_types
+ return kwargs
+
+
+class BrowserTaskPromptRail(SubagentRail):
+ """Append browser policy when the browser subagent is available."""
+
+ def __init__(
+ self,
+ *,
+ enable_async_subagent: bool = False,
+ enable_subagent_runtime: bool = False,
+ ) -> None:
+ super().__init__(
+ **_subagent_rail_init_kwargs(
+ enable_async_subagent=enable_async_subagent,
+ enable_subagent_runtime=enable_subagent_runtime,
+ task_prompt_extension=self._task_prompt_extension,
+ synchronous_subagent_types={"browser_agent"},
+ )
+ )
+ self.enable_subagent_runtime = bool(enable_subagent_runtime)
+
+ def _task_prompt_extension(
+ self,
+ ctx: AgentCallbackContext,
+ language: str,
+ ) -> str | None:
+ if not self._has_browser_agent(ctx.agent):
+ return None
+ return build_browser_task_prompt(language)
+
+ def _has_browser_agent(self, agent: object) -> bool:
+ deep_config = getattr(agent, "deep_config", None)
+ subagents = getattr(deep_config, "subagents", None) or []
+ return any(
+ self._extract_agent_meta(spec)[0] == "browser_agent"
+ for spec in subagents
+ )
+
+
+__all__ = ["BrowserTaskPromptRail"]
diff --git a/jiuwenswarm/agents/harness/common/rails/execution_guard/__init__.py b/jiuwenswarm/agents/harness/common/rails/execution_guard/__init__.py
new file mode 100644
index 0000000000..855b6c28aa
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/execution_guard/__init__.py
@@ -0,0 +1,8 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from .circuit_breaker_rail import CircuitBreakerConfig, CircuitBreakerRail
+
+__all__ = [
+ "CircuitBreakerConfig",
+ "CircuitBreakerRail",
+]
\ No newline at end of file
diff --git a/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py b/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
new file mode 100644
index 0000000000..71b588da7d
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
@@ -0,0 +1,654 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""CircuitBreakerRail - Agent 循环检测断路器.
+
+检测类型:
+ - generic_repeat: 相同工具+参数重复 (WARNING≥10)
+ - unknown_tool_repeat: 错误工具连续调用 (CRITICAL≥10)
+ - global_breaker: 工具无进展兜底中断 (CRITICAL≥30)
+ - ping_pong: 两工具交替循环,尾部无进展轮次 (WARNING≥10, CRITICAL≥20)
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import hashlib
+import json
+import re
+import time
+from dataclasses import dataclass
+from typing import Any
+
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, InvokeInputs
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+from jiuwenswarm.common.utils import logger
+
+
+@dataclass
+class CircuitBreakerConfig:
+ warning_threshold: int = 10
+ critical_threshold: int = 20
+ global_breaker_threshold: int = 30
+ unknown_tool_threshold: int = 10
+
+ @property
+ def history_size(self) -> int:
+ return max(
+ 4 * self.critical_threshold,
+ 2 * self.global_breaker_threshold,
+ 2 * self.unknown_tool_threshold,
+ )
+
+_invoke_sid: contextvars.ContextVar[str | None] = contextvars.ContextVar(
+ "circuit_breaker_invoke_sid",
+ default=None,
+)
+
+# 报错文案按语言 × 检测器分表,占位符 {tool_name} / {count} 在渲染时填充。
+# 语言键与 openjiuwen SUPPORTED_LANGUAGES 对齐:("cn", "en")。
+_MESSAGES: dict[str, dict[str, str]] = {
+ "cn": {
+ "global_circuit_breaker": "全局断路器: {tool_name} 连续 {count} 次无进展",
+ "unknown_tool_repeat": "未知工具 {tool_name} 连续调用 {count} 次,停止重试",
+ "ping_pong_critical": "Ping-Pong 循环: {count} 轮交替无进展,阻断",
+ "ping_pong_warning": "Ping-Pong 警告: {count} 轮交替无进展",
+ "generic_repeat": "工具 {tool_name} 已重复调用 {count} 次,请检查是否有效",
+ },
+ "en": {
+ "global_circuit_breaker": (
+ "Circuit breaker: {tool_name} made no progress for {count} consecutive calls"
+ ),
+ "unknown_tool_repeat": (
+ "Unknown tool {tool_name} called {count} times in a row, stopping retries"
+ ),
+ "ping_pong_critical": (
+ "Ping-pong loop: {count} alternating calls with no progress, blocked"
+ ),
+ "ping_pong_warning": "Ping-pong warning: {count} alternating calls with no progress",
+ "generic_repeat": (
+ "Tool {tool_name} has been repeated {count} times, please verify it is effective"
+ ),
+ },
+}
+
+_DEFAULT_LANGUAGE = "cn"
+
+# 按工具排除不影响执行语义的顶层 metadata 键(不参与 args_hash)。
+_METADATA_ONLY_TOP_LEVEL: dict[str, frozenset[str]] = {
+ "bash": frozenset({"description"}),
+ "powershell": frozenset({"description"}),
+ "Agent": frozenset({"description"}),
+}
+
+__all__ = [
+ "CircuitBreakerConfig",
+ "CircuitBreakerRail",
+ "ToolResultErrorDetector",
+ "ToolCallRecord",
+ "DetectionResult",
+ "PingPongResult",
+]
+
+
+def _normalize_language(language: str | None) -> str:
+ """归一语言键:config 用 zh,rail 内部用 cn;非法值回落默认。"""
+ lang = (language or "").strip().lower()
+ if lang == "zh":
+ lang = "cn"
+ return lang if lang in _MESSAGES else _DEFAULT_LANGUAGE
+
+
+class ToolResultErrorDetector:
+ """从工具返回结果的结构化字段推断是否发生错误。
+
+ 支持 ToolOutput / dict / JSON 字符串 / repr 字符串归一化后判定。
+ 当前与 CircuitBreakerRail 同文件维护;其他模块可直接 import 复用::
+
+ from jiuwenswarm.agents.harness.common.rails.execution_guard.circuit_breaker_rail import (
+ ToolResultErrorDetector,
+ )
+ """
+
+ _ERROR_STATUSES = frozenset({"error", "failed", "failure"})
+ _EXIT_KEYS = ("exit_code", "exitCode", "returncode", "return_code")
+ _REPR_SUCCESS_FALSE = re.compile(r"^success\s*=\s*False\b", re.IGNORECASE)
+ _REPR_SUCCESS_TRUE = re.compile(r"^success\s*=\s*True\b", re.IGNORECASE)
+
+ # 裸字符串失败标记:部分工具无法通过结构化 success 字段表达失败,只能在
+ # 没有产出结构化结果的路径上返回纯文本。只有当某个前缀是失败结果独有、
+ # 成功输出绝不会以其开头时才能加入(契约见
+ # tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py)。
+ #
+ # ``[ERROR]:`` 是项目内工具失败的通用约定(见
+ # jiuwenswarm/agents/harness/common/tools/ 下的 search / image / audio /
+ # video / pdf / web_fetch 等模块)。这些工具成功时本就返回纯文本 —— 结果
+ # 列表、转写、模型回答 —— 失败时没有结构化字段可用,只能靠该前缀表达。
+ #
+ # 功能特定的标记不应写死在这个通用探测器里 —— 类文档已声明它可被其他模块
+ # 直接复用,而各调用方对误判/漏判的容忍度并不相同,一个错误的前缀会同时
+ # 影响所有调用方。功能模块改用 register_plain_error_prefix 注册自己的
+ # 标记,无需改动本文件。
+ _PLAIN_ERROR_PREFIXES = ("[ERROR]:",)
+ _extra_plain_error_prefixes: set[str] = set()
+
+ @classmethod
+ def register_plain_error_prefix(cls, prefix: str) -> None:
+ """为"失败即裸字符串"的工具注册一个专属前缀,无需改动本文件。
+
+ 前缀必须是失败结果独有的标记,成功输出绝不会以其开头,否则会把成功
+ 结果误判为失败。匹配大小写不敏感。
+ """
+ marker = prefix.strip().upper()
+ if marker:
+ cls._extra_plain_error_prefixes.add(marker)
+
+ @classmethod
+ def _plain_error_prefixes(cls) -> tuple[str, ...]:
+ return cls._PLAIN_ERROR_PREFIXES + tuple(cls._extra_plain_error_prefixes)
+
+ @staticmethod
+ def has_error(value: Any) -> bool:
+ """结构化字段明确指示错误时返回 True,否则返回 False。"""
+ payload = ToolResultErrorDetector._normalize(value)
+ if payload is None:
+ return False
+ return ToolResultErrorDetector._dict_has_error(payload)
+
+ @staticmethod
+ def has_explicit_success(value: Any) -> bool:
+ """结构化字段明确指示成功时返回 True,否则返回 False。"""
+ payload = ToolResultErrorDetector._normalize(value)
+ if payload is None or "success" not in payload:
+ return False
+ if ToolResultErrorDetector._boolish_true(payload.get("success")):
+ return True
+ return False
+
+ @staticmethod
+ def ctx_has_error(ctx: AgentCallbackContext) -> bool:
+ """从回调上下文推断工具调用是否发生错误。"""
+ if ctx.exception is not None:
+ return True
+ tool_msg = getattr(ctx.inputs, "tool_msg", None)
+ if tool_msg is not None:
+ return ToolResultErrorDetector.has_error(getattr(tool_msg, "content", None))
+ return False
+
+ @staticmethod
+ def infer_record_has_error(
+ tool_result: Any,
+ ctx: AgentCallbackContext,
+ ) -> bool:
+ """推断单次工具调用是否计入 unknown_tool 连续错误 streak。
+
+ tool_result 能明确判定成功/失败时以其为准;仅在结果不可解析时
+ 才回退到 ctx.exception / tool_msg,避免成功结果被 ctx 误判为错误。
+ """
+ if ToolResultErrorDetector.has_error(tool_result):
+ return True
+ if ToolResultErrorDetector.has_explicit_success(tool_result):
+ return False
+ return ToolResultErrorDetector.ctx_has_error(ctx)
+
+ @staticmethod
+ def _normalize(value: Any) -> dict | None:
+ if value is None:
+ return None
+ if isinstance(value, dict):
+ return value
+ model_dump = getattr(value, "model_dump", None)
+ if callable(model_dump):
+ dumped = model_dump()
+ if isinstance(dumped, dict):
+ return dumped
+ if hasattr(value, "success"):
+ return {
+ "success": getattr(value, "success", None),
+ "data": getattr(value, "data", None),
+ "error": getattr(value, "error", None),
+ }
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return None
+ if text.startswith("{"):
+ try:
+ parsed = json.loads(text)
+ except (TypeError, ValueError):
+ parsed = None
+ if isinstance(parsed, dict):
+ return parsed
+ if ToolResultErrorDetector._REPR_SUCCESS_FALSE.match(text):
+ return {"success": False}
+ if ToolResultErrorDetector._REPR_SUCCESS_TRUE.match(text):
+ return {"success": True}
+ upper = text.upper()
+ for prefix in ToolResultErrorDetector._plain_error_prefixes():
+ if upper.startswith(prefix):
+ return {"success": False, "error": text}
+ return None
+
+ @staticmethod
+ def _dict_has_error(payload: dict, *, check_data: bool = True) -> bool:
+ if "success" in payload:
+ if ToolResultErrorDetector._boolish_false(payload.get("success")):
+ return True
+ if ToolResultErrorDetector._boolish_true(payload.get("success")):
+ return False
+ if (
+ ToolResultErrorDetector._boolish_true(payload.get("is_error"))
+ or ToolResultErrorDetector._boolish_true(payload.get("isError"))
+ ):
+ return True
+ status = payload.get("status")
+ if isinstance(status, str) and status.strip().lower() in ToolResultErrorDetector._ERROR_STATUSES:
+ return True
+ result_type = payload.get("result_type")
+ if isinstance(result_type, str) and result_type.strip().lower() == "error":
+ return True
+ err = payload.get("error")
+ if err is not None and str(err).strip() and str(err).strip().lower() != "none":
+ return True
+ for key in ToolResultErrorDetector._EXIT_KEYS:
+ code = payload.get(key)
+ if isinstance(code, int) and code != 0:
+ return True
+ if check_data:
+ data = payload.get("data")
+ if isinstance(data, dict) and ToolResultErrorDetector._dict_has_error(data, check_data=False):
+ return True
+ return False
+
+ @staticmethod
+ def _boolish_false(value: Any) -> bool:
+ if value is False:
+ return True
+ return isinstance(value, str) and value.strip().lower() in {"false", "0", "no"}
+
+ @staticmethod
+ def _boolish_true(value: Any) -> bool:
+ if value is True:
+ return True
+ return isinstance(value, str) and value.strip().lower() in {"true", "1", "yes"}
+
+
+@dataclass
+class ToolCallRecord:
+ tool_name: str
+ args_hash: str
+ result_hash: str | None
+ timestamp: float
+ has_error: bool = False
+
+
+@dataclass
+class DetectionResult:
+ stuck: bool = False
+ level: str = ""
+ detector: str = ""
+ count: int = 0
+ msg_key: str = ""
+ tool_name: str = ""
+
+
+@dataclass
+class PingPongResult:
+ no_progress_rounds: int = 0
+ paired_tool: str | None = None
+ no_progress: bool = False
+
+
+class CircuitBreakerRail(DeepAgentRail):
+ priority: int = 95
+
+ _SID_KEY = "__jiuwenswarm_cb_session_id__"
+ _STREAM_SID_KEY = "__jiuwenswarm_session_id__"
+
+ def __init__(
+ self,
+ config: CircuitBreakerConfig | None = None,
+ language: str = _DEFAULT_LANGUAGE,
+ ):
+ super().__init__()
+ self._config = config or CircuitBreakerConfig()
+ self._histories: dict[str, list[ToolCallRecord]] = {}
+ self._locks: dict[str, asyncio.Lock] = {}
+ self._language = _normalize_language(language)
+
+ def set_language(self, language: str) -> None:
+ """per-request 更新报错文案语言。"""
+ self._language = _normalize_language(language)
+
+ def cleanup_session(self, session_id: str = "") -> None:
+ """Remove per-session history and lock for *session_id*."""
+ sid = session_id or "default"
+ self._histories.pop(sid, None)
+ self._locks.pop(sid, None)
+
+ def _resolve_sid(self, ctx: AgentCallbackContext) -> str:
+ invoke_sid = _invoke_sid.get()
+ if isinstance(invoke_sid, str) and invoke_sid:
+ return invoke_sid
+
+ sid = ctx.extra.get(self._SID_KEY)
+ if isinstance(sid, str) and sid:
+ return sid
+
+ stream_sid = ctx.extra.get(self._STREAM_SID_KEY)
+ if isinstance(stream_sid, str) and stream_sid:
+ # Only reuse stream sid when it matches the active invoke bucket.
+ if invoke_sid is None or stream_sid == invoke_sid:
+ return stream_sid
+
+ return "default"
+
+ def _get_history(self, sid: str) -> list[ToolCallRecord]:
+ history = self._histories.get(sid)
+ if history is None:
+ history = []
+ self._histories[sid] = history
+ return history
+
+ def _get_lock(self, sid: str) -> asyncio.Lock:
+ lock = self._locks.get(sid)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._locks[sid] = lock
+ return lock
+
+ def _format_message(self, result: DetectionResult) -> str:
+ """按当前语言渲染检测结果文案。"""
+ table = _MESSAGES.get(self._language, _MESSAGES[_DEFAULT_LANGUAGE])
+ template = table.get(result.msg_key) or _MESSAGES[_DEFAULT_LANGUAGE].get(
+ result.msg_key, ""
+ )
+ return template.format(tool_name=result.tool_name, count=result.count)
+
+ # ------------------------------------------------------------------
+ # before_invoke: 每条新消息清空当前 session 历史
+ # before_tool_call: 绑定 invoke 级 sid
+ # after_tool_call: 记录调用 + 检测 + 告警/中断
+ # after_invoke: 清理 subagent / invoke 级状态
+ # ------------------------------------------------------------------
+
+ async def before_invoke(self, ctx: AgentCallbackContext) -> None:
+ if not isinstance(ctx.inputs, InvokeInputs):
+ return
+ raw_conv_id = ctx.inputs.conversation_id or ""
+ sid = raw_conv_id or "default"
+ ctx.extra[self._SID_KEY] = sid
+ _invoke_sid.set(sid)
+ self._histories[sid] = []
+
+ async def after_invoke(self, ctx: AgentCallbackContext) -> None:
+ sid = _invoke_sid.get()
+ if isinstance(sid, str) and sid:
+ self.cleanup_session(sid)
+ _invoke_sid.set(None)
+
+ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
+ sid = self._resolve_sid(ctx)
+ ctx.extra[self._SID_KEY] = sid
+
+ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
+ tool_call = ctx.inputs.tool_call
+ if tool_call is None:
+ return
+
+ tool_name = getattr(tool_call, "name", "")
+ tool_args = getattr(tool_call, "arguments", {})
+ tool_result = ctx.inputs.tool_result
+
+ if not tool_name:
+ return
+
+ sid = self._resolve_sid(ctx)
+ args_hash = self._hash_args(tool_name, tool_args)
+ result_hash = self._hash_outcome(tool_result)
+ has_error = ToolResultErrorDetector.infer_record_has_error(
+ tool_result, ctx,
+ )
+
+ async with self._get_lock(sid):
+ history = self._get_history(sid)
+ history.append(ToolCallRecord(
+ tool_name=tool_name,
+ args_hash=args_hash,
+ result_hash=result_hash,
+ timestamp=time.time(),
+ has_error=has_error,
+ ))
+ if len(history) > self._config.history_size:
+ self._histories[sid] = history[-self._config.history_size:]
+ history = self._histories[sid]
+
+ result = self._detect(history, tool_name, args_hash)
+
+ if result.stuck and result.level == "critical":
+ message = self._format_message(result)
+ logger.error("[CircuitBreaker] %s", message)
+ ctx.request_force_finish({
+ "output": message,
+ "result_type": "answer",
+ })
+ elif result.stuck and result.level == "warning":
+ logger.warning("[CircuitBreaker] %s", self._format_message(result))
+
+ # ------------------------------------------------------------------
+ # _detect: 四种检测器按优先级依次检查
+ # ------------------------------------------------------------------
+
+ def _detect(
+ self,
+ history: list[ToolCallRecord],
+ tool_name: str,
+ args_hash: str,
+ ) -> DetectionResult:
+ cfg = self._config
+
+ no_progress = self._get_no_progress_streak(history, tool_name, args_hash)
+ if no_progress >= cfg.global_breaker_threshold:
+ return DetectionResult(stuck=True, level="critical",
+ detector="global_circuit_breaker", count=no_progress,
+ msg_key="global_circuit_breaker", tool_name=tool_name)
+
+ unknown_streak = self._get_unknown_tool_streak(history, tool_name)
+ if unknown_streak >= cfg.unknown_tool_threshold:
+ return DetectionResult(stuck=True, level="critical",
+ detector="unknown_tool_repeat", count=unknown_streak,
+ msg_key="unknown_tool_repeat", tool_name=tool_name)
+
+ ping_pong = self._get_ping_pong_streak(history, args_hash)
+ if (
+ ping_pong.no_progress
+ and ping_pong.no_progress_rounds >= cfg.critical_threshold
+ ):
+ return DetectionResult(stuck=True, level="critical",
+ detector="ping_pong", count=ping_pong.no_progress_rounds,
+ msg_key="ping_pong_critical", tool_name=tool_name)
+ if (
+ ping_pong.no_progress
+ and ping_pong.no_progress_rounds >= cfg.warning_threshold
+ ):
+ return DetectionResult(stuck=True, level="warning",
+ detector="ping_pong", count=ping_pong.no_progress_rounds,
+ msg_key="ping_pong_warning", tool_name=tool_name)
+
+ recent = self._count_recent_same(history, tool_name, args_hash)
+ if recent >= cfg.warning_threshold:
+ return DetectionResult(stuck=True, level="warning",
+ detector="generic_repeat", count=recent,
+ msg_key="generic_repeat", tool_name=tool_name)
+
+ return DetectionResult(stuck=False)
+
+ @staticmethod
+ def _canonicalize_args_for_hash(tool_name: str, params: Any) -> Any:
+ """Strip tool-specific metadata keys before args hashing."""
+ if not isinstance(params, dict):
+ return params
+ excluded = _METADATA_ONLY_TOP_LEVEL.get(tool_name, frozenset())
+ if not excluded:
+ return params
+ return {key: value for key, value in params.items() if key not in excluded}
+
+ @staticmethod
+ def _hash_args(tool_name: str, params: dict) -> str:
+ canonical = json.dumps(
+ CircuitBreakerRail._canonicalize_args_for_hash(tool_name, params),
+ sort_keys=True,
+ default=str,
+ )
+ return hashlib.sha256(f"{tool_name}:{canonical}".encode()).hexdigest()
+
+ def _hash_outcome(self, result: Any) -> str | None:
+ if result is None:
+ return None
+ normalized = self._normalize_result(result)
+ return hashlib.sha256(
+ json.dumps(normalized, sort_keys=True, default=str).encode()
+ ).hexdigest()
+
+ @staticmethod
+ def _normalize_result(result: Any) -> dict:
+ if isinstance(result, dict):
+ return {
+ "content": str(result.get("content", "")).strip(),
+ "output": str(result.get("output", "")).strip(),
+ "error": str(result.get("error", "")).strip(),
+ "status": str(result.get("status", "")),
+ }
+ return {"raw": str(result)}
+
+ # ------------------------------------------------------------------
+ # 计数方法
+ # ------------------------------------------------------------------
+
+ def _get_no_progress_streak(
+ self,
+ history: list[ToolCallRecord],
+ tool_name: str,
+ args_hash: str,
+ ) -> int:
+ streak = 0
+ latest_hash = None
+ for record in reversed(history):
+ if record.tool_name != tool_name or record.args_hash != args_hash:
+ continue
+ if record.result_hash is None:
+ continue
+ if latest_hash is None:
+ latest_hash = record.result_hash
+ streak = 1
+ elif record.result_hash == latest_hash:
+ streak += 1
+ else:
+ break
+ return streak
+
+ @staticmethod
+ def _get_side_tail_streak(records: list[ToolCallRecord]) -> int:
+ """从该侧最后一次调用向前,统计连续相同 result_hash 次数."""
+ streak = 0
+ latest_hash = None
+ for record in reversed(records):
+ if record.result_hash is None:
+ break
+ if latest_hash is None:
+ latest_hash = record.result_hash
+ streak = 1
+ elif record.result_hash == latest_hash:
+ streak += 1
+ else:
+ break
+ return streak
+
+ @staticmethod
+ def _compute_ping_pong_no_progress_rounds(
+ side_a: list[ToolCallRecord],
+ side_b: list[ToolCallRecord],
+ ) -> int:
+ return min(
+ CircuitBreakerRail._get_side_tail_streak(side_a),
+ CircuitBreakerRail._get_side_tail_streak(side_b),
+ )
+
+ def _collect_alternating_streak(
+ self,
+ history: list[ToolCallRecord],
+ ) -> tuple[list[ToolCallRecord], str | None]:
+ """从末尾向前收集完整交替序列(含 last),时间正序返回."""
+ if len(history) < 2:
+ return [], None
+ last_hash = history[-1].args_hash
+ other_hash = other_name = None
+ for record in reversed(history[:-1]):
+ if record.args_hash != last_hash:
+ other_hash = record.args_hash
+ other_name = record.tool_name
+ break
+ if other_hash is None:
+ return [], None
+
+ streak_rev = [history[-1]]
+ expect = other_hash
+ for record in reversed(history[:-1]):
+ if record.args_hash != expect:
+ break
+ streak_rev.append(record)
+ expect = last_hash if expect == other_hash else other_hash
+ streak_rev.reverse()
+ return streak_rev, other_name
+
+ def _get_ping_pong_streak(
+ self,
+ history: list[ToolCallRecord],
+ _current_args_hash: str,
+ ) -> PingPongResult:
+ streak, paired_tool = self._collect_alternating_streak(history)
+ if len(streak) < 2:
+ return PingPongResult()
+
+ hash_last = streak[-1].args_hash
+ hash_other = next(r.args_hash for r in streak if r.args_hash != hash_last)
+
+ side_last = [r for r in streak if r.args_hash == hash_last]
+ side_other = [r for r in streak if r.args_hash == hash_other]
+
+ no_progress_rounds = self._compute_ping_pong_no_progress_rounds(
+ side_last, side_other,
+ )
+ no_progress = no_progress_rounds >= 2
+
+ return PingPongResult(
+ no_progress_rounds=no_progress_rounds,
+ paired_tool=paired_tool,
+ no_progress=no_progress,
+ )
+
+ def _count_recent_same(
+ self,
+ history: list[ToolCallRecord],
+ tool_name: str,
+ args_hash: str,
+ ) -> int:
+ return sum(
+ 1 for r in history
+ if r.tool_name == tool_name and r.args_hash == args_hash
+ )
+
+ def _get_unknown_tool_streak(
+ self,
+ history: list[ToolCallRecord],
+ tool_name: str,
+ ) -> int:
+ streak = 0
+ for record in reversed(history):
+ if record.tool_name != tool_name:
+ break
+ if not record.has_error:
+ break
+ streak += 1
+ return streak
\ No newline at end of file
diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
index b13fd9d88a..d598aaa026 100644
--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
@@ -100,6 +100,16 @@ class ProgressiveToolRail(DeepAgentRail):
"""
priority = 80
+ # Do NOT inherit this rail into a general-purpose subagent. init() /
+ # before_invoke bind ``_deep_agent`` / ``_runtime_agent`` and refresh the
+ # deferred-tool cache from that agent's ability_manager. Factory injects
+ # parent rails by reference; the child's init then rebinds the shared
+ # instance and overwrites the cache with the child's smaller tool set.
+ # Parent tools_search / invoke_tool for deferred names such as
+ # subagent_wait then miss (「未注册或不在按需可见工具列表中」) while the
+ # child is still running. react.tool_lazy_load.subagents.enabled is
+ # already false — this flag makes factory honor that.
+ inherit_to_subagents = False
def __init__(
self,
diff --git a/jiuwenswarm/agents/harness/common/tools/multi_session_toolkits.py b/jiuwenswarm/agents/harness/common/tools/multi_session_toolkits.py
index 90b6fe1d7d..1b8365178a 100644
--- a/jiuwenswarm/agents/harness/common/tools/multi_session_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/multi_session_toolkits.py
@@ -16,7 +16,7 @@ Agent 可以通过以下工具操控协程
协程管理原则:
1. 协程创建后,任务信息保存在self.sessions中
2. 协程取消后,对应信息需要同步在self.sessions中
-3. 某一协程结束后,会调用notify方法,通过AgentWebSocketServer将消息推送出去
+3. 某一协程结束后,会调用notify方法,通过 Runtime Host ``send_runtime_push`` 推送
"""
from __future__ import annotations
@@ -27,7 +27,7 @@ import logging
import secrets
import time
from enum import Enum
-from typing import Dict, List
+from typing import Any, Dict, List
from openjiuwen.core.runner import Runner
from openjiuwen.core.single_agent import ReActAgent, ReActAgentConfig, AgentCard
@@ -36,6 +36,7 @@ from pydantic import BaseModel
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
from jiuwenswarm.agents.harness.common.tools.mcp_toolkits import get_mcp_tools
+from jiuwenswarm.runtime.host_services import send_runtime_push
logger = logging.getLogger(__name__)
@@ -65,6 +66,7 @@ class MultiSessionToolkit:
sub_agent_config: ReActAgentConfig,
max_concurrent_tasks: int = 10,
task_timeout: float = 300.0,
+ agent_manager: Any = None,
) -> None:
"""Initialize MultiSessionToolkit for a session.
@@ -75,6 +77,8 @@ class MultiSessionToolkit:
sub_agent_config: Configuration for sub-agents.
max_concurrent_tasks: Maximum number of concurrent tasks (default: 10).
task_timeout: Timeout for each task in seconds (default: 300.0).
+ agent_manager: Optional explicit AgentManager. When omitted, notify
+ uses the live AgentServer singleton if one already exists.
"""
self.session_id = session_id
self.channel_id = channel_id
@@ -85,6 +89,7 @@ class MultiSessionToolkit:
self._max_concurrent_tasks = max_concurrent_tasks
self._task_timeout = task_timeout
self._semaphore = asyncio.Semaphore(max_concurrent_tasks)
+ self._agent_manager = agent_manager
logger.info(
"[MultiSessionToolkit] 初始化 parent_session_id=%s channel_id=%s request_id=%s "
"max_concurrent=%d timeout=%.1fs",
@@ -243,9 +248,37 @@ class MultiSessionToolkit:
index + 1,
total,
)
- from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
- server = AgentWebSocketServer.get_instance()
- await server.send_push(msg)
+ await self._push_or_keep_local(msg, session_id=session_id, kind="task notification")
+
+ def _resolve_summary_agent_wrapper(self) -> Any:
+ """Prefer an injected manager; otherwise use the live AgentServer."""
+ manager = self._agent_manager
+ server = None
+ if manager is None:
+ from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+ server = AgentWebSocketServer.current_instance()
+ if server is not None:
+ manager = server.get_agent_manager()
+ wrapper = manager.get_agent_nowait(self.channel_id) if manager is not None else None
+ if wrapper is None and server is not None:
+ wrapper = server.get_agent()
+ return wrapper
+
+ async def _push_or_keep_local(
+ self,
+ msg: dict[str, Any],
+ *,
+ session_id: str,
+ kind: str,
+ ) -> None:
+ if await send_runtime_push(msg):
+ return
+ logger.info(
+ "[MultiSessionToolkit] Runtime push host unavailable; "
+ "%s kept local session_id=%s",
+ kind,
+ session_id,
+ )
async def notify(
self,
@@ -254,23 +287,18 @@ class MultiSessionToolkit:
result: str = "",
error: str = "",
) -> None:
- """Send subtask update via AgentWebSocketServer. Called on completion (success/cancel/error/timeout)."""
+ """Send a subtask update through the active Runtime host."""
# 发送单个任务的状态更新
await self._send_task_notification(session_id, status, result, error)
# 检查是否所有任务都已完成,如果是则发送最终汇总
if self.all_tasks_done():
- from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
- server = AgentWebSocketServer.get_instance()
-
session_result_summary = "后台会话任务均已完成:\n"
for st in self.sessions:
session_result_summary += (f"\nsession_id: {st.session_id}\n"
f"description: {st.description}\nresult: {st.result}\n")
- agent_wrapper = server.get_agent_manager().get_agent_nowait(self.channel_id)
- if agent_wrapper is None:
- agent_wrapper = server.get_agent()
+ agent_wrapper = self._resolve_summary_agent_wrapper()
agent_instance = (
await agent_wrapper.ensure_instance() if agent_wrapper is not None else None
)
@@ -337,7 +365,9 @@ class MultiSessionToolkit:
"payload": payload,
"is_complete": True,
}
- await server.send_push(msg)
+ await self._push_or_keep_local(
+ msg, session_id=self.session_id, kind="final summary"
+ )
async def create_new_sessions(self, task_descriptions: List[str]) -> str:
"""Create sub-agent sessions for each task description."""
diff --git a/jiuwenswarm/agents/harness/common/tools/subagent_compat.py b/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
new file mode 100644
index 0000000000..2ca5ac1b47
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
@@ -0,0 +1,54 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Compatibility fixes for the OpenJiuWen persistent subagent runtime."""
+
+from __future__ import annotations
+
+from dataclasses import replace
+
+from openjiuwen.harness.subagent_runtime.control import ( # type: ignore[import-untyped]
+ SubagentControl,
+)
+from openjiuwen.harness.subagent_runtime.models import ( # type: ignore[import-untyped]
+ ResumeResult,
+ SubagentStatus,
+ SubagentStatusKind,
+)
+from openjiuwen.harness.tools.subagent import _control_registry # type: ignore[import-untyped]
+
+
+class CompatibleSubagentControl(SubagentControl):
+ """Report a restored subagent as idle until its next turn is submitted."""
+
+ async def resume(self, subagent_id: str) -> ResumeResult:
+ result = await super().resume(subagent_id)
+ if (
+ not result.restored
+ or result.status.kind is not SubagentStatusKind.PENDING_INIT
+ ):
+ return result
+
+ instance = self._manager.find(subagent_id) # pylint: disable=protected-access
+ if instance is None:
+ return result
+
+ current = instance.agent_status()
+ if current.kind is not SubagentStatusKind.PENDING_INIT:
+ return replace(result, status=current)
+
+ # OpenJiuWen represents a live, input-ready instance with a terminal
+ # turn status; COMPLETED is mapped to the public ``idle`` state.
+ idle = SubagentStatus.completed()
+ await instance.status.set(idle)
+ return replace(result, status=idle)
+
+
+def install_subagent_control_compat_patch() -> None:
+ """Use the compatible control for newly created parent-session runtimes."""
+ _control_registry.SubagentControl = CompatibleSubagentControl
+
+
+__all__ = [
+ "CompatibleSubagentControl",
+ "install_subagent_control_compat_patch",
+]
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.py
index 8d2e7ef6d2..1d29d68d6f 100644
--- a/jiuwenswarm/agents/swarm/config_specs.py
+++ b/jiuwenswarm/agents/swarm/config_specs.py
@@ -55,6 +55,9 @@ from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (
)
from jiuwenswarm.agents.swarm import registry
from jiuwenswarm.agents.swarm.providers import tools as _tools
+from jiuwenswarm.agents.harness.common.browser_defaults import (
+ DEFAULT_BROWSER_AGENT_MAX_ITERATIONS,
+)
# Modes that route to the code adapter and get the code member profile.
_CODE_MODES: frozenset[str] = frozenset({"code.team", "team.plan"})
@@ -679,6 +682,22 @@ def _is_subagent_enabled(sub_cfg: Any) -> bool:
return isinstance(sub_cfg, dict) and bool(sub_cfg.get("enabled", False))
+def _is_subagent_default_enabled(sub_cfg: Any) -> bool:
+ """Return True unless the entry is an explicit ``enabled: false``."""
+ if not isinstance(sub_cfg, dict):
+ return True
+ return sub_cfg.get("enabled", True) is not False
+
+
+def _subagent_default_max_iterations(name: str, react_cfg: dict[str, Any]) -> int:
+ """Resolve the default iteration budget for a named swarm sub-agent."""
+ if name == "browser_agent":
+ return DEFAULT_BROWSER_AGENT_MAX_ITERATIONS
+ if name == "statusline-setup":
+ return registry.DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS
+ return react_cfg.get("max_iterations", _DEFAULT_SUBAGENT_MAX_ITERATIONS)
+
+
def _subagent_language(mode: str, role: str, config: dict[str, Any]) -> str:
"""Resolve the code sub-agent runtime language (mirrors ``code_runtime_language``).
@@ -707,11 +726,14 @@ def _code_subagent_spec(
react_cfg.get("subagents", {}) if isinstance(react_cfg, dict) else {}
)
sub_cfg = subagents_cfg.get(name) if isinstance(subagents_cfg, dict) else None
- max_iterations = react_cfg.get("max_iterations", _DEFAULT_SUBAGENT_MAX_ITERATIONS)
+ max_iterations = _subagent_default_max_iterations(name, react_cfg)
if isinstance(sub_cfg, dict) and sub_cfg.get("max_iterations"):
max_iterations = sub_cfg["max_iterations"]
+ card_kwargs: dict[str, Any] = {"name": name}
+ if name == "statusline-setup":
+ card_kwargs["id"] = "jiuwenswarm.statusline-setup"
return SubAgentSpec(
- agent_card=AgentCard(name=name),
+ agent_card=AgentCard(**card_kwargs),
system_prompt="",
factory_name=factory_name,
factory_kwargs={
@@ -726,9 +748,10 @@ def build_member_subagent_specs(
mode: str,
role: str,
) -> list[SubAgentSpec]:
- """Build the declarative code sub-agent specs (empty for non-code modes).
+ """Build the declarative sub-agent specs for a swarm member.
- explore / plan are always present, while code / browser are config-gated via
+ Status-line setup is default-on for every mode. Code modes additionally
+ include explore / plan. code / browser are config-gated via
``react.subagents.<name>.enabled``.
Args:
@@ -737,19 +760,36 @@ def build_member_subagent_specs(
role: The member role (reserved, both roles get the same sub-agents).
Returns:
- The ``SubAgentSpec`` list (empty when not a code mode).
+ The ``SubAgentSpec`` list.
"""
- if not _is_code_mode(mode):
- return []
react = (config or {}).get("react", {})
react = react if isinstance(react, dict) else {}
subagents_cfg = react.get("subagents", {}) if isinstance(react, dict) else {}
language = _subagent_language(mode, role, config)
- specs: list[SubAgentSpec] = [
- _code_subagent_spec("explore_agent", registry.EXPLORE_AGENT, react, language),
- _code_subagent_spec("plan_agent", registry.PLAN_AGENT, react, language),
- ]
+ specs: list[SubAgentSpec] = []
+ statusline_cfg = (
+ subagents_cfg.get("statusline-setup")
+ if isinstance(subagents_cfg, dict)
+ else None
+ )
+ if _is_subagent_default_enabled(statusline_cfg):
+ specs.append(
+ _code_subagent_spec(
+ "statusline-setup",
+ registry.STATUSLINE_SETUP_AGENT,
+ react,
+ language,
+ )
+ )
+ if not _is_code_mode(mode):
+ return specs
+ specs.extend(
+ [
+ _code_subagent_spec("explore_agent", registry.EXPLORE_AGENT, react, language),
+ _code_subagent_spec("plan_agent", registry.PLAN_AGENT, react, language),
+ ]
+ )
if isinstance(subagents_cfg, dict):
if _is_subagent_enabled(subagents_cfg.get("code_agent")):
specs.append(
diff --git a/jiuwenswarm/agents/swarm/providers/code_subagents.py b/jiuwenswarm/agents/swarm/providers/code_subagents.py
index 11ea2f2738..072e91159b 100644
--- a/jiuwenswarm/agents/swarm/providers/code_subagents.py
+++ b/jiuwenswarm/agents/swarm/providers/code_subagents.py
@@ -40,16 +40,24 @@ from openjiuwen.agent_teams.harness.manifest import (
from openjiuwen.harness.subagents.browser_agent import build_browser_agent_config
from openjiuwen.harness.subagents.code_agent import build_code_agent_config
+from jiuwenswarm.agents.harness.common.browser_defaults import (
+ DEFAULT_BROWSER_AGENT_MAX_ITERATIONS,
+)
from jiuwenswarm.agents.swarm.context import SwarmBuildContext
from jiuwenswarm.agents.swarm.providers.code_rails import (
code_runtime_language,
CODING_MEMORY_EXTRAS_KEY,
)
+from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (
+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ build_statusline_setup_agent_config,
+)
logger = logging.getLogger(__name__)
CODE_AGENT = "swarm.code_agent"
SWARM_BROWSER_AGENT = "swarm.browser_agent"
+STATUSLINE_SETUP_AGENT = "swarm.statusline_setup_agent"
# Key under ``ctx.extras`` where ``DeepAgentSpec.build`` publishes the resolved
# parent member model for sub-agent providers to reuse.
@@ -118,11 +126,53 @@ def build_code_agent(factory_kwargs: dict[str, Any], ctx: SwarmBuildContext) ->
return spec
+def _parent_sys_operation(ctx: SwarmBuildContext) -> Any:
+ """Read the parent SysOperation from build-context extras when present.
+
+ Dest SDK does not yet export ``parent_sys_operation``; extras is the
+ documented BuildContext extension point for live handles.
+ """
+ extras = getattr(ctx, "extras", None)
+ if isinstance(extras, dict):
+ sys_operation = extras.get("sys_operation")
+ if sys_operation is None:
+ sys_operation = extras.get("_parent_sys_operation")
+ if sys_operation is not None:
+ return sys_operation
+ return getattr(ctx, "sys_operation", None)
+
+
+@harness_element(
+ kind=ElementKind.SUBAGENT,
+ name=STATUSLINE_SETUP_AGENT,
+ description="Built-in JiuwenSwarm TUI status-line setup subagent.",
+ input_model=CodeAgentInput,
+)
+def build_statusline_setup_agent(
+ factory_kwargs: dict[str, Any],
+ ctx: SwarmBuildContext,
+) -> Any:
+ """Build the status-line setup subagent for a team member."""
+
+ inp = CodeAgentInput.resolve(factory_kwargs, ctx)
+ model = ctx.extras.get(_PARENT_MODEL_EXTRAS_KEY)
+ if model is None:
+ logger.warning("[swarm.statusline_setup_agent] skipped: no parent model")
+ return None
+ return build_statusline_setup_agent_config(
+ model,
+ workspace=str(inp.workspace_root or "./"),
+ sys_operation=_parent_sys_operation(ctx),
+ language=inp.language,
+ max_iterations=inp.max_iterations,
+ )
+
+
class BrowserAgentInput(ConstructionInput):
"""Construction inputs for the swarm browser sub-agent."""
max_iterations: int = param_field(
- default=_DEFAULT_MAX_ITERATIONS,
+ default=DEFAULT_BROWSER_AGENT_MAX_ITERATIONS,
description="Maximum task-loop iterations for the sub-agent.",
)
workspace_root: str | None = context_field(
@@ -206,5 +256,7 @@ def build_swarm_browser_agent(factory_kwargs: dict[str, Any], ctx: SwarmBuildCon
__all__ = [
"CODE_AGENT",
+ "DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS",
+ "STATUSLINE_SETUP_AGENT",
"SWARM_BROWSER_AGENT",
]
diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.py
index 28602d5d96..2e3dbd3531 100644
--- a/jiuwenswarm/agents/swarm/registry.py
+++ b/jiuwenswarm/agents/swarm/registry.py
@@ -115,6 +115,10 @@ PLAN_AGENT = _OJ_PLAN_AGENT
BROWSER_AGENT = _OJ_BROWSER_AGENT
CODE_AGENT = _code_subagents.CODE_AGENT
SWARM_BROWSER_AGENT = _code_subagents.SWARM_BROWSER_AGENT
+DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS = (
+ _code_subagents.DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS
+)
+STATUSLINE_SETUP_AGENT = _code_subagents.STATUSLINE_SETUP_AGENT
# Swarm-owned no-parameter class rails declared in ``builtin_rails``.
RESPONSE_PROMPT = _builtin_rails.RESPONSE_PROMPT
@@ -231,5 +235,7 @@ __all__ = [
"PLAN_AGENT",
"CODE_AGENT",
"SWARM_BROWSER_AGENT",
+ "DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS",
+ "STATUSLINE_SETUP_AGENT",
"BROWSER_AGENT",
]
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index a2a2b16d02..5119a8d85f 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -561,6 +561,18 @@ def get_ttse_enabled(config: dict[str, Any] | None) -> bool:
return coerce_config_bool(_get_ttse_config(config).get("enabled"), False)
+def is_subagent_runtime_enabled(config: dict[str, Any] | None = None) -> bool:
+ """Return ``react.subagent_runtime.enabled`` for persistent subagent tools.
+
+ Missing or non-dict ``react.subagent_runtime`` is False. The shipped
+ template defaults to true; partial overrides without this key stay off.
+ """
+ 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
+ return bool(runtime_cfg.get("enabled")) if isinstance(runtime_cfg, dict) else False
+
+
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/common/openjiuwen_rail_compat.py b/jiuwenswarm/common/openjiuwen_rail_compat.py
index 7f24119a14..6d2e13ee5d 100644
--- a/jiuwenswarm/common/openjiuwen_rail_compat.py
+++ b/jiuwenswarm/common/openjiuwen_rail_compat.py
@@ -1,6 +1,6 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Drop newer evolution-rail kwargs when the installed openjiuwen SDK is older."""
+"""Drop newer SDK kwargs when the installed openjiuwen package is older."""
from __future__ import annotations
@@ -28,6 +28,17 @@ def filter_unsupported_kwargs(func: Callable[..., Any], kwargs: dict[str, Any])
return {key: value for key, value in kwargs.items() if key in allowed}
+async def call_attach_output(instance: Any, *, steal: bool = False) -> Any:
+ """Call ``attach_output``, dropping ``steal`` on dest-stable SDK builds.
+
+ Official dest-stable ``DeepAgent.attach_output`` has no ``steal`` keyword;
+ dest-stable jiuwenswarm still requests it for replica chat.send takeover.
+ """
+ attach = instance.attach_output
+ kwargs = filter_unsupported_kwargs(attach, {"steal": True} if steal else {})
+ return await attach(**kwargs)
+
+
def _wrap_init_for_extra_kwargs(cls: type) -> None:
"""Allow newer trajectory/signal kwargs against older rail constructors."""
original = cls.__init__
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index c33901cc92..bcf4a6e975 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -336,6 +336,7 @@ class EventType(Enum):
CHAT_EVOLUTION_GENERATED = "chat.evolution_generated"
CHAT_EVOLUTION_PUBLISHED = "chat.evolution_published"
CHAT_SUBTASK_UPDATE = "chat.subtask_update"
+ CHAT_SUBAGENT_ACTIVITY = "chat.subagent_activity"
CHAT_ASK_USER_QUESTION = "chat.ask_user_question"
PLAN_APPROVAL_REQUIRED = "plan.approval_required"
CHAT_SESSION_RESULT = "chat.session_result"
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py
index 5ad3067803..48f1c578ae 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py
@@ -89,6 +89,7 @@ _WEB_FULL_PAYLOAD_EVENT_TYPES = frozenset(
"chat.ask_user_question",
"chat.ask_user_question_expired",
"chat.subtask_update",
+ "chat.subagent_activity",
"chat.symphony_status",
"chat.notice",
"history.message",
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 794922a73a..6dc63de6f0 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -572,6 +572,10 @@ react:
task_planning:
enable_progress_repeat: ${TODO_PROGRESS_REPEAT:-true}
list_tool_call_interval: 20
+ # 常驻 subagent 运行时。开启后 task_tool 由 subagent_spawn/wait/list/
+ # send_input/close/resume 六个工具替换(两者互斥)。默认开启。
+ subagent_runtime:
+ enabled: true
# ProgressiveToolRail: 工具延迟加载,固定 eager_tools schema,deferred 工具通过
# tools_search → invoke_tool 间接调用,最大化 prefix cache 命中率。
tool_lazy_load:
@@ -624,6 +628,9 @@ react:
enabled: false
# max_iterations: 15
browser_agent:
+ enabled: true
+ # max_iterations: 100
+ statusline-setup:
enabled: true
# max_iterations: 15
# ============ SkillTurbo 配置 ============
@@ -918,6 +925,15 @@ execution_guard:
repeat_window_chars: 1024
# 单字符连续重复阈值,用于检测分隔线等场景,默认较高以减少误判
single_char_repeat_count: 90
+ # develop 防死循环 rail:重复调用 / ping-pong / 未知工具打断(force-finish)。
+ # 默认关闭,避免和 dest-stable 已开启的 agent_ras.repeat_tool 双挂。
+ # 不是 issue 的 OPEN/HALF_OPEN 恢复型熔断。
+ circuit_breaker:
+ enabled: false
+ warning_threshold: 10
+ critical_threshold: 20
+ global_breaker_threshold: 30
+ unknown_tool_threshold: 10
# Agent RAS 整体配置
agent_ras:
diff --git a/jiuwenswarm/runtime/__init__.py b/jiuwenswarm/runtime/__init__.py
new file mode 100644
index 0000000000..e13555adfa
--- /dev/null
+++ b/jiuwenswarm/runtime/__init__.py
@@ -0,0 +1,23 @@
+"""Minimal public surface for optional Runtime host capabilities.
+
+This package is not the Session Runtime in ``jiuwenswarm.server.runtime``.
+Commit 3 only exposes the push install/restore/send API used by AgentServer
+and MultiSessionToolkit. Wake/Xiaoyi providers and AgentRuntime are not
+exported here.
+"""
+
+from jiuwenswarm.runtime.host_services import (
+ RuntimeHostPushTransport,
+ RuntimePushHandler,
+ install_runtime_push_handler,
+ restore_runtime_push_handler,
+ send_runtime_push,
+)
+
+__all__ = [
+ "RuntimeHostPushTransport",
+ "RuntimePushHandler",
+ "install_runtime_push_handler",
+ "restore_runtime_push_handler",
+ "send_runtime_push",
+]
diff --git a/jiuwenswarm/runtime/host_services.py b/jiuwenswarm/runtime/host_services.py
new file mode 100644
index 0000000000..ae35e9c7cf
--- /dev/null
+++ b/jiuwenswarm/runtime/host_services.py
@@ -0,0 +1,100 @@
+"""Optional host capabilities injected into the transport-neutral Runtime.
+
+The process CLI leaves these capabilities unset. AgentServer may install a
+push handler for its service lifetime without making Runtime import or
+discover a Server/Gateway singleton.
+"""
+
+from __future__ import annotations
+
+import inspect
+import threading
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+RuntimePushHandler = Callable[
+ [dict[str, Any]],
+ Awaitable[bool | None] | bool | None,
+]
+
+_runtime_push_handler: RuntimePushHandler | None = None
+_runtime_push_handlers: list[RuntimePushHandler] = []
+_runtime_host_handlers_lock = threading.RLock()
+
+
+def _remove_handler_owner(handlers: list[Any], handler: Any) -> None:
+ """Remove one installed owner without reviving an already removed owner."""
+ for index in range(len(handlers) - 1, -1, -1):
+ candidate = handlers[index]
+ if candidate is handler:
+ handlers.pop(index)
+ return
+ # Bound methods compare equal across repeated attribute access. Retain the
+ # old equality compatibility when the exact callable object is unavailable.
+ for index in range(len(handlers) - 1, -1, -1):
+ try:
+ matches = handlers[index] == handler
+ except Exception:
+ matches = False
+ if matches:
+ handlers.pop(index)
+ return
+
+
+def install_runtime_push_handler(
+ handler: RuntimePushHandler,
+) -> RuntimePushHandler | None:
+ """Install a host-owned push handler and return the previous handler."""
+ global _runtime_push_handler
+
+ with _runtime_host_handlers_lock:
+ previous = _runtime_push_handler
+ if not _runtime_push_handlers and previous is not None:
+ _runtime_push_handlers.append(previous)
+ _runtime_push_handlers.append(handler)
+ _runtime_push_handler = handler
+ return previous
+
+
+def restore_runtime_push_handler(
+ handler: RuntimePushHandler,
+ previous: RuntimePushHandler | None,
+) -> None:
+ """Remove one push owner and activate the newest remaining owner."""
+ global _runtime_push_handler
+
+ _ = previous # retained for source/API compatibility
+ with _runtime_host_handlers_lock:
+ _remove_handler_owner(_runtime_push_handlers, handler)
+ _runtime_push_handler = (
+ _runtime_push_handlers[-1] if _runtime_push_handlers else None
+ )
+
+
+async def send_runtime_push(message: dict[str, Any]) -> bool:
+ """Send through the optional host adapter; return False when unavailable."""
+ with _runtime_host_handlers_lock:
+ handler = _runtime_push_handler
+ if handler is None:
+ return False
+ result = handler(message)
+ if inspect.isawaitable(result):
+ result = await result
+ return result if isinstance(result, bool) else True
+
+
+class RuntimeHostPushTransport:
+ """Structural push transport backed only by an explicitly installed host."""
+
+ async def send_push(self, message: dict[str, Any]) -> None:
+ if not await send_runtime_push(message):
+ raise RuntimeError("runtime push is unavailable without a resident host")
+
+
+__all__ = [
+ "RuntimePushHandler",
+ "RuntimeHostPushTransport",
+ "install_runtime_push_handler",
+ "restore_runtime_push_handler",
+ "send_runtime_push",
+]
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 0d07d765db..ebe8f3e94e 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -149,6 +149,10 @@ from jiuwenswarm.common.config import (
)
from jiuwenswarm.server.sandbox_config_rpc import get_sandbox_config_req_methods
from jiuwenswarm.server.sandbox.jiuwenbox_runner import JiuwenBoxRunner
+from jiuwenswarm.runtime.host_services import (
+ install_runtime_push_handler,
+ restore_runtime_push_handler,
+)
from jiuwenswarm.common.security.ws_origin import (
extract_handshake_request,
forbidden_origin_response,
@@ -374,6 +378,8 @@ class AgentWebSocketServer:
self._personal_context_start_task: asyncio.Task[None] | None = None
# Proactive recommendation engine (set by app_agentserver for debug trigger)
self._proactive_engine: Any = None
+ self._runtime_push_handler = None
+ self._previous_runtime_push_handler = None
get_acp_output_manager().set_send_push_callback(
lambda msg: asyncio.create_task(self.send_push(msg))
)
@@ -444,6 +450,11 @@ class AgentWebSocketServer:
"""重置单例(仅用于测试)。"""
cls._instance = None
+ @classmethod
+ def current_instance(cls) -> AgentWebSocketServer | None:
+ """Return the live singleton without creating a new AgentServer."""
+ return cls._instance
+
@property
def host(self) -> str:
return self._host
@@ -548,6 +559,25 @@ class AgentWebSocketServer:
# 启动 (用户依然可以在 TUI 里跑 /sandbox enable 重试)。
await self._bootstrap_internal_jiuwenbox()
await self._start_loop_lag_monitor()
+ self._install_runtime_push_host()
+
+ def _install_runtime_push_host(self) -> None:
+ """Register send_push as the optional Runtime host for this lifetime."""
+ if self._runtime_push_handler is not None:
+ return
+ self._runtime_push_handler = self.send_push
+ self._previous_runtime_push_handler = install_runtime_push_handler(
+ self._runtime_push_handler
+ )
+
+ def _restore_runtime_push_host(self) -> None:
+ """Drop this server's push ownership without reviving a removed owner."""
+ handler = self._runtime_push_handler
+ if handler is None:
+ return
+ restore_runtime_push_handler(handler, self._previous_runtime_push_handler)
+ self._runtime_push_handler = None
+ self._previous_runtime_push_handler = None
async def _start_loop_lag_monitor(self) -> None:
"""启动事件循环 lag 观测 task 与停摆探针(验收用,不主动断连/不发应用心跳)。"""
@@ -1054,6 +1084,8 @@ class AgentWebSocketServer:
await cancel_pending_tasks()
+ self._restore_runtime_push_host()
+
if not had_server:
return
try:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
index e3563a065d..2889031f06 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
@@ -20,7 +20,6 @@ from openjiuwen.harness.rails.base import DeepAgentRail
from openjiuwen.harness.tools.base_tool import ToolOutput
from openjiuwen.harness.workspace.workspace import Workspace
-from jiuwenswarm.common.utils import DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL
from jiuwenswarm.server.runtime.debug_trace import invoke_subagent_with_trace
if TYPE_CHECKING:
@@ -244,7 +243,12 @@ class AgentTool(Tool):
"workspace": workspace,
"skills": spec.skills,
"backend": spec.backend if spec.backend is not None else parent_config.backend,
- "sys_operation": None, # 子 agent 不继承 sys_operation
+ # 子 agent 必须复用父 agent 的 SysOperation:它才是用户配置的文件系统边界
+ # (本地全量访问 / jiuwenbox 沙箱 / allow-deny 路径)。传 None 会让
+ # create_deep_agent 另建一套 LOCAL SysOperation,并在 restrict_to_work_dir
+ # 打开 restrict_to_sandbox——本地模式下子 agent 反而被锁进 workspace,沙箱
+ # 模式下子 agent 又逃出沙箱直接落到宿主机。
+ "sys_operation": getattr(parent_config, "sys_operation", None),
"language": spec.language if spec.language is not None else parent_config.language,
"prompt_mode": spec.prompt_mode if spec.prompt_mode is not None else parent_config.prompt_mode,
"subagents": None,
@@ -254,8 +258,14 @@ class AgentTool(Tool):
}
factory_kwargs = dict(spec.factory_kwargs or {})
- # read_file 默认不读取图片:关闭多模态内联(agent 定义显式开启时遵从)。
- factory_kwargs.setdefault("enable_read_image_multimodal", DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL)
+ # CodeAgentRail creates custom subagents directly instead of using
+ # DeepAgent.create_subagent(). Preserve the parent's explicit image
+ # policy by default, while allowing a custom Agent with another model
+ # to declare its own value through factory_kwargs.
+ factory_kwargs.setdefault(
+ "enable_read_image_multimodal",
+ getattr(parent_config, "enable_read_image_multimodal", None),
+ )
sub_agent = create_deep_agent(**create_kwargs, **factory_kwargs)
logger.info("[AgentTool] Created sub-agent for '%s' via create_deep_agent()", agent_def.name)
@@ -379,6 +389,41 @@ class CodeAgentRail(DeepAgentRail):
self._unregister_agent_tool(agent)
self._agent = None
+ def set_workspace_dir(self, workspace_dir: str) -> None:
+ """Rebind custom-agent discovery to the current Code workspace.
+
+ ``AgentTool._create_sub_agent`` reads ``parent.deep_config.workspace``,
+ not this rail's directory. A live hot-switch that only updates
+ ``_workspace_dir`` would load the new agent files and then still spawn
+ children under the old root. Keep the parent workspace in lockstep.
+ """
+ normalized = str(workspace_dir or "").strip()
+ if not normalized or normalized == self._workspace_dir:
+ return
+ parent_config = getattr(self._agent, "deep_config", None) if self._agent is not None else None
+ if parent_config is not None:
+ old_workspace = getattr(parent_config, "workspace", None)
+ language = (
+ getattr(old_workspace, "language", None)
+ or getattr(parent_config, "language", None)
+ or "en"
+ )
+ try:
+ parent_config.workspace = Workspace(
+ root_path=normalized,
+ language=language,
+ )
+ except Exception as exc:
+ logger.error(
+ "[CodeAgentRail] rebind workspace failed, keeping previous dir: %s",
+ exc,
+ )
+ return
+ self._workspace_dir = normalized
+ if self._agent is not None:
+ self._unregister_agent_tool(self._agent)
+ self._register_agent_tool()
+
def _register_agent_tool(self) -> None:
custom_agents = self._load_custom_agents()
if not custom_agents:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 0ecd306c24..dd37bab0b0 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -4219,8 +4219,19 @@ class JiuWenSwarm:
async def cleanup_session_runtime(self, session_id: str) -> bool:
"""Release in-memory runtime owned by one session while keeping persisted history."""
- processor_cleaned = await self._session_manager.close_session(session_id)
adapter = self._adapter
+ if adapter is not None:
+ release_fn = getattr(adapter, "release_subagent_runtime_for_session", None)
+ if callable(release_fn):
+ try:
+ await release_fn(session_id, reason="session_deleted")
+ except Exception:
+ logger.warning(
+ "[JiuWenSwarm] release_subagent_runtime failed: session_id=%s",
+ session_id,
+ exc_info=True,
+ )
+ processor_cleaned = await self._session_manager.close_session(session_id)
if adapter is None:
return processor_cleaned
cleanup_fn = getattr(adapter, "cleanup_session_adapter", None)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 9df2c8c1be..f03e536928 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -41,6 +41,14 @@ from openjiuwen.harness.subagents.code_agent import build_code_agent_config
from openjiuwen.harness.subagents.explore_agent import build_explore_agent_config
from openjiuwen.harness.subagents.plan_agent import build_plan_agent_config
from openjiuwen.harness.tools.worktree import WorktreeConfig, WorktreeRail
+from jiuwenswarm.agents.harness.common.browser_defaults import (
+ DEFAULT_BROWSER_AGENT_MAX_ITERATIONS,
+)
+from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (
+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ STATUSLINE_SETUP_AGENT_TYPE,
+ build_statusline_setup_agent_config,
+)
from jiuwenswarm.edition import is_enterprise
from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
@@ -50,6 +58,7 @@ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
_RailBuildInfo,
_agent_def_to_subagent_config,
_deep_agent_kv_cache_affinity_config,
+ _optional_enable_subagent_runtime,
_resolve_instance_config_base,
parse_int,
)
@@ -547,6 +556,9 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
kv_cache_affinity_config=_deep_agent_kv_cache_affinity_config(config, model),
auto_create_workspace=is_enterprise(),
completion_timeout=config.get("completion_timeout", 3600.0),
+ **_optional_enable_subagent_runtime(
+ self._resolve_enable_subagent_runtime(config_base),
+ ),
)
# Keep ensure_initialized on the main event loop (same as interface_deep).
@@ -1001,25 +1013,52 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
config: dict[str, Any],
config_base: dict[str, Any] | None = None,
) -> tuple[list[Any] | None, bool]:
- """Build subagents for code mode: explore_agent + plan_agent + code_agent + browser_agent.
+ """Build subagents for code mode, including the built-in status-line setup agent.
explore_agent / plan_agent 固定挂载(Code 模式核心子代理)。
code_agent / browser_agent 按配置启用。
+
+ 每个 spec 都带上父 Agent 的 ``sys_operation``,子 Agent 才能和父 Agent 落在
+ 同一套文件系统边界上。
"""
react_cfg = config if isinstance(config, dict) else {}
subagents_cfg = react_cfg.get("subagents")
resolved_language = self._resolve_runtime_language()
workspace = self._workspace_dir or "./"
+ sys_operation = self._sys_operation
subagents: list[Any] = []
self._sync_browser_runtime_environment(config_base)
+ statusline_setup_cfg = (
+ subagents_cfg.get(STATUSLINE_SETUP_AGENT_TYPE)
+ if isinstance(subagents_cfg, dict)
+ else None
+ )
+ if self._is_subagent_default_enabled(statusline_setup_cfg):
+ statusline_setup_options = (
+ statusline_setup_cfg if isinstance(statusline_setup_cfg, dict) else {}
+ )
+ subagents.append(
+ build_statusline_setup_agent_config(
+ model,
+ workspace=workspace,
+ sys_operation=sys_operation,
+ language=resolved_language,
+ max_iterations=parse_int(
+ statusline_setup_options.get("max_iterations"),
+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ ),
+ )
+ )
+
# ── 固定挂载:explore_agent(Code 模式核心子代理,始终启用)──
if not self._subagent_list_has_name(subagents, "explore_agent"):
explore_agent_cfg = subagents_cfg.get("explore_agent") if isinstance(subagents_cfg, dict) else None
explore_spec = build_explore_agent_config(
model=model,
workspace=workspace,
+ sys_operation=sys_operation,
language=resolved_language,
max_iterations=parse_int(
explore_agent_cfg.get("max_iterations") if isinstance(explore_agent_cfg, dict) else None,
@@ -1035,6 +1074,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
plan_spec = build_plan_agent_config(
model=model,
workspace=workspace,
+ sys_operation=sys_operation,
language=resolved_language,
max_iterations=parse_int(
plan_agent_cfg.get("max_iterations") if isinstance(plan_agent_cfg, dict) else None,
@@ -1058,6 +1098,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
code_spec = build_code_agent_config(
model,
workspace=workspace,
+ sys_operation=sys_operation,
language=resolved_language,
rails=code_agent_rails,
max_iterations=parse_int(
@@ -1079,14 +1120,18 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
"[JiuwenSwarmCodeAdapter] browser subagent enabled without BROWSER_DRIVER; "
"defaulting to managed mode"
)
+ browser_max_iterations = None
+ if isinstance(browser_agent_cfg, dict):
+ browser_max_iterations = browser_agent_cfg.get("max_iterations")
browser_spec = build_browser_agent_config(
model,
workspace=workspace,
+ sys_operation=sys_operation,
language=resolved_language,
max_iterations=parse_int(
- browser_agent_cfg.get("max_iterations") if isinstance(browser_agent_cfg, dict) else None,
- react_cfg.get("max_iterations", 15),
- )
+ browser_max_iterations,
+ DEFAULT_BROWSER_AGENT_MAX_ITERATIONS,
+ ),
)
browser_spec.factory_kwargs = {"auto_create_workspace": False}
subagents.append(browser_spec)
@@ -1322,6 +1367,10 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
runtime_config.trusted_dirs,
)
+ code_agent_rail = getattr(self, "_code_agent_rail", None)
+ if code_agent_rail is not None:
+ code_agent_rail.set_workspace_dir(project_workspace)
+
# code 模式始终走 _update_rails_for_mode 的 code 逻辑
await self._update_rails_for_mode(runtime_config.mode)
await self._set_user_interaction_enabled(runtime_config.supports_user_interaction)
@@ -1597,8 +1646,14 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
deep_config = getattr(agent, "deep_config", None)
if deep_config is not None and getattr(deep_config, "model", None) is None:
deep_config.model = model
- if deep_config is not None and getattr(deep_config, "sys_operation", None) is None:
- deep_config.sys_operation = self._create_sys_operation()
+ inherited_sys_operation = (
+ getattr(deep_config, "sys_operation", None) if deep_config is not None else None
+ )
+ if inherited_sys_operation is None:
+ inherited_sys_operation = self._create_sys_operation()
+ if deep_config is not None:
+ deep_config.sys_operation = inherited_sys_operation
+ self._sys_operation = inherited_sys_operation
tool_cards = self.build_code_tool_cards(agent_id)
added_tools = _merge_tool_cards(agent, tool_cards)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 9e5be22769..63d1eebc76 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -119,6 +119,14 @@ from openjiuwen.harness.schema.interaction import (
)
from openjiuwen.harness.schema.task import TodoStatus
from openjiuwen.harness.workspace.workspace import Workspace, WorkspaceNode
+from jiuwenswarm.agents.harness.common.browser_defaults import (
+ DEFAULT_BROWSER_AGENT_MAX_ITERATIONS,
+)
+from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (
+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ STATUSLINE_SETUP_AGENT_TYPE,
+ build_statusline_setup_agent_config,
+)
from jiuwenswarm.agents.harness.common.tools.deepresearch import (
get_deepresearch_tools,
@@ -277,9 +285,17 @@ from jiuwenswarm.agents.harness.common.tools.todo_compat import (
CompatibleTodoModifyTool,
install_todo_modify_compat_patch,
)
-from jiuwenswarm.common.openjiuwen_rail_compat import install_evolution_rail_kwargs_compat
+from jiuwenswarm.common.openjiuwen_rail_compat import (
+ call_attach_output,
+ filter_unsupported_kwargs,
+ install_evolution_rail_kwargs_compat,
+)
from jiuwenswarm.agents.harness.common.prompt.prompt_builder import build_agent_identity_prompt
from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import NotifyingLLMRetryRail
+from jiuwenswarm.agents.harness.common.rails.execution_guard import (
+ CircuitBreakerConfig,
+ CircuitBreakerRail,
+)
from jiuwenswarm.agents.harness.common.rails import (
DeepResearchExecutionRail,
JiuSwarmStreamEventRail,
@@ -405,6 +421,10 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_slash import (
handle_evolution_slash_command,
)
from jiuwenswarm.server.runtime.agent_adapter import evolution_version as evolution_version_ctl
+from jiuwenswarm.server.runtime.agent_adapter.subagent_stream import (
+ clear_subagent_progress_batch,
+ try_handle_subagent_chunk,
+)
from jiuwenswarm.server.utils.stream_utils import (
build_tool_result_payload,
parse_ask_user_question_payload,
@@ -513,6 +533,7 @@ from jiuwenswarm.common.config import (
_get_ttse_config,
get_ttse_embedding_config,
get_ttse_enabled,
+ is_subagent_runtime_enabled,
resolve_env_vars,
resolve_string_or_list_config,
)
@@ -2330,6 +2351,22 @@ class _RuntimeCronToolContext:
return self._tool_scope
+def _optional_enable_subagent_runtime(enabled: bool) -> dict[str, bool]:
+ """Pass ``enable_subagent_runtime`` only when ``DeepAgentConfig`` accepts it.
+
+ Official ``dev-stable`` openjiuwen 0.1.16 is a dataclass without this
+ field; constructing it with the keyword raises TypeError. Do not filter
+ against ``create_deep_agent``: that factory still has ``**config_kwargs``,
+ so signature filtering would keep the keyword and only warn, or the
+ hot-reload path would still TypeError because it builds ``DeepAgentConfig``
+ directly. Fork overlay and a future official 3A merge keep the field.
+ """
+ return filter_unsupported_kwargs(
+ DeepAgentConfig.__init__,
+ {"enable_subagent_runtime": enabled},
+ )
+
+
def _agent_ras_kwargs_from_config(config_base: dict[str, Any] | None) -> dict[str, Any]:
"""Thin YAML gate for create_deep_agent ``agent_ras``.
@@ -2533,6 +2570,7 @@ class JiuWenSwarmDeepAdapter:
# 延时重索引任务(debounce):连续改多次 embedding 只在最后一次后跑一次。
self._memory_reindex_task: asyncio.Task | None = None
self._llm_retry_rail: LLMRetryRail | None = None
+ self._circuit_breaker_rail: CircuitBreakerRail | None = None
self._heartbeat_rail: HeartbeatRail | None = None
self._skill_evolution_rail: SkillEvolutionRail | None = None
self._evolution_interrupt_rail: EvolutionInterruptRail | None = None
@@ -3008,6 +3046,13 @@ class JiuWenSwarmDeepAdapter:
lock.locked() or self._session_adapter_lock_has_waiters(lock)
):
continue
+ # Persistent subagents stay until an explicit close. Idle TTL must
+ # not cancel_all them. Session delete / hot-reload / process exit
+ # still use cleanup_session_adapter.
+ if adapter is not None and self._session_has_live_subagent_runtime(
+ adapter, sid
+ ):
+ continue
if await self.cleanup_session_adapter(sid):
evicted += 1
@@ -3019,6 +3064,10 @@ class JiuWenSwarmDeepAdapter:
return False
if self.is_session_active(sid) or self.is_deep_agent_executing_for_session(sid):
return False
+ await self.release_subagent_runtime_for_session(
+ sid,
+ reason="session_adapter_cleanup",
+ )
await self.cleanup()
return True
@@ -3045,6 +3094,14 @@ class JiuWenSwarmDeepAdapter:
if adapter.is_session_active(sid) or adapter.is_deep_agent_executing_for_session(sid):
return False
try:
+ release_fn = getattr(
+ adapter, "release_subagent_runtime_for_session", None
+ )
+ if callable(release_fn):
+ await release_fn(
+ sid,
+ reason="session_adapter_cleanup",
+ )
await adapter.cleanup()
except Exception as exc:
logger.warning(
@@ -3062,6 +3119,68 @@ class JiuWenSwarmDeepAdapter:
logger.info("[JiuWenSwarmDeepAdapter] session scoped DeepAgent removed: session_id=%s", sid)
return cleaned
+ @staticmethod
+ def _session_has_live_subagent_runtime(
+ adapter: "JiuWenSwarmDeepAdapter",
+ session_id: str,
+ ) -> bool:
+ """Return True when a session still has live subagent slots in use.
+
+ A missing control is idle: dest-stable SDK and never-spawned parents
+ have no ``_subagent_controls``. If ``capacity()`` raises, treat the
+ session as occupied so TTL cannot evict an Adapter that may still
+ hold children.
+ """
+ deep_agent = getattr(adapter, "_instance", None)
+ if deep_agent is None:
+ return False
+ controls = getattr(deep_agent, "_subagent_controls", None) or {}
+ if not isinstance(controls, dict):
+ controls = {}
+ control = controls.get(session_id)
+ if control is None:
+ return False
+ try:
+ return int(control.capacity().get("used", 0)) > 0
+ except Exception:
+ # Occupancy unknown: skip TTL eviction rather than drop live children.
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] subagent capacity probe failed; "
+ "treating session as occupied: session_id=%s",
+ session_id,
+ )
+ return True
+
+ async def release_subagent_runtime_for_session(
+ self,
+ session_id: str | None,
+ *,
+ reason: str = "session_deleted",
+ ) -> None:
+ """Cancel cached subagents and flush persistence for one parent session."""
+ sid = self._session_adapter_key(session_id)
+ if not sid:
+ return
+ clear_subagent_progress_batch(sid)
+ if not self._is_session_scoped_adapter:
+ child = self._session_adapters.get(sid)
+ if child is not None and child is not self:
+ await child.release_subagent_runtime_for_session(sid, reason=reason)
+ return
+ deep_agent = self._instance
+ if deep_agent is None:
+ return
+ try:
+ from openjiuwen.harness.tools.subagent import release_subagent_control
+
+ await release_subagent_control(deep_agent, sid, reason=reason)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] release_subagent_runtime failed: session_id=%s error=%s",
+ sid,
+ exc,
+ )
+
def _is_session_lock_idle(self, sid: str, lock: asyncio.Lock) -> bool:
"""Check whether the session lock is the current one and has no active holders or waiters."""
return (
@@ -3208,6 +3327,17 @@ class JiuWenSwarmDeepAdapter:
"[JiuWenSwarmDeepAdapter] cleanup_session(%s) failed: %s",
sid, exc,
)
+ if cleanup_rail:
+ circuit_breaker_rail = getattr(self, "_circuit_breaker_rail", None)
+ if circuit_breaker_rail is not None:
+ try:
+ circuit_breaker_rail.cleanup_session(sid)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] circuit_breaker cleanup_session(%s) failed: %s",
+ sid,
+ exc,
+ )
else:
self._active_session_ids[sid] = count - 1
@@ -4208,9 +4338,32 @@ class JiuWenSwarmDeepAdapter:
resolved_language = self._resolve_runtime_language()
workspace = self._workspace_dir or "./"
+ sys_operation = self._sys_operation
subagents: list[Any] = []
should_add_general_purpose = False
+ statusline_setup_cfg = (
+ subagents_cfg.get(STATUSLINE_SETUP_AGENT_TYPE)
+ if isinstance(subagents_cfg, dict)
+ else None
+ )
+ if self._is_subagent_default_enabled(statusline_setup_cfg):
+ statusline_setup_options = (
+ statusline_setup_cfg if isinstance(statusline_setup_cfg, dict) else {}
+ )
+ subagents.append(
+ build_statusline_setup_agent_config(
+ model,
+ workspace=workspace,
+ sys_operation=sys_operation,
+ language=resolved_language,
+ max_iterations=parse_int(
+ statusline_setup_options.get("max_iterations"),
+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ ),
+ )
+ )
+
# Build progressive tool rail for subagents if enabled.
subagent_rails: list[Any] | None = None
if is_subagent_tool_lazy_load_enabled(react_cfg):
@@ -4239,6 +4392,7 @@ class JiuWenSwarmDeepAdapter:
build_research_agent_config(
model,
workspace=workspace,
+ sys_operation=sys_operation,
language=resolved_language,
max_iterations=parse_int(
research_agent_cfg.get("max_iterations"),
@@ -4271,18 +4425,18 @@ class JiuWenSwarmDeepAdapter:
"[JiuWenSwarmDeepAdapter] browser subagent enabled without BROWSER_DRIVER; "
"defaulting to managed mode"
)
+ browser_max_iterations = None
+ if isinstance(browser_agent_cfg, dict):
+ browser_max_iterations = browser_agent_cfg.get("max_iterations")
subagents.append(
build_browser_agent_config(
model,
workspace=workspace,
+ sys_operation=sys_operation,
language=resolved_language,
max_iterations=parse_int(
- (
- browser_agent_cfg.get("max_iterations")
- if isinstance(browser_agent_cfg, dict)
- else None
- ),
- react_cfg.get("max_iterations", 15),
+ browser_max_iterations,
+ DEFAULT_BROWSER_AGENT_MAX_ITERATIONS,
),
rails=subagent_rails,
)
@@ -4303,6 +4457,7 @@ class JiuWenSwarmDeepAdapter:
_load_custom_subagents(
self._workspace_dir, subagents_cfg, model, workspace,
__name__, model_cache=self._model_cache,
+ sys_operation=sys_operation,
)
)
except Exception:
@@ -8736,12 +8891,42 @@ class JiuWenSwarmDeepAdapter:
task_planning_rail = None
return task_planning_rail
- @staticmethod
- def _build_subagent_rail() -> SubagentRail | None:
- """Build SubagentRail for subagent delegation."""
+ def _build_subagent_rail(
+ self,
+ config_base: dict[str, Any] | None = None,
+ ) -> SubagentRail | None:
+ """Build SubagentRail for subagent delegation.
+
+ The adapter supplies this rail so ``create_deep_agent()`` skips its
+ own default SubagentRail. That is the only place
+ ``react.subagent_runtime.enabled`` can reach the rail.
+ """
+ from jiuwenswarm.agents.harness.common.rails.browser_task_prompt_rail import (
+ BrowserTaskPromptRail,
+ )
+
+ enable_runtime = self._resolve_enable_subagent_runtime(config_base)
try:
- subagent_rail = SubagentRail()
- logger.info("[JiuWenSwarmDeepAdapter] SubagentRail create success")
+ from jiuwenswarm.agents.harness.common.tools.subagent_compat import (
+ install_subagent_control_compat_patch,
+ )
+
+ install_subagent_control_compat_patch()
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] subagent control compat skipped: %s",
+ exc,
+ )
+ enable_runtime = False
+ try:
+ subagent_rail = BrowserTaskPromptRail(
+ enable_subagent_runtime=enable_runtime,
+ )
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] SubagentRail create success "
+ "(load-aware browser policy, subagent_runtime=%s)",
+ enable_runtime,
+ )
except Exception as exc:
logger.warning("[JiuWenSwarmDeepAdapter] SubagentRail create failed: %s", exc)
subagent_rail = None
@@ -8983,6 +9168,72 @@ class JiuWenSwarmDeepAdapter:
logger.warning("[JiuWenSwarmDeepAdapter] LLMRetryRail create failed: %s", exc)
return None
+ @staticmethod
+ def _coerce_circuit_breaker_threshold(value: object, default: int) -> int:
+ try:
+ parsed = int(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return default
+ if parsed <= 0:
+ return default
+ return parsed
+
+ @staticmethod
+ def _circuit_breaker_config_from_mapping(
+ cb_cfg: dict,
+ defaults: CircuitBreakerConfig,
+ ) -> CircuitBreakerConfig | None:
+ warning = JiuWenSwarmDeepAdapter._coerce_circuit_breaker_threshold(
+ cb_cfg.get("warning_threshold", defaults.warning_threshold),
+ defaults.warning_threshold,
+ )
+ critical = JiuWenSwarmDeepAdapter._coerce_circuit_breaker_threshold(
+ cb_cfg.get("critical_threshold", defaults.critical_threshold),
+ defaults.critical_threshold,
+ )
+ global_breaker = JiuWenSwarmDeepAdapter._coerce_circuit_breaker_threshold(
+ cb_cfg.get("global_breaker_threshold", defaults.global_breaker_threshold),
+ defaults.global_breaker_threshold,
+ )
+ unknown = JiuWenSwarmDeepAdapter._coerce_circuit_breaker_threshold(
+ cb_cfg.get("unknown_tool_threshold", defaults.unknown_tool_threshold),
+ defaults.unknown_tool_threshold,
+ )
+ if warning > critical:
+ return None
+ if critical > global_breaker:
+ return None
+ return CircuitBreakerConfig(
+ warning_threshold=warning,
+ critical_threshold=critical,
+ global_breaker_threshold=global_breaker,
+ unknown_tool_threshold=unknown,
+ )
+
+ def _build_circuit_breaker_rail(self) -> CircuitBreakerRail | None:
+ """Build develop's loop-detection rail. Default off; dest-stable RAS stays on."""
+ try:
+ guard_cfg = (get_config() or {}).get("execution_guard") or {}
+ cb_cfg = guard_cfg.get("circuit_breaker") if isinstance(guard_cfg, dict) else {}
+ if not isinstance(cb_cfg, dict):
+ cb_cfg = {}
+ if cb_cfg.get("enabled", False) is not True:
+ logger.info("[JiuWenSwarmDeepAdapter] CircuitBreakerRail disabled by config")
+ return None
+ defaults = CircuitBreakerConfig()
+ config = self._circuit_breaker_config_from_mapping(cb_cfg, defaults)
+ if config is None:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] CircuitBreakerRail invalid thresholds"
+ )
+ return None
+ rail = CircuitBreakerRail(config, language=self._resolve_runtime_language())
+ logger.info("[JiuWenSwarmDeepAdapter] CircuitBreakerRail create success")
+ return rail
+ except Exception as exc:
+ logger.warning("[JiuWenSwarmDeepAdapter] CircuitBreakerRail create failed: %s", exc)
+ return None
+
def _build_runtime_prompt_rail(self) -> RuntimePromptRail | None:
"""Build RuntimePromptRail for per-model-call time/channel/runtime injection."""
try:
@@ -9322,8 +9573,13 @@ class JiuWenSwarmDeepAdapter:
self._build_llm_retry_rail,
{"config_base": config_base},
),
+ _RailBuildInfo("_circuit_breaker_rail", self._build_circuit_breaker_rail),
_RailBuildInfo("_avatar_rail", self._build_avatar_rail),
- _RailBuildInfo("_subagent_rail", self._build_subagent_rail),
+ _RailBuildInfo(
+ "_subagent_rail",
+ self._build_subagent_rail,
+ {"config_base": config_base},
+ ),
_RailBuildInfo(
"_permission_rail",
self._build_permission_rail_for_agent,
@@ -9498,6 +9754,15 @@ class JiuWenSwarmDeepAdapter:
return True
return configured_value
+ @staticmethod
+ def _resolve_enable_subagent_runtime(
+ config_base: dict[str, Any] | None = None,
+ ) -> bool:
+ """Return whether persistent subagent runtime tools should be enabled."""
+ return is_subagent_runtime_enabled(
+ config_base if config_base is not None else get_config()
+ )
+
def _make_deep_agent_config(
self,
*,
@@ -9560,6 +9825,9 @@ class JiuWenSwarmDeepAdapter:
audio_model_config=self._audio_model_config,
enable_read_image_multimodal=self._resolve_enable_read_image_multimodal(config),
completion_timeout=config.get("completion_timeout", 21600.0),
+ **_optional_enable_subagent_runtime(
+ self._resolve_enable_subagent_runtime(config_base),
+ ),
)
def _update_permission_rail(
@@ -10526,6 +10794,11 @@ class JiuWenSwarmDeepAdapter:
# agent_ras YAML passthrough (Agent RAS owns loop detection / recovery).
common_kwargs.update(_agent_ras_kwargs_from_config(config_base))
+ common_kwargs.update(
+ _optional_enable_subagent_runtime(
+ self._resolve_enable_subagent_runtime(config_base),
+ )
+ )
self._instance = create_deep_agent(
**common_kwargs,
@@ -12071,6 +12344,9 @@ class JiuWenSwarmDeepAdapter:
)
stage_timer.mark("cwd_seed")
+ circuit_breaker_rail = getattr(self, "_circuit_breaker_rail", None)
+ if circuit_breaker_rail is not None:
+ circuit_breaker_rail.set_language(resolved_language)
if self._runtime_prompt_rail:
self._runtime_prompt_rail.set_language(resolved_language)
self._runtime_prompt_rail.set_channel(resolved_channel)
@@ -18274,10 +18550,9 @@ class JiuWenSwarmDeepAdapter:
steal_output = self._should_steal_output_lease(
request.params, req_method=request.req_method
)
- if steal_output:
- interaction_stream = await self._instance.attach_output(steal=True)
- else:
- interaction_stream = await self._instance.attach_output()
+ interaction_stream = await call_attach_output(
+ self._instance, steal=steal_output
+ )
if interaction_stream is not None:
await self._instance.send_input(
SendInputRequest(
@@ -18309,7 +18584,10 @@ class JiuWenSwarmDeepAdapter:
mark_request_first_byte()
else:
# check for error in other typed chunks (e.g. controller_output.task_failed)
- parsed = self._parse_stream_chunk(chunk)
+ parsed = self._parse_stream_chunk(
+ chunk,
+ _parent_session_id=session_id,
+ )
if parsed is not None:
event_type = str(parsed.get("event_type") or "").strip()
if event_type in ("chat.error", "error"):
@@ -19625,10 +19903,9 @@ class JiuWenSwarmDeepAdapter:
steal_output = self._should_steal_output_lease(
request.params, req_method=request.req_method
)
- if steal_output:
- interaction_stream = await self._instance.attach_output(steal=True)
- else:
- interaction_stream = await self._instance.attach_output()
+ interaction_stream = await call_attach_output(
+ self._instance, steal=steal_output
+ )
if interaction_stream is None:
async for chunk in _yield_runtime_accepted():
yield chunk
@@ -20029,6 +20306,7 @@ class JiuWenSwarmDeepAdapter:
parsed = self._parse_stream_chunk(
chunk,
_streamed_text=segment_streamed_text,
+ _parent_session_id=session_id,
)
parsed = self._adapt_goal_intermediate_final(parsed)
if parsed is not None:
@@ -20968,6 +21246,7 @@ class JiuWenSwarmDeepAdapter:
_stage: str = "",
_streamed_text: str = "",
_protocol_buffer: Any = None,
+ _parent_session_id: str | None = None,
) -> dict | None:
"""将 SDK OutputSchema 转为前端可消费的 payload dict.
@@ -20978,6 +21257,7 @@ class JiuWenSwarmDeepAdapter:
_streamed_text: 本段已通过 chat.delta 发出的可见正文(用于空 final / drain)
_protocol_buffer: 调用方持有的 StreamProtocolBuffer;跨 chunk 缓冲在 call site
feed/flush,此处仅吸收关键字以免 TypeError
+ _parent_session_id: parent session fallback for native subagent persist
Returns:
dict – 含 event_type 的 payload,或 None(需跳过的帧)。
@@ -21293,6 +21573,14 @@ class JiuWenSwarmDeepAdapter:
}
return None
+ handled, parsed = try_handle_subagent_chunk(
+ chunk_type,
+ payload,
+ parent_session_id=_parent_session_id,
+ )
+ if handled:
+ return parsed
+
if chunk_type == "context.usage":
if isinstance(payload, dict):
usage_payload = {
@@ -22742,6 +23030,7 @@ def _agent_def_to_subagent_config(
model: Any,
workspace: str,
model_cache: dict[str, Any] | None = None,
+ sys_operation: SysOperation | None = None,
) -> SubAgentConfig:
"""将 AgentDefinition 转换为 SubAgentConfig,用于 SubagentRail 注册。
@@ -22750,6 +23039,10 @@ def _agent_def_to_subagent_config(
model: 父 agent 的 Model 实例(作为默认模型)
workspace: 工作空间路径
model_cache: 模型缓存字典(用于按名称查找指定模型)
+ sys_operation: 父 agent 的 SysOperation。子 agent 必须复用同一文件系统
+ 边界。``DeepAgent.create_subagent`` 只在 ``spec.workspace`` 同时非空时
+ 才采用 ``spec.sys_operation``,因此 workspace 也要一并写入 spec,否则
+ 会落到一套带 ``restrict_to_sandbox`` 约束的新 LOCAL SysOperation。
"""
from openjiuwen.harness.schema.config import SubAgentConfig
@@ -22797,6 +23090,8 @@ def _agent_def_to_subagent_config(
system_prompt=agent_def.prompt,
tools=tools,
model=resolved_model,
+ workspace=workspace,
+ sys_operation=sys_operation,
skills=agent_def.skills,
max_iterations=agent_def.max_iterations,
enable_task_loop=True,
@@ -22822,13 +23117,14 @@ def _load_custom_subagents(
model: 模型配置
workspace: 工作空间路径
logger_name: 日志记录器名称
- **kwargs: 额外参数,支持 model_cache 等
+ **kwargs: 额外参数,支持 model_cache、sys_operation 等
"""
from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService
_logger = logging.getLogger(logger_name)
agent_service = AgentConfigService(workspace_dir)
model_cache: dict | None = kwargs.get("model_cache")
+ sys_operation = kwargs.get("sys_operation")
result: list[Any] = []
for agent_def in agent_service.list_agents():
if agent_def.source == "builtin":
@@ -22837,7 +23133,9 @@ def _load_custom_subagents(
# 只有显式 enabled: true 才加载
if not (isinstance(subagent_cfg, dict) and bool(subagent_cfg.get("enabled", False))):
continue
- custom_spec = _agent_def_to_subagent_config(agent_def, model, workspace, model_cache)
+ custom_spec = _agent_def_to_subagent_config(
+ agent_def, model, workspace, model_cache, sys_operation,
+ )
custom_spec.factory_kwargs = {"auto_create_workspace": False}
result.append(custom_spec)
_logger.info("loaded custom agent '%s' from %s", agent_def.name, agent_def.source)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/statusline_setup_agent.py b/jiuwenswarm/server/runtime/agent_adapter/statusline_setup_agent.py
new file mode 100644
index 0000000000..1207d16863
--- /dev/null
+++ b/jiuwenswarm/server/runtime/agent_adapter/statusline_setup_agent.py
@@ -0,0 +1,129 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Built-in subagent used by the TUI ``/statusline`` command."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from openjiuwen.core.single_agent import AgentCard
+from openjiuwen.harness.rails import SysOperationRail
+from openjiuwen.harness.schema.config import SubAgentConfig
+from openjiuwen.harness.workspace.workspace import Workspace
+
+
+STATUSLINE_SETUP_AGENT_TYPE = "statusline-setup"
+DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS = 15
+STATUSLINE_SETUP_AGENT_DESCRIPTION = (
+ "Configure the JiuwenSwarm TUI status line. Use only for explicit "
+ "/statusline setup, review, modification, or removal requests."
+)
+
+STATUSLINE_SETUP_SYSTEM_PROMPT = """\
+You are the built-in statusline-setup subagent for JiuwenSwarm. Configure, review, modify, or
+remove the user's TUI status line according to the delegated request.
+
+## Storage and runtime
+
+- The user config is `~/.jiuwenswarm-tui/config.json`.
+- The standard schema is `{"statusLine":{"type":"command","command":"...","padding":0}}`.
+- The TUI runs the command every 2 seconds, pipes one JSON object to stdin, and displays stdout.
+- The config file is polled automatically, so a successful edit takes effect without a restart.
+
+Always read the config before acting. Preserve every unrelated field, including `trustedDirs`,
+theme, and other settings. Never overwrite the whole file with only `statusLine`.
+
+## Existing configuration
+
+- If a status line exists and the request does not specify a change, inspect its command and any
+ referenced script, summarize what it does, and ask whether the user wants to modify or remove it.
+- For a modification, update the existing generated script when practical.
+- For removal, remove only the `statusLine` field. Remove a script only when it is clearly owned by
+ this status-line setup and the user asked to remove it.
+- Do not replace a working status line merely because this subagent was opened.
+
+## New configuration
+
+When no status line exists, or the user explicitly requests creation or replacement:
+
+1. Detect the operating system and available runtimes.
+2. Create a persistent script under `~/.jiuwenswarm-tui/`.
+3. Test it with representative JSON on stdin and verify that stdout is concise and non-empty.
+4. Merge the command configuration into `config.json`, preserving unrelated fields.
+5. Read the result back and report exactly what was configured.
+
+On Windows, prefer `~/.jiuwenswarm-tui/statusline.ps1`, parse stdin with
+`[Console]::In.ReadToEnd()` and `ConvertFrom-Json`, and configure an explicit command such as:
+
+```
+powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:/Users/USER/.jiuwenswarm-tui/statusline.ps1"
+```
+
+This avoids assuming that `jq` is installed. On macOS/Linux, prefer
+`~/.jiuwenswarm-tui/statusline.sh`; use `jq` only after confirming it is available, and make the
+script executable. Keep `type` equal to `command`; do not invent another status-line type.
+
+Useful input fields include `mode`, `model`, `provider`, `cwd`, `session_id`, `session_name`,
+`version`, `connection`, `is_processing`, `last_error`, `evolution_status`,
+`active_subtask_count`, `todo_count`, `trusted_dirs`, `usage.total_input_tokens`,
+`usage.total_output_tokens`, `usage.total_tokens`, `context_window.context_window_size`,
+`context_window.used_percentage`, and `context_window.remaining_percentage`.
+
+Never put secrets in the command or script. Keep failures graceful and the displayed output short.
+"""
+
+
+def build_statusline_setup_dispatch(description: str) -> str:
+ """Return the hidden parent-agent instruction that launches the subagent."""
+
+ task = json.dumps(description.strip(), ensure_ascii=False)
+ return (
+ "Invoke `task_tool` exactly once with `subagent_type` set to "
+ f"`{STATUSLINE_SETUP_AGENT_TYPE}` and `task_description` set to {task}. "
+ "Do not configure the status line in the parent agent. Wait for the subagent result, "
+ "then relay its result or question to the user."
+ )
+
+
+def build_statusline_setup_agent_config(
+ model: Any,
+ *,
+ workspace: str | Workspace,
+ sys_operation: Any = None,
+ language: str = "en",
+ max_iterations: int = DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+) -> SubAgentConfig:
+ """Build the runtime config registered with ``SubagentRail``."""
+
+ spec = SubAgentConfig(
+ agent_card=AgentCard(
+ id="jiuwenswarm.statusline-setup",
+ name=STATUSLINE_SETUP_AGENT_TYPE,
+ description=STATUSLINE_SETUP_AGENT_DESCRIPTION,
+ ),
+ system_prompt=STATUSLINE_SETUP_SYSTEM_PROMPT,
+ model=model,
+ rails=[SysOperationRail()],
+ workspace=workspace,
+ sys_operation=sys_operation,
+ language=language,
+ # TaskTool invokes ephemeral subagents without the Session object that
+ # DeepAgent's outer task-loop mode requires. A normal ReAct loop still
+ # supports the multi-step read/edit/test workflow needed here.
+ enable_task_loop=False,
+ max_iterations=max_iterations,
+ restrict_to_work_dir=False,
+ )
+ spec.factory_kwargs = {"auto_create_workspace": False}
+ return spec
+
+
+__all__ = [
+ "DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS",
+ "STATUSLINE_SETUP_AGENT_DESCRIPTION",
+ "STATUSLINE_SETUP_AGENT_TYPE",
+ "STATUSLINE_SETUP_SYSTEM_PROMPT",
+ "build_statusline_setup_agent_config",
+ "build_statusline_setup_dispatch",
+]
diff --git a/jiuwenswarm/server/runtime/agent_adapter/subagent_stream.py b/jiuwenswarm/server/runtime/agent_adapter/subagent_stream.py
new file mode 100644
index 0000000000..4182955182
--- /dev/null
+++ b/jiuwenswarm/server/runtime/agent_adapter/subagent_stream.py
@@ -0,0 +1,302 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Dest-native subagent stream projection, batching, and parent-scoped persist.
+
+Ported from develop persist/project helpers. Batches are keyed by parent
+session; the lock never surrounds await. Dest ``task.*`` / Skill Turbo
+``stream_source_id`` stay on their existing paths.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+try:
+ from openjiuwen.harness.subagent_runtime import (
+ SUBAGENT_ACTIVITY_EVENT_TYPE,
+ SUBAGENT_MESSAGE_EVENT_TYPE,
+ SUBAGENT_UPDATED_EVENT_TYPE,
+ )
+except ImportError: # official dest-stable SDK may not have 3A yet
+ SUBAGENT_UPDATED_EVENT_TYPE = "subagent_updated"
+ SUBAGENT_MESSAGE_EVENT_TYPE = "subagent_message"
+ SUBAGENT_ACTIVITY_EVENT_TYPE = "subagent_activity"
+
+_SUBAGENT_PROGRESS_BATCHES: dict[str, list[str]] = {}
+_SUBAGENT_PROGRESS_BATCHES_LOCK = threading.Lock()
+
+
+def clear_subagent_progress_batch(parent_session_id: str | None) -> None:
+ """Drop the parallel-index batch for one parent session."""
+ if not parent_session_id:
+ return
+ with _SUBAGENT_PROGRESS_BATCHES_LOCK:
+ _SUBAGENT_PROGRESS_BATCHES.pop(parent_session_id, None)
+
+
+def clear_all_subagent_progress_batches() -> None:
+ """Test helper: reset every parent-session batch."""
+ with _SUBAGENT_PROGRESS_BATCHES_LOCK:
+ _SUBAGENT_PROGRESS_BATCHES.clear()
+
+
+def resolve_subagent_parallel_fields(
+ *,
+ parent_session_id: str,
+ subagent_id: str,
+ legacy_status: str,
+) -> tuple[int, int, bool]:
+ """Assign stable 0-based index/total for legacy Web SubtaskProgress."""
+ if not parent_session_id or not subagent_id:
+ return 0, 1, False
+
+ with _SUBAGENT_PROGRESS_BATCHES_LOCK:
+ order = _SUBAGENT_PROGRESS_BATCHES.setdefault(parent_session_id, [])
+
+ if legacy_status in ("completed", "error"):
+ if subagent_id not in order:
+ return 0, 1, False
+ index = order.index(subagent_id)
+ total = max(len(order), 1)
+ order.remove(subagent_id)
+ if not order:
+ _SUBAGENT_PROGRESS_BATCHES.pop(parent_session_id, None)
+ return index, total, total > 1
+
+ if subagent_id not in order:
+ order.append(subagent_id)
+ index = order.index(subagent_id)
+ total = len(order)
+ return index, total, total > 1
+
+
+def resolve_subagent_legacy_status(projection: dict[str, Any]) -> tuple[str, str]:
+ """Return (legacy_status, message) for Web SubtaskProgress compatibility."""
+ status = str(projection.get("status") or "running")
+ closed_reason = projection.get("closed_reason")
+ message = ""
+ if status == "closed":
+ if closed_reason == "failed":
+ legacy_status = "error"
+ error = projection.get("error")
+ if isinstance(error, dict):
+ message = str(error.get("message") or "")
+ else:
+ legacy_status = "completed"
+ elif status == "idle":
+ turn_outcome = projection.get("turn_outcome")
+ if turn_outcome == "failed":
+ legacy_status = "error"
+ error = projection.get("error")
+ if isinstance(error, dict):
+ message = str(error.get("message") or "")
+ else:
+ legacy_status = "completed"
+ else:
+ legacy_status = "starting"
+ return legacy_status, message
+
+
+def project_subagent_updated_for_web(projection: dict[str, Any]) -> dict[str, Any]:
+ """Project runtime subagent_updated for Web without overwriting canonical status."""
+ subagent_id = str(projection.get("subagent_id") or "")
+ description = (
+ str(projection.get("display_name") or "").strip()
+ or str(projection.get("task_description") or "").strip()
+ or subagent_id
+ )
+ legacy_status, message = resolve_subagent_legacy_status(projection)
+
+ parent_session_id = str(projection.get("parent_session_id") or "")
+ index, total, is_parallel = resolve_subagent_parallel_fields(
+ parent_session_id=parent_session_id,
+ subagent_id=subagent_id,
+ legacy_status=legacy_status,
+ )
+
+ payload: dict[str, Any] = {
+ "event_type": "chat.subtask_update",
+ **projection,
+ "session_id": parent_session_id,
+ "task_id": subagent_id,
+ "description": description,
+ "legacy_status": legacy_status,
+ "index": index,
+ "total": total,
+ "is_parallel": is_parallel,
+ }
+ if message:
+ payload["message"] = message
+ return payload
+
+
+def persist_subagent_transcript_message(projection: dict[str, Any]) -> None:
+ """Write a child transcript row under the parent session, not the parent jsonl."""
+ from jiuwenswarm.server.runtime.session.session_history import append_history_record
+
+ parent_session_id = str(projection.get("parent_session_id") or "").strip()
+ subagent_id = str(projection.get("subagent_id") or "").strip()
+ if not parent_session_id or not subagent_id:
+ return
+
+ seq = projection.get("seq")
+ request_id = f"{subagent_id}:{seq}" if seq is not None else subagent_id
+ role = str(projection.get("role") or "assistant")
+ event_type = str(projection.get("event_type") or "").strip() or None
+ content = str(projection.get("content") or "")
+ timestamp_ms = projection.get("at_ms")
+ timestamp = float(timestamp_ms) / 1000 if timestamp_ms else time.time()
+
+ extra: dict[str, Any] = {}
+ reasoning_content = projection.get("reasoning_content")
+ if isinstance(reasoning_content, str) and reasoning_content.strip():
+ extra["reasoning_content"] = reasoning_content.strip()
+ try:
+ phase_id = int(projection.get("phase_id") or 0)
+ except (TypeError, ValueError):
+ phase_id = 0
+ if phase_id > 0:
+ extra["phase_id"] = phase_id
+ nested_extra = projection.get("extra")
+ if isinstance(nested_extra, dict):
+ extra.update(nested_extra)
+ extra["parent_session_id"] = parent_session_id
+
+ append_history_record(
+ session_id=parent_session_id,
+ subagent_id=subagent_id,
+ request_id=request_id,
+ channel_id="subagent",
+ role=role,
+ content=content,
+ timestamp=timestamp,
+ event_type=event_type if role == "assistant" else None,
+ extra=extra or None,
+ mode="subagent",
+ )
+
+
+def persist_subagent_activity(projection: dict[str, Any]) -> None:
+ """Write a child activity snapshot under the parent session."""
+ from jiuwenswarm.server.runtime.session.session_history import append_history_record
+
+ parent_session_id = str(projection.get("parent_session_id") or "").strip()
+ subagent_id = str(projection.get("subagent_id") or "").strip()
+ if not parent_session_id or not subagent_id:
+ return
+
+ task_id = str(projection.get("task_id") or "").strip() or "turn"
+ seq = projection.get("seq")
+ seq_part = str(seq) if seq is not None else str(projection.get("at_ms") or "0")
+ request_id = f"{subagent_id}:activity:{task_id}:{seq_part}"
+ timestamp_ms = projection.get("at_ms")
+ timestamp = float(timestamp_ms) / 1000 if timestamp_ms else time.time()
+ activity = {**projection, "parent_session_id": parent_session_id}
+ append_history_record(
+ session_id=parent_session_id,
+ subagent_id=subagent_id,
+ request_id=request_id,
+ channel_id="subagent",
+ role="assistant",
+ content=str(projection.get("summary") or ""),
+ timestamp=timestamp,
+ event_type="chat.subagent_activity",
+ extra={"subagent_activity": activity},
+ mode="subagent",
+ )
+
+
+def persist_subagent_roster_history(
+ projection: dict[str, Any],
+ web_payload: dict[str, Any],
+) -> None:
+ """Write a child roster snapshot under the parent session."""
+ from jiuwenswarm.server.runtime.session.session_history import append_history_record
+
+ parent_session_id = str(projection.get("parent_session_id") or "").strip()
+ subagent_id = str(projection.get("subagent_id") or "").strip()
+ if not parent_session_id or not subagent_id:
+ return
+
+ updated_at_ms = projection.get("updated_at_ms") or projection.get("created_at_ms")
+ timestamp = float(updated_at_ms) / 1000 if updated_at_ms else time.time()
+ revision = projection.get("revision")
+ request_id = (
+ f"subagent-roster-{subagent_id}:{revision}"
+ if revision is not None
+ else f"subagent-roster-{subagent_id}"
+ )
+ append_history_record(
+ session_id=parent_session_id,
+ subagent_id=subagent_id,
+ request_id=request_id,
+ channel_id="subagent",
+ role="assistant",
+ event_type="chat.subtask_update",
+ content=str(web_payload.get("description") or subagent_id),
+ timestamp=timestamp,
+ extra=web_payload,
+ mode="subagent",
+ )
+
+
+def _safe_persist(label: str, fn: Any, *args: Any) -> None:
+ try:
+ fn(*args)
+ except Exception:
+ logger.warning("persist %s failed", label, exc_info=True)
+
+
+def try_handle_subagent_chunk(
+ chunk_type: Any,
+ payload: Any,
+ *,
+ parent_session_id: str | None = None,
+) -> tuple[bool, dict[str, Any] | None]:
+ """Return (handled, web_payload). Message frames persist only (no web emit)."""
+ if chunk_type == SUBAGENT_UPDATED_EVENT_TYPE:
+ projection = payload.get("subagent_updated") if isinstance(payload, dict) else None
+ if not isinstance(projection, dict):
+ return True, None
+ web_payload = project_subagent_updated_for_web(projection)
+ _safe_persist(
+ "subagent roster",
+ persist_subagent_roster_history,
+ projection,
+ web_payload,
+ )
+ return True, web_payload
+
+ if chunk_type == SUBAGENT_MESSAGE_EVENT_TYPE:
+ projection = payload.get("subagent_message") if isinstance(payload, dict) else None
+ if not isinstance(projection, dict):
+ return True, None
+ _safe_persist("subagent transcript", persist_subagent_transcript_message, projection)
+ return True, None
+
+ if chunk_type == SUBAGENT_ACTIVITY_EVENT_TYPE:
+ projection = payload.get("subagent_activity") if isinstance(payload, dict) else None
+ if not isinstance(projection, dict):
+ return True, None
+ persist_projection = dict(projection)
+ resolved_parent = str(
+ persist_projection.get("parent_session_id") or parent_session_id or ""
+ ).strip()
+ if resolved_parent:
+ persist_projection["parent_session_id"] = resolved_parent
+ _safe_persist("subagent activity", persist_subagent_activity, persist_projection)
+ activity_payload: dict[str, Any] = {
+ "event_type": "chat.subagent_activity",
+ **projection,
+ }
+ if resolved_parent:
+ activity_payload["session_id"] = resolved_parent
+ activity_payload["parent_session_id"] = resolved_parent
+ return True, activity_payload
+
+ return False, None
diff --git a/jiuwenswarm/server/runtime/agent_config_service.py b/jiuwenswarm/server/runtime/agent_config_service.py
index 01d7d1e8dc..4876ad782e 100644
--- a/jiuwenswarm/server/runtime/agent_config_service.py
+++ b/jiuwenswarm/server/runtime/agent_config_service.py
@@ -21,6 +21,12 @@ from typing import Literal
import yaml
from jiuwenswarm.common.utils import get_user_workspace_dir
+from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (
+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ STATUSLINE_SETUP_AGENT_DESCRIPTION,
+ STATUSLINE_SETUP_AGENT_TYPE,
+ STATUSLINE_SETUP_SYSTEM_PROMPT,
+)
logger = logging.getLogger(__name__)
@@ -123,6 +129,15 @@ class UpdateAgentParams:
# ---------------------------------------------------------------------------
BUILTIN_AGENTS: list[AgentDefinition] = [
+ AgentDefinition(
+ name=STATUSLINE_SETUP_AGENT_TYPE,
+ description=STATUSLINE_SETUP_AGENT_DESCRIPTION,
+ prompt=STATUSLINE_SETUP_SYSTEM_PROMPT,
+ source="builtin",
+ tools=["Read", "Write", "Edit", "Bash"],
+ enabled=True,
+ max_iterations=DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ ),
AgentDefinition(
name="general-purpose",
description="通用多步任务 agent,适用于没有专用 agent 的各类任务",
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index f18d0c2dad..be84f99658 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -798,6 +798,22 @@ class AgentManager:
)
return cleaned
+ async def release_subagent_runtime_for_session(
+ self,
+ *,
+ channel_id: str | None,
+ session_id: str,
+ reason: str = "session_deleted",
+ ) -> bool:
+ """Release subagent control owned by the channel's existing Agent."""
+ agent = self.get_agent_nowait(channel_id=channel_id or "")
+ adapter = getattr(agent, "_adapter", None) if agent is not None else None
+ release_runtime = getattr(adapter, "release_subagent_runtime_for_session", None)
+ if not callable(release_runtime):
+ return False
+ await release_runtime(session_id, reason=reason)
+ return True
+
def get_client_capabilities(self, channel_id: str = "") -> dict[str, Any]:
channel_key = str(channel_id or "").strip()
caps = self._client_capabilities_by_channel.get(channel_key)
diff --git a/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
index f0ed56e18e..dc9db70315 100644
--- a/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
+++ b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
@@ -33,6 +33,7 @@ async def invoke_subagent_with_trace(
inputs: dict,
session: Any,
source_label: str,
+ session_id: str | None = None,
) -> dict:
"""Run *subagent*, capturing its stream into the active run's debug dump.
@@ -41,6 +42,8 @@ async def invoke_subagent_with_trace(
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``.
+ session_id: Parent session id used when *session* has no
+ ``get_session_id``. Dest still drives ``stream(session=None)``.
Returns:
An invoke-style result dict (``{"output": ..., "result_type": ...}``),
@@ -64,6 +67,8 @@ async def invoke_subagent_with_trace(
# custom AgentTool path inside the DeepAgent's supervisor task, where the
# per-request ContextVar isn't visible. Fall back to a session lookup.
sid = session.get_session_id() if hasattr(session, "get_session_id") else None
+ if not sid:
+ sid = session_id
if sid:
dbg = get_debug_trace_logger_for_session(sid)
if dbg is None or not dbg.captures_subagent_flow():
diff --git a/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py b/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
index 1af0fdc17c..c8e5e36d59 100644
--- a/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
+++ b/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
@@ -1,67 +1,41 @@
# 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.
+"""Attach subagent stream capture without replacing SDK TaskTool semantics.
+
+The SDK owns input validation, query budgets, focused browser resumes, resource
+cleanup, usage attribution, and authoritative result rendering. This patch only
+replaces its narrow subagent dispatch seam while a debug dump is active.
"""
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``.
+import logging
+from typing import Any
- 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]}"
+_PATCH_APPLIED = False
+_logger = logging.getLogger(__name__)
-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
+def _subagent_source_label(subagent: Any) -> str:
+ card = getattr(subagent, "card", None)
+ subagent_type = str(
+ getattr(card, "name", None) or getattr(card, "id", None) or "unknown"
+ )
+ return f"subagent:builtin:{subagent_type}"
- _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
+def _wrap_invoke_subagent(original_dispatch: Any):
+ """Wrap the SDK dispatch hook; capture only when a debug dump is active."""
+ async def _invoke_subagent_with_trace(
+ self: Any,
+ subagent: Any,
+ subagent_inputs: dict[str, Any],
+ *,
+ parent_session_id: str,
+ session: Any = None,
+ ) -> Any:
from jiuwenswarm.server.runtime.debug_trace import (
get_debug_trace_logger,
invoke_subagent_with_trace,
@@ -70,91 +44,55 @@ def apply_task_tool_debug_patch() -> None:
get_debug_trace_logger_for_session,
)
- # Not capturing -> pristine original SDK path, unchanged.
- dbg = get_debug_trace_logger()
- if dbg is None:
- # TaskTool.invoke runs in the DeepAgent's supervisor task (created at
- # session setup, before any /debug request publishes the ContextVar),
- # so the per-request binding above doesn't reach it. Fall back to the
- # session-keyed registry — we hold the parent Session in kwargs.
- parent_session = kwargs.get("session", None)
- if isinstance(parent_session, Session):
- dbg = get_debug_trace_logger_for_session(parent_session.get_session_id())
- if dbg is not None:
- logger.info(
- "[TaskTool] (debug) recovered trace logger via session "
- "registry: %s", parent_session.get_session_id(),
- )
- 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",
+ debug_logger = get_debug_trace_logger()
+ if debug_logger is None:
+ debug_logger = get_debug_trace_logger_for_session(parent_session_id)
+ if debug_logger is None or not debug_logger.captures_subagent_flow():
+ return await original_dispatch(
+ self,
+ subagent,
+ subagent_inputs,
+ parent_session_id=parent_session_id,
+ session=session,
)
+ return await invoke_subagent_with_trace(
+ subagent,
+ inputs=subagent_inputs,
+ session=session,
+ session_id=parent_session_id,
+ source_label=_subagent_source_label(subagent),
+ )
- 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)}",
- )
+ return _invoke_subagent_with_trace
- 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,
- )
+def apply_task_tool_debug_patch() -> None:
+ """Patch only the SDK dispatch seam used to invoke a created subagent."""
+ global _PATCH_APPLIED
+ if _PATCH_APPLIED:
+ return
- 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
+ from openjiuwen.harness.tools.subagent.task_tool import TaskTool
- 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
+ if getattr(TaskTool, "debug_trace_patch_applied", False):
+ _PATCH_APPLIED = True
+ return
+
+ original_dispatch = getattr(TaskTool, "_invoke_subagent", None)
+ if not callable(original_dispatch):
+ _logger.warning(
+ "TaskTool debug subagent-flow capture is unavailable because this SDK "
+ "does not expose the narrow dispatch hook; TaskTool behavior is unchanged."
+ )
+ TaskTool.debug_trace_patch_applied = True
+ TaskTool.debug_trace_patch_mode = "unsupported_sdk"
+ _PATCH_APPLIED = True
+ return
- TaskTool.invoke = _invoke_with_trace # type: ignore[assignment]
+ setattr(TaskTool, "_invoke_subagent", _wrap_invoke_subagent(original_dispatch))
TaskTool.debug_trace_patch_applied = True
+ TaskTool.debug_trace_patch_mode = "dispatch_only"
_PATCH_APPLIED = True
-__all__ = ["apply_task_tool_debug_patch"]
+__all__ = ["apply_task_tool_debug_patch", "_subagent_source_label"]
diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.py
index 6004c1318b..08469a159d 100644
--- a/jiuwenswarm/server/runtime/session/session_history.py
+++ b/jiuwenswarm/server/runtime/session/session_history.py
@@ -23,6 +23,11 @@ _FILE_LOCK = threading.Lock()
_WRITE_QUEUE: queue.Queue[tuple[str, list[dict[str, Any]], str | None]] = queue.Queue(maxsize=20000)
_WORKER_STARTED = False
_WORKER_LOCK = threading.Lock()
+_SUBAGENT_WRITE_QUEUE: queue.Queue[
+ tuple[str, str, list[dict[str, Any]], str | None]
+] = queue.Queue(maxsize=20000)
+_SUBAGENT_WORKER_STARTED = False
+_SUBAGENT_WORKER_LOCK = threading.Lock()
_LEGACY_HISTORY_FILENAME = "history.json"
_JSONL_HISTORY_FILENAME = "history.jsonl"
_LEGACY_HISTORY_ENV = "JIUWENSWARM_USE_LEGACY_HISTORY_JSON"
@@ -136,6 +141,15 @@ def _is_ephemeral_heartbeat_session(session_id: str) -> bool:
return (session_id or "").startswith("heartbeat")
+def _has_subtask_update_payload(payload: dict[str, Any]) -> bool:
+ """True when a blank chat.subtask_update still has persistable extras."""
+ return bool(
+ payload.get("task_id")
+ or payload.get("subagent_id")
+ or payload.get("description")
+ )
+
+
def _has_persistable_assistant_payload(
*,
content_text: str,
@@ -178,6 +192,10 @@ def _has_persistable_assistant_payload(
or payload.get("usage_metadata")
)
# HITL cards have empty content; questions / expiry live in extras.
+ if et == "chat.subagent_activity" and isinstance(payload.get("subagent_activity"), dict):
+ return True
+ if et == "chat.subtask_update" and _has_subtask_update_payload(payload):
+ return True
if et == "chat.ask_user_question":
questions = payload.get("questions")
return isinstance(questions, list) and bool(questions)
@@ -347,6 +365,43 @@ _MERGE = {
}
+def subagent_history_dir_name(subagent_id: str) -> str:
+ """Return a single path component for a child subagent history directory."""
+ normalized = (subagent_id or "").strip()
+ if is_valid_session_id(normalized):
+ return normalized
+ slug = re.sub(r"[^A-Za-z0-9_.-]", "_", normalized).strip("._-")
+ if len(slug) > 80:
+ slug = slug[:80]
+ return slug
+
+
+def resolve_subagent_history_path(
+ session_id: str,
+ subagent_id: str,
+ *,
+ create: bool = False,
+ sessions_root: str | Path | None = None,
+) -> tuple[Path | None, str | None]:
+ """Resolve ``<parent>/subagents/<id>/history.json(l)`` inside the parent session."""
+ root = Path(sessions_root) if sessions_root is not None else None
+ parent, error = resolve_session_dir(session_id, create=create, sessions_root=root)
+ if error or parent is None:
+ return None, error or "invalid session_id"
+ name = subagent_history_dir_name(subagent_id)
+ if not name:
+ return None, "invalid subagent_id"
+ sub_dir = (parent / "subagents" / name).resolve()
+ try:
+ sub_dir.relative_to(parent.resolve())
+ except ValueError:
+ return None, "invalid subagent_id"
+ if create:
+ sub_dir.mkdir(parents=True, exist_ok=True)
+ filename = _LEGACY_HISTORY_FILENAME if use_legacy_history_json() else _JSONL_HISTORY_FILENAME
+ return sub_dir / filename, None
+
+
def _session_dir(
session_id: str, *, create: bool = True, sessions_root: str | None = None
) -> Path:
@@ -426,8 +481,23 @@ def get_write_history_path(session_id: str, sessions_root: str | None = None) ->
return _history_jsonl_file(session_id, sessions_root=sessions_root)
-def get_read_history_path(session_id: str, sessions_root: str | None = None) -> Path:
+def get_read_history_path(
+ session_id: str,
+ sessions_root: str | None = None,
+ *,
+ subagent_id: str | None = None,
+) -> Path:
"""Return the preferred history source, falling back to legacy json."""
+ if subagent_id:
+ path, error = resolve_subagent_history_path(
+ session_id,
+ subagent_id,
+ create=False,
+ sessions_root=sessions_root,
+ )
+ if path is not None and error is None:
+ return path
+ return Path("__missing_subagent_history__")
if use_legacy_history_json():
legacy_path = _history_file(session_id, create=False, sessions_root=sessions_root)
if legacy_path.exists():
@@ -446,8 +516,17 @@ def get_read_history_path(session_id: str, sessions_root: str | None = None) ->
return jsonl_path
-def history_exists(session_id: str, sessions_root: str | None = None) -> bool:
- return get_read_history_path(session_id, sessions_root=sessions_root).exists()
+def history_exists(
+ session_id: str,
+ sessions_root: str | None = None,
+ *,
+ subagent_id: str | None = None,
+) -> bool:
+ return get_read_history_path(
+ session_id,
+ sessions_root=sessions_root,
+ subagent_id=subagent_id,
+ ).exists()
def get_history_mtime(session_id: str) -> float | None:
@@ -538,8 +617,20 @@ def _read_history_jsonl(path: Path) -> list[dict[str, Any]]:
return records
-def load_history_records(session_id: str, sessions_root: str | None = None) -> list[dict[str, Any]]:
- return _read_history(get_read_history_path(session_id, sessions_root=sessions_root))
+def load_history_records(
+ session_id: str,
+ sessions_root: str | None = None,
+ *,
+ subagent_id: str | None = None,
+) -> list[dict[str, Any]]:
+ _flush_subagent_history_writes()
+ return _read_history(
+ get_read_history_path(
+ session_id,
+ sessions_root=sessions_root,
+ subagent_id=subagent_id,
+ )
+ )
def _write_records_to_path(path: Path, records: list[dict[str, Any]]) -> None:
@@ -787,6 +878,83 @@ def _batch_write_items(session_id: str, items: list[dict], sessions_root: str |
fh.write("\n")
+def _batch_write_subagent_items(
+ session_id: str,
+ subagent_id: str,
+ items: list[dict],
+ sessions_root: str | None,
+) -> None:
+ """Queue JSONL rows for the child subagent file; dest parent buffer is untouched."""
+ if not items:
+ return
+ _ensure_subagent_history_worker_started()
+ try:
+ _SUBAGENT_WRITE_QUEUE.put_nowait(
+ (session_id, subagent_id, list(items), sessions_root)
+ )
+ except queue.Full:
+ _write_subagent_items_sync(session_id, subagent_id, items, sessions_root)
+
+
+def _write_subagent_items_sync(
+ session_id: str,
+ subagent_id: str,
+ items: list[dict],
+ sessions_root: str | None,
+) -> None:
+ path, error = resolve_subagent_history_path(
+ session_id,
+ subagent_id,
+ create=True,
+ sessions_root=sessions_root,
+ )
+ if error or path is None:
+ logger.warning(
+ "skip subagent history write: session_id=%s subagent_id=%s error=%s",
+ session_id,
+ subagent_id,
+ error,
+ )
+ return
+ with _FILE_LOCK:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8", newline="\n") as fh:
+ for item in items:
+ fh.write(json.dumps(item, ensure_ascii=False))
+ fh.write("\n")
+
+
+def _ensure_subagent_history_worker_started() -> None:
+ global _SUBAGENT_WORKER_STARTED
+ if _SUBAGENT_WORKER_STARTED:
+ return
+ with _SUBAGENT_WORKER_LOCK:
+ if _SUBAGENT_WORKER_STARTED:
+ return
+
+ def _worker() -> None:
+ while True:
+ sid, child_id, items, sessions_root = _SUBAGENT_WRITE_QUEUE.get()
+ try:
+ _write_subagent_items_sync(sid, child_id, items, sessions_root)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("subagent history 异步写入失败: %s", exc)
+ finally:
+ _SUBAGENT_WRITE_QUEUE.task_done()
+
+ t = threading.Thread(
+ target=_worker, name="subagent-history-writer", daemon=True
+ )
+ t.start()
+ _SUBAGENT_WORKER_STARTED = True
+
+
+def _flush_subagent_history_writes() -> None:
+ if not _SUBAGENT_WORKER_STARTED:
+ return
+ _SUBAGENT_WRITE_QUEUE.join()
+
+
def _ensure_worker_started() -> None:
global _WORKER_STARTED
if _WORKER_STARTED:
@@ -1041,6 +1209,7 @@ def shutdown() -> None:
logger.warning("history shutdown flush 失败: %s", exc)
try:
_force_flush_all_pending()
+ _flush_subagent_history_writes()
except Exception as exc: # noqa: BLE001
logger.warning("history shutdown 强制暂留落盘失败: %s", exc)
deadline = time.monotonic() + 5.0
@@ -1176,12 +1345,19 @@ def append_history_record(
if mode:
item["mode"] = str(mode)
item["session_id"] = sid
+ child_id = (subagent_id or "").strip() or None
+ if child_id:
+ item["subagent_id"] = child_id
# skill_envs injected into bash tool_args.env must not be persisted.
_strip_skill_env_from_history_item(item)
sessions_root_s = str(sessions_root) if sessions_root else None
et = event_type if (role_norm == "assistant" and event_type) else None
+ if child_id:
+ _batch_write_subagent_items(sid, child_id, [item], sessions_root_s)
+ return
+
_ensure_flush_thread_started()
try:
_flush_on_request_switch(sid, rid, sessions_root_s)
diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.py
index 2288e29a3b..8a156eb5e2 100644
--- a/jiuwenswarm/server/utils/stream_utils.py
+++ b/jiuwenswarm/server/utils/stream_utils.py
@@ -9,6 +9,10 @@ import logging
import uuid
from typing import Any
+from jiuwenswarm.server.runtime.agent_adapter.subagent_stream import (
+ try_handle_subagent_chunk,
+)
+
logger = logging.getLogger(__name__)
@@ -269,6 +273,12 @@ def _parse_typed_chunk(
}
return None
+ handled, parsed = try_handle_subagent_chunk(chunk_type, payload)
+ if handled:
+ if isinstance(parsed, dict):
+ parsed = {**parsed, **_propagate_stream_source_id(payload)}
+ return parsed
+
if isinstance(chunk_type, str) and "." in chunk_type:
if chunk_type == "context.compression_state":
if hasattr(payload, "model_dump"):
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index 6f76b11b7a..2e97260a3d 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -1955,8 +1955,9 @@ def test_code_subagent_specs_use_factory_names() -> None:
assert registry.EXPLORE_AGENT in factory_names
assert registry.PLAN_AGENT in factory_names
assert registry.CODE_AGENT in factory_names
- # Team mode has no code sub-agents.
- assert build_member_subagent_specs({}, "team", "leader") == []
+ team_specs = build_member_subagent_specs({}, "team", "leader")
+ assert [spec.agent_card.name for spec in team_specs] == ["statusline-setup"]
+ assert team_specs[0].factory_name == registry.STATUSLINE_SETUP_AGENT
def test_code_runtime_language_by_mode_and_role() -> None:
diff --git a/tests/integration/test_link_mtls_http_sse_e2e.py b/tests/integration/test_link_mtls_http_sse_e2e.py
index 0a8285eb9c..c003ce5010 100644
--- a/tests/integration/test_link_mtls_http_sse_e2e.py
+++ b/tests/integration/test_link_mtls_http_sse_e2e.py
@@ -853,6 +853,7 @@ async def test_agent_handler_initializes_without_plaintext_websocket(monkeypatch
_trigger_before_ws_server_start_hook=AsyncMock(),
_bootstrap_internal_jiuwenbox=AsyncMock(),
_start_loop_lag_monitor=AsyncMock(),
+ _install_runtime_push_host=lambda: None,
_start_personal_context_best_effort=AsyncMock(),
)
await module.AgentWebSocketServer.start(server, listen=False)
diff --git a/tests/unit/deep_agent/test_browser_subagent_integration.py b/tests/unit/deep_agent/test_browser_subagent_integration.py
index 678b50889f..5f8ff3467b 100644
--- a/tests/unit/deep_agent/test_browser_subagent_integration.py
+++ b/tests/unit/deep_agent/test_browser_subagent_integration.py
@@ -135,7 +135,7 @@ def _make_fake_runtime() -> MagicMock:
# ─── DeepAdapter (agent mode): only research_agent + browser_agent ──────
-def test_deep_adapter_subagents_defaults_to_none_when_unconfigured(
+def test_deep_adapter_subagents_defaults_to_statusline_when_unconfigured(
monkeypatch: pytest.MonkeyPatch,
) -> None:
adapter = _TestableJiuWenSwarmDeepAdapter()
@@ -145,14 +145,15 @@ def test_deep_adapter_subagents_defaults_to_none_when_unconfigured(
"_browser_runtime_enabled",
staticmethod(lambda: False),
)
- # DeepAdapter: no subagents configured, no browser → None
+ # DeepAdapter: no subagents configured, no browser → statusline still default-on
subagents, _ = adapter.build_configured_subagents(
model,
{"max_iterations": 8},
{},
)
- assert subagents is None
+ assert subagents is not None
+ assert [spec.agent_card.name for spec in subagents] == ["statusline-setup"]
def test_browser_runtime_environment_tracks_mode_and_chrome_path(
@@ -208,13 +209,16 @@ def test_deep_adapter_subagents_includes_browser_by_default_when_runtime_enabled
subagents, _ = adapter.build_configured_subagents(
model,
- {"max_iterations": 8},
+ {
+ "max_iterations": 8,
+ "subagents": {"statusline-setup": {"enabled": False}},
+ },
{},
)
assert subagents is not None
assert [item["name"] for item in subagents] == ["browser_agent"]
- assert subagents[-1]["kwargs"]["max_iterations"] == 8
+ assert subagents[-1]["kwargs"]["max_iterations"] == 100
def test_deep_adapter_subagents_only_includes_explicitly_enabled_agents(
@@ -248,6 +252,7 @@ def test_deep_adapter_subagents_only_includes_explicitly_enabled_agents(
"subagents": {
"research_agent": {"enabled": True, "max_iterations": 5},
"browser_agent": {"max_iterations": 7},
+ "statusline-setup": {"enabled": False},
},
},
{},
@@ -280,6 +285,7 @@ def test_deep_adapter_subagents_skips_browser_without_runtime(
{
"subagents": {
"browser_agent": {"max_iterations": 7},
+ "statusline-setup": {"enabled": False},
},
},
{},
diff --git a/tests/unit_tests/agents/harness/test_subagent_compat.py b/tests/unit_tests/agents/harness/test_subagent_compat.py
new file mode 100644
index 0000000000..343e5de358
--- /dev/null
+++ b/tests/unit_tests/agents/harness/test_subagent_compat.py
@@ -0,0 +1,82 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Regression tests for OpenJiuWen subagent runtime compatibility."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+pytest.importorskip("openjiuwen.harness.subagent_runtime")
+
+from openjiuwen.harness.subagent_runtime.control import SubagentControl
+from openjiuwen.harness.subagent_runtime.models import (
+ ResumeResult,
+ SubagentStatus,
+ SubagentStatusKind,
+)
+from openjiuwen.harness.subagent_runtime.status import StatusChannel
+from openjiuwen.harness.subagent_runtime.status_events import (
+ build_subagent_updated_payload,
+)
+
+from jiuwenswarm.agents.harness.common.tools.subagent_compat import (
+ CompatibleSubagentControl,
+ install_subagent_control_compat_patch,
+)
+
+
+class _RestoredInstance:
+ def __init__(self) -> None:
+ self.status = StatusChannel()
+
+ def agent_status(self) -> SubagentStatus:
+ return self.status.current()
+
+
+async def test_restored_subagent_is_reported_idle_and_accepts_input(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A resumed instance has no queued turn and must be externally idle."""
+ restored = _RestoredInstance()
+ control = object.__new__(CompatibleSubagentControl)
+ setattr(control, "_manager", SimpleNamespace(find=lambda subagent_id: restored))
+
+ async def _resume(_self: SubagentControl, subagent_id: str) -> ResumeResult:
+ assert subagent_id == "sub-1"
+ return ResumeResult(status=SubagentStatus.pending_init(), restored=True)
+
+ monkeypatch.setattr(SubagentControl, "resume", _resume)
+
+ result = await control.resume("sub-1")
+
+ assert result.status.kind is SubagentStatusKind.COMPLETED
+ payload = build_subagent_updated_payload(
+ subagent_id="sub-1",
+ subagent_type="explore_agent",
+ display_name="Explorer",
+ role="Explore code",
+ parent_session_id="parent-1",
+ task_description="Inspect the repository",
+ created_at_ms=1.0,
+ updated_at_ms=2.0,
+ closed_at_ms=None,
+ status=restored.agent_status(),
+ revision=restored.status.version(),
+ )
+ assert payload["status"] == "idle"
+ assert payload["can_send_input"] is True
+ assert payload["needs_resume"] is False
+
+
+def test_install_patch_rebinds_control_factory(monkeypatch: pytest.MonkeyPatch) -> None:
+ """New parent sessions must be created with the compatible control."""
+ from openjiuwen.harness.tools.subagent import _control_registry
+
+ monkeypatch.setattr(_control_registry, "SubagentControl", SubagentControl)
+
+ install_subagent_control_compat_patch()
+
+ assert _control_registry.SubagentControl is CompatibleSubagentControl
diff --git a/tests/unit_tests/agentserver/_run_live_ws.py b/tests/unit_tests/agentserver/_run_live_ws.py
new file mode 100644
index 0000000000..e96c1a2764
--- /dev/null
+++ b/tests/unit_tests/agentserver/_run_live_ws.py
@@ -0,0 +1,35 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+sys.path.insert(0, str(ROOT))
+
+from tests.unit_tests.agentserver.live_ws_harness import LiveWsHarness
+
+HARNESS_DIR = (
+ ROOT / "jiuwenswarm" / "channels" / "web" / "frontend" / "tests" / "live_ws"
+)
+RESULT = HARNESS_DIR / "snapshot.json"
+
+
+def main() -> int:
+ harness = LiveWsHarness(HARNESS_DIR, session_id="session-h")
+ harness.start()
+ print(f"LIVE_WS_URL={harness.http_url}", flush=True)
+ try:
+ snapshot = harness.wait_snapshot(timeout=60.0)
+ RESULT.write_text(json.dumps(snapshot, indent=2), encoding="utf-8")
+ print(f"LIVE_WS_SNAPSHOT={RESULT}", flush=True)
+ print(json.dumps(snapshot), flush=True)
+ return 0
+ finally:
+ harness.close()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/unit_tests/agentserver/live_ws_harness.py b/tests/unit_tests/agentserver/live_ws_harness.py
new file mode 100644
index 0000000000..acf340e558
--- /dev/null
+++ b/tests/unit_tests/agentserver/live_ws_harness.py
@@ -0,0 +1,270 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Stdlib HTTP + WebSocket harness for live-browser subagent store checks."""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import socket
+import threading
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any
+
+_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+
+
+def encode_ws_text(text: str) -> bytes:
+ payload = text.encode("utf-8")
+ header = bytearray([0x81])
+ length = len(payload)
+ if length < 126:
+ header.append(length)
+ elif length < 65536:
+ header.append(126)
+ header.extend(length.to_bytes(2, "big"))
+ else:
+ header.append(127)
+ header.extend(length.to_bytes(8, "big"))
+ return bytes(header) + payload
+
+
+def decode_ws_text(sock: socket.socket) -> str | None:
+ header = sock.recv(2)
+ if len(header) < 2:
+ return None
+ opcode = header[0] & 0x0F
+ masked = bool(header[1] & 0x80)
+ length = header[1] & 0x7F
+ if length == 126:
+ ext = sock.recv(2)
+ if len(ext) < 2:
+ return None
+ length = int.from_bytes(ext, "big")
+ elif length == 127:
+ ext = sock.recv(8)
+ if len(ext) < 8:
+ return None
+ length = int.from_bytes(ext, "big")
+ mask = sock.recv(4) if masked else b""
+ if masked and len(mask) < 4:
+ return None
+ data = b""
+ while len(data) < length:
+ chunk = sock.recv(length - len(data))
+ if not chunk:
+ return None
+ data += chunk
+ if masked:
+ data = bytes(byte ^ mask[index % 4] for index, byte in enumerate(data))
+ if opcode == 0x8:
+ return None
+ return data.decode("utf-8")
+
+
+def accept_ws_key(key: str) -> str:
+ digest = hashlib.sha1((key + _GUID).encode("utf-8")).digest()
+ return base64.b64encode(digest).decode("ascii")
+
+
+def three_child_ws_payloads(session_id: str) -> list[dict[str, Any]]:
+ """Backend-shaped Web payloads for the three-child H sequence."""
+ events: list[dict[str, Any]] = []
+ children = ("sa-a", "sa-b", "sa-c")
+ for index, child_id in enumerate(children):
+ events.append(
+ {
+ "event_type": "chat.subtask_update",
+ "session_id": session_id,
+ "parent_session_id": session_id,
+ "subagent_id": child_id,
+ "display_name": f"Child {child_id}",
+ "status": "running",
+ "legacy_status": "running",
+ "revision": 1,
+ "created_at": 1000 + index,
+ "updated_at": 1000 + index,
+ }
+ )
+ events.append(
+ {
+ "event_type": "chat.subagent_activity",
+ "session_id": session_id,
+ "parent_session_id": session_id,
+ "subagent_id": child_id,
+ "activity_id": f"{child_id}-think",
+ "task_id": f"task-{child_id}",
+ "seq": 1,
+ "kind": "thinking",
+ "summary": f"{child_id} thinking",
+ "at_ms": 1100 + index,
+ }
+ )
+ events.append(
+ {
+ "event_type": "chat.subtask_update",
+ "session_id": session_id,
+ "parent_session_id": session_id,
+ "subagent_id": "sa-a",
+ "display_name": "Child sa-a",
+ "status": "idle",
+ "legacy_status": "completed",
+ "turn_outcome": "completed",
+ "can_send_input": True,
+ "lifecycle": "live",
+ "revision": 2,
+ "created_at": 1000,
+ "updated_at": 2000,
+ }
+ )
+ events.append(
+ {
+ "event_type": "chat.subtask_update",
+ "session_id": session_id,
+ "parent_session_id": session_id,
+ "subagent_id": "sa-c",
+ "display_name": "Child sa-c",
+ "status": "closed",
+ "legacy_status": "error",
+ "closed_reason": "failed",
+ "revision": 2,
+ "created_at": 1002,
+ "updated_at": 2100,
+ }
+ )
+ return events
+
+
+class _HarnessHandler(SimpleHTTPRequestHandler):
+ snapshot: dict[str, Any] | None = None
+ snapshot_event = threading.Event()
+
+ def log_message(self, format: str, *args: object) -> None:
+ del format, args
+
+ def do_POST(self) -> None: # noqa: N802
+ if self.path != "/snapshot":
+ self.send_error(404)
+ return
+ length = int(self.headers.get("Content-Length", "0"))
+ body = self.rfile.read(length)
+ try:
+ payload = json.loads(body.decode("utf-8"))
+ except json.JSONDecodeError:
+ self.send_error(400)
+ return
+ type(self).snapshot = payload
+ type(self).snapshot_event.set()
+ self.send_response(204)
+ self.end_headers()
+
+
+class LiveWsHarness:
+ """Serve the frontend harness and push the three-child WS sequence."""
+
+ def __init__(self, root: Path, session_id: str = "session-h") -> None:
+ self.root = root
+ self.session_id = session_id
+ self.http: ThreadingHTTPServer | None = None
+ self.ws_sock: socket.socket | None = None
+ self._http_thread: threading.Thread | None = None
+ self._ws_thread: threading.Thread | None = None
+ self.ready = threading.Event()
+ self.done = threading.Event()
+ self.client_snapshot: dict[str, Any] | None = None
+
+ @property
+ def http_url(self) -> str:
+ if self.http is None:
+ raise RuntimeError("http server is not started")
+ host, port = self.http.server_address
+ return f"http://127.0.0.1:{port}/index.html?session={self.session_id}&ws=ws://127.0.0.1:{self.ws_port}"
+
+ @property
+ def ws_port(self) -> int:
+ if self.ws_sock is None:
+ raise RuntimeError("ws server is not started")
+ return int(self.ws_sock.getsockname()[1])
+
+ def start(self) -> None:
+ _HarnessHandler.snapshot = None
+ _HarnessHandler.snapshot_event.clear()
+ self.http = ThreadingHTTPServer(
+ ("127.0.0.1", 0),
+ lambda *args, **kwargs: _HarnessHandler(*args, directory=str(self.root), **kwargs),
+ )
+ self._http_thread = threading.Thread(target=self.http.serve_forever, daemon=True)
+ self._http_thread.start()
+ self.ws_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.ws_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.ws_sock.bind(("127.0.0.1", 0))
+ self.ws_sock.listen(1)
+ self._ws_thread = threading.Thread(target=self._serve_ws, daemon=True)
+ self._ws_thread.start()
+
+ def _serve_ws(self) -> None:
+ if self.ws_sock is None:
+ return
+ conn, _addr = self.ws_sock.accept()
+ with conn:
+ request = b""
+ while b"\r\n\r\n" not in request:
+ chunk = conn.recv(4096)
+ if not chunk:
+ return
+ request += chunk
+ headers = {}
+ for line in request.decode("iso-8859-1").split("\r\n")[1:]:
+ if ":" in line:
+ key, value = line.split(":", 1)
+ headers[key.strip().lower()] = value.strip()
+ key = headers.get("sec-websocket-key")
+ if not key:
+ return
+ accept = accept_ws_key(key)
+ response = (
+ "HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ f"Sec-WebSocket-Accept: {accept}\r\n\r\n"
+ )
+ conn.sendall(response.encode("ascii"))
+ first = decode_ws_text(conn)
+ if first is None:
+ return
+ self.ready.set()
+ for payload in three_child_ws_payloads(self.session_id):
+ conn.sendall(encode_ws_text(json.dumps(payload)))
+ conn.sendall(encode_ws_text(json.dumps({"type": "done"})))
+ snapshot_msg = decode_ws_text(conn)
+ if snapshot_msg:
+ try:
+ parsed = json.loads(snapshot_msg)
+ except json.JSONDecodeError:
+ parsed = None
+ if isinstance(parsed, dict) and parsed.get("type") == "snapshot":
+ snap = parsed.get("snapshot")
+ if isinstance(snap, dict):
+ self.client_snapshot = snap
+ self.done.set()
+
+ def wait_snapshot(self, timeout: float = 20.0) -> dict[str, Any]:
+ _HarnessHandler.snapshot_event.wait(timeout)
+ if isinstance(_HarnessHandler.snapshot, dict):
+ return _HarnessHandler.snapshot
+ self.done.wait(timeout)
+ if isinstance(self.client_snapshot, dict):
+ return self.client_snapshot
+ raise TimeoutError("live WS harness did not receive a browser snapshot")
+
+ def close(self) -> None:
+ if self.http is not None:
+ self.http.shutdown()
+ self.http.server_close()
+ if self.ws_sock is not None:
+ self.ws_sock.close()
+
+
+__all__ = ["LiveWsHarness", "three_child_ws_payloads"]
diff --git a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
new file mode 100644
index 0000000000..4d9f98764e
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
@@ -0,0 +1,200 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Loop-detection tests for develop's CircuitBreakerRail.
+
+These cover repeat / ping-pong / unknown-tool / no-progress interrupts.
+They are not the issue 3975 OPEN/HALF_OPEN recovery breaker.
+"""
+
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+
+from openjiuwen.core.single_agent.rail.base import (
+ AgentCallbackContext,
+ ToolCallInputs,
+)
+
+from jiuwenswarm.agents.harness.common.rails.execution_guard.circuit_breaker_rail import (
+ CircuitBreakerConfig,
+ CircuitBreakerRail,
+ ToolCallRecord,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+ _agent_ras_kwargs_from_config,
+)
+
+
+def _record(
+ tool_name: str,
+ args_hash: str,
+ result_hash: str | None = "r1",
+ *,
+ has_error: bool = False,
+) -> ToolCallRecord:
+ return ToolCallRecord(
+ tool_name=tool_name,
+ args_hash=args_hash,
+ result_hash=result_hash,
+ timestamp=time.time(),
+ has_error=has_error,
+ )
+
+
+def _rail(**overrides: int) -> CircuitBreakerRail:
+ return CircuitBreakerRail(
+ CircuitBreakerConfig(
+ warning_threshold=overrides.get("warning_threshold", 3),
+ critical_threshold=overrides.get("critical_threshold", 4),
+ global_breaker_threshold=overrides.get("global_breaker_threshold", 5),
+ unknown_tool_threshold=overrides.get("unknown_tool_threshold", 3),
+ )
+ )
+
+
+def test_generic_repeat_warns_without_force_finish() -> None:
+ rail = _rail(warning_threshold=3, global_breaker_threshold=10)
+ history = [
+ _record("read_file", "a", f"out-{index}")
+ for index in range(3)
+ ]
+ result = rail._detect(history, "read_file", "a")
+ assert result.stuck is True
+ assert result.level == "warning"
+ assert result.detector == "generic_repeat"
+
+
+def test_global_breaker_interrupts_no_progress() -> None:
+ rail = _rail(global_breaker_threshold=5)
+ history = [_record("bash", "cmd", "same") for _ in range(5)]
+ result = rail._detect(history, "bash", "cmd")
+ assert result.stuck is True
+ assert result.level == "critical"
+ assert result.detector == "global_circuit_breaker"
+
+
+def test_unknown_tool_repeat_interrupts_error_streak() -> None:
+ rail = _rail(unknown_tool_threshold=3, global_breaker_threshold=10)
+ history = [
+ _record("missing_tool", "x", f"err-{index}", has_error=True)
+ for index in range(3)
+ ]
+ result = rail._detect(history, "missing_tool", "x")
+ assert result.stuck is True
+ assert result.level == "critical"
+ assert result.detector == "unknown_tool_repeat"
+
+
+def test_ping_pong_critical_when_both_sides_stall() -> None:
+ rail = _rail(critical_threshold=3, warning_threshold=2, global_breaker_threshold=20)
+ history: list[ToolCallRecord] = []
+ for _ in range(3):
+ history.append(_record("read_file", "hash-a", "same-a"))
+ history.append(_record("write_file", "hash-b", "same-b"))
+ result = rail._detect(history, "write_file", "hash-b")
+ assert result.stuck is True
+ assert result.level == "critical"
+ assert result.detector == "ping_pong"
+
+
+def test_cleanup_session_drops_history() -> None:
+ rail = _rail()
+ rail._histories["s1"] = [_record("bash", "a")]
+ rail._histories["s2"] = [_record("bash", "b")]
+ rail.cleanup_session("s1")
+ assert "s1" not in rail._histories
+ assert "s2" in rail._histories
+
+
+def test_detect_is_isolated_per_session_history() -> None:
+ rail = _rail(warning_threshold=3, global_breaker_threshold=10)
+ session_a = [_record("read_file", "a", f"a-{index}") for index in range(3)]
+ session_b = [_record("read_file", "a", "once")]
+ hot = rail._detect(session_a, "read_file", "a")
+ cold = rail._detect(session_b, "read_file", "a")
+ assert hot.detector == "generic_repeat"
+ assert cold.stuck is False
+
+
+async def test_after_tool_call_force_finishes_unknown_tool() -> None:
+ rail = _rail(unknown_tool_threshold=2, global_breaker_threshold=10)
+ rail._histories["s1"] = [_record("ghost", "g", "e1", has_error=True)]
+ ctx = AgentCallbackContext(
+ agent=object(),
+ inputs=ToolCallInputs(
+ tool_call=SimpleNamespace(name="ghost", arguments={"k": 1}),
+ tool_result={"success": False, "error": "not found"},
+ ),
+ extra={"__jiuwenswarm_cb_session_id__": "s1"},
+ )
+ await rail.after_tool_call(ctx)
+ assert ctx.has_force_finish_request is True
+
+
+def test_circuit_breaker_builder_stays_disabled_by_default(monkeypatch) -> None:
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
+
+ monkeypatch.setattr(deep_mod, "get_config", lambda: {"execution_guard": {}})
+ adapter = JiuWenSwarmDeepAdapter()
+ assert adapter._build_circuit_breaker_rail() is None
+
+
+def test_circuit_breaker_builder_rejects_invalid_thresholds(monkeypatch) -> None:
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
+
+ monkeypatch.setattr(
+ deep_mod,
+ "get_config",
+ lambda: {
+ "execution_guard": {
+ "circuit_breaker": {
+ "enabled": True,
+ "warning_threshold": "10",
+ "critical_threshold": 5,
+ }
+ }
+ },
+ )
+ adapter = JiuWenSwarmDeepAdapter()
+ assert adapter._build_circuit_breaker_rail() is None
+
+
+def test_circuit_breaker_builder_coerces_string_thresholds(monkeypatch) -> None:
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
+
+ monkeypatch.setattr(
+ deep_mod,
+ "get_config",
+ lambda: {
+ "execution_guard": {
+ "circuit_breaker": {
+ "enabled": True,
+ "warning_threshold": "10",
+ "critical_threshold": "20",
+ "global_breaker_threshold": "30",
+ "unknown_tool_threshold": "10",
+ }
+ }
+ },
+ )
+ adapter = JiuWenSwarmDeepAdapter()
+ rail = adapter._build_circuit_breaker_rail()
+ assert rail is not None
+ assert rail._config.warning_threshold == 10
+ assert rail._config.critical_threshold == 20
+
+
+def test_dest_agent_ras_passthrough_is_not_disabled() -> None:
+ """dest-stable RAS remains the default loop detector; do not overwrite it."""
+ kwargs = _agent_ras_kwargs_from_config(
+ {
+ "agent_ras": {
+ "enabled": True,
+ "detectors": {"repeat_tool": {"enabled": True}},
+ }
+ }
+ )
+ assert kwargs["agent_ras"]["enabled"] is True
+ assert kwargs["agent_ras"]["detectors"]["repeat_tool"]["enabled"] is True
diff --git a/tests/unit_tests/agentserver/rails/test_progressive_tool_inherit_flag.py b/tests/unit_tests/agentserver/rails/test_progressive_tool_inherit_flag.py
new file mode 100644
index 0000000000..cba0a5e311
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_progressive_tool_inherit_flag.py
@@ -0,0 +1,71 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Regression guard for ``ProgressiveToolRail.inherit_to_subagents = False``.
+
+ProgressiveToolRail binds ``_deep_agent`` / ``_runtime_agent`` in ``init`` and
+refreshes the deferred-tool cache from that agent's ability_manager. A
+general-purpose subagent inherits parent rails by reference
+(``factory._inject_general_purpose_subagent``). The child's ``init`` then
+rebinds the shared instance and overwrites the cache with the child's
+smaller tool set (no ``subagent_wait``). Parent ``tools_search`` /
+``invoke_tool`` for deferred subagent tools then miss while the child is
+still running.
+
+``inherit_to_subagents = False`` opts the rail out at factory injection.
+This test locks the swarm-side half: the flag value as declared in source.
+It reads the module via ``ast`` — NOT importing it — so it runs in CI
+gates where the openjiuwen dependency may be unavailable.
+
+Removing the flag (or flipping to True) silently re-exposes the rebind bug.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[4]
+RAIL_PATH = (
+ ROOT
+ / "jiuwenswarm"
+ / "agents"
+ / "harness"
+ / "common"
+ / "rails"
+ / "progressive_tool_rail.py"
+)
+
+
+def _find_class_assignments(source: str, class_name: str) -> dict[str, ast.AST]:
+ """Return ``{attr_name: value_node}`` for top-level assigns in a class."""
+ tree = ast.parse(source, filename=str(RAIL_PATH))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ClassDef) and node.name == class_name:
+ assigns: dict[str, ast.AST] = {}
+ for stmt in node.body:
+ if (
+ isinstance(stmt, ast.Assign)
+ and len(stmt.targets) == 1
+ and isinstance(stmt.targets[0], ast.Name)
+ ):
+ assigns[stmt.targets[0].id] = stmt.value
+ return assigns
+ return {}
+
+
+def test_inherit_to_subagents_is_false():
+ """Flag must stay False — guards against accidental deletion/flipping."""
+ assert RAIL_PATH.is_file(), f"rail source not found: {RAIL_PATH}"
+ source = RAIL_PATH.read_text(encoding="utf-8")
+ assigns = _find_class_assignments(source, "ProgressiveToolRail")
+
+ assert "inherit_to_subagents" in assigns, (
+ "ProgressiveToolRail must declare inherit_to_subagents = False; "
+ "removing the flag silently re-exposes the subagent-rebind bug "
+ "(child init rebinds _deep_agent → deferred cache loses "
+ "subagent_wait → parent invoke_tool reports 未注册)"
+ )
+ value = assigns["inherit_to_subagents"]
+ assert ast.dump(value) == ast.dump(
+ ast.parse("False", mode="eval").body
+ ), "ProgressiveToolRail.inherit_to_subagents must be the literal False"
diff --git a/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py b/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py
new file mode 100644
index 0000000000..e663d29eac
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py
@@ -0,0 +1,255 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Contract tests for ToolResultErrorDetector.
+
+The detector's own docstring invites any module to import and reuse it, so
+its behaviour is a shared contract rather than a private helper of
+CircuitBreakerRail. Different consumers can want opposite things from it: a
+circuit breaker counting consecutive failures of one tool must not fire on a
+healthy result, while a rail that holds a task open until a required tool has
+succeeded must not read a failure as success.
+
+An unrecognised shape resolves to "no error", which is conservative for a
+consumer that only wants to avoid false positives and dangerous for one that
+must not miss a failure. That asymmetry is why every tool contract the
+detector is expected to understand is pinned here rather than left to
+whichever rail happens to exercise it.
+
+Adding a tool that signals failure in a bare string means registering its
+marker via ``ToolResultErrorDetector.register_plain_error_prefix`` from the
+feature's own module -- not editing ``_PLAIN_ERROR_PREFIXES``. That tuple
+stays generic; only ``[ERROR]:``, the project-wide tool-failure convention,
+belongs in it.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.rails.execution_guard.circuit_breaker_rail import (
+ ToolResultErrorDetector as Detector,
+)
+
+
+class _Result:
+ """A tool result object exposing success/data/error attributes."""
+
+ def __init__(self, success: bool, data=None, error=None) -> None:
+ self.success = success
+ self.data = data
+ self.error = error
+
+
+# ---------------------------------------------------------------------------
+# Failures the detector must recognise
+# ---------------------------------------------------------------------------
+
+FAILURES = [
+ pytest.param({"success": False, "error": "boom"}, id="dict-success-false"),
+ pytest.param({"is_error": True}, id="dict-is-error"),
+ pytest.param({"isError": "true"}, id="dict-isError-string"),
+ pytest.param({"status": "failed"}, id="dict-status-failed"),
+ pytest.param({"result_type": "error"}, id="dict-result-type"),
+ pytest.param({"error": "something went wrong"}, id="dict-error-field"),
+ pytest.param({"data": {"success": False}}, id="dict-nested-data"),
+ # mcp_exec_command: a completed command that exited non-zero.
+ pytest.param(
+ json.dumps({"command": "git log", "exit_code": 128, "stdout": "",
+ "stderr": "fatal: Out of memory, realloc failed"}),
+ id="json-exit-code",
+ ),
+ pytest.param({"returncode": 1}, id="dict-returncode"),
+ # Repr of a result object, as it reaches the session history.
+ pytest.param("success=False data={'content': 'x'} error='boom'", id="repr-false"),
+ # mcp_exec_command: the paths that never produce an exit code.
+ pytest.param("[ERROR]: command timed out after 300s.", id="shell-timeout"),
+ pytest.param("[ERROR]: command failed to start: No such file", id="shell-spawn"),
+ pytest.param("[ERROR]: command execution failed: boom", id="shell-exec"),
+ pytest.param("[ERROR]: background command failed: nope", id="shell-background"),
+ # The same convention from other tool modules.
+ pytest.param("[ERROR]: query cannot be empty.", id="search-empty-query"),
+ pytest.param("[ERROR]: failed to fetch webpage: timeout", id="web-fetch-failed"),
+ pytest.param("[ERROR]: read_pdf failed: boom", id="pdf-failed"),
+ pytest.param(_Result(False, error="boom"), id="object-success-false"),
+]
+
+
[email protected]("value", FAILURES)
+def test_failures_are_recognised(value) -> None:
+ assert Detector.has_error(value) is True
+
+
+# ---------------------------------------------------------------------------
+# Successes the detector must not misread
+# ---------------------------------------------------------------------------
+
+SUCCESSES = [
+ pytest.param({"success": True, "data": {"content": "ok"}}, id="dict-success-true"),
+ pytest.param({"status": "ok"}, id="dict-status-ok"),
+ pytest.param({"error": None}, id="dict-error-none"),
+ pytest.param({"error": "none"}, id="dict-error-literal-none"),
+ pytest.param(
+ json.dumps({"command": "git log", "exit_code": 0, "stdout": "d4c3e32a",
+ "stderr": ""}),
+ id="json-exit-zero",
+ ),
+ pytest.param("success=True data={'content': 'ok'} error=None", id="repr-true"),
+ # mcp_free_search on success: bare prose, no envelope, no marker.
+ pytest.param(
+ "Free search results (DuckDuckGo) for: circuit breaker\n"
+ "1. Circuit breaker pattern\n https://example.invalid/cb",
+ id="search-plain-success",
+ ),
+ # wiki_query on success: the model's answer, returned bare. Nothing in
+ # its shape separates it from arbitrary prose, which is exactly why a
+ # plain-string convention has to be a marker no success can start with.
+ pytest.param(
+ "The retry budget is consumed per tool, not per session.",
+ id="wiki-plain-success",
+ ),
+ pytest.param(_Result(True, data={"content": "ok"}), id="object-success-true"),
+]
+
+
[email protected]("value", SUCCESSES)
+def test_successes_are_not_flagged(value) -> None:
+ assert Detector.has_error(value) is False
+
+
+# ---------------------------------------------------------------------------
+# Shapes the detector cannot classify
+# ---------------------------------------------------------------------------
+
+UNCLASSIFIABLE = [
+ pytest.param(None, id="none"),
+ pytest.param("", id="empty-string"),
+ pytest.param("plain prose with no contract", id="free-text"),
+ pytest.param("{not json", id="broken-json"),
+]
+
+
[email protected]("value", UNCLASSIFIABLE)
+def test_unclassifiable_shapes_claim_neither(value) -> None:
+ """Neither an error nor an explicit success, and the consequences differ.
+
+ A consumer that only wants to avoid false positives reads "not an error"
+ and declines to count the call -- conservative, and it will not interrupt
+ a run spuriously.
+
+ A consumer that must not miss a failure reads the same value as
+ satisfied, because its rule is `if not errored`. That is not an oversight
+ to be tightened later: several tools return a bare string on success --
+ `wiki_query` returns the model's answer, `mcp_free_search` returns a
+ formatted result list -- so a gate that demanded explicit success would
+ reject every one of them.
+
+ The cost is real and worth stating plainly. A tool that signals failure
+ in free text opens the gate for such a consumer. That is exactly the
+ failure mode `_PLAIN_ERROR_PREFIXES` and `register_plain_error_prefix`
+ exist to close: for any tool whose failure is a bare string, a registered
+ marker is the only thing standing between a rejection and a task marked
+ complete.
+ """
+ assert Detector.has_error(value) is False
+ assert Detector.has_explicit_success(value) is False
+
+
+# ---------------------------------------------------------------------------
+# has_explicit_success is narrower than "not an error"
+# ---------------------------------------------------------------------------
+
+
+def test_explicit_success_requires_the_success_field() -> None:
+ assert Detector.has_explicit_success({"success": True}) is True
+ assert Detector.has_explicit_success({"status": "ok"}) is False
+ assert Detector.has_explicit_success("Free search results for: anything") is False
+
+
+def test_a_success_field_beats_a_nonzero_exit_code() -> None:
+ """An explicit success wins over the exit-code heuristic."""
+ assert Detector.has_error({"success": True, "exit_code": 1}) is False
+
+
+def test_plain_error_prefix_is_matched_case_insensitively() -> None:
+ assert Detector.has_error("[error]: command timed out after 300s.") is True
+
+
+def test_a_prefix_must_start_the_string() -> None:
+ """A mention inside prose is not a failure signal."""
+ assert Detector.has_error(
+ "The tool replied [ERROR]: earlier, but this run succeeded."
+ ) is False
+
+
+# ---------------------------------------------------------------------------
+# A deliberate non-match
+# ---------------------------------------------------------------------------
+
+WIKI_FAILURES = [
+ pytest.param("Error: Query cannot be empty.", id="wiki-error-colon"),
+ pytest.param("Error querying wiki: connection refused", id="wiki-error-querying"),
+ pytest.param("Wiki Query Error: boom", id="wiki-error-suffix"),
+]
+
+
[email protected]("value", WIKI_FAILURES)
+def test_bare_error_prose_is_not_matched(value) -> None:
+ """`wiki_tools` signals failure in prose, and that stays unrecognised.
+
+ Three different shapes appear in one file, and the common part is the word
+ "Error" in ordinary prose. Adding it as a prefix would flag any tool whose
+ successful output begins with that word, so the detector deliberately does
+ not match it.
+
+ This is a decision, not an oversight. The fix belongs in the tools:
+ converge those returns on the project's `[ERROR]:` convention, and they
+ are covered by the existing entry with no change here. Teaching this
+ detector every dialect is what produced the gap it was written to close.
+ """
+ assert Detector.has_error(value) is False
+
+
+# ---------------------------------------------------------------------------
+# register_plain_error_prefix: feature-owned markers, without editing the rail
+# ---------------------------------------------------------------------------
+
+
+def _clean_registered_prefixes():
+ """Isolate a test's registrations from every other test in the suite."""
+ saved = set(Detector._extra_plain_error_prefixes)
+ try:
+ yield
+ finally:
+ Detector._extra_plain_error_prefixes.clear()
+ Detector._extra_plain_error_prefixes.update(saved)
+
+
+def test_registered_prefix_is_recognised(_clean_registered_prefixes) -> None:
+ """A feature can teach the detector its own bare-string convention.
+
+ A tool whose failure contract is a bare string of its own -- rather than
+ the project-wide `[ERROR]:` -- registers that marker from its own module.
+ Nothing feature-specific has to be added to the rail for it to be counted.
+ """
+ assert Detector.has_error("EXAMPLE_TOOL_ERROR: unknown snapshot id.") is False
+
+ Detector.register_plain_error_prefix("EXAMPLE_TOOL_ERROR:")
+
+ assert Detector.has_error(
+ "EXAMPLE_TOOL_ERROR: unknown snapshot id. Correct the payload and "
+ "call the tool again."
+ ) is True
+
+
+def test_registered_prefix_is_matched_case_insensitively(_clean_registered_prefixes) -> None:
+ Detector.register_plain_error_prefix("my_tool_error:")
+ assert Detector.has_error("My_Tool_Error: boom") is True
+
+
+def test_registering_a_blank_prefix_is_a_no_op(_clean_registered_prefixes) -> None:
+ before = set(Detector._extra_plain_error_prefixes)
+ Detector.register_plain_error_prefix(" ")
+ assert Detector._extra_plain_error_prefixes == before
diff --git a/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py b/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py
index b4f6deb531..babbfbc53d 100644
--- a/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py
+++ b/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py
@@ -312,6 +312,56 @@ async def test_cleanup_session_runtime_rejects_retained_session_state() -> None:
)
+async def test_release_subagent_runtime_uses_existing_agent_adapter() -> None:
+ """Ported from develop e3ee2dec test_agent_manager_session_cleanup.py.
+
+ Origin: 移植. Dest AgentManager already exposes this facade; the
+ develop tests were missed when Commit 5 landed.
+ """
+ calls: list[tuple[str, str]] = []
+
+ class Adapter:
+ async def release_subagent_runtime_for_session(
+ self,
+ session_id: str,
+ *,
+ reason: str,
+ ) -> None:
+ calls.append((session_id, reason))
+
+ async def apply_sandbox_runtime_patch(self) -> None:
+ return None
+
+ class Agent:
+ def __init__(self) -> None:
+ self._adapter = Adapter()
+
+ manager = AgentManager()
+ manager.agents["web"] = {"agent::": Agent()}
+ released = await manager.release_subagent_runtime_for_session(
+ channel_id="web",
+ session_id="delete-session",
+ reason="session_deleted",
+ )
+ assert released is True
+ assert calls == [("delete-session", "session_deleted")]
+
+
+async def test_release_subagent_runtime_is_noop_without_existing_adapter() -> None:
+ """Ported from develop e3ee2dec test_agent_manager_session_cleanup.py.
+
+ Origin: 移植.
+ """
+ manager = AgentManager()
+ released = await manager.release_subagent_runtime_for_session(
+ channel_id="web",
+ session_id="missing-session",
+ )
+ assert released is False
+
+
@pytest.mark.asyncio
async def test_create_session_cron_channel_uses_path_safe_prefix() -> None:
from jiuwenswarm.server.runtime.prompt_attachment_loader import sanitize_session_id
diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.py
index fbb58b4c6a..5e40ba2004 100644
--- a/tests/unit_tests/agentserver/test_agentserver_modes.py
+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py
@@ -1931,7 +1931,7 @@ def test_deep_adapter_build_agent_rails_adds_ask_user_for_agent_modes(monkeypatc
monkeypatch.setattr(adapter, "_build_security_rail", lambda: None)
monkeypatch.setattr(adapter, "_build_heartbeat_rail", lambda: None)
monkeypatch.setattr(adapter, "_build_avatar_rail", lambda: None)
- monkeypatch.setattr(adapter, "_build_subagent_rail", lambda: None)
+ monkeypatch.setattr(adapter, "_build_subagent_rail", lambda **_kwargs: None)
monkeypatch.setattr(adapter, "_build_skill_rail", lambda **_kwargs: None)
monkeypatch.setattr(adapter, "_build_skill_retrieval_prompt_rail", lambda: None)
monkeypatch.setattr(adapter, "_build_symphony_orchestration_rail", lambda: orchestration_rail)
diff --git a/tests/unit_tests/agentserver/test_debug_trace.py b/tests/unit_tests/agentserver/test_debug_trace.py
index 5e04eeefa8..0c7739d336 100644
--- a/tests/unit_tests/agentserver/test_debug_trace.py
+++ b/tests/unit_tests/agentserver/test_debug_trace.py
@@ -12,6 +12,8 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any
+import pytest
+
from jiuwenswarm.server.runtime.debug_trace import (
DebugTraceLogger,
resolve_debug_trace_settings,
@@ -799,6 +801,41 @@ class TestSubagentCapture:
lg.end_run(status="ok")
lg.flush()
+ def test_invoke_subagent_with_trace_uses_session_id_fallback(self, tmp_path):
+ from jiuwenswarm.server.runtime.debug_trace import invoke_subagent_with_trace
+ from jiuwenswarm.server.runtime.debug_trace.context import (
+ register_debug_trace_logger,
+ unregister_debug_trace_logger,
+ )
+
+ lg = _logger(tmp_path, session_id="sid-parent")
+ lg.start_run()
+ register_debug_trace_logger("sid-parent", 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=None,
+ session_id="sid-parent",
+ source_label="subagent:builtin:explore_agent",
+ ))
+ finally:
+ unregister_debug_trace_logger("sid-parent")
+ lg.end_run(status="ok")
+ lg.flush()
+ assert captured.get("session") is None
+ assert "subagent start" in _read(lg)
+
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,
@@ -871,3 +908,178 @@ class TestSubagentCapture:
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
+ mode = getattr(TaskTool, "debug_trace_patch_mode", None)
+ assert mode in {"dispatch_only", "unsupported_sdk"}
+
+ def test_task_tool_source_label_prefers_card_name(self):
+ from types import SimpleNamespace
+
+ from jiuwenswarm.server.runtime.debug_trace.task_tool_patch import (
+ _subagent_source_label,
+ )
+
+ named = SimpleNamespace(card=SimpleNamespace(name="explore_agent", id="card-id"))
+ assert _subagent_source_label(named) == "subagent:builtin:explore_agent"
+ id_only = SimpleNamespace(card=SimpleNamespace(id="browser_agent"))
+ assert _subagent_source_label(id_only) == "subagent:builtin:browser_agent"
+ assert _subagent_source_label(SimpleNamespace()) == "subagent:builtin:unknown"
+
+ def test_task_tool_patch_forwards_sdk_session(self, monkeypatch):
+ from jiuwenswarm.server.runtime.debug_trace.task_tool_patch import (
+ _wrap_invoke_subagent,
+ )
+
+ forwarded: dict[str, Any] = {}
+ captured: dict[str, Any] = {}
+
+ async def original_dispatch(
+ self, subagent, inputs, *, parent_session_id, session=None,
+ ):
+ forwarded["sdk"] = {
+ "parent_session_id": parent_session_id,
+ "session": session,
+ "inputs": inputs,
+ }
+ return "from-sdk"
+
+ async def fake_capture(
+ subagent, *, inputs, session, source_label, session_id=None,
+ ):
+ captured["trace"] = {
+ "session": session,
+ "session_id": session_id,
+ "source_label": source_label,
+ "inputs": inputs,
+ }
+ return {"output": "from-trace"}
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.debug_trace.invoke_subagent_with_trace",
+ fake_capture,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.debug_trace.get_debug_trace_logger",
+ lambda: None,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.debug_trace.context.get_debug_trace_logger_for_session",
+ lambda _sid: None,
+ )
+
+ parent = SimpleNamespace(name="parent-session")
+ wrapped = _wrap_invoke_subagent(original_dispatch)
+ result = asyncio.run(wrapped(
+ None,
+ SimpleNamespace(card=SimpleNamespace(name="explore_agent")),
+ {"query": "q"},
+ parent_session_id="sid-parent",
+ session=parent,
+ ))
+ assert result == "from-sdk"
+ assert forwarded["sdk"]["session"] is parent
+ assert forwarded["sdk"]["parent_session_id"] == "sid-parent"
+
+ class _CaptureOn:
+ def captures_subagent_flow(self):
+ return True
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.debug_trace.get_debug_trace_logger",
+ lambda: _CaptureOn(),
+ )
+ result = asyncio.run(wrapped(
+ None,
+ SimpleNamespace(card=SimpleNamespace(name="explore_agent")),
+ {"query": "q"},
+ parent_session_id="sid-parent",
+ session=parent,
+ ))
+ assert result == {"output": "from-trace"}
+ assert captured["trace"]["session"] is parent
+ assert captured["trace"]["session_id"] == "sid-parent"
+ assert captured["trace"]["source_label"] == "subagent:builtin:explore_agent"
+
+ def test_task_tool_dump_file_golden_matches_dispatch_sections(self, tmp_path):
+ """Origin: 自拟 §6.I. Dump-file golden after a real TaskTool.invoke.
+
+ Not a projection-payload check. The dest debug logger writes the
+ same section order the UI dump file uses.
+ """
+ from openjiuwen.core.foundation.tool import ToolCard
+ from openjiuwen.core.session.agent import Session
+ from openjiuwen.harness.tools.subagent.task_tool import TaskTool
+
+ from jiuwenswarm.server.runtime.debug_trace import (
+ reset_debug_trace_logger,
+ set_debug_trace_logger,
+ )
+ from jiuwenswarm.server.runtime.debug_trace.task_tool_patch import (
+ apply_task_tool_debug_patch,
+ )
+
+ apply_task_tool_debug_patch()
+ if getattr(TaskTool, "debug_trace_patch_mode", None) == "unsupported_sdk":
+ pytest.skip("current SDK has no _invoke_subagent hook")
+
+ lg = _logger(tmp_path, session_id="dump-parent")
+ lg.start_run(input_text="explore the repo")
+ token = set_debug_trace_logger(lg)
+
+ class FakeSub:
+ card = SimpleNamespace(name="explore_agent", id="explore")
+
+ async def invoke(self, inputs, session=None):
+ del inputs, session
+ return {"output": "should-not-happen"}
+
+ async def stream(self, inputs, session=None):
+ del inputs, session
+ yield _chunk("llm_output", {"content": "hello "})
+ yield _chunk("llm_output", {"content": "world"})
+ yield _chunk("answer", {"output": "hello world", "result_type": "answer"})
+
+ tool = TaskTool(
+ card=ToolCard(id="task_tool", name="task_tool", description="task"),
+ parent_agent=SimpleNamespace(create_subagent=lambda *_a, **_k: FakeSub()),
+ )
+ try:
+ result = asyncio.run(
+ tool.invoke(
+ {
+ "subagent_type": "explore_agent",
+ "task_description": "explore the repo",
+ },
+ session=Session(session_id="dump-parent"),
+ )
+ )
+ finally:
+ reset_debug_trace_logger(token)
+ assert result.success is True
+ assert result.data["output"] == "hello world"
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert lg._path.name == "dump-code-dump-parent.txt"
+ assert [line for line in out.splitlines() if line.startswith("==========")] == [
+ "========== run start ==========",
+ "========== subagent start ==========",
+ "========== subagent end ==========",
+ "========== run end ==========",
+ ]
+ assert "source=subagent:builtin:explore_agent" in out
+ assert "prompt=explore the repo" in out
+ assert "hello world" in out
+ assert "should-not-happen" not in out
+
+ def test_task_tool_patch_marks_unsupported_sdk_without_behavior_change(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()
+ mode = getattr(TaskTool, "debug_trace_patch_mode", None)
+ if mode != "unsupported_sdk":
+ pytest.skip("current SDK already exposes _invoke_subagent")
+ assert TaskTool.invoke.__module__ == "openjiuwen.harness.tools.subagent.task_tool"
+ assert getattr(TaskTool, "_invoke_subagent", None) is None
diff --git a/tests/unit_tests/agentserver/test_deep_adapter_hot_reload_subagent_inherits_parent_env.py b/tests/unit_tests/agentserver/test_deep_adapter_hot_reload_subagent_inherits_parent_env.py
index 9c6f9a66d3..6b2dfca0e1 100644
--- a/tests/unit_tests/agentserver/test_deep_adapter_hot_reload_subagent_inherits_parent_env.py
+++ b/tests/unit_tests/agentserver/test_deep_adapter_hot_reload_subagent_inherits_parent_env.py
@@ -103,3 +103,55 @@ def test_hot_reload_injected_spec_carries_parent_workspace_and_sys_operation(
"mint a fresh LOCAL SysOperation for the general-purpose subagent"
)
assert getattr(spec.workspace, "root_path", None) == str(tmp_path)
+
+
+def test_deep_adapter_live_hot_switch_rebuilds_child_spec_on_same_adapter(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ """Same Deep adapter, no rebuild: switch workspace then remake config.
+
+ The new general-purpose spec must use the new root and the same
+ sys_operation instance the parent still carries.
+ """
+ old_root = tmp_path / "old"
+ new_root = tmp_path / "new"
+ old_root.mkdir()
+ new_root.mkdir()
+
+ adapter = JiuWenSwarmDeepAdapter()
+ sentinel_sysop = object()
+ adapter._sys_operation = sentinel_sysop
+ adapter._workspace_dir = str(old_root)
+
+ monkeypatch.setattr(interface_module, "get_config", lambda *a, **k: _CFG)
+ adapter._sync_browser_runtime_environment = lambda *a, **k: None # type: ignore[assignment]
+ adapter._browser_runtime_enabled = lambda *a, **k: False # type: ignore[assignment]
+
+ first = adapter._make_deep_agent_config(
+ model=object(),
+ config=_CFG,
+ config_base=_CFG,
+ agent_card=AgentCard(name="main_agent", description="verify"),
+ tool_cards=[],
+ rails=None,
+ )
+ first_spec = _general_purpose_spec(first)
+ assert getattr(first_spec.workspace, "root_path", None) == str(old_root)
+ assert first.sys_operation is sentinel_sysop
+
+ adapter._workspace_dir = str(new_root)
+ second = adapter._make_deep_agent_config(
+ model=object(),
+ config=_CFG,
+ config_base=_CFG,
+ agent_card=AgentCard(name="main_agent", description="verify"),
+ tool_cards=[],
+ rails=None,
+ )
+ second_spec = _general_purpose_spec(second)
+ assert second is not first
+ assert getattr(second.workspace, "root_path", None) == str(new_root)
+ assert getattr(second_spec.workspace, "root_path", None) == str(new_root)
+ assert second.sys_operation is sentinel_sysop
+ assert second_spec.sys_operation is sentinel_sysop
+ assert second_spec.workspace is second.workspace
diff --git a/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py b/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py
index 7912a2bfca..617c3c6e04 100644
--- a/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py
+++ b/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py
@@ -20,6 +20,8 @@ def _make_adapter(**state: object) -> JiuWenSwarmDeepAdapter:
class _IdleChildAdapter:
def __init__(self) -> None:
self.cleaned = False
+ self.released: list[tuple[str, str]] = []
+ self._instance = None
@staticmethod
def is_session_active(_session_id: str) -> bool:
@@ -29,6 +31,17 @@ class _IdleChildAdapter:
def is_deep_agent_executing_for_session(_session_id: str) -> bool:
return False
+ async def stop_interaction(self) -> None:
+ return None
+
+ async def release_subagent_runtime_for_session(
+ self,
+ session_id: str,
+ *,
+ reason: str = "",
+ ) -> None:
+ self.released.append((session_id, reason))
+
async def cleanup(self) -> None:
self.cleaned = True
diff --git a/tests/unit_tests/agentserver/test_multi_session_notify.py b/tests/unit_tests/agentserver/test_multi_session_notify.py
new file mode 100644
index 0000000000..adeb539c11
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_multi_session_notify.py
@@ -0,0 +1,142 @@
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.tools.multi_session_toolkits import (
+ MultiSessionToolkit,
+ SessionTask,
+ Status,
+)
+from jiuwenswarm.server.runtime.agent_manager import AgentManager
+
+
+def _completed_toolkit() -> MultiSessionToolkit:
+ toolkit = object.__new__(MultiSessionToolkit)
+ toolkit.session_id = "parent-session"
+ toolkit.channel_id = "web"
+ toolkit.request_id = "request-1"
+ toolkit._agent_manager = None
+ toolkit.sessions = [
+ SessionTask(
+ session_id="child-session",
+ description="Summarize the result",
+ status=Status.COMPLETED,
+ result="done",
+ )
+ ]
+ toolkit._send_task_notification = AsyncMock()
+ return toolkit
+
+
+async def test_completed_batch_uses_current_agent_manager_contract() -> None:
+ toolkit = _completed_toolkit()
+ manager = MagicMock(spec=AgentManager)
+ manager.get_agent_nowait.return_value = None
+ server = MagicMock()
+ server.get_agent_manager.return_value = manager
+ server.get_agent.return_value = None
+
+ with (
+ patch(
+ "jiuwenswarm.server.agent_ws_server.AgentWebSocketServer.current_instance",
+ return_value=server,
+ ),
+ patch(
+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",
+ new=AsyncMock(return_value=True),
+ ) as push,
+ ):
+ await toolkit.notify("child-session", Status.COMPLETED, result="done")
+
+ manager.get_agent_nowait.assert_called_once_with("web")
+ server.get_agent.assert_called_once()
+ push.assert_awaited_once()
+
+
+async def test_completed_batch_uses_injected_agent_manager() -> None:
+ toolkit = _completed_toolkit()
+ manager = MagicMock(spec=AgentManager)
+ manager.get_agent_nowait.return_value = None
+ toolkit._agent_manager = manager
+
+ with (
+ patch(
+ "jiuwenswarm.server.agent_ws_server.AgentWebSocketServer.current_instance",
+ ) as current_instance,
+ patch(
+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",
+ new=AsyncMock(return_value=True),
+ ) as push,
+ ):
+ await toolkit.notify("child-session", Status.COMPLETED, result="done")
+
+ current_instance.assert_not_called()
+ manager.get_agent_nowait.assert_called_once_with("web")
+ push.assert_awaited_once()
+
+
+async def test_notify_without_runtime_host_keeps_local_summary() -> None:
+ toolkit = _completed_toolkit()
+
+ with (
+ patch(
+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",
+ new=AsyncMock(return_value=False),
+ ) as push,
+ patch(
+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.logger"
+ ) as toolkit_logger,
+ ):
+ await toolkit.notify("child-session", Status.COMPLETED, result="done")
+
+ push.assert_awaited_once()
+ info_messages = [
+ " ".join(str(part) for part in call.args)
+ for call in toolkit_logger.info.call_args_list
+ ]
+ assert any("Runtime push host unavailable" in message for message in info_messages)
+ assert any("parent-session" in message for message in info_messages)
+
+
+async def test_agent_server_push_host_lifecycle_out_of_order(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jiuwenswarm.runtime import host_services
+ from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+
+ monkeypatch.setattr(host_services, "_runtime_push_handler", None)
+ monkeypatch.setattr(host_services, "_runtime_push_handlers", [])
+
+ first = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ first._runtime_push_handler = None
+ first._previous_runtime_push_handler = None
+
+ async def first_push(_msg: dict) -> int:
+ return 1
+
+ first.send_push = first_push # type: ignore[method-assign]
+
+ second = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ second._runtime_push_handler = None
+ second._previous_runtime_push_handler = None
+ calls: list[str] = []
+
+ async def second_push(_msg: dict) -> int:
+ calls.append("second")
+ return 1
+
+ second.send_push = second_push # type: ignore[method-assign]
+
+ first._install_runtime_push_host()
+ second._install_runtime_push_host()
+ first._restore_runtime_push_host()
+ assert await host_services.send_runtime_push({"value": 1}) is True
+ assert calls == ["second"]
+ second._restore_runtime_push_host()
+ assert await host_services.send_runtime_push({"value": 2}) is False
diff --git a/tests/unit_tests/agentserver/test_openjiuwen_rail_compat.py b/tests/unit_tests/agentserver/test_openjiuwen_rail_compat.py
index 9a9f836862..092517e21e 100644
--- a/tests/unit_tests/agentserver/test_openjiuwen_rail_compat.py
+++ b/tests/unit_tests/agentserver/test_openjiuwen_rail_compat.py
@@ -2,8 +2,11 @@
"""Compatibility for older openjiuwen evolution-rail constructors."""
+import asyncio
+
from jiuwenswarm.common.openjiuwen_rail_compat import (
_wrap_init_for_extra_kwargs,
+ call_attach_output,
filter_unsupported_kwargs,
install_evolution_rail_kwargs_compat,
)
@@ -21,6 +24,34 @@ def test_filter_drops_signal_trigger_when_constructor_lacks_it():
assert filtered == {"review_trigger": False}
+def test_filter_drops_unknown_dataclass_field():
+ """Official DeepAgentConfig is a dataclass without VAR_KEYWORD."""
+ from dataclasses import dataclass
+
+ @dataclass
+ class _LegacyDeepAgentConfig:
+ enable_task_loop: bool = False
+
+ filtered = filter_unsupported_kwargs(
+ _LegacyDeepAgentConfig.__init__,
+ {"enable_task_loop": True, "enable_subagent_runtime": True},
+ )
+ assert filtered == {"enable_task_loop": True}
+ _LegacyDeepAgentConfig(**filtered)
+
+
+def test_filter_keeps_kwargs_when_func_has_var_keyword():
+ """Official create_deep_agent still has **config_kwargs; do not use it as the gate."""
+ def _factory(*, model: str, **config_kwargs):
+ del model, config_kwargs
+
+ filtered = filter_unsupported_kwargs(
+ _factory,
+ {"enable_subagent_runtime": True},
+ )
+ assert filtered == {"enable_subagent_runtime": True}
+
+
def test_wrapped_rail_init_ignores_unknown_kwargs():
class DummyRail:
def __init__(self, *, review_trigger=None):
@@ -31,6 +62,28 @@ def test_wrapped_rail_init_ignores_unknown_kwargs():
assert rail.review_trigger is False
+def test_call_attach_output_drops_steal_on_legacy_sdk():
+ class Legacy:
+ async def attach_output(self):
+ return "ok"
+
+ assert asyncio.run(call_attach_output(Legacy(), steal=True)) == "ok"
+
+
+def test_call_attach_output_passes_steal_when_supported():
+ class Newer:
+ def __init__(self):
+ self.seen = None
+
+ async def attach_output(self, *, steal=False):
+ self.seen = steal
+ return "ok"
+
+ inst = Newer()
+ assert asyncio.run(call_attach_output(inst, steal=True)) == "ok"
+ assert inst.seen is True
+
+
def test_install_evolution_rail_kwargs_compat_is_idempotent():
install_evolution_rail_kwargs_compat()
install_evolution_rail_kwargs_compat()
diff --git a/tests/unit_tests/agentserver/test_statusline_setup_subagent.py b/tests/unit_tests/agentserver/test_statusline_setup_subagent.py
new file mode 100644
index 0000000000..26561371c7
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_statusline_setup_subagent.py
@@ -0,0 +1,209 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Registration tests for the built-in statusline-setup subagent."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+from openjiuwen.harness.rails import SysOperationRail
+
+from jiuwenswarm.agents.swarm.config_specs import build_member_subagent_specs
+from jiuwenswarm.agents.swarm import registry
+from jiuwenswarm.server.runtime.agent_adapter.interface_code import (
+ JiuwenSwarmCodeAdapter,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
+from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (
+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
+ STATUSLINE_SETUP_AGENT_TYPE,
+)
+from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService
+
+
+def test_statusline_setup_is_a_builtin_agent_definition(tmp_path):
+ definition = AgentConfigService(tmp_path).get_agent(STATUSLINE_SETUP_AGENT_TYPE)
+
+ assert definition is not None
+ assert definition.source == "builtin"
+ assert definition.tools == ["Read", "Write", "Edit", "Bash"]
+ assert "statusline-setup subagent" in definition.prompt
+
+
+def test_single_agent_runtime_registers_statusline_setup(monkeypatch, tmp_path):
+ adapter = JiuWenSwarmDeepAdapter()
+ adapter._workspace_dir = str(tmp_path)
+ adapter._sys_operation = None
+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
+
+ subagents, _ = adapter._build_configured_subagents(
+ MagicMock(),
+ {
+ "max_iterations": 20,
+ "subagents": {
+ STATUSLINE_SETUP_AGENT_TYPE: {
+ "enabled": True,
+ "max_iterations": 9,
+ }
+ },
+ },
+ {},
+ )
+
+ assert subagents is not None
+ assert [spec.agent_card.name for spec in subagents] == [STATUSLINE_SETUP_AGENT_TYPE]
+ assert subagents[0].max_iterations == 9
+ assert subagents[0].enable_task_loop is False
+ assert any(isinstance(rail, SysOperationRail) for rail in subagents[0].rails)
+
+
+def test_single_agent_runtime_does_not_register_when_disabled(monkeypatch, tmp_path):
+ adapter = JiuWenSwarmDeepAdapter()
+ adapter._workspace_dir = str(tmp_path)
+ adapter._sys_operation = None
+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
+
+ subagents, _ = adapter._build_configured_subagents(
+ MagicMock(),
+ {"subagents": {STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False}}},
+ {},
+ )
+
+ assert subagents is None
+
+
+def test_code_runtime_registers_statusline_setup_by_default(monkeypatch, tmp_path):
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._workspace_dir = str(tmp_path)
+ adapter._project_dir = str(tmp_path)
+ adapter._coding_memory_rail = None
+ sys_operation = MagicMock()
+ adapter._sys_operation = sys_operation
+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
+
+ subagents, _ = adapter._build_configured_subagents(
+ MagicMock(),
+ {"max_iterations": 20},
+ {},
+ )
+
+ assert subagents is not None
+ assert [spec.agent_card.name for spec in subagents] == [
+ STATUSLINE_SETUP_AGENT_TYPE,
+ "explore_agent",
+ "plan_agent",
+ ]
+ statusline_spec = subagents[0]
+ assert statusline_spec.max_iterations == DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS
+ assert statusline_spec.enable_task_loop is False
+ assert statusline_spec.sys_operation is sys_operation
+ assert statusline_spec.workspace == str(tmp_path)
+
+
+def test_code_runtime_honors_explicit_statusline_disable(monkeypatch, tmp_path):
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._workspace_dir = str(tmp_path)
+ adapter._project_dir = str(tmp_path)
+ adapter._coding_memory_rail = None
+ adapter._sys_operation = MagicMock()
+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
+
+ subagents, _ = adapter._build_configured_subagents(
+ MagicMock(),
+ {"subagents": {STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False}}},
+ {},
+ )
+
+ assert subagents is not None
+ assert [spec.agent_card.name for spec in subagents] == [
+ "explore_agent",
+ "plan_agent",
+ ]
+
+
+def test_code_runtime_honors_explicit_statusline_iteration_budget(
+ monkeypatch,
+ tmp_path,
+):
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._workspace_dir = str(tmp_path)
+ adapter._project_dir = str(tmp_path)
+ adapter._coding_memory_rail = None
+ adapter._sys_operation = MagicMock()
+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
+
+ subagents, _ = adapter._build_configured_subagents(
+ MagicMock(),
+ {
+ "max_iterations": 100,
+ "subagents": {
+ STATUSLINE_SETUP_AGENT_TYPE: {
+ "enabled": True,
+ "max_iterations": 7,
+ }
+ },
+ },
+ {},
+ )
+
+ assert subagents is not None
+ assert subagents[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE
+ assert subagents[0].max_iterations == 7
+
+
+def test_team_member_runtime_registers_same_builtin_subagent():
+ specs = build_member_subagent_specs(
+ {
+ "react": {
+ "subagents": {
+ STATUSLINE_SETUP_AGENT_TYPE: {"enabled": True},
+ }
+ }
+ },
+ "team",
+ "leader",
+ )
+
+ assert len(specs) == 1
+ assert specs[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE
+ assert specs[0].factory_name == registry.STATUSLINE_SETUP_AGENT
+ assert (
+ specs[0].factory_kwargs["max_iterations"]
+ == DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS
+ )
+
+
+def test_team_member_runtime_honors_statusline_disable_and_iteration_budget():
+ disabled_specs = build_member_subagent_specs(
+ {
+ "react": {
+ "subagents": {
+ STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False},
+ }
+ }
+ },
+ "team",
+ "leader",
+ )
+ assert disabled_specs == []
+
+ configured_specs = build_member_subagent_specs(
+ {
+ "react": {
+ "max_iterations": 100,
+ "subagents": {
+ STATUSLINE_SETUP_AGENT_TYPE: {
+ "enabled": True,
+ "max_iterations": 7,
+ },
+ },
+ }
+ },
+ "team",
+ "leader",
+ )
+ assert len(configured_specs) == 1
+ assert configured_specs[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE
+ assert configured_specs[0].factory_kwargs["max_iterations"] == 7
diff --git a/tests/unit_tests/agentserver/test_subagent_history_routing.py b/tests/unit_tests/agentserver/test_subagent_history_routing.py
index 9cfa09c41c..8123e782ba 100644
--- a/tests/unit_tests/agentserver/test_subagent_history_routing.py
+++ b/tests/unit_tests/agentserver/test_subagent_history_routing.py
@@ -4,22 +4,20 @@
from __future__ import annotations
+from jiuwenswarm.common.schema.message import EventType
+from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import (
+ _WEB_FULL_PAYLOAD_EVENT_TYPES,
+)
from jiuwenswarm.server.runtime.session import session_history, session_metadata
def test_subagent_history_writes_use_dedicated_child_bucket(monkeypatch) -> None:
- persisted: list[dict] = []
+ persisted: list[tuple[str, str, list[dict], str | None]] = []
metadata_updates: list[dict] = []
monkeypatch.setattr(
session_history,
- "_ensure_flush_thread_started",
- lambda: None,
- )
- monkeypatch.setattr(session_history, "_flush_on_request_switch", lambda *_args: None)
- monkeypatch.setattr(
- session_history,
- "_route_event",
- lambda _sid, item, _event_type, _root: persisted.append(item),
+ "_batch_write_subagent_items",
+ lambda sid, child_id, items, root: persisted.append((sid, child_id, items, root)),
)
monkeypatch.setattr(
session_metadata,
@@ -41,8 +39,78 @@ def test_subagent_history_writes_use_dedicated_child_bucket(monkeypatch) -> None
)
assert len(persisted) == 1
- assert persisted[0]["session_id"] == "parent-session"
- assert persisted[0]["subagent_id"] == "subagent-1"
- assert persisted[0]["mode"] == "subagent"
- assert metadata_updates[0]["session_id"] == "parent-session"
- assert metadata_updates[0]["mode"] is None
+ sid, child_id, items, _root = persisted[0]
+ assert sid == "parent-session"
+ assert child_id == "subagent-1"
+ assert len(items) == 1
+ assert items[0]["session_id"] == "parent-session"
+ assert items[0]["subagent_id"] == "subagent-1"
+ assert items[0]["mode"] == "subagent"
+ assert metadata_updates == []
+
+
+def test_subagent_rows_go_under_parent_subagents_dir(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
+ session_history.append_history_record(
+ session_id="parent1",
+ request_id="r-parent",
+ channel_id="web",
+ role="user",
+ content="hello",
+ timestamp=1.0,
+ )
+ session_history.append_history_record(
+ session_id="parent1",
+ subagent_id="sa-explore-1",
+ request_id="sa-explore-1:1",
+ channel_id="subagent",
+ role="assistant",
+ content="child note",
+ timestamp=2.0,
+ event_type="chat.delta",
+ mode="subagent",
+ extra={"parent_session_id": "parent1"},
+ )
+
+ parent_rows = session_history.load_history_records("parent1")
+ child_rows = session_history.load_history_records(
+ "parent1",
+ subagent_id="sa-explore-1",
+ )
+ assert [row.get("content") for row in parent_rows] == ["hello"]
+ assert any(row.get("content") == "child note" for row in child_rows)
+ child_path, error = session_history.resolve_subagent_history_path(
+ "parent1",
+ "sa-explore-1",
+ create=False,
+ )
+ assert error is None
+ assert child_path is not None
+ assert child_path.exists()
+ assert "subagents" in child_path.parts
+ assert not session_history.history_exists("parent1", subagent_id="../escape")
+
+
+def test_empty_subagent_activity_is_persistable(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
+ session_history.append_history_record(
+ session_id="parent1",
+ subagent_id="sa-1",
+ request_id="sa-1:activity:turn:1",
+ channel_id="subagent",
+ role="assistant",
+ content="",
+ timestamp=3.0,
+ event_type="chat.subagent_activity",
+ extra={"subagent_activity": {"subagent_id": "sa-1", "summary": ""}},
+ mode="subagent",
+ )
+ rows = session_history.load_history_records("parent1", subagent_id="sa-1")
+ assert len(rows) == 1
+ assert rows[0]["event_type"] == "chat.subagent_activity"
+
+
+def test_web_allowlist_includes_subagent_activity() -> None:
+ assert EventType.CHAT_SUBAGENT_ACTIVITY.value == "chat.subagent_activity"
+ assert "chat.subagent_activity" in _WEB_FULL_PAYLOAD_EVENT_TYPES
+ assert "task.start" in _WEB_FULL_PAYLOAD_EVENT_TYPES
diff --git a/tests/unit_tests/agentserver/test_subagent_live_ws_browser.py b/tests/unit_tests/agentserver/test_subagent_live_ws_browser.py
new file mode 100644
index 0000000000..661e713573
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_subagent_live_ws_browser.py
@@ -0,0 +1,80 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""§6.H live browser WebSocket: backend-shaped events into the real store."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from tests.unit_tests.agentserver.live_ws_harness import LiveWsHarness
+
+_FRONTEND = Path(__file__).resolve().parents[3] / "jiuwenswarm" / "channels" / "web" / "frontend"
+_HARNESS_DIR = _FRONTEND / "tests" / "live_ws"
+
+
+def _bundle_browser_store() -> None:
+ npx = shutil.which("npx")
+ if npx is None:
+ pytest.skip("npx is required to bundle the live WS browser harness")
+ commands = [
+ [
+ npx,
+ "--yes",
+ "esbuild",
+ "src/stores/subagentStore.ts",
+ "--bundle",
+ "--platform=browser",
+ "--format=esm",
+ f"--outfile={_HARNESS_DIR / 'subagentStore.browser.mjs'}",
+ ],
+ [
+ npx,
+ "--yes",
+ "esbuild",
+ "src/features/subagent/subagentNormalizer.ts",
+ "--bundle",
+ "--platform=browser",
+ "--format=esm",
+ f"--outfile={_HARNESS_DIR / 'subagentNormalizer.browser.mjs'}",
+ ],
+ ]
+ for command in commands:
+ try:
+ subprocess.run(command, cwd=_FRONTEND, check=True)
+ except (FileNotFoundError, subprocess.CalledProcessError) as exc:
+ pytest.skip(f"live WS browser harness bundle unavailable: {exc}")
+
+
+def _assert_three_child_snapshot(snapshot: dict) -> None:
+ assert snapshot["ids"] == ["sa-a", "sa-b", "sa-c"]
+ assert snapshot["a"] == "idle"
+ assert snapshot["b"] == "running"
+ assert snapshot["c"] == "closed"
+ assert snapshot["activitiesA"] == 1
+
+
+def test_live_ws_three_child_browser() -> None:
+ """Open the harness page, push the H sequence over WS, read the store snapshot."""
+ _bundle_browser_store()
+ harness = LiveWsHarness(_HARNESS_DIR, session_id="session-h")
+ harness.start()
+ try:
+ try:
+ from playwright.sync_api import sync_playwright
+ except ImportError:
+ pytest.importorskip("playwright.sync_api")
+ return
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless=True)
+ page = browser.new_page()
+ page.goto(harness.http_url, wait_until="domcontentloaded")
+ page.wait_for_selector("[data-ready='1']", timeout=20000)
+ browser.close()
+ snapshot = harness.wait_snapshot(timeout=5.0)
+ _assert_three_child_snapshot(snapshot)
+ finally:
+ harness.close()
diff --git a/tests/unit_tests/agentserver/test_subagent_runtime_acceptance.py b/tests/unit_tests/agentserver/test_subagent_runtime_acceptance.py
new file mode 100644
index 0000000000..50278e3bc5
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_subagent_runtime_acceptance.py
@@ -0,0 +1,598 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""§6 missing-test fill-in for issue 3975.
+
+Origin labels (also recorded in 迁移方案.md §6.1.1):
+
+- 移植: D lives in ``test_agent_manager_session_cleanup.py`` (develop
+ ``e3ee2dec``). This module does not duplicate those two functions.
+- 自拟: every test in this file. develop has no functions with these names.
+ B is spawn→TTL evict→real resume→second input. C is two real TaskTool
+ invokes with the flag off. Neither uses a live LLM.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
+from jiuwenswarm.server.runtime.agent_adapter.subagent_stream import (
+ clear_all_subagent_progress_batches,
+ persist_subagent_transcript_message,
+ resolve_subagent_parallel_fields,
+)
+from jiuwenswarm.server.runtime.session import session_history
+
+
+def _make_adapter(**state: object) -> JiuWenSwarmDeepAdapter:
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ for name, value in state.items():
+ setattr(adapter, name, value)
+ return adapter
+
+
+class _IdleChildAdapter:
+ def __init__(self) -> None:
+ self.cleaned = False
+ self.released: list[tuple[str, str]] = []
+ self._instance = None
+
+ @staticmethod
+ def is_session_active(_session_id: str) -> bool:
+ return False
+
+ @staticmethod
+ def is_deep_agent_executing_for_session(_session_id: str) -> bool:
+ return False
+
+ async def stop_interaction(self) -> None:
+ return None
+
+ async def release_subagent_runtime_for_session(
+ self,
+ session_id: str,
+ *,
+ reason: str = "",
+ ) -> None:
+ self.released.append((session_id, reason))
+
+ async def cleanup(self) -> None:
+ self.cleaned = True
+
+
+class _FailingCleanupChildAdapter(_IdleChildAdapter):
+ async def cleanup(self) -> None:
+ raise RuntimeError("child cleanup failed")
+
+
+@dataclass
+class _MockSubagentSession:
+ pre_run_calls: int = 0
+ close_stream_calls: int = 0
+ commit_calls: int = 0
+
+ async def pre_run(self, **kwargs: object) -> None:
+ del kwargs
+ self.pre_run_calls += 1
+
+ async def close_stream(self) -> None:
+ self.close_stream_calls += 1
+
+ async def commit(self) -> None:
+ self.commit_calls += 1
+
+
+@dataclass
+class _MockSubagent:
+ output: str = "first-turn"
+ card: SimpleNamespace = field(
+ default_factory=lambda: SimpleNamespace(id="sub-card", name="explore")
+ )
+
+ async def stream(
+ self,
+ inputs: dict[str, str],
+ *,
+ session: _MockSubagentSession,
+ ) -> AsyncIterator[dict[str, object]]:
+ del inputs, session
+ yield {"type": "llm_output", "payload": {"content": self.output}}
+ yield {
+ "type": "answer",
+ "payload": {"output": self.output, "result_type": "answer"},
+ }
+
+
+class _ControlParent:
+ def __init__(self, output: str = "first-turn") -> None:
+ self.output = output
+ self.created: list[_MockSubagent] = []
+
+ def create_subagent(
+ self,
+ subagent_type: str,
+ subsession_id: str,
+ browser_capabilities: list[str] | None = None,
+ ) -> _MockSubagent:
+ del subagent_type, subsession_id, browser_capabilities
+ agent = _MockSubagent(output=self.output)
+ self.created.append(agent)
+ return agent
+
+
+class _SeededCheckpointer:
+ def __init__(self) -> None:
+ self.ids: set[str] = set()
+
+ def seed(self, session_id: str) -> None:
+ self.ids.add(session_id)
+
+ async def session_exists(self, session_id: str) -> bool:
+ return session_id in self.ids
+
+
+async def _wait_spawned(control: Any, subagent_id: str) -> Any:
+ from openjiuwen.harness.subagent_runtime.models import SubagentStatusKind
+
+ deadline = asyncio.get_running_loop().time() + 2.0
+ while asyncio.get_running_loop().time() < deadline:
+ instance = control._manager.find(subagent_id)
+ if instance is not None and instance.agent_status().kind is SubagentStatusKind.COMPLETED:
+ return instance
+ await asyncio.sleep(0.01)
+ raise TimeoutError(f"subagent {subagent_id} did not finish a turn")
+
+
+def _parent_with_child(session_id: str, child: _IdleChildAdapter) -> JiuWenSwarmDeepAdapter:
+ return _make_adapter(
+ _is_session_scoped_adapter=False,
+ _session_adapters={session_id: child},
+ _session_adapter_locks={session_id: asyncio.Lock()},
+ _session_adapter_last_used={session_id: 0.0},
+ _session_adapter_versions={session_id: 1},
+ _session_adapter_reload_failures={},
+ SESSION_ADAPTER_EVICT_BATCH_SIZE=8,
+ SESSION_ADAPTER_IDLE_TTL_SEC=1.0,
+ )
+
+
+async def test_subagent_resume_after_adapter_eviction_preserves_context(
+ tmp_path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Origin: 自拟 §6.B. Connected spawn → persist → TTL evict → resume → send_input.
+
+ No live LLM. Uses CompatibleSubagentControl.spawn/close/hydrate/resume/send_input
+ and dest Adapter TTL. Does not monkeypatch ``SubagentControl.resume``.
+ """
+ pytest.importorskip("openjiuwen.harness.subagent_runtime")
+ from openjiuwen.core.session.agent import Session
+ from openjiuwen.harness.subagent_runtime.config import SubagentRuntimeConfig
+ from openjiuwen.harness.subagent_runtime.models import SubagentStatusKind
+ from openjiuwen.harness.subagent_runtime.persistence import read_subagent_bucket
+ from openjiuwen.harness.subagent_runtime.status_events import (
+ build_subagent_updated_payload,
+ )
+ from jiuwenswarm.agents.harness.common.tools.subagent_compat import (
+ CompatibleSubagentControl,
+ )
+
+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
+ parent_session_id = "parent-evict-1"
+ parent_session = Session(session_id=parent_session_id)
+ parent_session.commit = lambda: None
+ checkpointer = _SeededCheckpointer()
+ runtime_config = SubagentRuntimeConfig(
+ enable_activity_stream=False,
+ enable_transcript_stream=False,
+ )
+ old_control = None
+ new_control = None
+ try:
+ with patch(
+ "openjiuwen.harness.subagent_runtime.session_manager.create_agent_session",
+ side_effect=lambda **kwargs: _MockSubagentSession(),
+ ), patch(
+ "openjiuwen.harness.subagent_runtime.control.WAIT_TIMEOUT_MS_MIN",
+ 100,
+ ), patch(
+ "openjiuwen.harness.subagent_runtime.control.CheckpointerFactory.get_checkpointer",
+ return_value=checkpointer,
+ ):
+ old_parent = _ControlParent(output="first-turn")
+ old_control = CompatibleSubagentControl(
+ old_parent,
+ parent_session_id,
+ config=runtime_config,
+ parent_session=parent_session,
+ )
+ spawned = await old_control.spawn("explore", "first question")
+ subagent_id = spawned.subagent_id
+ persist_subagent_transcript_message(
+ {
+ "parent_session_id": parent_session_id,
+ "subagent_id": subagent_id,
+ "content": "child context before eviction",
+ "role": "assistant",
+ "seq": 1,
+ }
+ )
+ first = await _wait_spawned(old_control, subagent_id)
+ waited = await old_control.wait([subagent_id], timeout_ms=500)
+ assert waited.timed_out is False
+ assert first.last_output == "first-turn"
+ checkpointer.seed(subagent_id)
+ await old_control.close(subagent_id, reason="manual")
+ await old_control.persist()
+ assert int(old_control.capacity().get("used", 0)) == 0
+ assert subagent_id in read_subagent_bucket(parent_session)["records"]
+
+ old_adapter = _IdleChildAdapter()
+ old_adapter._instance = SimpleNamespace(
+ _subagent_controls={parent_session_id: old_control},
+ )
+ parent = _parent_with_child(parent_session_id, old_adapter)
+ await parent._evict_idle_session_adapters()
+ assert old_adapter.cleaned is True
+ assert parent._session_adapters == {}
+ rows = session_history.load_history_records(
+ parent_session_id,
+ subagent_id=subagent_id,
+ )
+ assert any(
+ row.get("content") == "child context before eviction" for row in rows
+ )
+ assert session_history.load_history_records(parent_session_id) == []
+
+ new_parent = _ControlParent(output="second-turn")
+ new_control = CompatibleSubagentControl(
+ new_parent,
+ parent_session_id,
+ config=runtime_config,
+ parent_session=parent_session,
+ )
+ assert new_control is not old_control
+ new_control.hydrate()
+ result = await new_control.resume(subagent_id)
+ assert result.restored is True
+ assert result.status.kind is SubagentStatusKind.COMPLETED
+ payload = build_subagent_updated_payload(
+ subagent_id=subagent_id,
+ subagent_type="explore",
+ display_name="Explorer",
+ role="researcher",
+ parent_session_id=parent_session_id,
+ task_description="first question",
+ created_at_ms=1.0,
+ updated_at_ms=2.0,
+ closed_at_ms=None,
+ status=result.status,
+ revision=1,
+ )
+ assert payload["status"] == "idle"
+ assert payload["can_send_input"] is True
+ assert payload["subagent_id"] == subagent_id
+
+ await new_control.send_input(subagent_id, "second question")
+ second = await _wait_spawned(new_control, subagent_id)
+ second_wait = await new_control.wait([subagent_id], timeout_ms=500)
+ assert second_wait.timed_out is False
+ assert second.last_output == "second-turn"
+ assert second.subagent_id == subagent_id
+
+ new_adapter = _IdleChildAdapter()
+ new_adapter._instance = SimpleNamespace(
+ _subagent_controls={parent_session_id: new_control},
+ )
+ parent._session_adapters[parent_session_id] = new_adapter
+ assert new_adapter is not old_adapter
+ assert parent._session_adapters[parent_session_id] is not old_adapter
+ finally:
+ for control in (old_control, new_control):
+ if control is None:
+ continue
+ for sid in list(control._manager.list_ids()):
+ await control._manager.remove(sid, reason="test_cleanup")
+ control._registry.release(sid)
+
+
+async def test_idle_eviction_skips_live_subagent_runtime() -> None:
+ """Origin: 自拟 §6.B/L TTL. Live children must block Adapter eviction."""
+ child = _IdleChildAdapter()
+ child._instance = SimpleNamespace(
+ _subagent_controls={
+ "sess-live": SimpleNamespace(capacity=lambda: {"used": 2}),
+ }
+ )
+ parent = _parent_with_child("sess-live", child)
+ await parent._evict_idle_session_adapters()
+ assert child.cleaned is False
+ assert parent._session_adapters["sess-live"] is child
+
+
+async def test_flag_off_task_tool_remains_ephemeral_end_to_end(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Origin: 自拟 §6.C. Two real TaskTool.invoke calls with the flag off.
+
+ No model. Flag-off rail.init registers the real task_tool, two invokes
+ create two ephemeral conversation ids, and no persistent control remains.
+ """
+ from openjiuwen.core.session.agent import Session
+ from openjiuwen.harness.rails.subagent import subagent_rail as rail_mod
+ from openjiuwen.harness.tools.subagent.task_tool import TaskTool
+ from jiuwenswarm.agents.harness.common.rails.browser_task_prompt_rail import (
+ BrowserTaskPromptRail,
+ )
+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter as DeepAdapter,
+ )
+
+ persistent_inits: list[str] = []
+ conversation_ids: list[str] = []
+
+ class _FakeSub:
+ card = SimpleNamespace(name="explore_agent", description="explore", id="explore")
+
+ async def invoke(self, inputs: dict[str, str], session: object = None) -> dict[str, str]:
+ del session
+ conversation_ids.append(str(inputs.get("conversation_id") or ""))
+ return {"output": f"done-{len(conversation_ids)}"}
+
+ def _persistent_tools(**kwargs: object) -> list[object]:
+ del kwargs
+ persistent_inits.append("subagent_spawn")
+ return [SimpleNamespace(card=SimpleNamespace(name="subagent_spawn"))]
+
+ if hasattr(rail_mod, "build_subagent_tools"):
+ monkeypatch.setattr(rail_mod, "build_subagent_tools", _persistent_tools)
+
+ registered: list[object] = []
+ parent_agent = SimpleNamespace(
+ create_subagent=lambda *_args, **_kwargs: _FakeSub(),
+ deep_config=SimpleNamespace(
+ subagents=[
+ SimpleNamespace(
+ card=SimpleNamespace(name="explore_agent", description="explore")
+ )
+ ]
+ ),
+ ability_manager=SimpleNamespace(
+ add_ability=lambda card, tool: registered.append((card, tool))
+ ),
+ card=SimpleNamespace(id="parent-agent"),
+ system_prompt_builder=SimpleNamespace(language="en"),
+ )
+
+ adapter = DeepAdapter()
+ off_rail = adapter._build_subagent_rail({})
+ assert isinstance(off_rail, BrowserTaskPromptRail)
+ assert off_rail.enable_subagent_runtime is False
+ off_rail.init(parent_agent)
+ assert persistent_inits == []
+ assert not hasattr(parent_agent, "_subagent_controls")
+ tools = [tool for _card, tool in registered if isinstance(tool, TaskTool)]
+ assert len(tools) == 1
+ tool = tools[0]
+ session = Session(session_id="parent-flag-off")
+ first = await tool.invoke(
+ {"subagent_type": "explore_agent", "task_description": "first"},
+ session=session,
+ )
+ second = await tool.invoke(
+ {"subagent_type": "explore_agent", "task_description": "second"},
+ session=session,
+ )
+ assert first.success is True
+ assert second.success is True
+ assert first.data["output"] == "done-1"
+ assert second.data["output"] == "done-2"
+ assert len(conversation_ids) == 2
+ assert conversation_ids[0] != conversation_ids[1]
+ assert conversation_ids[0].startswith("parent-flag-off_sub_explore_agent_")
+ assert persistent_inits == []
+ assert not hasattr(parent_agent, "_subagent_controls")
+ assert all(getattr(card, "name", "") == "task_tool" for card, _tool in registered)
+
+
+async def test_parent_cleanup_isolates_failing_session_adapter() -> None:
+ """Origin: 自拟 §6.L. One child cleanup exception must not skip siblings."""
+ failing = _FailingCleanupChildAdapter()
+ sibling = _IdleChildAdapter()
+ parent = _make_adapter(
+ _is_session_scoped_adapter=False,
+ _session_adapters={"sess-a": failing, "sess-b": sibling},
+ _session_adapter_locks={},
+ _session_adapter_last_used={},
+ _session_adapter_versions={},
+ _session_adapter_reload_failures={},
+ _instance=None,
+ _memory_reindex_task=None,
+ _a2x_client=None,
+ _retained_sys_operation_ids=[],
+ )
+ await parent.cleanup()
+ assert sibling.cleaned is True
+ assert parent._session_adapters == {}
+
+
+async def test_cancel_session_agent_tasks_gather_isolates_exceptions() -> None:
+ """Origin: 自拟 §6.L. Real asyncio.gather(..., return_exceptions=True)."""
+ adapter = _make_adapter(_session_agent_tasks={})
+
+ async def _boom() -> None:
+ try:
+ await asyncio.sleep(60)
+ except asyncio.CancelledError:
+ raise RuntimeError("task cleanup boom") from None
+
+ async def _quiet() -> None:
+ try:
+ await asyncio.sleep(60)
+ except asyncio.CancelledError:
+ return
+
+ boom_task = asyncio.create_task(_boom())
+ quiet_task = asyncio.create_task(_quiet())
+ adapter._session_agent_tasks["sess-gather"] = {boom_task, quiet_task}
+
+ cancelled = await adapter._cancel_session_agent_tasks("sess-gather")
+ assert cancelled == 2
+ assert boom_task.done() is True
+ assert quiet_task.done() is True
+ assert adapter._session_agent_tasks.get("sess-gather") in (None, set())
+
+
+def test_progress_batches_isolated_across_parent_sessions() -> None:
+ """Origin: 自拟 §6.L. Same child id under two parents must not share a batch."""
+ clear_all_subagent_progress_batches()
+ first = resolve_subagent_parallel_fields(
+ parent_session_id="parent-a",
+ subagent_id="sa-shared-name",
+ legacy_status="starting",
+ )
+ second = resolve_subagent_parallel_fields(
+ parent_session_id="parent-b",
+ subagent_id="sa-shared-name",
+ legacy_status="starting",
+ )
+ assert first == (0, 1, False)
+ assert second == (0, 1, False)
+ third = resolve_subagent_parallel_fields(
+ parent_session_id="parent-a",
+ subagent_id="sa-other",
+ legacy_status="starting",
+ )
+ assert third == (1, 2, True)
+ leftover_b = resolve_subagent_parallel_fields(
+ parent_session_id="parent-b",
+ subagent_id="sa-shared-name",
+ legacy_status="starting",
+ )
+ assert leftover_b == (0, 1, False)
+
+
+async def test_dual_parent_real_spawn_isolates_batches_and_ttl() -> None:
+ """Origin: 自拟 §6.L live. Two parents spawn two children each via gather.
+
+ No live LLM. Real ``CompatibleSubagentControl.spawn`` + wait. Batches and
+ TTL occupancy stay isolated; idle eviction must skip both live parents.
+ """
+ pytest.importorskip("openjiuwen.harness.subagent_runtime")
+ from openjiuwen.core.session.agent import Session
+ from openjiuwen.harness.subagent_runtime.config import SubagentRuntimeConfig
+ from jiuwenswarm.agents.harness.common.tools.subagent_compat import (
+ CompatibleSubagentControl,
+ )
+
+ clear_all_subagent_progress_batches()
+ runtime_config = SubagentRuntimeConfig(
+ enable_activity_stream=False,
+ enable_transcript_stream=False,
+ )
+ controls: list[CompatibleSubagentControl] = []
+
+ async def _spawn_parent(
+ session_id: str,
+ output: str,
+ ) -> tuple[CompatibleSubagentControl, list[str]]:
+ parent_session = Session(session_id=session_id)
+ parent_session.commit = lambda: None
+ control = CompatibleSubagentControl(
+ _ControlParent(output=output),
+ session_id,
+ config=runtime_config,
+ parent_session=parent_session,
+ )
+ controls.append(control)
+
+ async def _one(prompt: str) -> str:
+ spawned = await control.spawn("explore", prompt)
+ resolve_subagent_parallel_fields(
+ parent_session_id=session_id,
+ subagent_id=spawned.subagent_id,
+ legacy_status="starting",
+ )
+ await _wait_spawned(control, spawned.subagent_id)
+ return spawned.subagent_id
+
+ child_ids = await asyncio.gather(_one("q1"), _one("q2"))
+ return control, list(child_ids)
+
+ try:
+ with patch(
+ "openjiuwen.harness.subagent_runtime.session_manager.create_agent_session",
+ side_effect=lambda **kwargs: _MockSubagentSession(),
+ ), patch(
+ "openjiuwen.harness.subagent_runtime.control.WAIT_TIMEOUT_MS_MIN",
+ 100,
+ ):
+ (control_a, ids_a), (control_b, ids_b) = await asyncio.gather(
+ _spawn_parent("parent-l-a", "a-out"),
+ _spawn_parent("parent-l-b", "b-out"),
+ )
+ ids = ids_a + ids_b
+ assert len(set(ids)) == 4
+ leftover_a = resolve_subagent_parallel_fields(
+ parent_session_id="parent-l-a",
+ subagent_id=ids_a[0],
+ legacy_status="starting",
+ )
+ leftover_b = resolve_subagent_parallel_fields(
+ parent_session_id="parent-l-b",
+ subagent_id=ids_b[0],
+ legacy_status="starting",
+ )
+ assert leftover_a[1] == 2
+ assert leftover_b[1] == 2
+ assert leftover_a[2] is True
+ assert leftover_b[2] is True
+ assert int(control_a.capacity().get("used", 0)) >= 1
+ assert int(control_b.capacity().get("used", 0)) >= 1
+
+ child_a = _IdleChildAdapter()
+ child_a._instance = SimpleNamespace(
+ _subagent_controls={"parent-l-a": control_a},
+ )
+ child_b = _IdleChildAdapter()
+ child_b._instance = SimpleNamespace(
+ _subagent_controls={"parent-l-b": control_b},
+ )
+ parent = _make_adapter(
+ _is_session_scoped_adapter=False,
+ _session_adapters={"parent-l-a": child_a, "parent-l-b": child_b},
+ _session_adapter_locks={
+ "parent-l-a": asyncio.Lock(),
+ "parent-l-b": asyncio.Lock(),
+ },
+ _session_adapter_last_used={"parent-l-a": 0.0, "parent-l-b": 0.0},
+ _session_adapter_versions={"parent-l-a": 1, "parent-l-b": 1},
+ _session_adapter_reload_failures={},
+ SESSION_ADAPTER_EVICT_BATCH_SIZE=8,
+ SESSION_ADAPTER_IDLE_TTL_SEC=1.0,
+ )
+ await parent._evict_idle_session_adapters()
+ assert child_a.cleaned is False
+ assert child_b.cleaned is False
+ assert parent._session_adapters["parent-l-a"] is child_a
+ assert parent._session_adapters["parent-l-b"] is child_b
+ finally:
+ for control in controls:
+ for sid in list(control._manager.list_ids()):
+ await control._manager.remove(sid, reason="test_cleanup")
+ control._registry.release(sid)
diff --git a/tests/unit_tests/agentserver/test_subagent_runtime_wiring.py b/tests/unit_tests/agentserver/test_subagent_runtime_wiring.py
new file mode 100644
index 0000000000..837f6ee54e
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_subagent_runtime_wiring.py
@@ -0,0 +1,177 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Persistent subagent runtime wiring (shipped template on; missing key off)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+from jiuwenswarm.agents.harness.common.rails.browser_task_prompt_rail import (
+ BrowserTaskPromptRail,
+)
+from jiuwenswarm.common.config import is_subagent_runtime_enabled
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+ _agent_ras_kwargs_from_config,
+ _optional_enable_subagent_runtime,
+)
+
+
+def test_shipped_template_subagent_runtime_enabled_by_default() -> None:
+ config_path = (
+ Path(__file__).resolve().parents[3]
+ / "jiuwenswarm"
+ / "resources"
+ / "config.yaml"
+ )
+ config = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ assert config["react"]["subagent_runtime"]["enabled"] is True
+ assert is_subagent_runtime_enabled(config) is True
+
+
+def test_is_subagent_runtime_enabled_defaults_off() -> None:
+ assert is_subagent_runtime_enabled({}) is False
+ assert is_subagent_runtime_enabled({"react": {}}) is False
+ assert is_subagent_runtime_enabled({"react": {"subagent_runtime": {}}}) is False
+ assert is_subagent_runtime_enabled(
+ {"react": {"subagent_runtime": {"enabled": False}}}
+ ) is False
+ assert is_subagent_runtime_enabled(
+ {"react": {"subagent_runtime": {"enabled": True}}}
+ ) is True
+
+
+def test_resolve_enable_subagent_runtime_defaults_off() -> None:
+ adapter = JiuWenSwarmDeepAdapter()
+ assert adapter._resolve_enable_subagent_runtime({}) is False
+ assert adapter._resolve_enable_subagent_runtime(
+ {"react": {"subagent_runtime": {"enabled": True}}}
+ ) is True
+
+
+def test_build_subagent_rail_uses_browser_policy_and_stays_off() -> None:
+ adapter = JiuWenSwarmDeepAdapter()
+ rail = adapter._build_subagent_rail({})
+ assert isinstance(rail, BrowserTaskPromptRail)
+ assert rail.enable_subagent_runtime is False
+
+
+def test_session_has_live_subagent_runtime_reads_capacity() -> None:
+ live = SimpleNamespace(
+ _instance=SimpleNamespace(
+ _subagent_controls={
+ "sess-1": SimpleNamespace(capacity=lambda: {"used": 2}),
+ }
+ )
+ )
+ idle = SimpleNamespace(
+ _instance=SimpleNamespace(
+ _subagent_controls={
+ "sess-1": SimpleNamespace(capacity=lambda: {"used": 0}),
+ }
+ )
+ )
+ assert JiuWenSwarmDeepAdapter._session_has_live_subagent_runtime(
+ live, "sess-1"
+ ) is True
+ assert JiuWenSwarmDeepAdapter._session_has_live_subagent_runtime(
+ idle, "sess-1"
+ ) is False
+ assert JiuWenSwarmDeepAdapter._session_has_live_subagent_runtime(
+ SimpleNamespace(_instance=None), "sess-1"
+ ) is False
+
+
+def test_session_has_live_subagent_runtime_fail_closed_when_capacity_raises() -> None:
+ def _boom() -> dict[str, int]:
+ raise RuntimeError("capacity unavailable")
+
+ occupied = SimpleNamespace(
+ _instance=SimpleNamespace(
+ _subagent_controls={
+ "sess-1": SimpleNamespace(capacity=_boom),
+ }
+ )
+ )
+ assert JiuWenSwarmDeepAdapter._session_has_live_subagent_runtime(
+ occupied, "sess-1"
+ ) is True
+
+
+def test_session_has_live_subagent_runtime_missing_controls_is_idle() -> None:
+ """dest-stable SDK and never-spawned parents have no control map."""
+ missing = SimpleNamespace(_instance=SimpleNamespace())
+ invalid = SimpleNamespace(_instance=SimpleNamespace(_subagent_controls="bad"))
+ assert JiuWenSwarmDeepAdapter._session_has_live_subagent_runtime(
+ missing, "sess-1"
+ ) is False
+ assert JiuWenSwarmDeepAdapter._session_has_live_subagent_runtime(
+ invalid, "sess-1"
+ ) is False
+
+
+def test_release_subagent_runtime_clears_progress_batch() -> None:
+ from jiuwenswarm.server.runtime.agent_adapter.subagent_stream import (
+ clear_all_subagent_progress_batches,
+ resolve_subagent_parallel_fields,
+ )
+
+ clear_all_subagent_progress_batches()
+ resolve_subagent_parallel_fields(
+ parent_session_id="sess-1",
+ subagent_id="sa-a",
+ legacy_status="starting",
+ )
+ adapter = JiuWenSwarmDeepAdapter()
+ adapter._instance = None
+ adapter._is_session_scoped_adapter = True
+ adapter._parent_session_id = "sess-1"
+
+ import asyncio
+
+ asyncio.run(adapter.release_subagent_runtime_for_session("sess-1"))
+ again = resolve_subagent_parallel_fields(
+ parent_session_id="sess-1",
+ subagent_id="sa-b",
+ legacy_status="starting",
+ )
+ assert again == (0, 1, False)
+
+
+def test_agent_ras_passthrough_still_enabled() -> None:
+ kwargs = _agent_ras_kwargs_from_config({"agent_ras": {"enabled": True}})
+ assert "agent_ras" in kwargs
+ assert kwargs["agent_ras"] is not False
+
+
+def test_optional_enable_subagent_runtime_follows_deep_agent_config_signature() -> None:
+ """Official pin omits the field; overlay / post-3A SDK keeps it."""
+ from inspect import signature
+
+ from openjiuwen.harness.schema.config import DeepAgentConfig
+
+ got = _optional_enable_subagent_runtime(True)
+ params = signature(DeepAgentConfig.__init__).parameters
+ if "enable_subagent_runtime" in params:
+ assert got == {"enable_subagent_runtime": True}
+ else:
+ assert got == {}
+
+
+def test_optional_enable_subagent_runtime_omits_flag_on_legacy_config(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from dataclasses import dataclass
+
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
+
+ @dataclass
+ class _LegacyDeepAgentConfig:
+ enable_task_loop: bool = False
+
+ monkeypatch.setattr(deep_mod, "DeepAgentConfig", _LegacyDeepAgentConfig)
+ assert deep_mod._optional_enable_subagent_runtime(True) == {}
diff --git a/tests/unit_tests/agentserver/test_subagent_stream_events.py b/tests/unit_tests/agentserver/test_subagent_stream_events.py
new file mode 100644
index 0000000000..356ff04cd3
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_subagent_stream_events.py
@@ -0,0 +1,335 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Native subagent events project beside dest task.* / stream_source_id."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
+from jiuwenswarm.server.runtime.agent_adapter.subagent_stream import (
+ clear_all_subagent_progress_batches,
+ clear_subagent_progress_batch,
+ project_subagent_updated_for_web,
+ resolve_subagent_parallel_fields,
+ try_handle_subagent_chunk,
+)
+from jiuwenswarm.server.runtime.session import session_history
+from jiuwenswarm.server.utils.stream_utils import parse_stream_chunk
+
+
+def setup_function() -> None:
+ clear_all_subagent_progress_batches()
+
+
+def test_parallel_fields_use_dynamic_total() -> None:
+ first = resolve_subagent_parallel_fields(
+ parent_session_id="parent1",
+ subagent_id="sa-a",
+ legacy_status="starting",
+ )
+ second = resolve_subagent_parallel_fields(
+ parent_session_id="parent1",
+ subagent_id="sa-b",
+ legacy_status="starting",
+ )
+ assert first == (0, 1, False)
+ assert second == (1, 2, True)
+ done = resolve_subagent_parallel_fields(
+ parent_session_id="parent1",
+ subagent_id="sa-a",
+ legacy_status="completed",
+ )
+ assert done == (0, 2, True)
+ leftover = resolve_subagent_parallel_fields(
+ parent_session_id="parent1",
+ subagent_id="sa-b",
+ legacy_status="starting",
+ )
+ assert leftover == (0, 1, False)
+
+
+def test_project_keeps_canonical_status() -> None:
+ payload = project_subagent_updated_for_web(
+ {
+ "subagent_id": "sa-1",
+ "parent_session_id": "parent1",
+ "status": "running",
+ "display_name": "Explore",
+ }
+ )
+ assert payload["event_type"] == "chat.subtask_update"
+ assert payload["session_id"] == "parent1"
+ assert payload["status"] == "running"
+ assert payload["legacy_status"] == "starting"
+ assert payload["task_id"] == "sa-1"
+ assert payload["description"] == "Explore"
+ assert payload["total"] >= 1
+
+
+def test_parse_stream_chunk_maps_activity_and_keeps_task_complete() -> None:
+ activity = try_handle_subagent_chunk(
+ "subagent_activity",
+ {
+ "subagent_activity": {
+ "subagent_id": "sa-1",
+ "parent_session_id": "parent1",
+ "summary": "searching",
+ }
+ },
+ )
+ assert activity[0] is True
+ assert activity[1] is not None
+ assert activity[1]["event_type"] == "chat.subagent_activity"
+ assert activity[1]["session_id"] == "parent1"
+
+ task_chunk = SimpleNamespace(
+ type="task.complete",
+ payload={
+ "task_id": "todo:1",
+ "task_content": "done",
+ "status": "completed",
+ },
+ )
+ parsed = JiuWenSwarmDeepAdapter._parse_stream_chunk(task_chunk)
+ assert parsed is not None
+ assert parsed["event_type"] == "task.complete"
+ assert parsed["task_id"] == "todo:1"
+
+
+def test_stream_utils_keeps_stream_source_id_on_activity() -> None:
+ chunk = SimpleNamespace(
+ type="subagent_activity",
+ payload={
+ "subagent_activity": {
+ "subagent_id": "sa-1",
+ "parent_session_id": "parent1",
+ "summary": "x",
+ },
+ "stream_source_id": "skill-turbo-1",
+ },
+ )
+ parsed = parse_stream_chunk(chunk)
+ assert parsed is not None
+ assert parsed["event_type"] == "chat.subagent_activity"
+ assert parsed["stream_source_id"] == "skill-turbo-1"
+
+
+def test_message_chunk_persists_only(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
+ handled, parsed = try_handle_subagent_chunk(
+ "subagent_message",
+ {
+ "subagent_message": {
+ "subagent_id": "sa-1",
+ "parent_session_id": "parent1",
+ "content": "hello child",
+ "role": "assistant",
+ "seq": 3,
+ }
+ },
+ )
+ assert handled is True
+ assert parsed is None
+ rows = session_history.load_history_records("parent1", subagent_id="sa-1")
+ assert any(row.get("content") == "hello child" for row in rows)
+ assert session_history.load_history_records("parent1") == []
+
+
+def test_release_clears_parent_batch() -> None:
+ resolve_subagent_parallel_fields(
+ parent_session_id="parent1",
+ subagent_id="sa-a",
+ legacy_status="starting",
+ )
+ clear_subagent_progress_batch("parent1")
+ again = resolve_subagent_parallel_fields(
+ parent_session_id="parent1",
+ subagent_id="sa-b",
+ legacy_status="starting",
+ )
+ assert again == (0, 1, False)
+
+
+# Origin: 自拟 §6.H. Dest projection contract. Dump-file golden lives in test_debug_trace.
+_SUBAGENT_UPDATED_WEB_GOLDEN = {
+ "event_type": "chat.subtask_update",
+ "subagent_id": "sa-1",
+ "parent_session_id": "parent1",
+ "status": "running",
+ "display_name": "Explore",
+ "session_id": "parent1",
+ "task_id": "sa-1",
+ "description": "Explore",
+ "legacy_status": "starting",
+ "index": 0,
+ "total": 1,
+ "is_parallel": False,
+}
+
+
+def test_subagent_updated_payload_golden() -> None:
+ """Origin: 自拟 §6.H. Projection payload contract beside the WS-shaped sequence."""
+ payload = project_subagent_updated_for_web(
+ {
+ "subagent_id": "sa-1",
+ "parent_session_id": "parent1",
+ "status": "running",
+ "display_name": "Explore",
+ }
+ )
+ assert payload == _SUBAGENT_UPDATED_WEB_GOLDEN
+
+
+def test_subagent_updated_chunk_keeps_dest_task_fields(tmp_path, monkeypatch) -> None:
+ """Origin: 自拟 §6.H. One projected chunk still carries dest task fields."""
+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
+ handled, parsed = try_handle_subagent_chunk(
+ "subagent_updated",
+ {
+ "subagent_updated": {
+ "subagent_id": "sa-1",
+ "parent_session_id": "parent1",
+ "status": "running",
+ "display_name": "Explore",
+ }
+ },
+ )
+ assert handled is True
+ assert parsed is not None
+ assert parsed["event_type"] == "chat.subtask_update"
+ assert parsed["session_id"] == "parent1"
+ assert parsed["task_id"] == "sa-1"
+ assert parsed["legacy_status"] == "starting"
+ assert parsed["status"] == "running"
+ assert "task.start" != parsed["event_type"]
+
+
+def test_subagent_chunk_sequence_replays_three_children_and_isolates_sessions(
+ tmp_path,
+ monkeypatch,
+) -> None:
+ """Origin: 自拟 §6.H. WS-shaped chunk sequence + history + session isolation.
+
+ Not a live WebSocket. Feeds the dest projector the same event kinds the
+ frontend store replay uses: running, activity, idle/completed, failed.
+ """
+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
+ parent = "parent-h"
+ other = "parent-other"
+ children = ("sa-a", "sa-b", "sa-c")
+
+ emitted: list[dict] = []
+ for index, child_id in enumerate(children):
+ handled, running = try_handle_subagent_chunk(
+ "subagent_updated",
+ {
+ "subagent_updated": {
+ "subagent_id": child_id,
+ "parent_session_id": parent,
+ "status": "running",
+ "display_name": f"Child {child_id}",
+ "revision": 1,
+ "updated_at_ms": 1000 + index,
+ }
+ },
+ )
+ assert handled is True
+ assert running is not None
+ assert running["task_id"] == child_id
+ emitted.append(running)
+ handled, activity = try_handle_subagent_chunk(
+ "subagent_activity",
+ {
+ "subagent_activity": {
+ "subagent_id": child_id,
+ "parent_session_id": parent,
+ "task_id": f"task-{child_id}",
+ "seq": 1,
+ "kind": "thinking",
+ "summary": f"thinking {child_id}",
+ "at_ms": 1100 + index,
+ }
+ },
+ )
+ assert handled is True
+ assert activity is not None
+ assert activity["event_type"] == "chat.subagent_activity"
+ emitted.append(activity)
+
+ handled, idle = try_handle_subagent_chunk(
+ "subagent_updated",
+ {
+ "subagent_updated": {
+ "subagent_id": "sa-a",
+ "parent_session_id": parent,
+ "status": "idle",
+ "display_name": "Child sa-a",
+ "revision": 2,
+ "updated_at_ms": 2000,
+ }
+ },
+ )
+ assert handled is True
+ assert idle is not None
+ assert idle["legacy_status"] == "completed"
+ handled, failed = try_handle_subagent_chunk(
+ "subagent_updated",
+ {
+ "subagent_updated": {
+ "subagent_id": "sa-c",
+ "parent_session_id": parent,
+ "status": "closed",
+ "display_name": "Child sa-c",
+ "revision": 2,
+ "updated_at_ms": 2100,
+ "closed_reason": "failed",
+ }
+ },
+ )
+ assert handled is True
+ assert failed is not None
+ assert failed["legacy_status"] == "error"
+
+ handled, other_running = try_handle_subagent_chunk(
+ "subagent_updated",
+ {
+ "subagent_updated": {
+ "subagent_id": "sa-a",
+ "parent_session_id": other,
+ "status": "running",
+ "display_name": "Other child",
+ "revision": 1,
+ "updated_at_ms": 3000,
+ }
+ },
+ )
+ assert handled is True
+ assert other_running is not None
+
+ for child_id in children:
+ rows = session_history.load_history_records(parent, subagent_id=child_id)
+ assert rows
+ assert any(row.get("event_type") == "chat.subtask_update" for row in rows)
+ assert session_history.load_history_records(parent) == []
+ parent_a = session_history.load_history_records(parent, subagent_id="sa-a")
+ other_rows = session_history.load_history_records(other, subagent_id="sa-a")
+ assert parent_a
+ assert other_rows
+ assert parent_a != other_rows
+ leftover = resolve_subagent_parallel_fields(
+ parent_session_id=parent,
+ subagent_id="sa-b",
+ legacy_status="starting",
+ )
+ assert leftover == (0, 1, False)
+ other_batch = resolve_subagent_parallel_fields(
+ parent_session_id=other,
+ subagent_id="sa-a",
+ legacy_status="starting",
+ )
+ assert other_batch == (0, 1, False)
+ assert any(item.get("subagent_id") == "sa-a" for item in emitted)
+ assert any(item.get("subagent_id") == "sa-c" for item in emitted)
diff --git a/tests/unit_tests/agentserver/test_subagent_sys_operation_inheritance.py b/tests/unit_tests/agentserver/test_subagent_sys_operation_inheritance.py
new file mode 100644
index 0000000000..4172e322c9
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_subagent_sys_operation_inheritance.py
@@ -0,0 +1,289 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Subagents must share the parent agent's SysOperation.
+
+The SysOperation is the filesystem boundary the user configured (local full
+access / jiuwenbox sandbox / allow-deny paths). When a subagent spec leaves it
+unset, ``DeepAgent.create_subagent`` mints a fresh ``OperationMode.LOCAL``
+SysOperation with ``restrict_to_sandbox`` derived from
+``spec.restrict_to_work_dir or deep_config.restrict_to_work_dir`` — which both
+locks the subagent inside the workspace in local mode and lets it escape onto
+the host in sandbox mode.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+from openjiuwen.harness.schema.config import SubAgentConfig
+from openjiuwen.harness.workspace.workspace import Workspace
+
+from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import AgentTool, CodeAgentRail
+from jiuwenswarm.server.runtime.agent_adapter.interface_code import (
+ JiuwenSwarmCodeAdapter,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+ _agent_def_to_subagent_config,
+)
+
+
+def _spec_by_name(specs: list, name: str) -> SubAgentConfig | None:
+ """Return the spec whose agent card carries ``name``."""
+ for spec in specs:
+ if isinstance(spec, SubAgentConfig) and spec.agent_card.name == name:
+ return spec
+ return None
+
+
+def _make_agent_definition(name: str):
+ """Build a minimal custom agent definition."""
+ from jiuwenswarm.server.runtime.agent_config_service import AgentDefinition
+
+ return AgentDefinition(
+ name=name,
+ description="test",
+ prompt="You are a test agent.",
+ source="project",
+ tools=["*"],
+ when_to_use="testing",
+ )
+
+
+def test_code_subagents_inherit_parent_sys_operation(tmp_path):
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._workspace_dir = str(tmp_path)
+ adapter._project_dir = str(tmp_path)
+ adapter._coding_memory_rail = None
+ sys_operation = MagicMock()
+ adapter._sys_operation = sys_operation
+
+ config = {"subagents": {"code_agent": {"enabled": True}}, "max_iterations": 15}
+ with patch.object(adapter, "_browser_runtime_enabled", return_value=False):
+ subagents, _ = adapter._build_configured_subagents(MagicMock(), config, {})
+
+ assert subagents is not None
+ statusline_spec = _spec_by_name(subagents, "statusline-setup")
+ plan_spec = _spec_by_name(subagents, "plan_agent")
+ code_spec = _spec_by_name(subagents, "code_agent")
+ assert statusline_spec is not None
+ assert plan_spec is not None
+ assert code_spec is not None
+ # create_subagent only honours spec.sys_operation when spec.workspace is set too.
+ assert statusline_spec.sys_operation is sys_operation
+ assert statusline_spec.workspace == str(tmp_path)
+ assert plan_spec.sys_operation is sys_operation
+ assert plan_spec.workspace == str(tmp_path)
+ assert code_spec.sys_operation is sys_operation
+ assert code_spec.workspace == str(tmp_path)
+
+
+def test_deep_research_subagent_inherits_parent_sys_operation(tmp_path):
+ adapter = JiuWenSwarmDeepAdapter()
+ adapter._workspace_dir = str(tmp_path)
+ sys_operation = MagicMock()
+ adapter._sys_operation = sys_operation
+
+ config = {
+ "subagents": {
+ "research_agent": {"enabled": True},
+ "statusline-setup": {"enabled": False},
+ },
+ "max_iterations": 15,
+ }
+ with patch.object(adapter, "_browser_runtime_enabled", return_value=False):
+ subagents, _ = adapter._build_configured_subagents(MagicMock(), config, {})
+
+ assert subagents is not None
+ research_spec = _spec_by_name(subagents, "research_agent")
+ assert research_spec is not None
+ assert research_spec.sys_operation is sys_operation
+ assert research_spec.workspace == str(tmp_path)
+
+
+def test_custom_agent_spec_carries_sys_operation_and_workspace(tmp_path):
+ sys_operation = MagicMock()
+
+ spec = _agent_def_to_subagent_config(
+ _make_agent_definition("reviewer"),
+ MagicMock(),
+ str(tmp_path),
+ None,
+ sys_operation,
+ )
+
+ assert spec.sys_operation is sys_operation
+ assert spec.workspace == str(tmp_path)
+
+
+def test_agent_tool_subagent_reuses_parent_sys_operation(tmp_path):
+ sys_operation = MagicMock()
+ parent_config = MagicMock()
+ parent_config.model = MagicMock()
+ parent_config.workspace = Workspace(root_path=str(tmp_path), language="en")
+ parent_config.language = "en"
+ parent_config.backend = None
+ parent_config.max_iterations = 15
+ parent_config.prompt_mode = None
+ parent_config.sys_operation = sys_operation
+ parent_config.enable_read_image_multimodal = False
+
+ parent_agent = MagicMock()
+ parent_agent.deep_config = parent_config
+ parent_agent.ability_manager.list.return_value = []
+
+ agent_def = _make_agent_definition("reviewer")
+ tool = AgentTool(MagicMock(), parent_agent, [agent_def])
+
+ with patch(
+ "openjiuwen.harness.factory.create_deep_agent",
+ return_value=MagicMock(),
+ ) as create_deep_agent:
+ tool._create_sub_agent(agent_def, "session_custom_reviewer_1")
+
+ assert create_deep_agent.call_args.kwargs["sys_operation"] is sys_operation
+ assert (
+ create_deep_agent.call_args.kwargs["enable_read_image_multimodal"]
+ is False
+ )
+
+
+def test_code_agent_rail_hot_switch_rebinds_custom_agent_registry():
+ """Switching workspace must drop the old custom-agent tool and load the new dir."""
+ rail = CodeAgentRail(workspace_dir="/old-workspace")
+ agent = MagicMock()
+ old_def = _make_agent_definition("old_agent")
+ new_def = _make_agent_definition("new_agent")
+
+ with patch.object(
+ rail, "_load_custom_agents", side_effect=[[old_def], [new_def]]
+ ) as load_custom:
+ rail.init(agent)
+ assert rail._agent_tool is not None
+ assert "old_agent" in rail._agent_tool._custom_agents
+
+ rail.set_workspace_dir("/new-workspace")
+
+ assert rail._workspace_dir == "/new-workspace"
+ assert load_custom.call_count == 2
+ assert rail._agent_tool is not None
+ assert "new_agent" in rail._agent_tool._custom_agents
+ assert "old_agent" not in rail._agent_tool._custom_agents
+ agent.ability_manager.remove_ability.assert_called()
+ assert agent.ability_manager.add_ability.call_count == 2
+
+
+def test_code_agent_rail_set_workspace_dir_is_noop_for_same_path():
+ rail = CodeAgentRail(workspace_dir="/same")
+ agent = MagicMock()
+ with patch.object(rail, "_load_custom_agents", return_value=[]):
+ rail.init(agent)
+ rail.set_workspace_dir("/same")
+ rail.set_workspace_dir(" /same ")
+ assert rail._workspace_dir == "/same"
+ agent.ability_manager.add_ability.assert_not_called()
+
+
+def test_code_agent_rail_set_workspace_dir_rolls_back_on_workspace_error():
+ rail = CodeAgentRail(workspace_dir="/old-workspace")
+ old_workspace = object()
+ agent = MagicMock()
+ agent.deep_config.workspace = old_workspace
+ with patch.object(rail, "_load_custom_agents", return_value=[]), patch(
+ "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail.Workspace",
+ side_effect=ValueError("bad root"),
+ ):
+ rail.init(agent)
+ rail.set_workspace_dir("/new-workspace")
+ assert rail._workspace_dir == "/old-workspace"
+ assert agent.deep_config.workspace is old_workspace
+
+
+def _write_project_agent(workspace: Path, name: str) -> Path:
+ agents_dir = workspace / ".jiuwenswarm" / "agents"
+ agents_dir.mkdir(parents=True, exist_ok=True)
+ path = agents_dir / f"{name}.md"
+ path.write_text(
+ (
+ f"---\nname: {name}\ndescription: live {name}\n"
+ "when_to_use: testing\n---\n\n"
+ f"You are {name}.\n"
+ ),
+ encoding="utf-8",
+ )
+ return path
+
+
+def test_code_agent_rail_live_hot_switch_loads_real_files_and_creates_child(
+ tmp_path, monkeypatch
+):
+ """Live G: real agent markdown files, no parent rebuild, then create child.
+
+ After ``set_workspace_dir``, the new custom agent must be visible and the
+ created child must inherit the new workspace root plus the same
+ SysOperation instance.
+ """
+ old_root = tmp_path / "old"
+ new_root = tmp_path / "new"
+ _write_project_agent(old_root, "old_reviewer")
+ _write_project_agent(new_root, "new_reviewer")
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_config_service.get_user_workspace_dir",
+ lambda: tmp_path / "empty-user-home",
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.common.config.get_config",
+ lambda: {
+ "react": {
+ "subagents": {
+ "old_reviewer": {"enabled": True},
+ "new_reviewer": {"enabled": True},
+ }
+ }
+ },
+ )
+
+ sys_operation = MagicMock()
+ parent_config = MagicMock()
+ parent_config.model = MagicMock()
+ parent_config.workspace = Workspace(root_path=str(old_root), language="en")
+ parent_config.language = "en"
+ parent_config.backend = None
+ parent_config.max_iterations = 15
+ parent_config.prompt_mode = None
+ parent_config.sys_operation = sys_operation
+ parent_config.enable_read_image_multimodal = False
+
+ parent_agent = MagicMock()
+ parent_agent.deep_config = parent_config
+ parent_agent.ability_manager.list.return_value = []
+ parent_agent.card = SimpleNamespace(id="parent-live-g")
+
+ rail = CodeAgentRail(workspace_dir=str(old_root))
+ rail.init(parent_agent)
+ assert rail._agent_tool is not None
+ assert "old_reviewer" in rail._agent_tool._custom_agents
+ assert "new_reviewer" not in rail._agent_tool._custom_agents
+
+ rail.set_workspace_dir(str(new_root))
+ assert rail._workspace_dir == str(new_root)
+ assert rail._agent_tool is not None
+ assert "new_reviewer" in rail._agent_tool._custom_agents
+ assert "old_reviewer" not in rail._agent_tool._custom_agents
+ assert parent_config.workspace.root_path == str(new_root)
+
+ new_def = rail._agent_tool._custom_agents["new_reviewer"]
+ with patch(
+ "openjiuwen.harness.factory.create_deep_agent",
+ return_value=MagicMock(),
+ ) as create_deep_agent:
+ rail._agent_tool._create_sub_agent(
+ new_def,
+ "session_custom_new_reviewer_1",
+ )
+
+ child_workspace = create_deep_agent.call_args.kwargs["workspace"]
+ assert create_deep_agent.call_args.kwargs["sys_operation"] is sys_operation
+ assert str(new_root) in str(child_workspace.root_path)
+ assert str(old_root) not in str(child_workspace.root_path)
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index b157b17a0e..4529cbe055 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -1166,6 +1166,7 @@ def test_deep_adapter_subagents_includes_optional_browser_and_configured_researc
"subagents": {
"research_agent": {"enabled": True},
"browser_agent": {"max_iterations": 7},
+ "statusline-setup": {"enabled": False},
},
}
@@ -1187,6 +1188,7 @@ def test_deep_adapter_subagents_includes_optional_browser_and_configured_researc
mock_research.assert_called_once_with(
model,
workspace="/tmp/jiuwenswarm-workspace",
+ sys_operation=adapter._sys_operation,
language="cn",
max_iterations=9,
rails=None,
@@ -1199,6 +1201,7 @@ def test_deep_adapter_subagents_includes_optional_browser_and_configured_researc
mock_browser.assert_called_once_with(
model,
workspace="/tmp/jiuwenswarm-workspace",
+ sys_operation=adapter._sys_operation,
language="cn",
max_iterations=7,
rails=None,
@@ -1209,7 +1212,10 @@ def test_deep_adapter_subagents_omits_research_without_explicit_enable():
adapter = _TestableJiuWenSwarmDeepAdapter()
adapter.set_workspace_dir("/tmp/jiuwenswarm-workspace")
model = object()
- config = {"max_iterations": 9}
+ config = {
+ "max_iterations": 9,
+ "subagents": {"statusline-setup": {"enabled": False}},
+ }
with (
patch.object(adapter, "_resolve_runtime_language", return_value="cn"),
diff --git a/tests/unit_tests/runtime/test_runtime_host_services.py b/tests/unit_tests/runtime/test_runtime_host_services.py
new file mode 100644
index 0000000000..50350f4fae
--- /dev/null
+++ b/tests/unit_tests/runtime/test_runtime_host_services.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.runtime import host_services
+
+
[email protected](autouse=True)
+def _isolate_host_handlers(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(host_services, "_runtime_push_handler", None)
+ monkeypatch.setattr(host_services, "_runtime_push_handlers", [])
+
+
+async def test_push_owner_out_of_order_restore_does_not_revive_stale_owner() -> None:
+ calls: list[str] = []
+
+ async def first(_message: dict) -> None:
+ calls.append("first")
+
+ async def second(_message: dict) -> None:
+ calls.append("second")
+
+ first_previous = host_services.install_runtime_push_handler(first)
+ second_previous = host_services.install_runtime_push_handler(second)
+
+ host_services.restore_runtime_push_handler(first, first_previous)
+ assert await host_services.send_runtime_push({"value": 1}) is True
+ assert calls == ["second"]
+
+ host_services.restore_runtime_push_handler(second, second_previous)
+ assert await host_services.send_runtime_push({"value": 2}) is False
+ assert calls == ["second"]
+
+
+async def test_runtime_host_push_transport_has_explicit_unavailable_contract() -> None:
+ transport = host_services.RuntimeHostPushTransport()
+
+ with pytest.raises(RuntimeError, match="without a resident host"):
+ await transport.send_push({"value": 1})
+
+ captured: list[dict] = []
+
+ async def capture(message: dict) -> None:
+ captured.append(message)
+
+ previous = host_services.install_runtime_push_handler(capture)
+ try:
+ await transport.send_push({"value": 2})
+ finally:
+ host_services.restore_runtime_push_handler(capture, previous)
+
+ assert captured == [{"value": 2}]
+
+
+async def test_runtime_push_propagates_explicit_delivery_failure() -> None:
+ async def reject(_message: dict) -> bool:
+ return False
+
+ previous = host_services.install_runtime_push_handler(reject)
+ try:
+ assert await host_services.send_runtime_push({"value": 1}) is False
+ with pytest.raises(RuntimeError, match="without a resident host"):
+ await host_services.RuntimeHostPushTransport().send_push({"value": 2})
+ finally:
+ host_services.restore_runtime_push_handler(reject, previous)
diff --git a/tests/unit_tests/test_session_history_empty_filter.py b/tests/unit_tests/test_session_history_empty_filter.py
index 60533e0c21..8476dd2fae 100644
--- a/tests/unit_tests/test_session_history_empty_filter.py
+++ b/tests/unit_tests/test_session_history_empty_filter.py
@@ -172,6 +172,19 @@ def test_has_persistable_assistant_payload_tool_update_is_merged():
) is True
+def test_has_persistable_assistant_payload_keeps_subtask_update():
+ assert session_history._has_persistable_assistant_payload(
+ content_text="",
+ event_type="chat.subtask_update",
+ extra={"task_id": "t1", "description": "wait"},
+ ) is True
+ assert session_history._has_persistable_assistant_payload(
+ content_text="",
+ event_type="chat.subtask_update",
+ extra={},
+ ) is False
+
+
def test_append_history_persists_tool_result(tmp_path, monkeypatch):
monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)