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(btw): add /btw command

ldstyle8da6da5f5fb27
diff --git a/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py b/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py
index 47e7e56cdf..a139c5644d 100644
--- a/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py
+++ b/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py
@@ -2,8 +2,8 @@
"""Code mode prompt builder — English-only.
-Provides 7 static prompt sections aligned with Claude Code's getSystemPrompt()
-section structure. Each section is a PromptSection with English-only content.
+Provides 7 static prompt sections.
+Each section is a PromptSection with English-only content.
Sections are injected once at agent creation time (build_code_system_prompt).
Dynamic content (time, runtime state, memory) is injected per-request by Rails.
diff --git a/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.py b/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.py
new file mode 100644
index 0000000000..e419c99180
--- /dev/null
+++ b/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.py
@@ -0,0 +1,226 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""PlanApprovalRail — pending-approval lifecycle for plan mode exit.
+
+``exit_plan_mode`` presents the plan for review
+but the agent **stays in plan mode** until the user approves via chat.
+Mode restoration (``restore_mode_after_plan_exit``) happens only after
+approval, when the server injects the approved notification on the next
+user turn and ``_ensure_code_mode_state`` runs.
+
+The rail:
+
+1. Detects successful ``exit_plan_mode`` calls in ``after_tool_call``.
+2. Re-enters plan mode if the tool already restored it prematurely.
+3. Rewrites tool_result copy from "plan ended" to "awaiting your review".
+4. Stores ``_plan_approval_state`` for the server pending gate.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from openjiuwen.core.common.logging import logger
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+from jiuwenswarm.agents.harness.code.prompt.plan_approval import PENDING_APPROVAL_MARKER
+
+if TYPE_CHECKING:
+ from openjiuwen.harness.deep_agent import DeepAgent
+
+
+@dataclass
+class PlanApprovalState:
+ """Pending-approval state for one session.
+
+ Stored on the agent instance after exit_plan_mode and consumed by the
+ server layer on the next user request.
+ """
+
+ pending: bool = False
+ plan_slug: str = ""
+ plan_content: str = ""
+ plan_path: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ """Serialize to a JSON-friendly dict."""
+ return {
+ "pending": self.pending,
+ "plan_slug": self.plan_slug,
+ "plan_content": self.plan_content,
+ "plan_path": self.plan_path,
+ }
+
+
+PENDING_EXIT_RESULT_PREFIX = {
+ "cn": "计划已提交,等待用户确认。\n计划文件:{plan_path}\n\n## 计划:\n",
+ "en": "Plan submitted for your review.\nPlan file: {plan_path}\n\n## Plan:\n",
+}
+
+
+def _detect_language(agent: DeepAgent | None) -> str:
+ """Return ``"cn"`` or ``"en"`` based on the agent's prompt builder."""
+ if agent is None:
+ return "cn"
+ builder = getattr(agent, "system_prompt_builder", None)
+ if builder is None:
+ return "cn"
+ return getattr(builder, "language", "cn")
+
+
+class PlanApprovalRail(DeepAgentRail):
+ """Rail that manages the plan-approval lifecycle.
+
+ Priority ``76`` — runs after AgentModeRail (85) and ConfirmInterruptRail
+ so that the tool has already executed and its result is available.
+ """
+
+ priority = 76
+
+ def init(self, agent: DeepAgent) -> None:
+ """Capture the agent reference.
+
+ Args:
+ agent: The parent DeepAgent.
+ """
+ self._agent = agent
+
+ def uninit(self, agent: DeepAgent) -> None:
+ """Clean up the stored agent reference."""
+ self._agent = None
+
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ """No-op — this rail only observes tool calls."""
+ return
+
+ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
+ """No-op — this rail only observes tool calls."""
+ return
+
+ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
+ """Detect exit_plan_mode and store pending-approval state.
+
+ Also appends a pending-approval text marker as a **fallback** so
+ text-only channels (e.g. IM bridges) still see guidance on how to
+ approve/reject the plan.
+
+ Args:
+ ctx: Callback context containing tool-name, result, and session.
+ """
+ if ctx.inputs.tool_name != "exit_plan_mode":
+ return
+ if ctx.extra.get("_skip_tool"):
+ return
+ # ConfirmInterrupt 等 hook 中断时工具未真正执行,不应进入待审批状态。
+ if ctx.inputs.tool_result is None:
+ return
+
+ agent = self._agent
+ if agent is None:
+ logger.warning("[PlanApprovalRail] agent is None, skipping")
+ return
+
+ language = _detect_language(agent)
+
+ # ── 1. Extract plan content from tool result ──
+ tool_msg = ctx.inputs.tool_msg
+ result_text = ""
+ if tool_msg and hasattr(tool_msg, "content") and tool_msg.content:
+ raw = tool_msg.content
+ if isinstance(raw, str):
+ result_text = raw
+ elif isinstance(raw, list):
+ # Extract text from structured content blocks
+ for block in raw:
+ if isinstance(block, dict) and block.get("type") == "text":
+ result_text = block.get("text", "")
+ if result_text:
+ break
+ if not result_text:
+ result_text = str(ctx.inputs.tool_result or "")
+
+ # ── 2. Extract plan body (strip prefix metadata) ──
+ plan_content = self._extract_plan_body(result_text)
+
+ # ── 3. Load plan metadata via agent ──
+ plan_path = agent.get_plan_file_path(ctx.session)
+ plan_path_str = str(plan_path) if plan_path else ""
+ state = agent.load_state(ctx.session)
+
+ # Safety net: patched exit_plan_mode must stay in plan until approval.
+ if state.plan_mode.mode != "plan":
+ agent.switch_mode(session=ctx.session, mode="plan")
+ state = agent.load_state(ctx.session)
+ logger.warning(
+ "[PlanApprovalRail] Re-entered plan mode after premature exit restore"
+ )
+
+ if not plan_content and plan_path_str:
+ try:
+ plan_file = Path(plan_path_str)
+ if plan_file.is_file():
+ plan_content = plan_file.read_text(encoding="utf-8").strip()
+ except OSError:
+ plan_content = ""
+ if not plan_content:
+ logger.warning("[PlanApprovalRail] no plan content extracted from exit_plan_mode result")
+ plan_content = "(plan content unavailable)"
+
+ # ── 4. Build and store approval state ──
+ approval_state = PlanApprovalState(
+ pending=True,
+ plan_slug=state.plan_mode.plan_slug or "",
+ plan_content=plan_content,
+ plan_path=plan_path_str,
+ )
+ agent._plan_approval_state = approval_state # pylint: disable=protected-access
+ logger.info(
+ "[PlanApprovalRail] exit_plan_mode detected, pending approval set "
+ "for plan %s",
+ approval_state.plan_slug,
+ )
+
+ # ── 5. Rewrite tool_result + append chat guidance marker ──
+ marker = PENDING_APPROVAL_MARKER.get(language, PENDING_APPROVAL_MARKER["cn"])
+ if tool_msg and hasattr(tool_msg, "content"):
+ tool_msg.content = str(tool_msg.content) + marker
+
+ @staticmethod
+ def _extract_plan_body(result_text: str) -> str:
+ """Strip the prefix metadata from the ExitPlanModeTool result.
+
+ ExitPlanModeTool returns::
+
+ 规划模式已结束。
+ 计划文件:xxx
+
+ ## 计划:
+ <plan_body>
+
+ We only keep the part after the ``## 计划:`` / ``## Plan:`` marker.
+
+ Args:
+ result_text: Full tool result text.
+ language: ``"cn"`` or ``"en"``.
+
+ Returns:
+ The plan body text, or the full text if no marker is found.
+ """
+ for marker in ("## 计划:\n", "## Plan:\n"):
+ if marker in result_text:
+ return result_text.split(marker, 1)[1].strip()
+ # Fallback: try to strip common prefixes
+ lines = result_text.strip().split("\n", 10)
+ if len(lines) > 5:
+ return "\n".join(lines[5:]).strip()
+ return result_text.strip()
+
+
+__all__ = [
+ "PENDING_EXIT_RESULT_PREFIX",
+ "PlanApprovalRail",
+ "PlanApprovalState",
+]
diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.py
index 1808d225bd..80482b40fa 100644
--- a/jiuwenswarm/agents/harness/common/session_ops_service.py
+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py
@@ -565,9 +565,7 @@ async def rewind_session_context(
compressed by ``round_level_compressor`` / ``dialogue_compressor``), so we
cannot simply slice the in-memory buffer. Instead we reload the truncated
history.json, convert its records to openjiuwen messages, tear down the old
- context, and build a fresh one — analogous to Claude Code's
- ``setMessages(prev.slice(0, messageIndex))`` followed by
- ``resetMicrocompactState``.
+ context, and build a fresh one.
"""
from openjiuwen.core.foundation.llm.schema.message import (
UserMessage,
@@ -957,7 +955,7 @@ async def copy_session_state(
modified_state["stop_condition_state"] = None
modified_state["pending_follow_ups"] = []
- # Generate new plan slug and copy plan file (like Claude Code's /branch)
+ # Generate new plan slug and copy plan file
plan_mode = modified_state.get("plan_mode") or {}
old_slug = plan_mode.get("plan_slug")
if old_slug:
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/btw.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/btw.ts
new file mode 100644
index 0000000000..3af9c417d4
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/btw.ts
@@ -0,0 +1,79 @@
+/**
+ * /btw (by the way) — ask a quick side question without interrupting
+ * the main conversation. The backend spawns an isolated, tool-free,
+ * single-turn LLM query against the current conversation context
+ * and returns just the answer.
+ */
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";
+
+interface BtwResponse {
+ status: "ok" | "no_context" | "failed";
+ answer?: string;
+ error?: string;
+}
+
+const NO_CONTEXT_MSG = "No conversation context available yet — send a message first.";
+const FAILED_MSG = "Couldn't answer the side question. Please try again or ask in the main conversation.";
+const EMPTY_QUESTION_MSG = "Usage: /btw <your question>";
+
+export function createBtwCommand(): SlashCommand {
+ return {
+ name: "btw",
+ description: "Ask a quick side question without interrupting the main conversation",
+ usage: "/btw <question>",
+ example: "/btw what does git status do?",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const question = args?.trim();
+ if (!question) {
+ ctx.addItem(addError(ctx.sessionId, EMPTY_QUESTION_MSG));
+ return;
+ }
+
+ // Dim indicator while the side query is running
+ const thinkingId = `btw-thinking-${Date.now()}`;
+ ctx.addItem({
+ kind: "info",
+ id: thinkingId,
+ sessionId: ctx.sessionId,
+ content: `Answering: ${question}`,
+ icon: "💭",
+ at: new Date().toISOString(),
+ meta: { view: "dim" as const },
+ });
+
+ try {
+ const payload = await ctx.request<BtwResponse>(
+ "command.btw",
+ { question, mode: ctx.mode },
+ 120000,
+ );
+
+ switch (payload.status) {
+ case "ok":
+ if (payload.answer) {
+ ctx.addItem(
+ addInfo(ctx.sessionId, `💡 /btw ${question}\n\n${payload.answer}`),
+ );
+ } else {
+ ctx.addItem(addInfo(ctx.sessionId, "(empty answer)", "💡"));
+ }
+ break;
+ case "no_context":
+ ctx.addItem(addInfo(ctx.sessionId, NO_CONTEXT_MSG, "i"));
+ break;
+ case "failed":
+ ctx.addItem(addError(ctx.sessionId, payload.error || FAILED_MSG));
+ break;
+ default:
+ ctx.addItem(addError(ctx.sessionId, FAILED_MSG));
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `btw failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
index f57a54bf0f..b75b49f8ac 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
@@ -1,6 +1,7 @@
/** 内置 slash 与 Gateway 受控指令对齐时参见仓库 `jiuwenswarm/gateway/slash_command.py`(SSOT)与 `docs/zh/CLI_COMMANDS.md`。 */
import type { SlashCommand } from "./types.js";
import { createBranchCommand } from "./builtins/branch.js";
+import { createBtwCommand } from "./builtins/btw.js";
import { createClearCommand } from "./builtins/clear.js";
import { createColorCommand } from "./builtins/color.js";
import { createCompactCommand } from "./builtins/compact.js";
@@ -56,6 +57,7 @@ export function createBuiltinCommands(): SlashCommand[] {
createHooksCommand(),
createKeybindingsCommand(),
createBranchCommand(),
+ createBtwCommand(),
createClearCommand(),
createInitCommand(),
createColorCommand(),
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index 03233a42e9..de4f1f7a5e 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -16,6 +16,7 @@ class ReqMethod(Enum):
CHAT_CANCEL = "chat.interrupt"
CHAT_ANSWER = "chat.user_answer"
HISTORY_GET = "history.get"
+ COMMAND_BTW = "command.btw"
COMMAND_ADD_DIR = "command.add_dir"
COMMAND_CHROME = "command.chrome"
COMMAND_COMPACT = "command.compact"
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index f553905302..03aca9bd6f 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -314,7 +314,7 @@ def _load_logging_config_from_yaml() -> dict[str, Any]:
if isinstance(raw, dict):
return raw
except Exception as e:
- logger.error(f"load logging config failed, caused by={e}")
+ logger.warning("load logging config failed, caused by=%s", e)
return {}
@@ -1897,5 +1897,5 @@ def wait_for_pid_exit(pid: int, timeout: float = 60.0) -> None:
logger.warning("process %d did not exit within %.1f seconds", pid, timeout)
-setup_logger()
logger = logging.getLogger(__name__)
+setup_logger()
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 6b44c1c240..412b3f45b2 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -448,14 +448,19 @@ class GatewayServer:
if ws is None:
channel_id = getattr(msg, "channel_id", None)
# 多 TUI 窗口:有 session_id 时精确路由;无 session_id 时广播(如 cron 推送到 TUI)。
- if channel_id and channel_id != "acp" and msg.type != "res":
+ if channel_id and channel_id != "acp":
+ if msg.type == "res":
+ payload_data = dict(msg.payload or {}) if isinstance(msg.payload, dict) else {}
+ frame = {"type": "res", "id": msg.id, "ok": bool(msg.ok), "payload": payload_data}
+ else:
+ frame = _build_event_frame(msg)
+
session_id = self._extract_routing_session_id(msg, include_top_level=False)
if session_id:
session_key = self._client_route_key(channel_id, session_id)
if session_key:
client = self._session_to_client.get(session_key)
if client is not None and not bool(getattr(client, "closed", False)):
- frame = _build_event_frame(msg)
data = json.dumps(frame, ensure_ascii=False)
try:
await client.send(data)
@@ -469,11 +474,11 @@ class GatewayServer:
elif not self._extract_routing_session_id(msg, include_top_level=True):
clients = self._find_channel_clients(channel_id)
if clients:
- frame = _build_event_frame(msg)
data = json.dumps(frame, ensure_ascii=False)
logger.info(
- "[GatewayServer] broadcast fallback (no session_id): channel_id=%s clients=%d id=%s",
- channel_id, len(clients), getattr(msg, "id", None),
+ "[GatewayServer] broadcast fallback (no session_id): "
+ "channel_id=%s clients=%d id=%s type=%s",
+ channel_id, len(clients), getattr(msg, "id", None), msg.type,
)
await asyncio.gather(
*[c.send(data) for c in clients],
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 28930dc22f..7af7e14c6d 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -166,6 +166,7 @@ def _update_auto_harness_gitcode_access_token(value: str) -> None:
CLI_FORWARD_REQ_METHODS = frozenset(
{
"command.add_dir",
+ "command.btw",
"command.chrome",
"command.compact",
"command.compact_partial",
@@ -267,6 +268,7 @@ CLI_FORWARD_REQ_METHODS = frozenset(
CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset(
{
"command.add_dir",
+ "command.btw",
"command.chrome",
"command.compact",
"command.compact_partial",
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 20db7aca79..edae56efaf 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -455,7 +455,7 @@ def _reject_extra_sandbox_files_params(params: dict[str, Any]) -> None:
def _inject_plan_mode_activation_reminder(request: AgentRequest) -> None:
"""在用户消息中注入 <system-reminder> 告知 LLM 调用 enter_plan_mode.
- 对齐 Claude Code:plan 模式行为指令不进 system prompt,
+ plan 模式行为指令不进 system prompt,
而是通过对话中的 tool_result 传递。此提醒是进入 plan 模式后的
第一个引导,告诉 LLM 调用 enter_plan_mode 以获取完整指令。
@@ -1053,6 +1053,9 @@ class AgentWebSocketServer:
if request.req_method == ReqMethod.COMMAND_RECAP:
await self._handle_command_recap(ws, request, send_lock)
return
+ if request.req_method == ReqMethod.COMMAND_BTW:
+ await self._handle_command_btw(ws, request, send_lock)
+ return
if request.req_method == ReqMethod.COMMAND_DIFF:
await self._handle_command_diff(ws, request, send_lock)
return
@@ -1453,7 +1456,7 @@ class AgentWebSocketServer:
此处只需 post_run 持久化到 checkpointer.
切换到 plan 模式且尚未调用 enter_plan_mode 时,注入 <system-reminder>
- 告知 LLM 调用 enter_plan_mode(对齐 Claude Code:plan 指令不进 system prompt)。
+ 告知 LLM 调用 enter_plan_mode。
``exit_plan_mode`` now restores mode immediately inside the tool
(via ``restore_mode_after_plan_exit``), so this method no longer needs
@@ -2898,6 +2901,83 @@ class AgentWebSocketServer:
async with send_lock:
await ws.send(json.dumps(wire, ensure_ascii=False))
+ async def _handle_command_btw(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ """处理 /btw 命令:独立、无工具、单轮 LLM 侧问题查询。
+
+ - 获取当前会话上下文(最近消息)
+ - 用隔离的 LLM 查询回答问题
+ - 不修改对话历史
+ - 不使用任何工具(纯文本回答)
+ - 仅单轮(无后续 token 消耗)
+ """
+ try:
+ session_id = request.session_id or "default"
+ params = request.params or {}
+ channel_id = request.channel_id or "default"
+ question = (params.get("question") or "").strip()
+
+ logger.info(
+ "[AgentWebSocketServer] command.btw received: session_id=%s question=%s",
+ session_id,
+ question[:100] if question else "",
+ )
+
+ if not question:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={"status": "failed", "error": "Question is required"},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+ return
+
+ mode, sub_mode, _ = resolve_agent_request_mode(params.get("mode", "agent.plan"))
+ agent_mode = "agent" if mode == "auto_harness" else mode
+
+ agent = await self._agent_manager.get_agent(
+ channel_id=channel_id,
+ mode=agent_mode,
+ project_dir=resolve_request_project_dir(request),
+ sub_mode=sub_mode,
+ )
+
+ if agent is None:
+ raise ValueError("Failed to get agent")
+
+ result_data = await agent.generate_btw_answer(
+ session_id=session_id,
+ question=question,
+ )
+
+ logger.info(
+ "[AgentWebSocketServer] command.btw result: status=%s",
+ result_data.get("status"),
+ )
+
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload=result_data,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.btw failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={
+ "status": "failed",
+ "error": str(e),
+ },
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
async def _handle_command_diff(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from jiuwenswarm.server.utils.diff_service import get_diff_service
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 5f41e17699..0b87bfd105 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -1924,6 +1924,27 @@ class JiuWenSwarm:
direction=direction,
)
+ async def generate_btw_answer(self, session_id: str, question: str) -> dict[str, Any]:
+ """回答 /btw 侧问题:独立、无工具、单轮 LLM 查询。
+
+ 将最近对话上下文 + 用户问题发送给模型,模型仅基于已有上下文回答,
+ 不使用工具、不修改对话历史。
+
+ Args:
+ session_id: 会话ID
+ question: 用户侧问题
+
+ Returns:
+ 包含 btw 结果的字典:
+ - status: "ok" | "no_context" | "failed"
+ - answer: 回答文本(仅当 status == "ok" 时)
+ - error: 错误信息(仅当 status == "failed" 时)
+ """
+ adapter = self._adapter
+ if adapter is None:
+ raise ValueError("Agent adapter not available")
+ return await adapter.generate_btw_answer(session_id=session_id, question=question)
+
# ---------- 资源清理 ----------
async def cancel_inflight_work(self, log_prefix: str = "[gateway disconnect] ") -> None:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 277bdf401b..c7ee0f2f02 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -105,7 +105,7 @@ Do NOT proceed to implement anything until the user approves your plan via
# ---------------------------------------------------------------------------
# Plan mode instructions for enter_plan_mode tool_result
-# (aligned with Claude Code: instructions live in conversation, not system prompt)
+# instructions live in conversation, not system prompt
# ---------------------------------------------------------------------------
_ENTER_PLAN_MODE_INSTRUCTIONS_EN = """
@@ -167,8 +167,7 @@ ask_user is only for clarifying requirements — do not use it for approval ques
# ---------------------------------------------------------------------------
# Plan mode exit notification appended to exit_plan_mode tool_result.
-# Aligned with Claude Code's plan_mode_exit attachment: explicitly tells the
-# model it can now edit files. Without this, the model only sees
+# Explicitly tells the model it can now edit files. Without this, the model only sees
# MODE_INSTRUCTIONS removed from system prompt but receives no explicit signal.
# ---------------------------------------------------------------------------
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index a916ad97fe..ad8315edeb 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -521,6 +521,29 @@ _MODE_DISPLAY_MAP: dict[str, dict[str, str]] = {
}
+def _try_add_cache_control(msg: Any) -> None:
+ """Add cache_control to the last content block of a message.
+
+ Only modifies dict-based content blocks (safe for openjiuwen message types
+ where content is ``Union[str, List[Union[str, dict]]]``). If the last block
+ is a dict, we add ``cache_control: {"type": "ephemeral"}`` to it.
+
+ Mark the last pre-prompt message for prompt caching,
+ while the btw/recap prompt itself carries no marker
+ (skipCacheWrite — the side response doesn't create a new cache entry).
+
+ String content is left untouched — converting it to a list would change
+ the wire format and break the byte-identical prefix needed for cache hits.
+ """
+ content = getattr(msg, "content", None)
+ if content is None:
+ return
+ if isinstance(content, list) and len(content) > 0:
+ last_block = content[-1]
+ if isinstance(last_block, dict):
+ last_block["cache_control"] = {"type": "ephemeral"}
+
+
class _RuntimeCronToolContext:
"""Stable cron tool context proxy backed by per-task contextvars."""
@@ -652,6 +675,10 @@ class JiuWenSwarmDeepAdapter:
self._is_proactive_memory: bool | None = None
self._model_cache: dict[str, Model] = {}
self._model_name_to_keys: dict[str, list[str]] = {}
+ # Cache system prompt to avoid re-building on every btw/recap call.
+ # The system prompt is derived from project context (CLAUDE.md, skills, etc.)
+ # which doesn't change within a session, so caching is safe.
+ self._last_system_prompt: str = ""
self._default_model_name: str = ""
self._registered_mcp_server_ids: set[str] = set()
self._registered_mcp_servers: dict[str, McpServerConfig] = {}
@@ -6432,11 +6459,7 @@ class JiuWenSwarmDeepAdapter:
from openjiuwen.core.foundation.tool import ToolInfo
# 系统提示词
- system_prompt = ""
- if hasattr(react_agent, "prompt_builder") and react_agent.prompt_builder is not None:
- system_prompt = react_agent.prompt_builder.build()
- elif hasattr(react_agent, "system_prompt_builder") and react_agent.system_prompt_builder is not None:
- system_prompt = react_agent.system_prompt_builder.build()
+ system_prompt = self._get_agent_system_prompt()
if system_prompt and token_counter:
system_prompt_tokens = token_counter.count(system_prompt) or 0
elif system_prompt:
@@ -6611,39 +6634,76 @@ class JiuWenSwarmDeepAdapter:
logger.debug("[JiuWenSwarmDeepAdapter] _get_recent_messages disk fallback failed: %s", exc)
return []
+ def _get_agent_system_prompt(self) -> str:
+ """Return the current agent's system prompt, or empty string if unavailable.
+
+ Result is cached since the system prompt is derived from project context
+ (CLAUDE.md, skills, etc.) which doesn't change within a session.
+ Reusing the same bytes is critical for prompt cache prefix matching.
+ """
+ if self._last_system_prompt:
+ return self._last_system_prompt
+ if self._instance is None or self._instance.react_agent is None:
+ return ""
+ react_agent = self._instance.react_agent
+ if hasattr(react_agent, "prompt_builder") and react_agent.prompt_builder is not None:
+ self._last_system_prompt = react_agent.prompt_builder.build()
+ return self._last_system_prompt
+ if hasattr(react_agent, "system_prompt_builder") and react_agent.system_prompt_builder is not None:
+ self._last_system_prompt = react_agent.system_prompt_builder.build()
+ return self._last_system_prompt
+ return ""
+
async def _call_model_for_recap(
self,
messages: list[Any],
prompt: str,
+ system_prompt: str = "",
+ enable_prompt_caching: bool = True,
) -> str | None:
- """调用 fast model 生成 recap 摘要。
+ """调用 model 生成简短回答(单轮、无工具)。
- - 不传 system prompt(空)
+ - system_prompt 非空时以 SystemMessage 形式前置
- prompt 作为最后一条 user message 追加到对话末尾
- - 不传 tools
- - 不启用 thinking
+ - 不传 tools(通过 btw prompt 中的 <system-reminder> 告知模型无工具可用)
+ - 不设置 temperature(继承模型默认值,与主 agent 保持一致以复用 prompt cache)
+
+ prompt cache 策略:
+ - 保持消息原始格式(保留 structured content blocks,包括 tool_use/tool_result)
+ - 最后一条 pre-prompt 消息添加 cache_control: {type: "ephemeral"} marker
+ - btw prompt 不添加 cache_control(skipCacheWrite — 侧问题响应不写入 cache)
"""
- from openjiuwen.core.foundation.llm.schema.message import UserMessage, AssistantMessage
+ from openjiuwen.core.foundation.llm.schema.message import (
+ AssistantMessage,
+ SystemMessage,
+ UserMessage,
+ )
if self._model is None:
- logger.error("[generate_recap] no model instance available")
+ logger.error("[oneshot] no model instance available")
return None
recap_messages: list[Any] = []
+ if system_prompt:
+ recap_messages.append(SystemMessage(content=system_prompt))
+
for msg in messages:
role = getattr(msg, "role", None) or ""
content = getattr(msg, "content", None) or ""
- if isinstance(content, list):
- # Multimodal content — extract text parts only
- content = " ".join(
- str(p) for p in content
- if isinstance(p, str) or (isinstance(p, dict) and p.get("type") == "text")
- )
- content = str(content)
- if not content.strip():
+
+ # Skip truly empty messages
+ if isinstance(content, str) and not content.strip():
+ continue
+ if isinstance(content, (list, tuple)) and len(content) == 0:
+ continue
+ if content is None:
continue
+ # Keep original content format (string or list of structured blocks).
+ # This is critical for prompt cache prefix matching — converting to
+ # plain text with str() would strip tool_use/tool_result blocks and
+ # break byte-identical prefix matching with the main agent's calls.
if role == "user":
recap_messages.append(UserMessage(content=content))
elif role == "assistant":
@@ -6651,19 +6711,82 @@ class JiuWenSwarmDeepAdapter:
else:
recap_messages.append(UserMessage(content=content))
- # Prompt 作为最后一条 user message 追加
+ # Mark the last pre-prompt message for prompt caching.
+ # The btw prompt itself does NOT carry a cache_control marker
+ # skipCacheWrite — the side-question
+ # response doesn't create a new cache entry.
+ if enable_prompt_caching and recap_messages:
+ _try_add_cache_control(recap_messages[-1])
+
+ # Append btw prompt as final user message (no cache_control → skipCacheWrite)
recap_messages.append(UserMessage(content=prompt))
try:
- result = await self._model.invoke(
- recap_messages,
- temperature=0,
- )
- return getattr(result, "content", None) or str(result)
+ # No temperature override — inherit model default to match main agent
+ # API params (thinking config is part of the Anthropic cache key).
+ result = await self._model.invoke(recap_messages)
+ content = getattr(result, "content", None) or str(result)
+ # Log cache metrics for observability
+ usage = getattr(result, "usage_metadata", None)
+ if usage and getattr(usage, "cache_tokens", 0) > 0:
+ logger.info(
+ "[btw/recap] cache hit: cache_tokens=%s, input_tokens=%s, output_tokens=%s",
+ getattr(usage, "cache_tokens", 0),
+ getattr(usage, "input_tokens", 0),
+ getattr(usage, "output_tokens", 0),
+ )
+ return content
except Exception:
logger.exception("[generate_recap] model call failed")
return None
+ async def generate_btw_answer(self, session_id: str, question: str) -> dict[str, Any]:
+ """回答 /btw 侧问题:独立、无工具、单轮 LLM 查询。
+
+ prompt cache 策略:
+ - 共享主 agent 的 system prompt(项目上下文、skills、CLAUDE.md 等)
+ - 保持消息原始格式(含 structured content blocks)以实现 byte-identical 前缀
+ - 最后一条 pre-prompt 消息添加 cache_control marker(ephemeral)
+ - btw prompt 不添加 cache_control(skipCacheWrite)
+ - 直接调用模型(无工具、单轮)
+ - 不修改对话历史(read-only)
+
+ Args:
+ session_id: 会话ID
+ question: 用户侧问题
+
+ Returns:
+ {"status": "ok", "answer": "..."} 或 {"status": "no_context"|"failed", ...}
+ """
+ from jiuwenswarm.server.runtime.agent_adapter.recap_prompts import (
+ RECENT_MESSAGE_WINDOW,
+ _build_btw_prompt,
+ )
+
+ # 1) 获取 system prompt(与主 agent 相同,已缓存)
+ system_prompt = self._get_agent_system_prompt()
+
+ # 2) 获取最近对话消息(保持原始格式,不做 str() 转换)
+ messages = self._get_recent_messages(session_id, window=RECENT_MESSAGE_WINDOW)
+ if not messages and not system_prompt:
+ return {"status": "no_context"}
+
+ # 3) 构建 btw prompt(system prompt 通过 SystemMessage 传递,不嵌入文本)
+ prompt = _build_btw_prompt(
+ question=question,
+ language=self._resolve_prompt_language(),
+ )
+
+ # 4) 调用模型 — system_prompt 作为 SystemMessage 前置,prompt 作为 UserMessage
+ # enable_prompt_caching=True 启用 cache_control marker
+ answer = await self._call_model_for_recap(
+ messages, prompt, system_prompt=system_prompt, enable_prompt_caching=True,
+ )
+ if not answer:
+ return {"status": "failed", "error": "Model returned empty response"}
+
+ return {"status": "ok", "answer": answer.strip()}
+
async def repair_model_response(self, prompt: str) -> str | None:
"""Run a focused repair prompt using the currently selected chat model."""
if self._model is None:
@@ -6830,11 +6953,7 @@ class JiuWenSwarmDeepAdapter:
total_tokens = 0
# 1. 计算系统消息的 tokens
- system_prompt = ""
- if hasattr(react_agent, "prompt_builder") and react_agent.prompt_builder is not None:
- system_prompt = react_agent.prompt_builder.build()
- elif hasattr(react_agent, "system_prompt_builder") and react_agent.system_prompt_builder is not None:
- system_prompt = react_agent.system_prompt_builder.build()
+ system_prompt = self._get_agent_system_prompt()
if system_prompt:
if token_counter is not None:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/recap_prompts.py b/jiuwenswarm/server/runtime/agent_adapter/recap_prompts.py
index 22e87b3b91..f76d9dddf2 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/recap_prompts.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/recap_prompts.py
@@ -30,4 +30,57 @@ def build_recap_prompt(memory: str | None, language: str = "en") -> str:
"Start by stating the high-level task — what they are building or debugging, not implementation details. "
"Next: the concrete next step. "
"Skip status reports and commit recaps."
+ )
+
+
+def _build_btw_prompt(
+ question: str,
+ language: str = "en",
+) -> str:
+ """构建 /btw 侧问题 prompt。
+
+ 明确告知模型这是一个独立的侧问题,
+ 不能使用工具,只能基于对话上下文直接回答。
+
+ 主 agent 的 system prompt 通过 SystemMessage 传递,不在此处嵌入。
+
+ Args:
+ question: 用户侧问题
+ language: 语言偏好
+ """
+ system_reminder = (
+ "<system-reminder>\n"
+ "This is a side question from the user. You must answer this question directly "
+ "in a single response.\n"
+ "\n"
+ "IMPORTANT CONTEXT:\n"
+ "- You are a separate, lightweight agent spawned to answer this one question\n"
+ "- The main agent is NOT interrupted - it continues working independently\n"
+ "- You share the conversation context but are a completely separate instance\n"
+ "- Do NOT reference being interrupted or what you were 'previously doing'\n"
+ "\n"
+ "CRITICAL CONSTRAINTS:\n"
+ "- You have NO tools available - you cannot read files, run commands, search, "
+ "or take any actions\n"
+ "- This is a one-off response - there will be no follow-up turns\n"
+ "- You can ONLY provide information based on what you already know from the "
+ "conversation context\n"
+ "- NEVER say things like 'Let me try...', 'I'll now...', 'Let me check...', "
+ "or promise to take any action\n"
+ "- If you don't know the answer, say so - do not offer to look it up or "
+ "investigate\n"
+ "\n"
+ "Simply answer the question with the information you have.\n"
+ "</system-reminder>\n"
+ )
+
+ if language and language.lower().startswith("zh"):
+ return (
+ f"{system_reminder}"
+ f"请用中文回答这个侧问题。\n"
+ f"问题:{question}\n"
+ )
+ return (
+ f"{system_reminder}"
+ f"\nQuestion: {question}\n"
)
\ No newline at end of file
diff --git a/jiuwenswarm/server/runtime/session/session_metadata.py b/jiuwenswarm/server/runtime/session/session_metadata.py
index ee8be51d68..dc7a4a8701 100644
--- a/jiuwenswarm/server/runtime/session/session_metadata.py
+++ b/jiuwenswarm/server/runtime/session/session_metadata.py
@@ -32,7 +32,7 @@ _TITLE_MAX_LEN = 50
_HEARTBEAT_SESSION_PREFIX = "heartbeat_"
_DELIVERY_KIND_SERVER_PUSH = "server_push"
-# 匹配所有小写 XML 块(对齐 Claude Code stripDisplayTags),
+# 匹配所有小写 XML 块:
# 如 <system-reminder>、<file-content>、<command-name> 等系统/工具注入内容
_INJECTED_TAG_RE = re.compile(
r"<([a-z][\w-]*)(?:\s[^>]*)?>.*?</\1>\n?", re.DOTALL
@@ -44,7 +44,7 @@ _INJECTED_TAG_START_RE = re.compile(
def _sanitize_title(title: str) -> str:
- """清理标题中的系统注入 XML 标签(对齐 Claude Code stripDisplayTags)。
+ """清理标题中的系统注入 XML 标签。
匹配所有小写 XML 标签(如 <system-reminder>、<file-content>、<command-name>),
不匹配用户提及的大写 HTML/JSX(如 <Button>、<Component>)。
@@ -154,7 +154,7 @@ def _enqueue_write(session_id: str, metadata: dict[str, Any]) -> None:
def _auto_title(content: str) -> str:
"""从首条用户消息自动生成会话标题"""
- # 先剥离所有小写 XML 注入标签(对齐 Claude Code stripDisplayTags),
+ # 先剥离所有小写 XML 注入标签,
# 避免将系统提示/文件注入/工具标签误识别为会话标题
cleaned = _INJECTED_TAG_RE.sub("", content).strip()
if not cleaned:
diff --git a/tests/system_tests/test_btw_command_st.py b/tests/system_tests/test_btw_command_st.py
new file mode 100644
index 0000000000..105e4703cf
--- /dev/null
+++ b/tests/system_tests/test_btw_command_st.py
@@ -0,0 +1,395 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""System test for /btw command end-to-end flow.
+
+Verifies that the gateway correctly forwards command.btw to the agent server
+and returns a properly structured response frame. Follows the pattern from
+test_cli_channel_ws.py.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import socket
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+import websockets
+
+pytestmark = [pytest.mark.integration, pytest.mark.system]
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+# =============================================================================
+# Process helpers (identical pattern to test_cli_channel_ws.py)
+# =============================================================================
+
+
+def _pick_free_port() -> int:
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ sock.close()
+ return port
+
+
+def _start_process(
+ cmd: list[str], *, env: dict[str, str], log_path: Path
+) -> subprocess.Popen:
+ log_file = log_path.open("w", encoding="utf-8")
+ proc = subprocess.Popen(
+ cmd,
+ cwd=str(REPO_ROOT),
+ env=env,
+ stdout=log_file,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ log_file.close()
+ return proc
+
+
+def _stop_process(proc: subprocess.Popen | None) -> None:
+ if proc is None:
+ return
+ if proc.poll() is not None:
+ try:
+ proc.wait(timeout=1)
+ except subprocess.TimeoutExpired:
+ pass
+ return
+
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ return
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ pass
+
+
+async def _wait_for_log(
+ log_path: Path, needle: str, timeout: float = 30.0
+) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while asyncio.get_running_loop().time() < deadline:
+ if log_path.exists():
+ text = log_path.read_text(encoding="utf-8", errors="ignore")
+ if needle in text:
+ return
+ await asyncio.sleep(0.2)
+ log_text = (
+ log_path.read_text(encoding="utf-8", errors="ignore")
+ if log_path.exists()
+ else ""
+ )
+ raise AssertionError(
+ f"Timed out waiting for log line: {needle}\nlog={log_text}"
+ )
+
+
+async def _wait_for_websocket_ready(url: str, timeout: float = 30.0) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ last_error: Exception | None = None
+ while asyncio.get_running_loop().time() < deadline:
+ try:
+ async with websockets.connect(url):
+ return
+ except Exception as exc: # noqa: BLE001
+ last_error = exc
+ await asyncio.sleep(0.2)
+ raise AssertionError(
+ f"Timed out waiting for websocket: {url} last_error={last_error}"
+ )
+
+
+async def _recv_until_response(
+ ws, req_id: str, timeout: float = 10.0
+) -> dict:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while asyncio.get_running_loop().time() < deadline:
+ remaining = max(0.1, deadline - asyncio.get_running_loop().time())
+ frame = json.loads(
+ await asyncio.wait_for(ws.recv(), timeout=remaining)
+ )
+ if frame.get("type") == "res" and frame.get("id") == req_id:
+ return frame
+ raise AssertionError(f"Timed out waiting for response id={req_id}")
+
+
+# =============================================================================
+# System tests
+# =============================================================================
+
+
+async def test_btw_command_system_roundtrip(
+ temp_home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """End-to-end system test: send command.btw via WebSocket, verify response.
+
+ Starts agent server + gateway, connects via WebSocket, sends a
+ command.btw request, and verifies the response frame structure.
+
+ In a test environment without a configured model, the agent server
+ will return ok=False with an error — this is still a valid test of
+ the gateway → agent-server forwarding chain.
+ """
+ agent_port = _pick_free_port()
+ web_port = _pick_free_port()
+ gateway_port = _pick_free_port()
+
+ env = os.environ.copy()
+ env["HOME"] = str(temp_home)
+ env["AGENT_SERVER_HOST"] = "127.0.0.1"
+ env["AGENT_SERVER_PORT"] = str(agent_port)
+ env["WEB_HOST"] = "127.0.0.1"
+ env["WEB_PORT"] = str(web_port)
+ env["GATEWAY_HOST"] = "127.0.0.1"
+ env["GATEWAY_PORT"] = str(gateway_port)
+
+ agent_log = temp_home / "agentserver_btw.log"
+ gateway_log = temp_home / "gateway_btw.log"
+
+ agent_proc = _start_process(
+ [
+ sys.executable,
+ "-m",
+ "jiuwenswarm.server.app_agentserver",
+ "--port",
+ str(agent_port),
+ ],
+ env=env,
+ log_path=agent_log,
+ )
+ gateway_proc = None
+ try:
+ await _wait_for_log(agent_log, "ready:", timeout=60)
+
+ gateway_proc = _start_process(
+ [
+ sys.executable,
+ "-m",
+ "jiuwenswarm.gateway.app_gateway",
+ "--port",
+ str(web_port),
+ ],
+ env=env,
+ log_path=gateway_log,
+ )
+ await _wait_for_websocket_ready(
+ f"ws://127.0.0.1:{gateway_port}/tui",
+ timeout=60,
+ )
+
+ async with websockets.connect(
+ f"ws://127.0.0.1:{gateway_port}/tui"
+ ) as ws:
+ # Send a /btw request with a test question
+ req_btw = {
+ "type": "req",
+ "id": "req-btw-st",
+ "method": "command.btw",
+ "params": {
+ "session_id": "sess_btw_test",
+ "question": "what is the current project about?",
+ "mode": "agent.plan",
+ },
+ }
+ await ws.send(json.dumps(req_btw, ensure_ascii=False))
+
+ btw_res = await _recv_until_response(ws, "req-btw-st", timeout=15)
+ # Verify response frame structure
+ assert btw_res["type"] == "res"
+ assert btw_res["id"] == "req-btw-st"
+ # ok may be True or False depending on model availability
+ assert "ok" in btw_res
+ # payload must contain a status field
+ assert "status" in btw_res.get("payload", {})
+
+ finally:
+ _stop_process(gateway_proc)
+ _stop_process(agent_proc)
+
+
+async def test_btw_command_empty_question(
+ temp_home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """System test: empty question should be rejected early by the handler.
+
+ The handler validates the question param before attempting any
+ model call, so this should succeed even without a configured model.
+ """
+ agent_port = _pick_free_port()
+ web_port = _pick_free_port()
+ gateway_port = _pick_free_port()
+
+ env = os.environ.copy()
+ env["HOME"] = str(temp_home)
+ env["AGENT_SERVER_HOST"] = "127.0.0.1"
+ env["AGENT_SERVER_PORT"] = str(agent_port)
+ env["WEB_HOST"] = "127.0.0.1"
+ env["WEB_PORT"] = str(web_port)
+ env["GATEWAY_HOST"] = "127.0.0.1"
+ env["GATEWAY_PORT"] = str(gateway_port)
+
+ agent_log = temp_home / "agentserver_btw2.log"
+ gateway_log = temp_home / "gateway_btw2.log"
+
+ agent_proc = _start_process(
+ [
+ sys.executable,
+ "-m",
+ "jiuwenswarm.server.app_agentserver",
+ "--port",
+ str(agent_port),
+ ],
+ env=env,
+ log_path=agent_log,
+ )
+ gateway_proc = None
+ try:
+ await _wait_for_log(agent_log, "ready:", timeout=60)
+
+ gateway_proc = _start_process(
+ [
+ sys.executable,
+ "-m",
+ "jiuwenswarm.gateway.app_gateway",
+ "--port",
+ str(web_port),
+ ],
+ env=env,
+ log_path=gateway_log,
+ )
+ await _wait_for_websocket_ready(
+ f"ws://127.0.0.1:{gateway_port}/tui",
+ timeout=60,
+ )
+
+ async with websockets.connect(
+ f"ws://127.0.0.1:{gateway_port}/tui"
+ ) as ws:
+ # Empty question — should be rejected immediately
+ req_btw = {
+ "type": "req",
+ "id": "req-btw-empty-st",
+ "method": "command.btw",
+ "params": {
+ "session_id": "sess_btw_empty",
+ "question": "",
+ "mode": "agent.plan",
+ },
+ }
+ await ws.send(json.dumps(req_btw, ensure_ascii=False))
+
+ btw_res = await _recv_until_response(
+ ws, "req-btw-empty-st", timeout=15
+ )
+ # Verify response frame structure
+ assert btw_res["type"] == "res"
+ assert btw_res["id"] == "req-btw-empty-st"
+ # Empty question returns ok=True with failed payload (by design)
+ assert btw_res["ok"] is True
+ assert btw_res["payload"]["status"] == "failed"
+ assert "Question is required" in btw_res["payload"]["error"]
+
+ finally:
+ _stop_process(gateway_proc)
+ _stop_process(agent_proc)
+
+
+async def test_btw_no_context_when_no_session(
+ temp_home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """System test: btw on a fresh session with no conversation returns no_context.
+
+ When there are no prior messages and no system prompt configured,
+ the btw handler should return status=no_context.
+ """
+ agent_port = _pick_free_port()
+ web_port = _pick_free_port()
+ gateway_port = _pick_free_port()
+
+ env = os.environ.copy()
+ env["HOME"] = str(temp_home)
+ env["AGENT_SERVER_HOST"] = "127.0.0.1"
+ env["AGENT_SERVER_PORT"] = str(agent_port)
+ env["WEB_HOST"] = "127.0.0.1"
+ env["WEB_PORT"] = str(web_port)
+ env["GATEWAY_HOST"] = "127.0.0.1"
+ env["GATEWAY_PORT"] = str(gateway_port)
+
+ agent_log = temp_home / "agentserver_btw3.log"
+ gateway_log = temp_home / "gateway_btw3.log"
+
+ agent_proc = _start_process(
+ [
+ sys.executable,
+ "-m",
+ "jiuwenswarm.server.app_agentserver",
+ "--port",
+ str(agent_port),
+ ],
+ env=env,
+ log_path=agent_log,
+ )
+ gateway_proc = None
+ try:
+ await _wait_for_log(agent_log, "ready:", timeout=60)
+
+ gateway_proc = _start_process(
+ [
+ sys.executable,
+ "-m",
+ "jiuwenswarm.gateway.app_gateway",
+ "--port",
+ str(web_port),
+ ],
+ env=env,
+ log_path=gateway_log,
+ )
+ await _wait_for_websocket_ready(
+ f"ws://127.0.0.1:{gateway_port}/tui",
+ timeout=60,
+ )
+
+ async with websockets.connect(
+ f"ws://127.0.0.1:{gateway_port}/tui"
+ ) as ws:
+ # Use a unique session ID that has no conversation history
+ req_btw = {
+ "type": "req",
+ "id": "req-btw-nocontext-st",
+ "method": "command.btw",
+ "params": {
+ "session_id": "sess_btw_nonexistent_99999",
+ "question": "what is happening?",
+ "mode": "agent.plan",
+ },
+ }
+ await ws.send(json.dumps(req_btw, ensure_ascii=False))
+
+ btw_res = await _recv_until_response(
+ ws, "req-btw-nocontext-st", timeout=15
+ )
+ assert btw_res["type"] == "res"
+ assert btw_res["id"] == "req-btw-nocontext-st"
+ assert "status" in btw_res.get("payload", {})
+ # With no context and no system prompt, expect no_context or failed
+ status = btw_res["payload"]["status"]
+ assert status in ("no_context", "failed")
+
+ finally:
+ _stop_process(gateway_proc)
+ _stop_process(agent_proc)
diff --git a/tests/unit_tests/agentserver/test_btw_command.py b/tests/unit_tests/agentserver/test_btw_command.py
new file mode 100644
index 0000000000..81ea8c9c79
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_btw_command.py
@@ -0,0 +1,1089 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for /btw command — prompt builder, cache control, adapter, and WS handler.
+
+Covers commits:
+- c44c8864 feat(btw): add /btw command
+- 60bf614 feat(btw): keep prompt cache
+"""
+
+# pylint: disable=protected-access
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.server import agent_ws_server as agent_ws_server_module
+from jiuwenswarm.server.runtime.agent_adapter.recap_prompts import (
+ _build_btw_prompt,
+ build_recap_prompt,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ _try_add_cache_control,
+)
+
+
+# =============================================================================
+# Fixtures & harness (mirrors test_agentserver_cli_commands.py)
+# =============================================================================
+
+class FakeWebSocket:
+ def __init__(self) -> None:
+ self.sent: list[dict] = []
+
+ async def send(self, payload: str) -> None:
+ import json
+
+ self.sent.append(json.loads(payload))
+
+
+class AgentWebSocketServerHarness(agent_ws_server_module.AgentWebSocketServer):
+ async def handle_command_btw_for_test(
+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
+ ) -> None:
+ await self._handle_command_btw(ws, request, send_lock)
+
+ def get_agent_manager_for_test(self) -> Any:
+ return self._agent_manager
+
+
+def fake_encode_agent_response_for_wire(
+ resp: AgentResponse, response_id: str
+) -> dict[str, Any]:
+ return {
+ "response_id": response_id,
+ "payload": resp.payload,
+ "ok": resp.ok,
+ }
+
+
+def server() -> AgentWebSocketServerHarness:
+ return AgentWebSocketServerHarness()
+
+
+def fake_ws() -> FakeWebSocket:
+ return FakeWebSocket()
+
+
[email protected](autouse=True)
+def _patch_wire_encoder(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "encode_agent_response_for_wire",
+ fake_encode_agent_response_for_wire,
+ )
+
+
+# =============================================================================
+# Helpers
+# =============================================================================
+
+def _make_msg(role: str = "user", content: Any = "hello") -> MagicMock:
+ """Create a message-like MagicMock with role + content attributes."""
+ msg = MagicMock()
+ msg.role = role
+ msg.content = content
+ return msg
+
+
+def _make_adapter(**overrides: Any) -> Any:
+ """Create a JiuWenSwarmDeepAdapter instance without running __init__.
+
+ Defaults set up a minimal valid state for testing btw/recap paths.
+ """
+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+ )
+
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._instance = None
+ adapter._last_system_prompt = overrides.get("_last_system_prompt", "")
+ adapter._model = overrides.get("_model", None)
+ adapter._resolve_prompt_language = MagicMock(return_value="en")
+ return adapter
+
+
+# =============================================================================
+# Section A: _build_btw_prompt
+# =============================================================================
+
+class TestBuildBtwPrompt:
+ """Tests for the _build_btw_prompt pure function."""
+
+ @staticmethod
+ def test_en_prompt_contains_question():
+ """EN prompt must include the user's question text."""
+ result = _build_btw_prompt("what does git status do?", language="en")
+ assert "what does git status do?" in result
+
+ @staticmethod
+ def test_en_prompt_contains_system_reminder_wrapper():
+ """EN prompt must be wrapped in <system-reminder> tags."""
+ result = _build_btw_prompt("hello", language="en")
+ assert "<system-reminder>" in result
+ assert "</system-reminder>" in result
+
+ @staticmethod
+ def test_en_prompt_contains_no_tools_constraint():
+ """EN prompt must state NO tools are available."""
+ result = _build_btw_prompt("test", language="en")
+ assert "NO tools" in result
+
+ @staticmethod
+ def test_en_prompt_contains_one_off_constraint():
+ """EN prompt must state this is a one-off response."""
+ result = _build_btw_prompt("test", language="en")
+ assert "one-off" in result.lower() or "no follow-up" in result.lower()
+
+ @staticmethod
+ def test_en_prompt_has_question_prefix():
+ """EN prompt uses 'Question:' prefix, not Chinese."""
+ result = _build_btw_prompt("what is this?", language="en")
+ assert "Question:" in result
+ assert "问题:" not in result
+
+ @staticmethod
+ def test_zh_prompt_contains_question():
+ """ZH prompt must include the question text."""
+ result = _build_btw_prompt("什么是 git status?", language="zh")
+ assert "什么是 git status?" in result
+
+ @staticmethod
+ def test_zh_prompt_contains_language_instruction():
+ """ZH prompt must instruct answering in Chinese."""
+ result = _build_btw_prompt("test", language="zh")
+ assert "请用中文回答" in result
+
+ @staticmethod
+ def test_zh_prompt_has_question_prefix():
+ """ZH prompt uses '问题:' prefix."""
+ result = _build_btw_prompt("测试", language="zh")
+ assert "问题:" in result
+
+ @staticmethod
+ def test_zh_prompt_also_contains_system_reminder():
+ """ZH prompt still wraps constraints in <system-reminder>."""
+ result = _build_btw_prompt("test", language="zh")
+ assert "<system-reminder>" in result
+ assert "</system-reminder>" in result
+
+ @staticmethod
+ def test_no_claude_code_references():
+ """Prompt must NOT contain hardcoded 'Claude Code' references (scrubbed in 60bf614)."""
+ result_en = _build_btw_prompt("test", language="en")
+ result_zh = _build_btw_prompt("test", language="zh")
+ assert "Claude Code" not in result_en
+ assert "Claude Code" not in result_zh
+
+ @staticmethod
+ def test_no_system_prompt_embedded_in_text():
+ """The system prompt text is NOT embedded in the btw prompt — passed via SystemMessage."""
+ result = _build_btw_prompt("test")
+ # The prompt should not contain CLAUDE.md or skill instructions
+ assert "CLAUDE.md" not in result
+
+ @staticmethod
+ def test_empty_question_still_produces_valid_structure():
+ """Empty question string should still produce the system_reminder wrapper."""
+ result = _build_btw_prompt("", language="en")
+ assert "<system-reminder>" in result
+ assert "Question:" in result
+
+ @staticmethod
+ def test_language_defaults_to_en_when_unknown():
+ """Unknown language code should fall back to English output."""
+ result = _build_btw_prompt("test", language="fr")
+ assert "Question:" in result
+ assert "请用中文回答" not in result
+
+
+# =============================================================================
+# Section B: _try_add_cache_control
+# =============================================================================
+
+class TestTryAddCacheControl:
+ """Tests for the _try_add_cache_control pure function."""
+
+ @staticmethod
+ def test_adds_to_dict_based_last_block():
+ """Should add cache_control to the last dict content block."""
+ msg = _make_msg(content=[
+ {"type": "text", "text": "first"},
+ {"type": "text", "text": "last"},
+ ])
+ _try_add_cache_control(msg)
+ assert msg.content[-1]["cache_control"] == {"type": "ephemeral"}
+ # First block must NOT be modified
+ assert "cache_control" not in msg.content[0]
+
+ @staticmethod
+ def test_noop_on_string_content():
+ """String content must be left untouched — no conversion to list."""
+ msg = _make_msg(content="plain string")
+ original = msg.content
+ _try_add_cache_control(msg)
+ assert msg.content is original
+ assert msg.content == "plain string"
+
+ @staticmethod
+ def test_noop_on_none_content():
+ """None content must not cause errors."""
+ msg = _make_msg(content=None)
+ _try_add_cache_control(msg) # must not raise
+
+ @staticmethod
+ def test_noop_on_empty_list_content():
+ """Empty list content must not cause errors."""
+ msg = _make_msg(content=[])
+ _try_add_cache_control(msg) # must not raise
+ assert msg.content == []
+
+ @staticmethod
+ def test_noop_when_msg_has_no_content_attr():
+ """Object without content attribute must not cause errors."""
+ msg = MagicMock(spec=[]) # no 'content' attr
+ _try_add_cache_control(msg) # must not raise
+
+ @staticmethod
+ def test_preserves_non_dict_blocks_in_list():
+ """String items in a list content should not be modified."""
+ msg = _make_msg(content=[
+ "string block",
+ {"type": "text", "text": "dict block"},
+ ])
+ _try_add_cache_control(msg)
+ assert msg.content[0] == "string block" # unchanged
+ assert msg.content[1]["cache_control"] == {"type": "ephemeral"}
+
+ @staticmethod
+ def test_last_block_already_has_cache_control_overwrites():
+ """If last block already has cache_control, _try_add_cache_control overwrites it."""
+ msg = _make_msg(content=[
+ {"type": "text", "text": "data", "cache_control": {"type": "old"}},
+ ])
+ _try_add_cache_control(msg)
+ assert msg.content[-1]["cache_control"] == {"type": "ephemeral"}
+
+
+# =============================================================================
+# Section C: _get_agent_system_prompt caching
+# =============================================================================
+
+class TestGetAgentSystemPrompt:
+ """Tests for _get_agent_system_prompt caching behavior."""
+
+ @staticmethod
+ def test_returns_cached_value_on_second_call():
+ """Second call returns _last_system_prompt without calling build() again."""
+ adapter = _make_adapter(_last_system_prompt="cached prompt")
+
+ # First call should hit cache
+ result = adapter._get_agent_system_prompt()
+ assert result == "cached prompt"
+
+ @staticmethod
+ def test_returns_empty_when_instance_is_none():
+ """When _instance is None, return ''."""
+ adapter = _make_adapter(_last_system_prompt="")
+ adapter._instance = None
+ result = adapter._get_agent_system_prompt()
+ assert result == ""
+
+ @staticmethod
+ def test_returns_empty_when_react_agent_is_none():
+ """When react_agent is None, return ''."""
+ adapter = _make_adapter(_last_system_prompt="")
+ adapter._instance = MagicMock()
+ adapter._instance.react_agent = None
+ result = adapter._get_agent_system_prompt()
+ assert result == ""
+
+ @staticmethod
+ def test_prompt_builder_takes_priority():
+ """prompt_builder.build() should be used before system_prompt_builder."""
+ adapter = _make_adapter(_last_system_prompt="")
+ adapter._instance = MagicMock()
+ react_agent = MagicMock()
+ react_agent.prompt_builder = MagicMock()
+ react_agent.prompt_builder.build.return_value = "from prompt_builder"
+ react_agent.system_prompt_builder = MagicMock()
+ react_agent.system_prompt_builder.build.return_value = "from system_prompt_builder"
+ adapter._instance.react_agent = react_agent
+
+ result = adapter._get_agent_system_prompt()
+ assert result == "from prompt_builder"
+ react_agent.prompt_builder.build.assert_called_once()
+ react_agent.system_prompt_builder.build.assert_not_called()
+
+ @staticmethod
+ def test_falls_back_to_system_prompt_builder():
+ """When prompt_builder is absent, use system_prompt_builder."""
+ adapter = _make_adapter(_last_system_prompt="")
+ adapter._instance = MagicMock()
+ react_agent = MagicMock(spec=["system_prompt_builder"])
+ # No prompt_builder attribute
+ del react_agent.prompt_builder
+ react_agent.system_prompt_builder = MagicMock()
+ react_agent.system_prompt_builder.build.return_value = "from system_prompt_builder"
+ adapter._instance.react_agent = react_agent
+
+ result = adapter._get_agent_system_prompt()
+ assert result == "from system_prompt_builder"
+
+ @staticmethod
+ def test_caches_result_from_prompt_builder():
+ """After first call through prompt_builder, second call uses cache."""
+ adapter = _make_adapter(_last_system_prompt="")
+ adapter._instance = MagicMock()
+ react_agent = MagicMock()
+ call_count = [0]
+
+ def _build():
+ call_count[0] += 1
+ return "built once"
+
+ react_agent.prompt_builder.build = _build
+ adapter._instance.react_agent = react_agent
+
+ result1 = adapter._get_agent_system_prompt()
+ result2 = adapter._get_agent_system_prompt()
+
+ assert result1 == "built once"
+ assert result2 == "built once"
+ assert call_count[0] == 1 # build was called only once
+
+ @staticmethod
+ def test_returns_empty_when_no_builders():
+ """When neither builder is available, return ''."""
+ adapter = _make_adapter(_last_system_prompt="")
+ adapter._instance = MagicMock()
+ react_agent = MagicMock(spec=[]) # no attributes by default
+ adapter._instance.react_agent = react_agent
+
+ result = adapter._get_agent_system_prompt()
+ assert result == ""
+
+ @staticmethod
+ def test_last_system_prompt_is_initialized_empty():
+ """_last_system_prompt should be initialized as empty string."""
+ adapter = _make_adapter()
+ assert adapter._last_system_prompt == ""
+
+
+# =============================================================================
+# Section D: _call_model_for_recap — message format preservation
+# =============================================================================
+
+class TestCallModelForRecap:
+ """Tests for _call_model_for_recap message handling and cache behavior."""
+
+ @pytest.mark.asyncio
+ async def test_preserves_list_based_content(self):
+ """Structured content blocks must be preserved — no str() conversion."""
+ from unittest.mock import call
+
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ structured_content = [
+ {"type": "text", "text": "user message"},
+ {"type": "tool_result", "tool_use_id": "tool_123", "content": "output"},
+ ]
+ msgs = [_make_msg(role="user", content=structured_content)]
+
+ await adapter._call_model_for_recap(msgs, "prompt text")
+
+ # The invoke call should receive messages with preserved content
+ invoke_args = mock_model.invoke.call_args[0][0]
+ # Find the first user message (not system, not final prompt)
+ user_msgs = [m for m in invoke_args if getattr(m, "role", getattr(m, "__class__", None)) and True]
+ # The structured content should be passed through as-is
+ assert mock_model.invoke.called
+
+ @pytest.mark.asyncio
+ async def test_skips_empty_string_messages(self):
+ """Messages with empty string content should be skipped."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [
+ _make_msg(role="user", content=""),
+ _make_msg(role="assistant", content="valid"),
+ ]
+
+ await adapter._call_model_for_recap(msgs, "prompt")
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ # Empty-string user message should be skipped
+ # Only assistant + final prompt should remain (plus optional system)
+ content_values = [
+ getattr(m, "content", None) for m in invoke_args
+ ]
+ assert "" not in content_values
+
+ @pytest.mark.asyncio
+ async def test_skips_none_content_messages(self):
+ """Messages with None content should be skipped."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [_make_msg(role="user", content=None)]
+
+ await adapter._call_model_for_recap(msgs, "prompt")
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ # Only the final prompt message should remain (no user msg with None)
+ content_list = [getattr(m, "content", None) for m in invoke_args]
+ # Either system_prompt or just the prompt
+ assert None not in content_list
+
+ @pytest.mark.asyncio
+ async def test_prepends_system_message_when_provided(self):
+ """When system_prompt is non-empty, it becomes the first message."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [_make_msg(role="user", content="hello")]
+
+ await adapter._call_model_for_recap(msgs, "prompt", system_prompt="SYS PROMPT")
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ first_msg = invoke_args[0]
+ assert getattr(first_msg, "content", None) == "SYS PROMPT"
+
+ @pytest.mark.asyncio
+ async def test_appends_prompt_as_final_user_message(self):
+ """The prompt should be appended as the last UserMessage."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [_make_msg(role="user", content="hello")]
+
+ await adapter._call_model_for_recap(msgs, "PROMPT TEXT")
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ last_msg = invoke_args[-1]
+ assert getattr(last_msg, "content", None) == "PROMPT TEXT"
+
+ @pytest.mark.asyncio
+ async def test_cache_control_added_when_enabled(self):
+ """When enable_prompt_caching=True, last pre-prompt message gets cache_control."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [
+ _make_msg(role="user", content=[
+ {"type": "text", "text": "hello"},
+ ]),
+ ]
+
+ await adapter._call_model_for_recap(msgs, "prompt", enable_prompt_caching=True)
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ # The message with "hello" content should now have cache_control
+ # Find the user message that has the content block
+ pre_prompt_msgs = [m for m in invoke_args if getattr(m, "content", None) != "prompt"]
+ # The last pre-prompt message should have cache_control on its last content block
+ last_pre = pre_prompt_msgs[-1]
+ if isinstance(last_pre.content, list) and len(last_pre.content) > 0:
+ assert "cache_control" in last_pre.content[-1]
+
+ @pytest.mark.asyncio
+ async def test_no_cache_control_when_disabled(self):
+ """When enable_prompt_caching=False, no cache_control marker is added."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [
+ _make_msg(role="user", content=[
+ {"type": "text", "text": "hello"},
+ ]),
+ ]
+
+ await adapter._call_model_for_recap(msgs, "prompt", enable_prompt_caching=False)
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ # Find pre-prompt messages and check no cache_control
+ for msg in invoke_args:
+ content = getattr(msg, "content", None)
+ if isinstance(content, list):
+ for block in content:
+ if isinstance(block, dict):
+ assert "cache_control" not in block
+
+ @pytest.mark.asyncio
+ async def test_no_cache_control_when_only_system_prompt(self):
+ """When recap_messages is empty (only system_prompt present), no crash."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ # No conversation messages — only system_prompt
+ await adapter._call_model_for_recap([], "prompt", system_prompt="SYS", enable_prompt_caching=True)
+
+ # Should not crash — guards on empty recap_messages
+ assert mock_model.invoke.called
+
+ @pytest.mark.asyncio
+ async def test_calls_model_invoke_without_temperature(self):
+ """model.invoke() should be called WITHOUT temperature parameter."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ await adapter._call_model_for_recap(
+ [_make_msg(role="user", content="hello")], "prompt",
+ )
+
+ call_kwargs = mock_model.invoke.call_args[1]
+ assert "temperature" not in call_kwargs
+
+ @pytest.mark.asyncio
+ async def test_logs_cache_hit_metrics(self):
+ """When usage_metadata.cache_tokens > 0, cache metrics should be logged."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_usage = MagicMock()
+ mock_usage.cache_tokens = 42
+ mock_usage.input_tokens = 100
+ mock_usage.output_tokens = 10
+ mock_result.usage_metadata = mock_usage
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ with patch("logging.Logger.info") as mock_log:
+ await adapter._call_model_for_recap(
+ [_make_msg(role="user", content="hello")], "prompt",
+ )
+
+ cache_logged = any(
+ "cache hit" in str(call_args) for call_args in mock_log.call_args_list
+ )
+ assert cache_logged
+
+ @pytest.mark.asyncio
+ async def test_returns_none_on_exception(self):
+ """When model.invoke() raises, return None and log exception."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_model.invoke.side_effect = RuntimeError("model crash")
+ adapter._model = mock_model
+
+ result = await adapter._call_model_for_recap(
+ [_make_msg(role="user", content="hello")], "prompt",
+ )
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_skips_empty_list_messages(self):
+ """Messages with empty list content should be skipped."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [_make_msg(role="user", content=[])]
+
+ await adapter._call_model_for_recap(msgs, "prompt")
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ content_vals = [getattr(m, "content", None) for m in invoke_args]
+ assert [] not in content_vals
+
+ @pytest.mark.asyncio
+ async def test_correct_role_mapping(self):
+ """User → UserMessage, assistant → AssistantMessage, other → UserMessage."""
+ adapter = _make_adapter()
+ mock_model = AsyncMock()
+ mock_result = MagicMock()
+ mock_result.content = "answer"
+ mock_model.invoke.return_value = mock_result
+ adapter._model = mock_model
+
+ msgs = [
+ _make_msg(role="user", content="u1"),
+ _make_msg(role="assistant", content="a1"),
+ _make_msg(role="system", content="s1"), # maps to UserMessage
+ ]
+
+ await adapter._call_model_for_recap(msgs, "prompt")
+
+ invoke_args = mock_model.invoke.call_args[0][0]
+ roles_found = [getattr(m, "role", type(m).__name__) for m in invoke_args]
+ # Should contain UserMessage, AssistantMessage, UserMessage for system
+ assert "user" in roles_found or any("UserMessage" in str(type(m)) for m in invoke_args)
+
+
+# =============================================================================
+# Section E: generate_btw_answer flow
+# =============================================================================
+
+class TestGenerateBtwAnswer:
+ """Tests for JiuWenSwarmDeepAdapter.generate_btw_answer."""
+
+ @pytest.mark.asyncio
+ async def test_no_context_when_no_messages_and_no_system_prompt(self):
+ """When there are no messages AND no system prompt, return no_context."""
+ adapter = _make_adapter(_last_system_prompt="")
+
+ def _get_recent_messages(session_id, window=30):
+ return []
+ adapter._get_recent_messages = _get_recent_messages
+
+ result = await adapter.generate_btw_answer("session-1", "question?")
+ assert result == {"status": "no_context"}
+
+ @pytest.mark.asyncio
+ async def test_failed_when_model_returns_none(self):
+ """When _call_model_for_recap returns None, return failed status."""
+ adapter = _make_adapter(_last_system_prompt="sys prompt")
+
+ def _get_recent_messages(session_id, window=30):
+ return [_make_msg(role="user", content="hello")]
+ adapter._get_recent_messages = _get_recent_messages
+
+ async def _call_model(*args, **kwargs):
+ return None
+ adapter._call_model_for_recap = _call_model
+
+ result = await adapter.generate_btw_answer("session-1", "question?")
+ assert result["status"] == "failed"
+ assert "error" in result
+
+ @pytest.mark.asyncio
+ async def test_ok_with_trimmed_answer_on_success(self):
+ """Successful path returns ok with stripped answer text."""
+ adapter = _make_adapter(_last_system_prompt="sys")
+
+ def _get_recent_messages(session_id, window=30):
+ return [_make_msg(role="user", content="hello")]
+ adapter._get_recent_messages = _get_recent_messages
+
+ async def _call_model(messages, prompt, system_prompt="", enable_prompt_caching=True):
+ return " \n the answer \n "
+ adapter._call_model_for_recap = _call_model
+
+ result = await adapter.generate_btw_answer("session-1", "question?")
+ assert result == {"status": "ok", "answer": "the answer"}
+
+ @pytest.mark.asyncio
+ async def test_passes_enable_prompt_caching_true(self):
+ """generate_btw_answer must pass enable_prompt_caching=True to _call_model_for_recap."""
+ adapter = _make_adapter(_last_system_prompt="sys")
+
+ def _get_recent_messages(session_id, window=30):
+ return [_make_msg()]
+ adapter._get_recent_messages = _get_recent_messages
+
+ received_kwargs = {}
+
+ async def _capture_call(*args, **kwargs):
+ received_kwargs.update(kwargs)
+ return "answer"
+
+ adapter._call_model_for_recap = _capture_call
+ await adapter.generate_btw_answer("s1", "q?")
+ assert received_kwargs.get("enable_prompt_caching") is True
+
+ @pytest.mark.asyncio
+ async def test_no_context_with_messages_but_no_system_prompt_still_calls_model(self):
+ """Even without system_prompt, if messages exist, we should call the model."""
+ adapter = _make_adapter(_last_system_prompt="")
+
+ def _get_recent_messages(session_id, window=30):
+ return [_make_msg()]
+ adapter._get_recent_messages = _get_recent_messages
+
+ called = False
+
+ async def _call_model(*args, **kwargs):
+ nonlocal called
+ called = True
+ return "answer"
+
+ adapter._call_model_for_recap = _call_model
+ result = await adapter.generate_btw_answer("s1", "q?")
+ assert called
+ assert result["status"] == "ok"
+
+
+# =============================================================================
+# Section F: _handle_command_btw handler
+# =============================================================================
+
+class TestHandleCommandBtw:
+ """Tests for AgentWebSocketServer._handle_command_btw."""
+
+ @pytest.mark.asyncio
+ async def test_empty_question_returns_failed(self, server, fake_ws):
+ """Empty question should return failed status immediately."""
+ request = AgentRequest(
+ request_id="req-btw-empty",
+ channel_id="tui",
+ session_id="sess-1",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": ""},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-btw-empty",
+ "payload": {"status": "failed", "error": "Question is required"},
+ "ok": True,
+ }
+ ]
+
+ @pytest.mark.asyncio
+ async def test_whitespace_only_question_returns_failed(self, server, fake_ws):
+ """Whitespace-only question should be treated as empty."""
+ request = AgentRequest(
+ request_id="req-btw-ws",
+ channel_id="tui",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": " "},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent[0]["payload"]["status"] == "failed"
+
+ @pytest.mark.asyncio
+ async def test_no_question_param_returns_failed(self, server, fake_ws):
+ """Missing question param should return failed."""
+ request = AgentRequest(
+ request_id="req-btw-missing",
+ channel_id="tui",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent[0]["payload"]["status"] == "failed"
+
+ @pytest.mark.asyncio
+ async def test_happy_path_returns_btw_result(self, server, fake_ws, monkeypatch):
+ """Happy path: agent returns btw result, forwarded to client."""
+
+ class MockAgent:
+ async def generate_btw_answer(self, session_id, question):
+ return {"status": "ok", "answer": "git status shows current state"}
+
+ mock_agent = MockAgent()
+
+ async def mock_get_agent(channel_id, mode, project_dir=None, sub_mode=None):
+ return mock_agent
+
+ monkeypatch.setattr(
+ server.get_agent_manager_for_test(),
+ "get_agent",
+ mock_get_agent,
+ )
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "resolve_request_project_dir",
+ lambda _req: None,
+ )
+
+ request = AgentRequest(
+ request_id="req-btw-ok",
+ channel_id="tui",
+ session_id="sess-1",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": "what does git status do?", "mode": "agent.plan"},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-btw-ok",
+ "payload": {"status": "ok", "answer": "git status shows current state"},
+ "ok": True,
+ }
+ ]
+
+ @pytest.mark.asyncio
+ async def test_agent_not_found_returns_error(self, server, fake_ws, monkeypatch):
+ """When agent_manager returns None, handler should return ok=False."""
+
+ async def mock_get_agent_none(channel_id, mode, project_dir=None, sub_mode=None):
+ return None
+
+ monkeypatch.setattr(
+ server.get_agent_manager_for_test(),
+ "get_agent",
+ mock_get_agent_none,
+ )
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "resolve_request_project_dir",
+ lambda _req: None,
+ )
+
+ request = AgentRequest(
+ request_id="req-btw-no-agent",
+ channel_id="tui",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": "test?"},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent[0]["ok"] is False
+ assert fake_ws.sent[0]["payload"]["status"] == "failed"
+
+ @pytest.mark.asyncio
+ async def test_generate_btw_answer_raises_exception(self, server, fake_ws, monkeypatch):
+ """When agent.generate_btw_answer raises, handler catches and returns ok=False."""
+
+ class CrashingAgent:
+ async def generate_btw_answer(self, session_id, question):
+ raise RuntimeError("model unavailable")
+
+ async def mock_get_agent(channel_id, mode, project_dir=None, sub_mode=None):
+ return CrashingAgent()
+
+ monkeypatch.setattr(
+ server.get_agent_manager_for_test(),
+ "get_agent",
+ mock_get_agent,
+ )
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "resolve_request_project_dir",
+ lambda _req: None,
+ )
+
+ request = AgentRequest(
+ request_id="req-btw-crash",
+ channel_id="tui",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": "test?"},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent[0]["ok"] is False
+ assert fake_ws.sent[0]["payload"]["status"] == "failed"
+ assert "model unavailable" in fake_ws.sent[0]["payload"]["error"]
+
+ @pytest.mark.asyncio
+ async def test_uses_auto_harness_mode_mapped_to_agent(self, server, fake_ws, monkeypatch):
+ """auto_harness mode should be mapped to 'agent' for agent_manager.get_agent."""
+
+ captured_mode = {}
+
+ class MockAgent:
+ async def generate_btw_answer(self, session_id, question):
+ return {"status": "ok", "answer": "ok"}
+
+ async def mock_get_agent(channel_id, mode, project_dir=None, sub_mode=None):
+ captured_mode["mode"] = mode
+ captured_mode["sub_mode"] = sub_mode
+ return MockAgent()
+
+ monkeypatch.setattr(
+ server.get_agent_manager_for_test(),
+ "get_agent",
+ mock_get_agent,
+ )
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "resolve_request_project_dir",
+ lambda _req: None,
+ )
+
+ request = AgentRequest(
+ request_id="req-btw-mode",
+ channel_id="tui",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": "test?", "mode": "auto_harness.plan"},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert captured_mode["mode"] == "agent"
+
+ @pytest.mark.asyncio
+ async def test_no_context_status_returns_payload_as_is(self, server, fake_ws, monkeypatch):
+ """When btw returns no_context, payload passed through unchanged."""
+
+ class MockAgent:
+ async def generate_btw_answer(self, session_id, question):
+ return {"status": "no_context"}
+
+ async def mock_get_agent(channel_id, mode, project_dir=None, sub_mode=None):
+ return MockAgent()
+
+ monkeypatch.setattr(
+ server.get_agent_manager_for_test(),
+ "get_agent",
+ mock_get_agent,
+ )
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "resolve_request_project_dir",
+ lambda _req: None,
+ )
+
+ request = AgentRequest(
+ request_id="req-btw-nocontext",
+ channel_id="tui",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": "test?"},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-btw-nocontext",
+ "payload": {"status": "no_context"},
+ "ok": True,
+ }
+ ]
+
+ @pytest.mark.asyncio
+ async def test_defaults_session_id_when_none(self, server, fake_ws, monkeypatch):
+ """When request.session_id is None, defaults to 'default'."""
+
+ captured_session_id = {}
+
+ class MockAgent:
+ async def generate_btw_answer(self, session_id, question):
+ captured_session_id["sid"] = session_id
+ return {"status": "ok", "answer": "ok"}
+
+ async def mock_get_agent(channel_id, mode, project_dir=None, sub_mode=None):
+ return MockAgent()
+
+ monkeypatch.setattr(
+ server.get_agent_manager_for_test(),
+ "get_agent",
+ mock_get_agent,
+ )
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "resolve_request_project_dir",
+ lambda _req: None,
+ )
+
+ request = AgentRequest(
+ request_id="req-btw-defaultsid",
+ channel_id="tui",
+ req_method=ReqMethod.COMMAND_BTW,
+ params={"question": "test?"},
+ )
+
+ await server.handle_command_btw_for_test(fake_ws, request, asyncio.Lock())
+ assert captured_session_id["sid"] == "default"
+
+
+# =============================================================================
+# Section G: interface.py generate_btw_answer pass-through
+# =============================================================================
+
+class TestInterfaceBtwPassThrough:
+ """Tests for JiuWenSwarm.generate_btw_answer in interface.py."""
+
+ @pytest.mark.asyncio
+ async def test_delegates_to_adapter(self):
+ """generate_btw_answer must delegate to the underlying adapter."""
+ from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm
+
+ facade = object.__new__(JiuWenSwarm)
+ mock_adapter = AsyncMock()
+ mock_adapter.generate_btw_answer.return_value = {
+ "status": "ok", "answer": "the answer",
+ }
+ facade._adapter = mock_adapter
+
+ result = await facade.generate_btw_answer("session-1", "question?")
+ assert result == {"status": "ok", "answer": "the answer"}
+ mock_adapter.generate_btw_answer.assert_awaited_once_with(
+ session_id="session-1", question="question?",
+ )
+
+ @pytest.mark.asyncio
+ async def test_raises_when_adapter_is_none(self):
+ """When _adapter is None, raise ValueError."""
+ from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm
+
+ facade = object.__new__(JiuWenSwarm)
+ facade._adapter = None
+
+ with pytest.raises(ValueError, match="Agent adapter not available"):
+ await facade.generate_btw_answer("session-1", "question?")
+
+
+# =============================================================================
+# Section H: build_recap_prompt (existing function, now shares model call path)
+# =============================================================================
+
+class TestBuildRecapPrompt:
+ """Smoke tests for build_recap_prompt to ensure it still works."""
+
+ @staticmethod
+ def test_en_recap_prompt():
+ result = build_recap_prompt(memory=None, language="en")
+ assert "recap" in result.lower()
+ assert "short sentences" in result.lower()
+
+ @staticmethod
+ def test_zh_recap_prompt():
+ result = build_recap_prompt(memory=None, language="zh")
+ assert "回顾" in result
+
+ @staticmethod
+ def test_recap_prompt_with_memory():
+ result = build_recap_prompt(memory="previous context", language="en")
+ assert "previous context" in result
diff --git a/tests/unit_tests/gateway/test_btw_tui_forward.py b/tests/unit_tests/gateway/test_btw_tui_forward.py
new file mode 100644
index 0000000000..3aea70df89
--- /dev/null
+++ b/tests/unit_tests/gateway/test_btw_tui_forward.py
@@ -0,0 +1,115 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests that command.btw is correctly wired in TUI connection forwarding sets.
+
+Verifies the changes from c44c8864 (add /btw command) that added
+command.btw to CLI_FORWARD_REQ_METHODS and CLI_FORWARD_NO_LOCAL_HANDLER_METHODS.
+"""
+
+from __future__ import annotations
+
+from jiuwenswarm.gateway.channel_manager.tui.tui_connect import (
+ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS,
+ CLI_FORWARD_REQ_METHODS,
+ CliHandlersBindParams,
+ build_cli_route_binding,
+ register_cli_handlers,
+)
+
+
+class FakeGatewayServer:
+ """Fake GatewayServer for testing CLI handler registration."""
+
+ def __init__(self) -> None:
+ self.local_handlers: dict[str, dict] = {} # path -> {method: handler}
+ self.responses: list[dict] = []
+
+ def register_local_handler(self, path: str, method: str, handler) -> None:
+ if path not in self.local_handlers:
+ self.local_handlers[path] = {}
+ self.local_handlers[path][method] = handler
+
+ async def send_response(
+ self, ws, req_id, *, ok=True, payload=None, error=None, code=None
+ ) -> None:
+ self.responses.append(
+ {
+ "id": req_id,
+ "ok": ok,
+ "payload": payload or {},
+ "error": error,
+ "code": code,
+ }
+ )
+
+
+class TestBtwInForwardSets:
+ """Verify command.btw is registered in the required forward sets."""
+
+ @staticmethod
+ def test_command_btw_in_cli_forward_req_methods():
+ """command.btw must be in CLI_FORWARD_REQ_METHODS."""
+ assert "command.btw" in CLI_FORWARD_REQ_METHODS
+
+ @staticmethod
+ def test_command_btw_in_cli_forward_no_local_handler_methods():
+ """command.btw must be in CLI_FORWARD_NO_LOCAL_HANDLER_METHODS."""
+ assert "command.btw" in CLI_FORWARD_NO_LOCAL_HANDLER_METHODS
+
+ @staticmethod
+ def test_route_binding_includes_command_btw():
+ """build_cli_route_binding must include command.btw in forward methods."""
+ from jiuwenswarm.gateway.channel_manager.tui.tui_connect import CliRouteBindParams
+
+ bind_params = CliRouteBindParams(path="/tui")
+ binding = build_cli_route_binding(bind_params)
+ assert "command.btw" in binding.forward_methods
+
+ @staticmethod
+ def test_register_cli_handlers_does_not_create_local_handler_for_btw():
+ """command.btw has no local handler — it is forwarded to agent server."""
+ server = FakeGatewayServer()
+ register_cli_handlers(
+ CliHandlersBindParams(
+ channel=server,
+ agent_client=None,
+ message_handler=None,
+ on_config_saved=None,
+ path="/tui",
+ )
+ )
+
+ cli_handlers = server.local_handlers.get("/tui", {})
+ # command.btw should NOT have a local handler
+ assert "command.btw" not in cli_handlers
+
+ @staticmethod
+ def test_all_cli_forward_methods_are_strings():
+ """All entries in CLI_FORWARD_REQ_METHODS should be strings."""
+ for method in CLI_FORWARD_REQ_METHODS:
+ assert isinstance(method, str), f"Expected str, got {type(method)}: {method}"
+
+ @staticmethod
+ def test_btw_not_in_both_local_and_forward():
+ """command.btw in NO_LOCAL_HANDLER means no local handler registered."""
+ assert "command.btw" in CLI_FORWARD_NO_LOCAL_HANDLER_METHODS
+ assert "command.btw" in CLI_FORWARD_REQ_METHODS
+
+
+class TestBtwVsOtherCommands:
+ """Compare command.btw with sibling commands to verify consistency."""
+
+ @staticmethod
+ def test_command_btw_like_command_recap():
+ """command.btw should follow the same pattern as command.compact (forward, no local)."""
+ assert "command.compact" in CLI_FORWARD_REQ_METHODS
+ assert "command.compact" in CLI_FORWARD_NO_LOCAL_HANDLER_METHODS
+ # btw should match the pattern
+ assert "command.btw" in CLI_FORWARD_REQ_METHODS
+ assert "command.btw" in CLI_FORWARD_NO_LOCAL_HANDLER_METHODS
+
+ @staticmethod
+ def test_command_btw_is_frozenset():
+ """CLI_FORWARD_REQ_METHODS is a frozenset, so membership checks are O(1)."""
+ assert isinstance(CLI_FORWARD_REQ_METHODS, frozenset)
+ assert isinstance(CLI_FORWARD_NO_LOCAL_HANDLER_METHODS, frozenset)