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

feature: Agent模式下,ttse支持sub agent

xinyang_balia3c506f7fcbc
diff --git a/docs/en/TTSE.md b/docs/en/TTSE.md
index a8e7058b27..fd91480cf2 100644
--- a/docs/en/TTSE.md
+++ b/docs/en/TTSE.md
@@ -28,3 +28,49 @@ The rule bank is always `workspace/.ttse/bank.json`. Disclosure is always `disk_
Auto-dream performs hygiene on an existing FACT/TIP bank (TTL prune, near-duplicate merge, low-quality TIP purge). It is independent of online `induce` / `blame`. The four `dream_*` fields above override the defaults.
`consult_retrieve_mode` selects scoring (`hybrid` / `embed` / `bm25`); missing or failed embeddings fall back to BM25, and a small pool still dumps. Call `ttse_consult(category=…, query=<situation sentence>)` with both arguments required; use `category=all` for the whole bank.
+
+## Main agent consultation order
+
+When TTSE injection is enabled and the tool is available, the main-agent prompt
+requires a standalone `ttse_consult` as the first tool call for each new non-chat
+task, before loading skills, creating todos, or using business tools. Use `all`
+when the category is uncertain, and consult even with an empty catalog. Continue
+after no matches or failure; task continuations and approval resumes reuse results.
+Small talk, unavailable tools, and explicit user opt-outs are exempt. This is a
+prompt constraint, not runtime enforcement, and requires the updated agent-core guidance.
+
+## Subagent consultation
+
+When the parent has usable TTSE, all subagents (general-purpose, research, browser,
+statusline-setup and custom agents) query its current bank. No separate subagent bank
+is created. Dependencies are no longer filtered by the `agent` mode name, so Flash
+and other non-Code instances can also use them. A parent without TTSE provides no
+consultation capability. Both `task_tool` and the persistent subagent runtime install a lightweight
+consultation rail through their common creation entry point. The tool is visible
+in the first model call, including when progressive tool loading is enabled.
+
+The subagent prompt requires exactly one standalone `ttse_consult` as the first
+tool call for each new non-chat task when the tool is available. Read its result
+before loading skills, making an execution plan, creating todos or calling other
+tools, even when the user specifies a skill or the catalog is unmatched or empty.
+Small talk, unavailable tools and explicit user opt-outs are exempt.
+If no catalog is attached, the prompt says so and uses `category=all` for the lookup.
+The runtime supplies
+the tool, guidance and shared category catalog without retrieving experience bodies.
+The model initiates the lookup; this is a prompt constraint, not runtime enforcement.
+Choose a relevant category, or
+`all` if uncertain, and build query from subtask and environment keywords rather
+than copying the full request. Continue on no matches or failure. Reuse results
+for the same task, tool-result continuations and approval resumes; consult again
+for more specific experience if needed. Subagents do not start their own induction,
+blame or Auto-dream.
+
+Logs mark model-initiated lookups with `source=model`. Task summaries include
+`consult_calls` for the current invocation; zero calls do not imply that earlier
+invocations of the same task have no lookup results.
+
+The existing TTSE/injection switches and explicit tool disabling apply, including
+custom agents' `disallowed_tools: [ttse_consult]`. Live children synchronize changes
+at their next execution boundary. Tool resources are independent while the bank
+is shared. Code instances remain excluded; this consultation entry point does not
+enable parent TTSE for other modes.
diff --git a/docs/zh/TTSE.md b/docs/zh/TTSE.md
index 254d15de25..35fdef9f16 100644
--- a/docs/zh/TTSE.md
+++ b/docs/zh/TTSE.md
@@ -27,4 +27,41 @@ react:
规则库固定在 agent workspace 下的 `.ttse/bank.json`,注入方式固定为 `disk_catalog`(P:45 只写指引,FACT/TIP 走 `ttse_consult`),二者都不作为用户配置项。`embedding` 可选;变量名以 `secret_registry` 为准(`EMBED_API_KEY` / `EMBED_API_BASE` / `EMBED_MODEL`)。三段齐全且解析非空时 consult 在类内做 BM25+embedding 混合召回,否则 BM25 兜底。模型应调用 `ttse_consult(category=…, query=处境短句)`;`category` 与 `query` 都必须填,查全集用 `category=all`。正文不灌进 system。
+## 主 Agent 查询顺序
+
+TTSE 注入开启且工具可用时,主 Agent 的提示要求:新非闲聊任务的首次工具调用只调用
+`ttse_consult`,阅读结果后再加载技能、创建 todo 或调用业务工具;分类不明确时使用 `all`,
+目录为空也先查询。无命中或失败后继续,同一任务续跑、审批恢复不重复查询。
+闲聊、工具不可用及用户明确要求不查询时除外。这是提示词约束,不提供运行时强制保证,
+需要使用包含该指引更新的 agent-core 版本。
+
+## 子 Agent 查询经验
+
+父级已有可用 TTSE 时,general-purpose、research、browser、statusline-setup 和自定义子 Agent
+均复用主 Agent 当前的经验库,不在子 Agent workspace 下创建独立经验库。
+查询依赖不再按 `agent` 模式名过滤,flash 等非 Code 实例同样可用;父级未挂载 TTSE 时不提供查询能力。
+`task_tool` 和持久子 Agent runtime 共用创建入口,自动装配轻量查询 Rail;
+工具直接出现在首轮 schema,无需先调用 `tools_search`。
+
+子 Agent 的提示要求:当 `ttse_consult` 可用时,收到新非闲聊任务后,首次工具调用必须仅调用一次
+`ttse_consult`,收到并阅读结果后才能加载技能、制定执行计划、创建 todo 或调用其他工具。
+即使用户指定技能、目录无匹配分类或为空,也必须先查询;闲聊、工具不可用或用户明确要求不查询时除外。
+若缺少目录附件,则明确告知本次未提供目录,并按 `category=all` 查询。
+运行时仅提供工具、查询指引和共享经验分类目录,不自动查询或注入经验正文。
+查询由模型发起,这是提示词约束,不提供运行时强制保证。
+category 按目录选择,无法判断时使用 `all`;query 提取子任务和环境关键词,不整句粘贴任务原文。
+无命中或失败后正常继续;同一任务已有结果、工具结果续跑或审批恢复时无需为流程重复查询,
+需要更具体的经验时可补查。子 Agent 不启动独立归纳、blame 或 Auto-dream。
+
+沿用 `react.ttse.enabled`、`inject_enabled` 和显式工具禁用配置;自定义 Agent 的
+`disallowed_tools: [ttse_consult]` 同样生效。配置关闭后,存活子 Agent 在下一执行边界
+移除工具和提示。各子 Agent 独立管理工具资源,底层经验数据共享;Code 实例仍排除,
+此查询入口不负责为其他模式启用父级 TTSE。
+
+日志搜索 `[subagent.ttse]`:`consult_start` 表示实际开始调用,`consult_completed`
+表示调用完成,`consult_failed` / `consult_cancelled` 表示失败或取消。日志包含子 Agent
+类型、子会话 ID、工具 ID 和单次调用 ID,完成日志另含耗时及返回字符数,不记录查询或经验正文。
+`source=model` 表示模型发起查询。每次任务结束的 `task_summary` 包含本次执行的
+`consult_calls`;为 0 表示本次未调用,不代表同一任务之前没有查询结果。
+
Auto-dream 对已有 FACT/TIP bank 做卫生(TTL 剪枝、近重合并、低质量 TIP 清洗),与在线 `induce`/`blame` 独立;上述四个 `dream_*` 字段可在配置中覆盖默认值。`consult_retrieve_mode` 选打分路径(`hybrid` / `embed` / `bm25`);向量缺失或失败走 BM25,池子不够仍 dump。
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py
index 08a355f3c9..6e0d9d5d3c 100644
--- a/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py
@@ -29,6 +29,11 @@ _CN_PROTOCOL = """## 技能执行规范(强制)
可用技能清单与加载约定见本 prompt 的「技能」段(SkillUseRail 注入),**须与该段一致**。
+### 经验查询与技能流程的顺序
+当前任务要求 TTSE 前置经验查询且 `ttse_consult` 可用时,**必须先单独查询并阅读结果,再加载技能**,不得与技能或 todo 工具同批调用。
+已有当前任务的查询结果或运行时前置查询结果附件时,先阅读结果,不重复查询。
+以下技能加载、“第一个工作工具”、todo 及新任务清理旧 todo 的顺序要求,均从前置查询完成后开始适用;用户明确要求不查询经验时遵循用户要求。
+
### 加载 SKILL.md 正文(禁止用 bash 执行工具名)
- **必须**且**只能**使用 `skill_tool(skill_name=..., relative_file_path="SKILL.md")` 加载。不要把工具名当作 shell 命令执行。
- **禁止**用 `read_file` 或任何其它工具读取、拼凑 SKILL.md。遇到技能名或 `.../<skill_name>/SKILL.md` 路径一律走 `skill_tool`;普通参考文件不受此限制。
@@ -72,6 +77,11 @@ _EN_PROTOCOL = """## Skill Execution Protocol (Mandatory)
The "Skills" section of this prompt (from SkillUseRail) lists available skills and how to load them — **follow that section**.
+### Experience lookup before the skill workflow
+When this task requires a TTSE lookup and `ttse_consult` is available, **consult alone and read the result before loading a skill**; never batch it with skill or todo tools.
+Read an existing consult or runtime preflight result for this task without repeating the lookup.
+The skill-loading, first-work-tool, todo, and old-todo cleanup rules below apply after the lookup completes; follow explicit user instructions not to consult.
+
### Load SKILL.md body (never run tool names as shell/bash commands)
- You **must** use **only** `skill_tool(skill_name=..., relative_file_path="SKILL.md")` to load the body. Do not execute tool names as shell commands.
- **Never** use `read_file` or any other tool to read or stitch together SKILL.md. Whenever you see a skill name or a `.../<skill_name>/SKILL.md` path, go through `skill_tool`; ordinary reference files are not affected.
diff --git a/jiuwenswarm/agents/harness/common/rails/subagent_ttse_consult_rail.py b/jiuwenswarm/agents/harness/common/rails/subagent_ttse_consult_rail.py
new file mode 100644
index 0000000000..53904e3e1c
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/subagent_ttse_consult_rail.py
@@ -0,0 +1,393 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""子 Agent 的 TTSE 查询能力;经验库由父 adapter 提供,不执行演进。"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+from uuid import uuid4
+
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.single_agent.prompts.builder import PromptSection
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+logger = logging.getLogger(__name__)
+TOOL_NAME = "ttse_consult"
+_CONSULT_UNAVAILABLE = "TTSE consultation unavailable; continue with the current task."
+
+
+@dataclass(frozen=True)
+class TTSEConsultDependencies:
+ """仅包含查询所需依赖,不向子 Agent 暴露父 Rail。"""
+
+ store: Any
+ max_chars: int = 8000
+ max_rules: int = 40
+ default_top_k: int = 8
+ rrf_k: int = 60
+
+
+TTSEConsultProvider = Callable[[], TTSEConsultDependencies | None]
+
+
+class SubagentTTSEConsultRail(DeepAgentRail):
+ # 在 ProgressiveToolRail 过滤 schema 前同步 eager 配置和工具。
+ priority = 95
+ inherit_to_subagents = False
+
+ def __init__(
+ self,
+ provider: TTSEConsultProvider,
+ *,
+ subagent_type: str = "",
+ subsession_id: str = "",
+ ) -> None:
+ super().__init__()
+ self._provider = provider
+ self._subagent_type = subagent_type
+ self._subsession_id = subsession_id
+ self._consult_calls = 0
+ self._agent: Any = None
+ self._tool: Any = None
+ self._dependencies: TTSEConsultDependencies | None = None
+ self._section = f"subagent_ttse_{uuid4().hex}"
+ self._attachments: dict[str, Any] = {}
+ self._builders: list[Any] = []
+ self._eager_rails: list[Any] = []
+ self._cleanup_tasks: set[asyncio.Task] = set()
+
+ def init(self, agent: Any) -> None:
+ self._agent = agent
+ self._sync()
+
+ def bind_task_context(self, subagent_type: str, subsession_id: str) -> None:
+ """刷新复用实例的任务日志标识,不重复装配 Rail。"""
+ self._subagent_type = subagent_type
+ self._subsession_id = subsession_id
+
+ def _rails(self) -> list[Any]:
+ return list(self._agent.configured_rails())
+
+ def _drop_tool(self) -> None:
+ tool, self._tool = self._tool, None
+ if tool is not None:
+ manager = self._agent.ability_manager
+ if manager.get(TOOL_NAME) is tool.card:
+ manager.remove(TOOL_NAME)
+ if Runner.resource_mgr.get_tool(tool.card.id) is tool:
+ Runner.resource_mgr.remove_tool(tool.card.id)
+ self._dependencies = None
+ for rail in self._eager_rails:
+ users = rail.jiuwenswarm_ttse_eager_users - 1
+ rail.jiuwenswarm_ttse_eager_users = users
+ if users == 0 and not rail.jiuwenswarm_ttse_eager_original:
+ rail.eager_tools = [
+ name for name in rail.eager_tools if name != TOOL_NAME
+ ]
+ self._eager_rails.clear()
+
+ def _sync(self) -> None:
+ try:
+ dependencies = self._provider()
+ rails = self._rails()
+ if any(TOOL_NAME in getattr(rail, "_disabled_tools", ()) for rail in rails):
+ dependencies = None
+ if dependencies is None:
+ self._drop_tool()
+ return
+ previous = self._dependencies
+ changed = (
+ previous is None
+ or previous.store is not dependencies.store
+ or (
+ previous.max_chars,
+ previous.max_rules,
+ previous.default_top_k,
+ previous.rrf_k,
+ )
+ != (
+ dependencies.max_chars,
+ dependencies.max_rules,
+ dependencies.default_top_k,
+ dependencies.rrf_k,
+ )
+ )
+ if (
+ changed
+ or self._agent.ability_manager.get(TOOL_NAME) is not self._tool.card
+ ):
+ self._drop_tool()
+ from openjiuwen.agent_evolving.ttse.consult import (
+ create_ttse_consult_tools,
+ )
+
+ tool = create_ttse_consult_tools(
+ dependencies.store,
+ max_chars=dependencies.max_chars,
+ max_rules=dependencies.max_rules,
+ default_top_k=dependencies.default_top_k,
+ rrf_k=dependencies.rrf_k,
+ )[0]
+ original_invoke = tool.invoke
+
+ async def consult(inputs: Any, **kwargs: Any) -> Any:
+ call_id = uuid4().hex[:12]
+ started = time.monotonic()
+ self._consult_calls += 1
+ category = (
+ inputs.get("category") if isinstance(inputs, dict) else None
+ )
+ query = inputs.get("query", "") if isinstance(inputs, dict) else ""
+ # 用调用 id 串联并发查询;不把任务正文或经验正文写入日志。
+ log_context = (
+ f"subagent_type={self._subagent_type!r} "
+ f"subsession_id={self._subsession_id!r} "
+ f"tool_id={tool.card.id} call_id={call_id} source=model"
+ )
+ logger.info(
+ "[subagent.ttse] consult_start %s category=%r query_chars=%d",
+ log_context,
+ category,
+ len(str(query)),
+ )
+ try:
+ result = await original_invoke(inputs, **kwargs)
+ except asyncio.CancelledError:
+ logger.info(
+ "[subagent.ttse] consult_cancelled %s elapsed_ms=%.1f",
+ log_context,
+ (time.monotonic() - started) * 1000,
+ )
+ raise
+ except Exception:
+ logger.warning(
+ "[subagent.ttse] consult_failed %s elapsed_ms=%.1f",
+ log_context,
+ (time.monotonic() - started) * 1000,
+ exc_info=True,
+ )
+ return _CONSULT_UNAVAILABLE
+ logger.info(
+ "[subagent.ttse] consult_completed %s elapsed_ms=%.1f result_chars=%d",
+ log_context,
+ (time.monotonic() - started) * 1000,
+ len(result) if isinstance(result, str) else 0,
+ )
+ return result
+
+ # 保留 factory 工具已有的生命周期事件包装,避免再套一个
+ # LocalFunction 导致一条查询产生两组 tool-call 事件。
+ tool.invoke = consult
+ # 同类型子 Agent 的 owner/card id 可能相同,因此单独管理此工具的
+ # 唯一资源 id;不能让 add_ability 再按公共 owner id 重写它。
+ tool.card.id = f"{TOOL_NAME}_{uuid4().hex}"
+ Runner.resource_mgr.add_tool(tool)
+ self._tool = tool
+ # 继承下来的同名 card 只是子 Agent 的引用;替换引用时不能
+ # 注销它指向的父 Agent 资源。
+ self._agent.ability_manager.remove(TOOL_NAME)
+ self._agent.ability_manager.add(tool.card)
+ self._dependencies = dependencies
+ for rail in rails:
+ eager = getattr(rail, "eager_tools", None)
+ if isinstance(eager, list) and not any(
+ item is rail for item in self._eager_rails
+ ):
+ users = getattr(rail, "jiuwenswarm_ttse_eager_users", 0)
+ if users == 0:
+ rail.jiuwenswarm_ttse_eager_original = TOOL_NAME in eager
+ rail.jiuwenswarm_ttse_eager_users = users + 1
+ if TOOL_NAME not in eager:
+ rail.eager_tools = [*eager, TOOL_NAME]
+ self._eager_rails.append(rail)
+ except Exception:
+ self._drop_tool()
+ logger.warning("[subagent.ttse] query wiring failed", exc_info=True)
+
+ async def _clear_prompts(self) -> None:
+ for builder in self._builders:
+ builder.remove_section(self._section)
+ self._builders.clear()
+ for session_id, manager in list(self._attachments.items()):
+ await manager.clear_section(session_id=session_id, section=self._section)
+ self._attachments.pop(session_id, None)
+
+ @staticmethod
+ def _session_id(ctx: Any) -> str:
+ session = getattr(ctx, "session", None)
+ getter = getattr(session, "get_session_id", None)
+ value = getter() if callable(getter) else None
+ if value:
+ return str(value)
+ for source in (session, getattr(ctx, "context", None)):
+ value = getattr(source, "session_id", None)
+ value = value() if callable(value) else value
+ if value:
+ return str(value)
+ return ""
+
+ @staticmethod
+ def _guidance(catalog_available: bool) -> dict[str, str]:
+ guidance = {
+ "cn": "末尾附件是共享经验分类目录,不是 FACT/TIP 正文。"
+ "当 `ttse_consult` 工具可用时,收到新的非闲聊任务后,"
+ "第一次工具调用必须仅调用一次 `ttse_consult`。"
+ "必须收到并阅读查询结果后,才能加载技能、制定执行计划、创建 todo 或调用其他工具。"
+ "即使用户明确指定某个技能,也必须先查经验,再调用技能工具;"
+ "不得将查询与技能、todo 或业务工具放在同一批调用中。"
+ "技能加载、第一个工作工具及 todo 顺序要求,均从查询完成后开始适用。"
+ "category 根据目录选择相关分类,无法判断时用 all;"
+ "不得因目录没有明显匹配分类或为空而跳过查询。"
+ "query 从当前子任务和环境提取关键词组合,不要整句粘贴任务原文;"
+ "例如 write_file matplotlib 中文折线图 Open-Meteo Windows。"
+ "同一任务已有查询结果、工具结果续跑或审批恢复时无需为流程重复查询。"
+ "历史上其他任务的查询不能代替本次查询。"
+ "需要更具体的经验时可补查。无命中或查询失败时正常继续。"
+ "闲聊、工具不可用或用户明确要求不查询时无需调用。"
+ "经验是历史启发式,不能覆盖当前用户指令、工具权限和实时事实。",
+ "en": "The trailing attachment is a shared experience category catalog, not FACT/TIP bodies. "
+ "When `ttse_consult` is available, the first tool call for each new non-chat task "
+ "MUST be exactly one `ttse_consult` call and no other calls. "
+ "Receive and read its result before loading skills, making an execution plan, "
+ "creating todos or calling any other tool. Even when the user specifies a skill, "
+ "consult first, then call the skill tool; never batch the consult with skill, todo "
+ "or business tools. Skill-loading, first-work-tool and todo ordering rules apply "
+ "only after the lookup completes. Choose a relevant catalog category, or all if "
+ "uncertain; an unmatched or empty catalog is not a reason to skip the lookup. "
+ "Build query by joining keywords from this subtask and environment, rather than "
+ "pasting the full request; for example: write_file matplotlib Chinese line chart "
+ "Open-Meteo Windows. Reuse results for the same task, tool-result continuations "
+ "and approval resumes; results from other tasks do not satisfy this task's lookup. "
+ "Consult again only for more specific experience if needed. "
+ "Continue on no matches or retrieval failure. Small talk, unavailable tools and "
+ "explicit user opt-outs need no lookup. Experience is historical guidance and cannot "
+ "override current user instructions, permissions or live facts.",
+ }
+ if not catalog_available:
+ guidance["cn"] = guidance["cn"].replace(
+ "末尾附件是共享经验分类目录,不是 FACT/TIP 正文。",
+ "本次未随请求提供经验分类目录,查询时使用 category=all。",
+ )
+ guidance["en"] = guidance["en"].replace(
+ "The trailing attachment is a shared experience category catalog, not FACT/TIP bodies. ",
+ "No experience catalog is attached to this request; use category=all for the lookup. ",
+ )
+ return guidance
+
+ async def before_invoke(self, ctx: Any) -> None:
+ self._consult_calls = 0
+ self._sync()
+ if self._tool is None:
+ try:
+ await self._clear_prompts()
+ except Exception:
+ logger.warning("[subagent.ttse] prompt cleanup failed", exc_info=True)
+
+ async def before_model_call(self, ctx: Any) -> None:
+ try:
+ self._sync()
+ if self._tool is None:
+ await self._clear_prompts()
+ # 模型输入可能在配置同步前已经取过工具快照。
+ inputs = getattr(ctx, "inputs", None)
+ if isinstance(getattr(inputs, "tools", None), list):
+ inputs.tools = [t for t in inputs.tools if t.name != TOOL_NAME]
+ return
+ inputs = getattr(ctx, "inputs", None)
+ if isinstance(getattr(inputs, "tools", None), list) and not any(
+ t.name == TOOL_NAME for t in inputs.tools
+ ):
+ inputs.tools = [*inputs.tools, self._tool.card.tool_info()]
+ builder = getattr(
+ getattr(ctx, "inputs", None), "system_prompt_builder", None
+ )
+ if builder is None:
+ builder = self._agent.system_prompt_builder
+ session_id = self._session_id(ctx)
+ manager = getattr(self._agent, "prompt_attachment_manager", None)
+ catalog_available = False
+ if session_id and manager is not None:
+ try:
+ from openjiuwen.agent_evolving.ttse.catalog import (
+ render_catalog_markdown,
+ )
+ from openjiuwen.harness.prompts.prompt_attachment_manager import (
+ PromptAttachmentKind,
+ )
+
+ content = render_catalog_markdown(
+ self._dependencies.store.catalog_counts()
+ )
+ await manager.add_section(
+ session_id=str(session_id),
+ section=self._section,
+ content=content,
+ kind=PromptAttachmentKind.TEXT,
+ source="subagent_ttse",
+ priority=45,
+ content_kind="text/markdown",
+ )
+ self._attachments[str(session_id)] = manager
+ except Exception:
+ logger.warning("[subagent.ttse] catalog attachment failed", exc_info=True)
+ else:
+ catalog_available = True
+ builder.add_section(
+ PromptSection(
+ name=self._section,
+ priority=45,
+ content=self._guidance(catalog_available),
+ )
+ )
+ if not any(item is builder for item in self._builders):
+ self._builders.append(builder)
+ except Exception:
+ logger.warning("[subagent.ttse] prompt sync failed", exc_info=True)
+
+ async def after_invoke(self, ctx: Any) -> None:
+ logger.info(
+ "[subagent.ttse] task_summary subagent_type=%r subsession_id=%r consult_calls=%d",
+ self._subagent_type,
+ self._subsession_id,
+ self._consult_calls,
+ )
+ # 一次性 task_tool 子 Agent 不一定主动卸载 rails;任务结束即释放资源。
+ # 持久子 Agent 的下次调用会在 before_invoke 重新绑定同一个共享库。
+ self._drop_tool()
+ try:
+ await self._clear_prompts()
+ except Exception:
+ logger.warning("[subagent.ttse] task cleanup failed", exc_info=True)
+
+ def uninit(self, agent: Any) -> None:
+ self._drop_tool()
+ for builder in self._builders:
+ builder.remove_section(self._section)
+ self._builders.clear()
+ attachments, self._attachments = self._attachments, {}
+
+ async def clear_attachments() -> None:
+ for session_id, manager in attachments.items():
+ try:
+ await manager.clear_section(
+ session_id=session_id, section=self._section
+ )
+ except Exception:
+ logger.warning(
+ "[subagent.ttse] attachment cleanup failed", exc_info=True
+ )
+
+ if attachments:
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ asyncio.run(clear_attachments())
+ else:
+ task = loop.create_task(clear_attachments())
+ self._cleanup_tasks.add(task)
+ task.add_done_callback(self._cleanup_tasks.discard)
+ self._agent = None
diff --git a/jiuwenswarm/agents/harness/common/tools/subagent_executor/ttse.py b/jiuwenswarm/agents/harness/common/tools/subagent_executor/ttse.py
new file mode 100644
index 0000000000..ce23be38ba
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/subagent_executor/ttse.py
@@ -0,0 +1,103 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""在统一子 Agent 创建入口追加 TTSE 查询 Rail。"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+from jiuwenswarm.agents.harness.common.rails.subagent_ttse_consult_rail import (
+ SubagentTTSEConsultRail,
+ TTSEConsultProvider,
+)
+
+logger = logging.getLogger(__name__)
+_MARKER = "_jiuwenswarm_ttse_wiring_installed"
+_CHILD_MARKER = "_jiuwenswarm_ttse_consult_rail"
+
+
+def _register_before_execution(child: Any, rail: SubagentTTSEConsultRail) -> None:
+ """在公开执行入口补挂 Rail,避免创建时后台注册的竞态。"""
+ lock = asyncio.Lock()
+
+ async def ensure_registered() -> None:
+ async with lock:
+ try:
+ if child.is_registered_rail(rail):
+ return
+ await child.register_rail(rail)
+ except asyncio.CancelledError:
+ await rollback_registration()
+ raise
+ except Exception:
+ logger.warning(
+ "[subagent.ttse] deferred rail registration failed",
+ exc_info=True,
+ )
+ await rollback_registration()
+
+ async def rollback_registration() -> None:
+ try:
+ await child.unregister_rail(rail)
+ except Exception:
+ logger.warning(
+ "[subagent.ttse] deferred rail registration cleanup failed",
+ exc_info=True,
+ )
+
+ original_invoke = child.invoke
+ original_stream = child.stream
+
+ async def invoke(*args: Any, **kwargs: Any) -> Any:
+ await ensure_registered()
+ return await original_invoke(*args, **kwargs)
+
+ async def stream(*args: Any, **kwargs: Any) -> Any:
+ await ensure_registered()
+ source = original_stream(*args, **kwargs)
+ try:
+ async for chunk in source:
+ yield chunk
+ finally:
+ await source.aclose()
+
+ child.invoke = invoke
+ child.stream = stream
+
+
+def install_subagent_ttse_wiring(agent: Any, provider: TTSEConsultProvider) -> bool:
+ if getattr(agent, _MARKER, False):
+ return True
+ original = getattr(agent, "create_subagent", None)
+ if not callable(original):
+ return False
+
+ def create_subagent(*args: Any, **kwargs: Any) -> Any:
+ child = original(*args, **kwargs)
+ subagent_type = str(args[0] if args else kwargs.get("subagent_type", ""))
+ subsession_id = str(args[1] if len(args) > 1 else kwargs.get("subsession_id", ""))
+ existing_rail = getattr(child, _CHILD_MARKER, None)
+ if existing_rail is not None:
+ existing_rail.bind_task_context(subagent_type, subsession_id)
+ return child
+ try:
+ rail = SubagentTTSEConsultRail(
+ provider,
+ subagent_type=subagent_type,
+ subsession_id=subsession_id,
+ )
+ if child.is_initialized:
+ # DeepAgent 实例也可直接作为 spec。已初始化实例的 pending rail
+ # 不会再装配,推迟到公开执行入口注册,避免后台注册竞态。
+ _register_before_execution(child, rail)
+ else:
+ child.add_rail(rail)
+ setattr(child, _CHILD_MARKER, rail)
+ except Exception:
+ logger.warning("[subagent.ttse] rail attachment failed", exc_info=True)
+ return child
+
+ agent.create_subagent = create_subagent
+ setattr(agent, _MARKER, True)
+ return True
diff --git a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
index 1758ae7e9c..f90945dd99 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py
@@ -239,12 +239,19 @@ class AgentTool(Tool):
)
# 构建 create_kwargs(对齐 DeepAgent.create_subagent 的字段映射)
+ subagent_rails = None
+ if spec.rails is not None:
+ subagent_rails = []
+ for rail in spec.rails:
+ fork_for_agent = getattr(rail, "fork_for_agent", None)
+ subagent_rails.append(fork_for_agent() if callable(fork_for_agent) else rail)
create_kwargs = {
"model": spec.model or parent_config.model,
"card": spec.agent_card,
"system_prompt": spec.system_prompt,
"tools": parent_tool_cards,
"mcps": spec.mcps,
+ "rails": subagent_rails,
"enable_task_loop": spec.enable_task_loop,
"max_iterations": spec.max_iterations if spec.max_iterations is not None else parent_config.max_iterations,
"workspace": workspace,
@@ -483,4 +490,4 @@ class CodeAgentRail(DeepAgentRail):
return []
-__all__ = ["CodeAgentRail", "AgentTool", "DISALLOWED_FOR_SUBAGENTS", "TOOL_GROUPS", "_filter_tool_cards"]
\ No newline at end of file
+__all__ = ["CodeAgentRail", "AgentTool", "DISALLOWED_FOR_SUBAGENTS", "TOOL_GROUPS", "_filter_tool_cards"]
diff --git a/jiuwenswarm/server/runtime/agent_adapter/deep/subagent_load.py b/jiuwenswarm/server/runtime/agent_adapter/deep/subagent_load.py
index 46d910ddfe..95cad0217a 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/deep/subagent_load.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/deep/subagent_load.py
@@ -17,6 +17,7 @@ from openjiuwen.core.sys_operation import SysOperation
from openjiuwen.harness.prompts import resolve_language
from openjiuwen.harness.schema.config import SubAgentConfig
+from jiuwenswarm.agents.harness.common.rails.disabled_tools_rail import DisabledToolsRail
from jiuwenswarm.common.config import get_config
from jiuwenswarm.server.runtime.agent_adapter.deep.progressive_tools import (
build_progressive_tool_rail_from_config,
@@ -85,6 +86,9 @@ def _agent_def_to_subagent_config(
if progressive_rail is not None:
custom_rails = [progressive_rail]
+ if "ttse_consult" in (agent_def.disallowed_tools or []):
+ custom_rails = [*(custom_rails or []), DisabledToolsRail(["ttse_consult"])]
+
return SubAgentConfig(
agent_card=card,
system_prompt=agent_def.prompt,
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index a2e4b23438..5376659f3d 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -5178,6 +5178,51 @@ class JiuWenSwarmDeepAdapter:
exc_info=True,
)
+ def _subagent_ttse_consult_dependencies(self) -> Any | None:
+ """子 Agent 查询父 TTSE 内部状态的唯一入口;始终读取当前实例。"""
+ from jiuwenswarm.agents.harness.common.rails.subagent_ttse_consult_rail import (
+ TTSEConsultDependencies,
+ )
+
+ if self._is_code_agent:
+ return None
+ rail = self._ttse_rail
+ config = self._resolved_ttse_config()
+ if rail is None or not get_ttse_enabled({"ttse": config}):
+ return None
+ if not coerce_config_bool(config.get("inject_enabled"), True):
+ return None
+ disabled = resolve_string_or_list_config(self._config_cache.get("disabled_tools"))
+ live_disabled = getattr(self._disabled_tools_rail, "_disabled_tools", ())
+ if "ttse_consult" in disabled or "ttse_consult" in live_disabled:
+ return None
+ store = getattr(rail, "_ttse_store", None)
+ rail_config = getattr(rail, "_ttse_config", None)
+ if store is None or rail_config is None or not rail_config.inject_enabled:
+ return None
+ return TTSEConsultDependencies(
+ store=store,
+ max_chars=int(getattr(rail_config, "consult_max_chars", 8000) or 8000),
+ max_rules=int(getattr(rail_config, "consult_max_rules", 40) or 40),
+ default_top_k=int(getattr(rail_config, "consult_top_k", 8) or 8),
+ rrf_k=int(getattr(rail_config, "consult_rrf_k", 60) or 60),
+ )
+
+ def _bind_subagent_ttse_wiring(self) -> None:
+ """为非 Code 实例装配查询入口,能力由父级 TTSE 状态和开关决定。"""
+ if self._instance is None or self._is_code_agent:
+ return
+ try:
+ from jiuwenswarm.agents.harness.common.tools.subagent_executor.ttse import (
+ install_subagent_ttse_wiring,
+ )
+
+ install_subagent_ttse_wiring(
+ self._instance, self._subagent_ttse_consult_dependencies,
+ )
+ except Exception:
+ logger.warning("[subagent.ttse] wiring installation failed", exc_info=True)
+
def _resolve_model_for_request(self, request: AgentRequest) -> Model:
"""根据请求中的 model_name 参数查找对应模型(支持别名),未匹配则回退默认模型。
@@ -9403,6 +9448,7 @@ class JiuWenSwarmDeepAdapter:
)
self._bind_subagent_model_resolver()
self._bind_subagent_authorization_wiring()
+ self._bind_subagent_ttse_wiring()
_apply_llm_io_trace_patch()
diff --git a/tests/unit_tests/agentserver/test_code_agent_rail.py b/tests/unit_tests/agentserver/test_code_agent_rail.py
index b0bee93939..09dc53970f 100644
--- a/tests/unit_tests/agentserver/test_code_agent_rail.py
+++ b/tests/unit_tests/agentserver/test_code_agent_rail.py
@@ -36,6 +36,39 @@ class TestBuildAgentToolCard:
class TestAgentTool:
+ @pytest.mark.parametrize("lazy", [False, True])
+ def test_create_subagent_preserves_spec_rails(self, monkeypatch, tmp_path, lazy):
+ from openjiuwen.harness.workspace.workspace import Workspace
+ from jiuwenswarm.agents.harness.common.rails.disabled_tools_rail import DisabledToolsRail
+ from jiuwenswarm.server.runtime.agent_adapter.deep import subagent_load
+
+ forked = object()
+ fork = MagicMock(return_value=forked)
+ progressive = SimpleNamespace(fork_for_agent=fork)
+ monkeypatch.setattr(subagent_load, "get_config", dict)
+ monkeypatch.setattr(subagent_load, "is_subagent_tool_lazy_load_enabled", lambda _: lazy)
+ monkeypatch.setattr(subagent_load, "build_progressive_tool_rail_from_config", lambda *args, **kwargs: progressive)
+ parent = SimpleNamespace(
+ deep_config=SimpleNamespace(
+ model=object(), workspace=Workspace(root_path=str(tmp_path)),
+ max_iterations=10, backend=None, sys_operation=None,
+ language="cn", prompt_mode=None, enable_read_image_multimodal=False,
+ ),
+ ability_manager=SimpleNamespace(list=list),
+ )
+ definition = _make_agent_def()
+ definition.disallowed_tools = ["ttse_consult"]
+ tool = _make_agent_tool(parent=parent, custom_agents=[definition])
+ with patch("openjiuwen.harness.factory.create_deep_agent") as factory:
+ tool._create_sub_agent(definition, "child-session")
+ rails = factory.call_args.kwargs["rails"]
+ assert any(isinstance(rail, DisabledToolsRail) and "ttse_consult" in rail._disabled_tools for rail in rails)
+ if lazy:
+ assert forked in rails
+ fork.assert_called_once_with()
+ else:
+ assert len(rails) == 1
+
@pytest.mark.asyncio
async def test_invoke_missing_subagent_type_raises(self):
tool = _make_agent_tool()
diff --git a/tests/unit_tests/agentserver/test_subagent_ttse_consult.py b/tests/unit_tests/agentserver/test_subagent_ttse_consult.py
new file mode 100644
index 0000000000..f7ddcc84f3
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_subagent_ttse_consult.py
@@ -0,0 +1,762 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""子 Agent 共享 TTSE 查询库、工具所有权及配置生命周期回归。"""
+
+import asyncio
+import logging
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from openjiuwen.agent_evolving.ttse.config import TTSEConfig
+from openjiuwen.agent_evolving.ttse.stores import TTSERecordStore
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.single_agent.ability_manager import AbilityManager
+from openjiuwen.core.single_agent.prompts.builder import SystemPromptBuilder
+
+from jiuwenswarm.agents.harness.common.rails.disabled_tools_rail import (
+ DisabledToolsRail,
+)
+from jiuwenswarm.agents.harness.common.rails.subagent_ttse_consult_rail import (
+ SubagentTTSEConsultRail,
+ TTSEConsultDependencies,
+)
+from jiuwenswarm.agents.harness.common.tools.subagent_executor.ttse import (
+ install_subagent_ttse_wiring,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
+
+
+def child_agent(rails=None):
+ # 故意使用相同 owner,验证不会因内建 Agent card 重用而串工具。
+ configured = list(rails or [])
+ return SimpleNamespace(
+ ability_manager=AbilityManager(owner_id="same-child-card"),
+ system_prompt_builder=SystemPromptBuilder(),
+ prompt_attachment_manager=SimpleNamespace(
+ add_section=AsyncMock(),
+ clear_section=AsyncMock(),
+ ),
+ configured_rails=lambda: configured,
+ add_rail=configured.append,
+ is_initialized=False,
+ _initialized=False,
+ )
+
+
+def context(child):
+ return SimpleNamespace(
+ agent=child,
+ session=SimpleNamespace(get_session_id=lambda: "child-session"),
+ inputs=SimpleNamespace(
+ system_prompt_builder=child.system_prompt_builder, tools=[]
+ ),
+ )
+
+
+def runtime_context(child, query, state):
+ ctx = context(child)
+ ctx.inputs.query = query
+ ctx.session.get_state = state.get
+ ctx.session.update_state = state.update
+ return ctx
+
+
+async def test_shared_store_real_query_concurrent_owners_and_cleanup(tmp_path, caplog):
+ caplog.set_level(logging.INFO, logger=SubagentTTSEConsultRail.__module__)
+ store = TTSERecordStore(TTSEConfig(store_path=str(tmp_path / "bank.json")))
+ await store.add_fact("项目测试必须使用 pytest 执行。")
+ dependencies = TTSEConsultDependencies(store=store)
+ children = [child_agent(), child_agent()]
+ rails = [SubagentTTSEConsultRail(lambda: dependencies) for _ in children]
+ for child, rail in zip(children, rails):
+ child.configured_rails().append(rail)
+ rail.init(child)
+ tools = [
+ Runner.resource_mgr.get_tool(c.ability_manager.get("ttse_consult").id)
+ for c in children
+ ]
+ try:
+ assert tools[0] is not tools[1]
+ assert tools[0].card.id != tools[1].card.id
+ results = await asyncio.gather(
+ *[
+ tool.invoke({"category": "all", "query": "项目测试 pytest"})
+ for tool in tools
+ ]
+ )
+ assert all("pytest" in result for result in results)
+ messages = [
+ r.getMessage()
+ for r in caplog.records
+ if r.name == SubagentTTSEConsultRail.__module__
+ ]
+ assert sum("consult_start " in message for message in messages) == 2
+ assert sum("consult_completed " in message for message in messages) == 2
+ assert all(
+ "elapsed_ms=" in message
+ for message in messages
+ if "consult_completed " in message
+ )
+ rails[0].uninit(children[0])
+ assert Runner.resource_mgr.get_tool(tools[0].card.id) is None
+ assert Runner.resource_mgr.get_tool(tools[1].card.id) is tools[1]
+ assert "pytest" in await tools[1].invoke({"category": "all", "query": "测试"})
+ finally:
+ for child, rail in zip(children, rails):
+ if rail._agent is not None:
+ rail.uninit(child)
+
+
[email protected]("lazy", [False, True])
+async def test_visibility_catalog_hot_reload_and_disable(tmp_path, lazy):
+ store = TTSERecordStore(TTSEConfig(store_path=str(tmp_path / "bank.json")))
+ current = TTSEConsultDependencies(store=store)
+ progressive = SimpleNamespace(eager_tools=["tools_search"])
+ child = child_agent([progressive] if lazy else [])
+ rail = SubagentTTSEConsultRail(lambda: current)
+ child.configured_rails().append(rail)
+ rail.init(child)
+ ctx = context(child)
+ try:
+ await rail.before_invoke(ctx)
+ first = rail._tool
+ await rail.before_model_call(ctx)
+ assert child.ability_manager.get("ttse_consult") is first.card
+ assert "ttse_consult" in child.system_prompt_builder.build()
+ assert child.prompt_attachment_manager.add_section.await_count == 1
+ if lazy:
+ assert "ttse_consult" in progressive.eager_tools
+ current = TTSEConsultDependencies(store=store, default_top_k=2)
+ await rail.before_invoke(ctx)
+ assert rail._tool is not first
+ assert Runner.resource_mgr.get_tool(first.card.id) is None
+ current = None
+ ctx.inputs.tools = [SimpleNamespace(name="ttse_consult")]
+ await rail.before_invoke(ctx)
+ await rail.before_model_call(ctx)
+ assert child.ability_manager.get("ttse_consult") is None
+ assert "ttse_consult" not in child.system_prompt_builder.build()
+ assert ctx.inputs.tools == []
+ child.prompt_attachment_manager.clear_section.assert_awaited_once()
+ if lazy:
+ assert "ttse_consult" not in progressive.eager_tools
+ current = TTSEConsultDependencies(store=store)
+ await rail.before_invoke(ctx)
+ assert rail._tool is not None
+ finally:
+ rail.uninit(child)
+ if rail._cleanup_tasks:
+ await asyncio.gather(*rail._cleanup_tasks)
+
+
[email protected]("language", ["cn", "en"])
+async def test_catalog_guidance_requires_lookup_independently_of_parent(monkeypatch, language):
+ from openjiuwen.agent_evolving.ttse import render
+
+ parent_guidance = {
+ "cn": "没有相关类或附件为 `(empty)` 时直接执行。",
+ "en": "If none apply or the attachment is `(empty)`, proceed.",
+ }
+ monkeypatch.setattr(render, "DISK_CATALOG_GUIDANCE_CN", parent_guidance["cn"])
+ monkeypatch.setattr(render, "DISK_CATALOG_GUIDANCE_EN", parent_guidance["en"])
+ child = child_agent()
+ child.system_prompt_builder.language = language
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=SimpleNamespace(catalog_counts=dict)))
+ rail.init(child)
+ try:
+ await rail.before_model_call(context(child))
+ prompt = child.system_prompt_builder.build()
+ assert parent_guidance[language] not in prompt
+ if language == "cn":
+ assert "第一次工具调用必须仅调用一次 `ttse_consult`" in prompt
+ assert "不得因目录没有明显匹配分类或为空而跳过查询" in prompt
+ else:
+ assert "MUST be exactly one `ttse_consult` call and no other calls" in prompt
+ assert "an unmatched or empty catalog is not a reason to skip" in prompt
+ finally:
+ await rail.after_invoke(context(child))
+ rail.uninit(child)
+
+
[email protected]("callable_id", [False, True])
+async def test_context_session_fallback_attaches_catalog(callable_id):
+ child = child_agent()
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=SimpleNamespace(catalog_counts=dict)))
+ rail.init(child)
+ ctx = context(child)
+ ctx.session = None
+ ctx.context = SimpleNamespace(session_id=(lambda: "fallback-session") if callable_id else "fallback-session")
+ try:
+ await rail.before_model_call(ctx)
+ assert child.prompt_attachment_manager.add_section.call_args.kwargs["session_id"] == "fallback-session"
+ finally:
+ await rail.after_invoke(ctx)
+ rail.uninit(child)
+
+
[email protected]("language", ["cn", "en"])
[email protected]("missing", ["session", "manager", "attachment_error"])
+async def test_missing_catalog_does_not_claim_attachment(language, missing):
+ child = child_agent()
+ child.system_prompt_builder.language = language
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=SimpleNamespace(catalog_counts=dict)))
+ rail.init(child)
+ ctx = context(child)
+ if missing == "session":
+ ctx.session = None
+ elif missing == "manager":
+ child.prompt_attachment_manager = None
+ else:
+ child.prompt_attachment_manager.add_section.side_effect = RuntimeError("attachment unavailable")
+ try:
+ await rail.before_model_call(ctx)
+ prompt = child.system_prompt_builder.build()
+ if language == "cn":
+ assert "未随请求提供经验分类目录" in prompt
+ assert "末尾附件" not in prompt
+ else:
+ assert "No experience catalog is attached" in prompt
+ assert "trailing attachment" not in prompt
+ assert "category=all" in prompt
+ assert (
+ "第一次工具调用必须仅调用一次 `ttse_consult`" if language == "cn"
+ else "MUST be exactly one `ttse_consult` call and no other calls"
+ ) in prompt
+ finally:
+ await rail.after_invoke(ctx)
+ rail.uninit(child)
+
+
+async def test_reused_child_refreshes_query_and_summary_log_context(caplog, tmp_path):
+ caplog.set_level(logging.INFO, logger=SubagentTTSEConsultRail.__module__)
+ store = TTSERecordStore(TTSEConfig(store_path=str(tmp_path / "bank.json")))
+ child = child_agent()
+ parent = SimpleNamespace(create_subagent=lambda *args, **kwargs: child)
+ install_subagent_ttse_wiring(parent, lambda: TTSEConsultDependencies(store=store))
+ parent.create_subagent("general-purpose", "first-task")
+ rail = child.configured_rails()[0]
+ rail.init(child)
+ try:
+ await rail._tool.invoke({"category": "all", "query": "test"})
+ await rail.after_invoke(context(child))
+ caplog.clear()
+ assert parent.create_subagent(subagent_type="custom", subsession_id="second-task") is child
+ assert child.configured_rails() == [rail]
+ await rail.before_invoke(context(child))
+ await rail._tool.invoke({"category": "all", "query": "test"})
+ await rail.after_invoke(context(child))
+ assert "subagent_type='custom' subsession_id='second-task'" in caplog.text
+ assert "consult_start" in caplog.text and "task_summary" in caplog.text
+ assert "first-task" not in caplog.text
+ finally:
+ rail.uninit(child)
+
+
+def test_explicit_disabled_tools_and_missing_dependencies():
+ child = child_agent([DisabledToolsRail(["ttse_consult"])])
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=object()))
+ rail.init(child)
+ assert child.ability_manager.get("ttse_consult") is None
+ rail.uninit(child)
+
+
+async def test_cleanup_preserves_replacement_and_cancellation():
+ store = SimpleNamespace(catalog_counts=dict)
+ child = child_agent()
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=store))
+ rail.init(child)
+ replacement = rail._tool.card.model_copy(update={"id": "replacement"})
+ child.ability_manager.remove("ttse_consult")
+ child.ability_manager.add(replacement)
+ rail.uninit(child)
+ assert child.ability_manager.get("ttse_consult") is replacement
+
+ def cancelled():
+ raise asyncio.CancelledError
+
+ rail = SubagentTTSEConsultRail(cancelled)
+ with pytest.raises(asyncio.CancelledError):
+ rail.init(child)
+
+
+ "agent_type",
+ [
+ "general-purpose",
+ "research_agent",
+ "browser_agent",
+ "statusline-setup",
+ "custom",
+ ],
+)
+def test_creation_wiring_preserves_arguments_and_is_idempotent(agent_type):
+ child = child_agent()
+ calls = []
+
+ def create(*args, **kwargs):
+ calls.append((args, kwargs))
+ return child
+
+ parent = SimpleNamespace(create_subagent=create)
+ assert install_subagent_ttse_wiring(parent, lambda: None)
+ wrapped = parent.create_subagent
+ assert install_subagent_ttse_wiring(parent, lambda: None)
+ assert parent.create_subagent is wrapped
+ model = object()
+ assert parent.create_subagent(agent_type, "session", model=model) is child
+ parent.create_subagent(agent_type, "session")
+ assert len(child.configured_rails()) == 1
+ rail = child.configured_rails()[0]
+ assert rail._subagent_type == agent_type
+ assert rail._subsession_id == "session"
+ assert calls[0] == ((agent_type, "session"), {"model": model})
+
+
+async def test_already_initialized_child_registers_before_execution():
+ child = child_agent()
+ child.is_initialized = True
+ registered = []
+ closed_streams = []
+
+ async def register(rail):
+ await asyncio.sleep(0)
+ rail.init(child)
+ registered.append(rail)
+
+ async def invoke(query):
+ assert registered
+ return query
+
+ async def stream(query):
+ assert registered
+ try:
+ yield query
+ finally:
+ closed_streams.append(query)
+
+ child.is_registered_rail = lambda rail: rail in registered
+ child.register_rail = AsyncMock(side_effect=register)
+ child.invoke = invoke
+ child.stream = stream
+ parent = SimpleNamespace(create_subagent=lambda *args: child)
+ install_subagent_ttse_wiring(parent, lambda: None)
+ parent.create_subagent("custom", "session")
+ child.register_rail.assert_not_awaited()
+
+ async def collect():
+ return [chunk async for chunk in child.stream("stream")]
+
+ results = await asyncio.gather(child.invoke("invoke"), collect())
+ assert results == ["invoke", ["stream"]]
+ child.register_rail.assert_awaited_once()
+ assert await child.invoke("again") == "again"
+ child.register_rail.assert_awaited_once()
+ early_stream = child.stream("early")
+ assert await anext(early_stream) == "early"
+ await early_stream.aclose()
+ assert closed_streams == ["stream", "early"]
+ registered[0].uninit(child)
+
+
[email protected]("entrypoint", ["invoke", "stream"])
[email protected]("cancel", [False, True])
+async def test_deferred_registration_failure_rolls_back_and_preserves_task(entrypoint, cancel, caplog):
+ child = child_agent()
+ child.is_initialized = True
+ configured = child.configured_rails()
+ fail = True
+ executions = []
+
+ async def register(rail):
+ rail.init(child)
+ configured.append(rail)
+ if fail:
+ if cancel:
+ raise asyncio.CancelledError
+ raise RuntimeError("callback registration failed")
+
+ async def unregister(rail):
+ configured.remove(rail)
+ rail.uninit(child)
+
+ async def invoke():
+ executions.append(child.ability_manager.get("ttse_consult") is not None)
+ return "done"
+
+ async def stream():
+ yield await invoke()
+
+ child.is_registered_rail = lambda rail: rail in configured
+ child.register_rail = AsyncMock(side_effect=register)
+ child.unregister_rail = AsyncMock(side_effect=unregister)
+ child.invoke, child.stream = invoke, stream
+ parent = SimpleNamespace(create_subagent=lambda *args: child)
+ install_subagent_ttse_wiring(parent, lambda: TTSEConsultDependencies(store=object()))
+ parent.create_subagent("custom", "failed-registration")
+
+ async def execute():
+ if entrypoint == "invoke":
+ return await child.invoke()
+ return [chunk async for chunk in child.stream()]
+
+ try:
+ if cancel:
+ with pytest.raises(asyncio.CancelledError):
+ await execute()
+ assert executions == []
+ else:
+ assert await execute() == ("done" if entrypoint == "invoke" else ["done"])
+ assert executions == [False]
+ assert "deferred rail registration failed" in caplog.text
+ child.unregister_rail.assert_awaited_once()
+ assert child.ability_manager.get("ttse_consult") is None
+ assert configured == []
+ fail = False
+ await execute()
+ assert executions[-1] is True
+ finally:
+ for rail in list(configured):
+ await child.unregister_rail(rail)
+
+
+def test_uninit_clears_real_attachments_without_running_loop():
+ from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentManager
+
+ child = child_agent()
+ child.prompt_attachment_manager = PromptAttachmentManager()
+ store = SimpleNamespace(catalog_counts=dict)
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=store))
+ rail.init(child)
+ manager = child.prompt_attachment_manager
+ try:
+ asyncio.run(rail.before_model_call(context(child)))
+ assert asyncio.run(manager.collect_for_session("child-session"))
+ finally:
+ rail.uninit(child)
+ assert asyncio.run(manager.collect_for_session("child-session")) == []
+ assert not rail._cleanup_tasks
+
+
+async def test_retrieval_uses_live_shared_store_mode(tmp_path, monkeypatch):
+ config = TTSEConfig(store_path=str(tmp_path / "bank.json"), consult_retrieve_mode="bm25")
+ store = TTSERecordStore(config)
+ await store.add_fact("Use pytest for tests.")
+ rank = AsyncMock(return_value=([], "test"))
+ monkeypatch.setattr(store.index, "rank_track", rank)
+ monkeypatch.setattr(store.index, "ensure_chroma", AsyncMock())
+ child = child_agent()
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=store))
+ rail.init(child)
+ try:
+ for mode in ("bm25", "embed", "hybrid"):
+ config.consult_retrieve_mode = mode
+ rank.reset_mock()
+ await rail._tool.invoke({"category": "all", "query": "pytest"})
+ assert rank.await_count == 2
+ assert all(call.kwargs["retrieve_mode"] == mode for call in rank.await_args_list)
+ finally:
+ rail.uninit(child)
+
+
[email protected]("mode", ["agent", "flash", "team"])
+def test_adapter_dependency_provider_tracks_parent_and_switches(monkeypatch, mode):
+ adapter = JiuWenSwarmDeepAdapter()
+ adapter._session_instance_mode = mode
+ config = {"enabled": True, "inject_enabled": True}
+ monkeypatch.setattr(adapter, "_resolved_ttse_config", lambda: config)
+ store = object()
+ adapter._ttse_rail = SimpleNamespace(
+ _ttse_store=store,
+ _ttse_config=TTSEConfig(consult_top_k=3),
+ )
+ assert adapter._subagent_ttse_consult_dependencies().store is store
+ assert adapter._subagent_ttse_consult_dependencies().default_top_k == 3
+ adapter._config_cache["disabled_tools"] = ["ttse_consult"]
+ assert adapter._subagent_ttse_consult_dependencies() is None
+ adapter._config_cache.clear()
+ adapter._disabled_tools_rail = DisabledToolsRail(["ttse_consult"])
+ assert adapter._subagent_ttse_consult_dependencies() is None
+ adapter._disabled_tools_rail = None
+ config["inject_enabled"] = False
+ assert adapter._subagent_ttse_consult_dependencies() is None
+ config["inject_enabled"] = True
+ adapter._is_code_agent = True
+ assert adapter._subagent_ttse_consult_dependencies() is None
+ adapter._is_code_agent = False
+ adapter._ttse_rail = None
+ assert adapter._subagent_ttse_consult_dependencies() is None
+
+
[email protected]("originally_eager", [False, True])
+async def test_shared_progressive_rail_survives_other_child_cleanup(originally_eager):
+ from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (
+ ProgressiveToolRail,
+ )
+
+ progressive = ProgressiveToolRail(eager_tools=["ttse_consult"] if originally_eager else [])
+ children = [child_agent([progressive]), child_agent([progressive])]
+ rails = [
+ SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=object()))
+ for _ in children
+ ]
+ for child, rail in zip(children, rails):
+ rail.init(child)
+ try:
+ await rails[0].after_invoke(context(children[0]))
+ assert "ttse_consult" in progressive.eager_tools
+ finally:
+ for child, rail in zip(children, rails):
+ rail.uninit(child)
+ assert ("ttse_consult" in progressive.eager_tools) is originally_eager
+
+
[email protected]("consult", [False, True])
[email protected]("mode", ["agent", "flash"])
+async def test_scripted_model_controls_consult_invocation(tmp_path, monkeypatch, consult, mode):
+ """Only model tool calls trigger retrieval; the runtime does not enforce the prompt."""
+
+ from openjiuwen.core.foundation.llm import (
+ Model,
+ ModelClientConfig,
+ ModelRequestConfig,
+ )
+ from openjiuwen.core.foundation.llm.schema.message import AssistantMessage
+ from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall
+ from openjiuwen.core.foundation.tool import LocalFunction, ToolCard
+ from openjiuwen.core.single_agent.schema.agent_card import AgentCard
+ from openjiuwen.harness import create_deep_agent
+ from openjiuwen.harness.schema.config import SubAgentConfig
+
+ from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (
+ ProgressiveToolRail,
+ )
+
+ store = TTSERecordStore(TTSEConfig(store_path=str(tmp_path / "bank.json")))
+ await store.add_fact("部署前必须运行 pytest。")
+ events = []
+
+ async def business():
+ events.append("business")
+ return "completed"
+
+ async def scripted(self, messages, *, tools=None, **kwargs):
+ events.append("model")
+ model_calls = events.count("model")
+ if model_calls == 1:
+ assert "ttse_consult" in [t.name for t in tools]
+ prompt = "\n".join(str(getattr(m, "content", "")) for m in messages)
+ assert "ttse_consult" in prompt
+ assert "经验目录" in prompt
+ assert "source=runtime" not in prompt
+ assert "pytest" not in prompt
+ assert child._jiuwenswarm_ttse_consult_rail._consult_calls == 0
+ if consult:
+ return AssistantMessage(
+ content="",
+ tool_calls=[
+ ToolCall(
+ id="consult-call",
+ type="function",
+ name="ttse_consult",
+ arguments='{"category": "all", "query": "pytest"}',
+ )
+ ],
+ )
+ if model_calls == (2 if consult else 1):
+ if consult:
+ prompt = "\n".join(str(getattr(m, "content", "")) for m in messages)
+ assert "部署前必须运行 pytest。" in prompt
+ assert child._jiuwenswarm_ttse_consult_rail._consult_calls == 1
+ return AssistantMessage(
+ content="",
+ tool_calls=[
+ ToolCall(
+ id="business-call",
+ type="function",
+ name="business",
+ arguments="{}",
+ )
+ ],
+ )
+ return AssistantMessage(content="done")
+
+ monkeypatch.setattr(Model, "invoke", scripted)
+ model = Model(
+ ModelClientConfig(
+ client_provider="OpenAI",
+ api_key="offline",
+ api_base="https://example.invalid",
+ ),
+ ModelRequestConfig(model="offline"),
+ )
+ tool = LocalFunction(
+ ToolCard(
+ name="business",
+ id="ttse-test-business",
+ input_params={
+ "type": "object",
+ "properties": {},
+ },
+ ),
+ business,
+ )
+ parent = create_deep_agent(
+ model,
+ workspace=str(tmp_path),
+ add_general_purpose_agent=False,
+ enable_read_image_multimodal=False,
+ subagents=[
+ SubAgentConfig(
+ agent_card=AgentCard(name="custom", id=f"ttse-test-child-{mode}-{consult}"),
+ system_prompt="Execute the assigned task.",
+ tools=[tool],
+ enable_task_loop=False,
+ rails=[ProgressiveToolRail(eager_tools=["business"])],
+ )
+ ],
+ )
+ if mode == "flash":
+ from jiuwenswarm.server.runtime.agent_adapter.interface_flash import JiuwenSwarmFlashAdapter
+
+ adapter = JiuwenSwarmFlashAdapter()
+ else:
+ adapter = JiuWenSwarmDeepAdapter()
+ adapter._session_instance_mode = mode
+ monkeypatch.setattr(
+ adapter, "_resolved_ttse_config", lambda: {"enabled": True, "inject_enabled": True}
+ )
+ adapter._ttse_rail = SimpleNamespace(_ttse_store=store, _ttse_config=TTSEConfig())
+ install_subagent_ttse_wiring(parent, adapter._subagent_ttse_consult_dependencies)
+ child = parent.create_subagent("custom", f"ttse-scripted-{mode}-{consult}")
+ try:
+ await child.invoke({"query": "部署任务"})
+ assert events == (["model"] if consult else []) + ["model", "business", "model"]
+ assert child.ability_manager.get("ttse_consult") is None
+ finally:
+ for rail in list(child.configured_rails()):
+ await child.unregister_rail(rail)
+ child.ability_manager.teardown_tools()
+
+
+async def test_retrieval_failure_does_not_abort_task(caplog):
+ caplog.set_level(logging.INFO, logger=SubagentTTSEConsultRail.__module__)
+ child = child_agent()
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=object()))
+ rail.init(child)
+ try:
+ result = await rail._tool.invoke({"category": "all", "query": "test"})
+ assert "continue with the current task" in result
+ assert "consult_start " in caplog.text
+ assert "consult_failed " in caplog.text
+ assert "consult_completed " not in caplog.text
+ await rail.after_invoke(context(child))
+ assert "consult_calls=1" in caplog.text
+ assert child.ability_manager.get("ttse_consult") is None
+ await rail.before_invoke(context(child))
+ assert rail._tool is not None
+ finally:
+ rail.uninit(child)
+
+
+async def test_task_summary_identifies_no_consultation(caplog):
+ caplog.set_level(logging.INFO, logger=SubagentTTSEConsultRail.__module__)
+ child = child_agent()
+ rail = SubagentTTSEConsultRail(
+ lambda: None,
+ subagent_type="research_agent",
+ subsession_id="child-log-test",
+ )
+ rail.init(child)
+ await rail.before_invoke(context(child))
+ await rail.after_invoke(context(child))
+ assert (
+ "task_summary subagent_type='research_agent' subsession_id='child-log-test' consult_calls=0"
+ in caplog.text
+ )
+ assert "consult_start " not in caplog.text
+ rail.uninit(child)
+
+
+def test_custom_agent_explicit_disallow_is_preserved(tmp_path, monkeypatch):
+ from unittest.mock import MagicMock
+
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep
+ from jiuwenswarm.server.runtime.agent_adapter.deep import subagent_load
+ from jiuwenswarm.server.runtime.agent_config_service import AgentDefinition
+
+ monkeypatch.setattr(subagent_load, "get_config", dict)
+ definition = AgentDefinition(
+ name="restricted",
+ description="test",
+ prompt="test",
+ source="project",
+ tools=["*"],
+ disallowed_tools=["ttse_consult"],
+ )
+ spec = interface_deep._agent_def_to_subagent_config(
+ definition,
+ MagicMock(),
+ str(tmp_path),
+ )
+ assert any(
+ "ttse_consult" in getattr(rail, "_disabled_tools", ()) for rail in spec.rails
+ )
+
+
[email protected]("resume", [False, True])
[email protected]("language", ["cn", "en"])
+async def test_lifecycle_exposes_catalog_without_invoking_consult(tmp_path, resume, language):
+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput
+
+ store = TTSERecordStore(TTSEConfig(store_path=str(tmp_path / "bank.json")))
+ await store.add_fact("Experience body must only be returned by a model lookup.")
+ child = child_agent()
+ child.system_prompt_builder.language = language
+ rail = SubagentTTSEConsultRail(lambda: TTSEConsultDependencies(store=store))
+ rail.init(child)
+ state = {}
+ ctx = runtime_context(child, InteractiveInput() if resume else "new task", state)
+ try:
+ invoke = rail._tool.invoke = AsyncMock()
+ await rail.before_invoke(ctx)
+ await rail.before_model_call(ctx)
+ await rail.before_model_call(ctx)
+ invoke.assert_not_awaited()
+ assert rail._consult_calls == 0
+ assert state == {}
+ assert "ttse_consult" in [tool.name for tool in ctx.inputs.tools]
+ attachment = child.prompt_attachment_manager.add_section.call_args.kwargs["content"]
+ assert "Experience body must only" not in attachment
+ assert "source=runtime" not in attachment
+ prompt = child.system_prompt_builder.build()
+ if language == "cn":
+ assert "第一次工具调用必须仅调用一次 `ttse_consult`" in prompt
+ assert "必须收到并阅读查询结果后" in prompt
+ assert "不要求每个任务都查询" not in prompt
+ else:
+ assert "MUST be exactly one `ttse_consult` call and no other calls" in prompt
+ assert "Receive and read its result before loading skills" in prompt
+ assert "not required for every task" not in prompt
+ await rail.after_invoke(ctx)
+ assert child.ability_manager.get("ttse_consult") is None
+ finally:
+ rail.uninit(child)
+ if rail._cleanup_tasks:
+ await asyncio.gather(*rail._cleanup_tasks)