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

fix: SkillTurbo fallback 子代理执行失败与外部 config_base 模板合并缺失

white2025c15c50392a43
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index da725c9551..a32787b55e 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -365,6 +365,31 @@ def _deep_merge(
return result
+def fill_template_defaults(
+ target: dict[str, Any],
+ template: dict[str, Any],
+ depth: int = 0,
+) -> dict[str, Any]:
+ """模板补缺型合并:以 target 为主体,模板仅补全 target 缺失的键。
+
+ 与 merge_template_with_override 不同:
+ - target 独有的键(模板中没有)**原样保留**,不做清理;
+ - target 显式设置的值不被模板覆盖;
+ - 双方均为 dict 的键递归补缺(上限 4 层,与 merge_template_with_override 一致)。
+ 适用于外部传入的稀疏配置(如企业同步 spec.config):补齐模板默认值
+ (如 react.subagents)且不丢弃外部配置的任何键。
+ """
+ if depth >= 4:
+ return target
+ result = copy.deepcopy(target)
+ for key, tmpl_val in template.items():
+ if key not in result:
+ result[key] = copy.deepcopy(tmpl_val)
+ elif isinstance(result[key], dict) and isinstance(tmpl_val, dict):
+ result[key] = fill_template_defaults(result[key], tmpl_val, depth + 1)
+ return result
+
+
def load_yaml_dict(path: Path) -> dict[str, Any]:
"""用 yaml.safe_load 读取 YAML 文件为 dict;不存在或无效时返回空 dict。"""
if not path.exists():
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index d8d0c1264d..62b10444b2 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -414,6 +414,7 @@ from jiuwenswarm.server.runtime.skill.skill_whitelist import (
)
from jiuwenswarm.common.utils import (
DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL,
+ fill_template_defaults,
get_agent_evolution_trajectories_dir,
get_agent_root_dir,
get_agent_skills_dir,
@@ -428,6 +429,8 @@ from jiuwenswarm.common.utils import (
resolve_tenant_sessions_dir,
reset_free_search_runtime_flags,
resolve_agent_registered_skill_dirs,
+ load_yaml_dict,
+ resolve_shipped_template_config_path,
)
from jiuwenswarm.dotenv_early import load_dotenv_runtime
@@ -1269,7 +1272,11 @@ def _resolve_instance_config_base(config_base: dict[str, Any] | None) -> dict[st
return get_config()
if not isinstance(config_base, dict):
raise TypeError("config_base must be a dict when provided")
- return resolve_env_vars(config_base)
+ # 外部传入的 config_base(如企业同步的稀疏 override)与 shipped 模板做补缺型
+ # 合并:模板补全缺失键(如 react.subagents),外部显式键与独有键全部保留,
+ # 保证与 config_base=None 时 get_config() 的模板合并语义一致。
+ template = load_yaml_dict(resolve_shipped_template_config_path())
+ return resolve_env_vars(fill_template_defaults(config_base, template))
def _deep_agent_context_engine_config(react_cfg: dict[str, Any] | None) -> ContextEngineConfig:
@@ -9155,6 +9162,120 @@ class JiuWenSwarmDeepAdapter:
session_id="",
)
+ async def spawn_fallback(
+ self,
+ query: str,
+ parent_session: Any | None = None,
+ ) -> str:
+ """执行 SkillTurbo fallback:以隔离 subagent 跑一次任务,返回子代理输出文本。
+
+ 复用 openjiuwen 原生 ``create_subagent("general-purpose", ...)``(继承父 agent
+ 工具与 SysOperationRail),经 ``invoke_subagent_with_trace`` 阻塞执行。
+ fallback 子代理临时禁用权限审批 rail(spawn 结束后恢复共享实例状态),
+ 避免工具调用中断等待审批导致输出为空。
+ 抛异常表示子代理执行失败;返回字符串表示已跑完(是否达成节点契约由 handler 判定)。
+ """
+ from jiuwenswarm.server.runtime.debug_trace import invoke_subagent_with_trace
+
+ parent_session_id = ""
+ if parent_session is not None and hasattr(parent_session, "get_session_id"):
+ parent_session_id = str(parent_session.get_session_id() or "")
+ sub_session_id = (
+ f"{parent_session_id or 'skill_turbo'}_skill_turbo_fallback_{uuid.uuid4().hex[:8]}"
+ )
+
+ subagent = self._instance.create_subagent("general-purpose", sub_session_id)
+ restore_rails = self._suspend_subagent_permission_rails(subagent)
+ try:
+ result = await invoke_subagent_with_trace(
+ subagent,
+ inputs={"query": query, "conversation_id": sub_session_id},
+ session=parent_session,
+ source_label="subagent:skill_turbo_fallback",
+ )
+ finally:
+ restore_rails()
+
+ output = ""
+ if isinstance(result, dict):
+ output = result.get("output", "") or ""
+ return str(output)
+
+ @staticmethod
+ def _suspend_subagent_permission_rails(subagent: Any) -> Callable[[], None]:
+ """临时禁用 fallback 子代理继承的权限审批 rail,返回恢复函数。
+
+ general-purpose 子代理与父 agent **共享同一个** PermissionInterruptRail 实例
+ (factory 注入时按引用复制),直接改共享实例会污染父 agent 后续的权限审批,
+ 因此采用 suspend/restore:调用方在 spawn 结束后(finally 中)执行恢复。
+ ``resolve_interrupt`` 首次工具调用时会用 ``host.get_permissions_snapshot``
+ 刷新配置覆盖本设置,因此该回调也需临时替换。
+ """
+ configured = (
+ subagent.configured_rails()
+ if hasattr(subagent, "configured_rails")
+ else []
+ )
+ rail_names = [rail.__class__.__name__ for rail in configured or []]
+
+ def _disabled_permission_snapshot() -> dict:
+ """临时权限审批快照:返回禁用状态,避免工具调用被审批 rail 中断。"""
+ return {"enabled": False}
+
+ def _make_restore(
+ rail: Any,
+ saved_config: dict,
+ host: Any,
+ saved_snapshot: Any,
+ ) -> Callable[[], None]:
+ """构造恢复函数,捕获当前循环轮次 rail 的挂起状态。"""
+
+ def _restore() -> None:
+ try:
+ rail.update_config(saved_config)
+ except Exception:
+ logger.warning(
+ "[spawn_fallback] failed to restore permission rail config",
+ exc_info=True,
+ )
+ if host is not None:
+ host.get_permissions_snapshot = saved_snapshot
+
+ return _restore
+
+ restore_steps: list[Callable[[], None]] = []
+ for rail in configured or []:
+ cls_name = rail.__class__.__name__
+ if cls_name not in ("PermissionInterruptRail", "SkillTurboPermissionRail"):
+ continue
+ try:
+ saved_config = dict(getattr(rail, "_static_config", None) or {})
+ host = getattr(rail, "_host", None)
+ saved_snapshot = (
+ host.get_permissions_snapshot if host is not None else None
+ )
+ rail.update_config({"enabled": False})
+ if host is not None:
+ host.get_permissions_snapshot = _disabled_permission_snapshot
+ restore_steps.append(_make_restore(rail, saved_config, host, saved_snapshot))
+ except Exception:
+ logger.warning(
+ "[spawn_fallback] failed to suspend permission rail %s",
+ cls_name,
+ exc_info=True,
+ )
+ logger.info(
+ "[spawn_fallback] subagent rails=%s suspended_permission_rails=%d",
+ rail_names,
+ len(restore_steps),
+ )
+
+ def restore() -> None:
+ for step in restore_steps:
+ step()
+
+ return restore
+
@staticmethod
async def _read_skill_turbo_node_artifacts_summary(session: Any) -> str | None:
"""读取 SkillTurbo 节点产物记录,格式化为可读摘要文本。"""
diff --git a/jiuwenswarm/server/runtime/skill_turbo/fallback_handler.py b/jiuwenswarm/server/runtime/skill_turbo/fallback_handler.py
index dcdfcf6cea..e172414d1e 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/fallback_handler.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/fallback_handler.py
@@ -18,19 +18,6 @@ from typing import Any
from openjiuwen.core.session.agent import Session
-try:
- from jiuwenswarm.agents.harness.common.tools.subagent_models import SubagentTaskSpec
-except ImportError:
- from dataclasses import dataclass
-
- @dataclass
- class SubagentTaskSpec:
- """Minimal fallback for SubagentTaskSpec when subagent_models is unavailable."""
-
- role_id: str = ""
- objective: str = ""
- prompt: str = ""
-
logger = logging.getLogger(__name__)
@@ -109,15 +96,6 @@ class DeepAgentFallbackHandler(SkillTurboFallbackHandler):
self._channel_id = channel_id
self._session_id = session_id
- def _get_subagent_executor(self) -> Any:
- executor = None
- get_executor = getattr(self._adapter, "_get_fork_agent_executor", None)
- if callable(get_executor):
- executor = get_executor()
- if executor is None:
- raise RuntimeError("DeepAgent subagent executor not initialized")
- return executor
-
@staticmethod
def _build_fallback_query(
node_name: str,
@@ -310,16 +288,10 @@ class DeepAgentFallbackHandler(SkillTurboFallbackHandler):
inputs: dict[str, Any],
error: Exception,
parent_session: Session | None,
- ) -> Any:
- """通过现有 spawn subagent 执行 SkillTurbo fallback。"""
- executor = self._get_subagent_executor()
+ ) -> str:
+ """通过 adapter 的 ``spawn_fallback`` 执行 SkillTurbo fallback,返回子代理输出文本。"""
query = self._build_fallback_query(node_name, instruction, inputs, error)
- task = SubagentTaskSpec(
- role_id="SkillTurboFallback",
- objective=f"替代失败的 SkillTurbo 规划节点 {node_name} 完成任务",
- prompt=query,
- )
- return await executor.execute_spawn(task, parent_session=parent_session)
+ return await self._adapter.spawn_fallback(query, parent_session=parent_session)
async def fallback(
self,
@@ -330,22 +302,28 @@ class DeepAgentFallbackHandler(SkillTurboFallbackHandler):
parent_session: Session | None = None,
) -> dict[str, Any]:
"""非流式 fallback 实现。"""
- result = await self._execute_spawn_fallback(
- node_name,
- instruction,
- inputs,
- error,
- parent_session,
- )
- success = bool(getattr(result, "success", False))
- if not success:
- raise RuntimeError(getattr(result, "error", "fallback subagent failed") or "fallback subagent failed")
-
- fallback_output = getattr(result, "result", None) or ""
+ try:
+ fallback_output = await self._execute_spawn_fallback(
+ node_name,
+ instruction,
+ inputs,
+ error,
+ parent_session,
+ )
+ except Exception as e:
+ logger.error(
+ "[DeepAgentFallbackHandler] fallback error node=%s error=%s",
+ node_name,
+ e,
+ )
+ raise FallbackContractError(
+ node_name=node_name,
+ reason=f"fallback spawn 执行异常: {e}",
+ original_error=error,
+ ) from e
logger.warning(
- "[DeepAgentFallbackHandler] node fallback spawn finished node=%s task_id=%s error=%s",
+ "[DeepAgentFallbackHandler] node fallback spawn finished node=%s error=%s",
node_name,
- getattr(result, "task_id", ""),
error,
)
self._log_degraded_result(node_name, fallback_output, error)
@@ -394,9 +372,8 @@ class DeepAgentFallbackHandler(SkillTurboFallbackHandler):
) -> AsyncIterator[dict[str, Any]]:
"""流式 fallback 的实际实现。
- execute_spawn 会通过 SubagentSessionProxy 将模型流和工具事件写入 parent_session;
- SkillTurboExecutor._execute_node_stream 已经并发 drain 该 session,因此这里无需手工
- parse subagent stream,只负责 fallback 生命周期事件和最终结构化结果。
+ adapter.spawn_fallback 为阻塞式 invoke,不向 parent_session 转发子代理流式
+ 过程;此处只负责 fallback 生命周期事件和最终结构化结果。
"""
logger.warning(
"[DeepAgentFallbackHandler] node fallback_stream via spawn node=%s error=%s",
@@ -411,10 +388,8 @@ class DeepAgentFallbackHandler(SkillTurboFallbackHandler):
"timestamp": int(asyncio.get_event_loop().time() * 1000),
}
- result = None
- fallback_error: Exception | None = None
try:
- result = await self._execute_spawn_fallback(
+ fallback_output = await self._execute_spawn_fallback(
node_name,
instruction,
inputs,
@@ -422,17 +397,16 @@ class DeepAgentFallbackHandler(SkillTurboFallbackHandler):
parent_session,
)
except Exception as e:
- fallback_error = e
logger.error(
"[DeepAgentFallbackHandler] fallback_stream error node=%s error=%s",
node_name,
e,
)
- # 与其他失败路径(spawn success=false、契约不达成)保持一致:raise
- # FallbackContractError 将异常向上传播,让 executor 的 execute_plan_stream
- # 捕获并终止 plan,最终由 tool 层返回 success=false 给 LLM 触发降级。
- # 不 yield chat.error:会被 executor 透传并经 tool 转发到父会话,抢先于 tool
- # result 到达前端终结会话,LLM 来不及转 skill_tool 降级。
+ # 与其他失败路径(契约不达成)保持一致:raise FallbackContractError 将异常
+ # 向上传播,让 executor 的 execute_plan_stream 捕获并终止 plan,最终由 tool
+ # 层返回 success=false 给 LLM 触发降级。不 yield chat.error:会被 executor
+ # 透传并经 tool 转发到父会话,抢先于 tool result 到达前端终结会话,LLM 来不及
+ # 转 skill_tool 降级。
raise FallbackContractError(
node_name=node_name,
reason=f"fallback spawn 执行异常: {e}",
@@ -445,26 +419,6 @@ class DeepAgentFallbackHandler(SkillTurboFallbackHandler):
"timestamp": int(asyncio.get_event_loop().time() * 1000),
}
- if fallback_error is not None:
- return
-
- success = bool(getattr(result, "success", False))
- if not success:
- error_text = getattr(result, "error", "fallback subagent failed") or "fallback subagent failed"
- logger.error(
- "[DeepAgentFallbackHandler] node fallback_stream spawn reported failure node=%s error=%s, "
- "degrading to DeepAgent",
- node_name,
- error_text,
- )
- # 不 yield chat.error:同上,避免抢先终结前端阻断 LLM 降级。
- raise FallbackContractError(
- node_name=node_name,
- reason=f"fallback subagent 执行失败: {error_text}",
- original_error=error,
- )
-
- fallback_output = getattr(result, "result", None) or ""
self._log_degraded_result(node_name, fallback_output, error)
# 契约校验:subagent 必须自证达成节点目标,否则视为 fallback 失败,