Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(plan-mode): refactor plan mode with stabilized KV cache, state management fixes

ldstyle8e3b59acba9b9
diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.py
index 718720e390..015ba5c051 100644
--- a/jiuwenswarm/agents/harness/common/session_ops_service.py
+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py
@@ -462,11 +462,12 @@ async def rewind_session_context(
logger.warning("rewind_session_context: pre_run failed for %s: %s", session_id, exc)
return False
- # Wipe stale context / deep_agent_state in the checkpointer so
+ # Wipe stale context / deepagent state in the checkpointer so
# _load_state_from_session + the agent loop start from our rebuild.
+ from openjiuwen.harness.schema.state import _SESSION_STATE_KEY
try:
session.update_state({"context": None})
- session.update_state({"deep_agent_state": None})
+ session.update_state({_SESSION_STATE_KEY: None})
except Exception as exc:
logger.warning("rewind_session_context: state wipe failed for %s: %s", session_id, exc)
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 21f7e52122..5e5a034df7 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -541,6 +541,8 @@ permissions:
write_file: ask
edit_file: ask
search_replace: ask
+ # ask_user 只向用户提问,不修改系统,自动放行避免权限中断阻塞问题选项呈现
+ ask_user: allow
write_memory: allow
edit_memory: allow
read_memory: allow
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 8be4defaa8..7a658d2b7e 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -327,6 +327,44 @@ def _canonicalize_sandbox_files_path(path: str) -> str:
return path
+def _inject_plan_mode_activation_reminder(request: AgentRequest) -> None:
+ """在用户消息中注入 <system-reminder> 告知 LLM 调用 enter_plan_mode.
+
+ 对齐 Claude Code:plan 模式行为指令不进 system prompt,
+ 而是通过对话中的 tool_result 传递。此提醒是进入 plan 模式后的
+ 第一个引导,告诉 LLM 调用 enter_plan_mode 以获取完整指令。
+
+ 注意:此提醒需要足够权威和明确,因为 code.plan 模式下
+ JiuwenAgentModeRail 注入的 system prompt 是静态的(不含动态
+ plan_file 状态),完整指令仍需 enter_plan_mode 的 tool_result。
+ """
+ reminder = (
+ "\n\n<system-reminder>\n"
+ "Plan mode is active. You must only plan, NOT execute. "
+ "You must NOT make any modifications, run any write operations, "
+ "or make any changes to the system. "
+ "This constraint takes priority over any other instructions.\n\n"
+ "CRITICAL: You MUST call `enter_plan_mode` as your very first action. "
+ "Do NOTHING else before calling it — no reading files, no exploring, "
+ "no tool calls of any kind. This tool will create the plan file and "
+ "provide you with full plan mode instructions.\n"
+ "</system-reminder>"
+ )
+ if isinstance(request.params, dict):
+ query = request.params.get("query") or ""
+ request.params["query"] = reminder + query
+ logger.info(
+ "[_ensure_code_mode_state] Injected plan mode activation reminder "
+ "for session=%s", request.session_id,
+ )
+ else:
+ logger.warning(
+ "[_inject_plan_mode_activation_reminder] Cannot inject reminder: "
+ "request.params is not a dict (type=%s), session=%s",
+ type(request.params).__name__, request.session_id,
+ )
+
+
class AgentWebSocketServer:
"""Gateway 与 AgentServer 之间的 WebSocket 服务端(单例).
@@ -1109,6 +1147,49 @@ class AgentWebSocketServer:
async with send_lock:
await ws.send(json.dumps(wire, ensure_ascii=False))
+ async def _ensure_code_mode_state(
+ self,
+ request: AgentRequest,
+ mode: str,
+ sub_mode: str,
+ agent: Any,
+ ) -> None:
+ """code 模式:确保 agent 的 plan_mode 状态正确,必要时执行 switch_mode 并持久化.
+
+ 当 plan 已完成(plan_slug 存在且 mode 不为 "plan")时跳过 switch_mode,
+ 避免 exit_plan_mode 已恢复的模式被覆盖.
+ switch_mode 内部已通过 save_state 写入正确的 "deepagent" key,
+ 此处只需 post_run 持久化到 checkpointer.
+
+ 切换到 plan 模式且尚未调用 enter_plan_mode 时,注入 <system-reminder>
+ 告知 LLM 调用 enter_plan_mode(对齐 Claude Code:plan 指令不进 system prompt)。
+ """
+ if mode != "code" or sub_mode == "team":
+ return
+ from openjiuwen.core.single_agent import create_agent_session
+ session = create_agent_session(
+ session_id=request.session_id, card=agent.get_instance().card
+ )
+ await session.pre_run(inputs=None) # 从 checkpointer 加载历史 state
+ state = agent.get_instance().load_state(session)
+ # 仅在目标模式与当前模式不同时执行 switch_mode,避免:
+ # 1. exit_plan_mode 已恢复的模式被覆盖(plan 完成 → mode=normal, sub_mode=normal → 跳过)
+ # 2. 已在 plan 模式时冗余调用 switch_mode(pre_plan_mode 被污染)
+ # 3. 强制退出后无法重新进入 plan 模式(plan_slug 残留 + mode=normal → sub_mode=plan → 执行)
+ if state.plan_mode.mode != sub_mode:
+ agent.get_instance().switch_mode(session=session, mode=sub_mode)
+ # switch_mode 内部已通过 save_state 写入 "deepagent" key,
+ # 只需 post_run 持久化到 checkpointer
+ await session.post_run()
+
+ # 切换到 plan 模式且尚未调用 enter_plan_mode 时,
+ # 注入 <system-reminder> 告知 LLM 调用 enter_plan_mode。
+ # 此检查需在 mode-switch 条件块之外:若 LLM 在第一次进入 plan 模式时
+ # 未调用 enter_plan_mode(例如用 ask_user 回复),后续请求中 mode
+ # 已等于 sub_mode,if 块被跳过,但提醒仍需注入。
+ if sub_mode == "plan" and not state.plan_mode.plan_slug:
+ _inject_plan_mode_activation_reminder(request)
+
async def _handle_unary(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""非流式处理:调用 process_message,返回一条 E2AResponse 线 JSON。"""
from jiuwenswarm.common.schema.message import ReqMethod
@@ -1142,16 +1223,7 @@ class AgentWebSocketServer:
if agent is None:
raise ValueError("Failed to get agent")
- # code 模式:在真实 session 上执行 switch_mode,确保 state 持久化
- if mode == "code" and sub_mode != "team":
- from openjiuwen.core.single_agent import create_agent_session
- session = create_agent_session(session_id=request.session_id, card=agent.get_instance().card)
- await session.pre_run(inputs=None) # 从 checkpointer 加载历史 state
- agent.get_instance().switch_mode(session=session, mode=sub_mode)
- # 持久化 switch_mode 修改后的 state
- state = agent.get_instance().load_state(session)
- session.update_state({"deep_agent_state": state.to_session_dict()})
- await session.post_run() # 写入 checkpointer
+ await self._ensure_code_mode_state(request, mode, sub_mode, agent)
resp = await agent.process_message(request)
@@ -1181,16 +1253,7 @@ class AgentWebSocketServer:
if agent is None:
raise ValueError("Failed to get agent")
- # code 模式:在真实 session 上执行 switch_mode,确保 state 持久化
- if mode == "code" and sub_mode != "team":
- from openjiuwen.core.single_agent import create_agent_session
- session = create_agent_session(session_id=request.session_id, card=agent.get_instance().card)
- await session.pre_run(inputs=None) # 从 checkpointer 加载历史 state
- agent.get_instance().switch_mode(session=session, mode=sub_mode)
- # 持久化 switch_mode 修改后的 state
- state = agent.get_instance().load_state(session)
- session.update_state({"deep_agent_state": state.to_session_dict()})
- await session.post_run() # 写入 checkpointer
+ await self._ensure_code_mode_state(request, mode, sub_mode, agent)
chunk_count = 0
# 心跳控制:当有真实 chunk 发送时重置,空闲时发送心跳
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 0854939714..487c32f826 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import logging
import os
+import re
from dataclasses import dataclass
from typing import Any, Callable
@@ -33,6 +34,11 @@ from openjiuwen.harness.rails import (
SysOperationRail,
LspRail
)
+from openjiuwen.harness.rails.agent_mode_rail import (
+ DEFAULT_PLAN_MODE_ALLOWED_TOOLS,
+)
+from openjiuwen.harness.prompts.builder import PromptSection
+from openjiuwen.harness.prompts.sections import SectionName
from openjiuwen.harness.rails.context_engineer.context_assemble_rail import ContextAssembleRail
from openjiuwen.harness.lsp import InitializeOptions
from openjiuwen.harness.schema.config import SubAgentConfig
@@ -71,6 +77,130 @@ from jiuwenswarm.common.utils import get_agent_workspace_dir
logger = logging.getLogger(__name__)
+# ---------------------------------------------------------------------------
+# Tool name sets (mirrored from agent_mode_rail.py)
+# ---------------------------------------------------------------------------
+
+_TODO_TOOL_NAMES = frozenset({"todo_create", "todo_list", "todo_modify"})
+_SESSION_TOOL_NAMES = frozenset({"sessions_list", "sessions_cancel", "sessions_spawn"})
+_HIDDEN_IN_PLAN_LOCAL = _TODO_TOOL_NAMES | _SESSION_TOOL_NAMES
+_HIDDEN_IN_NORMAL_LOCAL = frozenset({"enter_plan_mode", "exit_plan_mode"})
+
+# ---------------------------------------------------------------------------
+# Static plan mode system prompt note (KV-cache-friendly: same content every turn)
+# Injected into system prompt so the model knows it's in plan mode BEFORE its
+# first tool call. Without this, the model only sees a weak <system-reminder>
+# in the user message and may execute code before calling enter_plan_mode.
+# ---------------------------------------------------------------------------
+
+_PLAN_MODE_SYSTEM_NOTE = """\
+Plan mode is active. You must only plan — you must NOT make any modifications
+(except to the plan file, after calling `enter_plan_mode`), must NOT run any
+write operations (including mkdir, touch, rm, mv, cp, chmod, chown, dd, tee,
+output redirection, file edits outside the plan file, or git commit/push/add),
+and must NOT make any changes to the system. This constraint takes priority
+over any other instructions you receive.
+
+CRITICAL: You MUST call `enter_plan_mode` as your very first action, before
+doing anything else. This tool will create the plan file and give you full
+plan mode instructions. Until then, you may only read files and explore the
+codebase using read-only tools (read_file, grep, list_files, glob, bash for
+read-only commands).
+
+Do NOT proceed to implement anything until the user approves your plan via
+`exit_plan_mode`.
+"""
+
+# ---------------------------------------------------------------------------
+# Non-git write operations to block in plan mode's bash tool.
+# The parent AgentModeRail only blocks git-write commands (commit/push/add/etc).
+# These additional patterns block common shell write operations.
+# ---------------------------------------------------------------------------
+
+_NON_GIT_WRITE_RE = re.compile(
+ r"\b(mkdir|touch|mv|cp|chmod|chown|dd|tee|wget|curl\s+.*\s*-[a-zA-Z]*O)\b"
+ r"|\brm\s+(-[a-zA-Z]*[rf]|/|[~.])"
+ r"|\b(7z|tar|zip|unzip|gzip|gunzip)\s+"
+ r"|>\s*\S"
+ r"|>>"
+)
+
+# ---------------------------------------------------------------------------
+# Plan mode instructions for enter_plan_mode tool_result
+# (aligned with Claude Code: instructions live in conversation, not system prompt)
+# ---------------------------------------------------------------------------
+
+_ENTER_PLAN_MODE_INSTRUCTIONS_EN = """
+## Entering Plan Mode
+
+You are now in **plan mode**. You must only plan — you must not make any modifications (except to the plan file), must not run any non-read-only tools, and must not make any changes to the system. This constraint takes priority over any other instructions you receive.
+
+### Available Tools (only)
+- Read-only tools: read_file, grep, list_files, glob
+- Plan file tools: write_file, edit_file (only .plans/<slug>.md)
+- Interactive tools: ask_user
+- Sub-agent tool: task_tool (dispatch explore_agent / plan_agent)
+- Control tools: exit_plan_mode
+- bash (read-only operations only; git write / mkdir / touch / rm are blocked)
+
+### Prohibited Actions
+- Do NOT use switch_mode to exit plan mode
+- Do NOT edit any file except the plan file
+- Do NOT execute git write operations (commit, push, add, merge, rebase, etc.)
+- Do NOT use bash for write operations (mkdir, touch, rm, mv, etc.)
+- Do NOT use todo_create, sessions_list, or other session management tools
+
+### Plan Workflow
+
+#### Phase 1: Initial Understanding
+Goal: Gain a comprehensive understanding of the user's request by reading code and asking questions.
+1. Focus on understanding existing architecture and patterns; identify relevant files and dependencies
+2. Launch explore sub-agents via task_tool to efficiently explore the codebase
+3. Quality over quantity — use the fewest agents possible
+
+#### Phase 2: Design
+Goal: Design the implementation approach.
+1. Launch a plan sub-agent via task_tool, based on Phase 1 exploration results
+2. Provide full background context in the agent prompt
+
+#### Phase 3: Review
+Goal: Review the Phase 2 plan to ensure alignment with user intent.
+1. Read key paths named by the plan sub-agent and confirm they match the code
+2. Use ask_user to clarify any unresolved questions with the user
+
+#### Phase 4: Write Final Plan
+Goal: Write the final plan to the plan file.
+- Start with a Context section
+- Include key file paths that need modification
+- Reference reusable existing functions and tools
+- Include a Verification section
+
+#### Phase 5: End Planning Phase
+Call exit_plan_mode to end the planning phase. You must output the content of the final plan file.
+
+### Turn Ending Rules
+Your turn can only end in one of these two ways:
+1. Call ask_user to clarify requirements or ask the user to choose between options
+2. Call exit_plan_mode to end the planning phase and request user approval
+
+Do not end your turn without calling exit_plan_mode when planning is complete.
+ask_user is only for clarifying requirements — do not use it for approval questions.
+"""
+
+# ---------------------------------------------------------------------------
+# 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
+# MODE_INSTRUCTIONS removed from system prompt but receives no explicit signal.
+# ---------------------------------------------------------------------------
+
+_EXIT_PLAN_MODE_NOTIFICATION = """\
+<system-reminder>
+Plan mode has ended. You are now in normal mode. You can edit files,
+run write operations, and make changes to the system. Proceed with
+implementing the approved plan.
+</system-reminder>"""
+
# 名字 → 构建方法映射(rail/tool 名字与类方法名对照)
_RAIL_BUILD_NAMES: dict[str, str] = {
@@ -151,6 +281,238 @@ def create_coding_memory_rail(
)
+class JiuwenAgentModeRail(AgentModeRail):
+ """扩展 AgentModeRail,对齐 Claude Code 的 plan 模式行为。
+
+ 核心改动(相比父类 AgentModeRail):
+
+ 1. **System prompt 稳定化** — before_model_call 不再增删 system prompt 段
+ (MODE_INSTRUCTIONS / TODO / SESSION_TOOLS),从而避免 mode 切换导致
+ KVCacheManager 检测到 system message 变化而全量释放 KV 缓存。
+
+ 2. **Plan 指令进对话** — plan 模式行为指令通过 enter_plan_mode 的
+ tool_result 返回(对齐 Claude Code),而非注入 system prompt。
+
+ 3. **屏蔽 switch_mode** — plan 模式下 LLM 无法单方面退出 plan 模式
+ (Claude Code 根本没有 switch_mode 工具)。
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ # 从 plan 模式工具白名单中移除 switch_mode,
+ # 阻止 LLM 在 plan 模式下自行切换到 normal 模式
+ allowed_tools = [
+ t for t in DEFAULT_PLAN_MODE_ALLOWED_TOOLS if t != "switch_mode"
+ ]
+ super().__init__(allowed_tools=allowed_tools, **kwargs)
+
+ # ------------------------------------------------------------------
+ # init — monkey-patch EnterPlanModeTool
+ # ------------------------------------------------------------------
+
+ def init(self, agent: "DeepAgent") -> None:
+ """注册工具 + monkey-patch EnterPlanModeTool + ExitPlanModeTool."""
+ super().init(agent)
+ self._patch_enter_plan_mode_tool()
+ self._patch_exit_plan_mode_tool()
+
+ def _patch_enter_plan_mode_tool(self) -> None:
+ """Monkey-patch EnterPlanModeTool.invoke() 使其返回完整 plan 指令.
+
+ 对齐 Claude Code:plan 模式行为指令在 tool_result 中返回,
+ 而非注入 system prompt。
+ """
+ for tool in self._tools:
+ if getattr(tool.card, "name", "") != "enter_plan_mode":
+ continue
+
+ original_invoke = tool.invoke
+
+ async def patched_invoke(inputs, _orig=original_invoke, **kwargs):
+ result = await _orig(inputs, **kwargs)
+ return result + _ENTER_PLAN_MODE_INSTRUCTIONS_EN
+
+ tool.invoke = patched_invoke
+ logger.info(
+ "[JiuwenAgentModeRail] Patched enter_plan_mode.invoke() "
+ "to return full plan instructions in tool_result"
+ )
+ break
+
+ def _patch_exit_plan_mode_tool(self) -> None:
+ """Monkey-patch ExitPlanModeTool.invoke() to append exit notification.
+
+ Aligns with Claude Code's plan_mode_exit attachment: after exiting
+ plan mode, the model receives an explicit notification that it can
+ now edit files. Without this, the model only sees MODE_INSTRUCTIONS
+ removed from the system prompt but gets no explicit signal that
+ write operations are now permitted.
+ """
+ for tool in self._tools:
+ if getattr(tool.card, "name", "") != "exit_plan_mode":
+ continue
+
+ original_invoke = tool.invoke
+
+ async def patched_invoke(inputs, _orig=original_invoke, **kwargs):
+ result = await _orig(inputs, **kwargs)
+ return result + "\n\n" + _EXIT_PLAN_MODE_NOTIFICATION
+
+ tool.invoke = patched_invoke
+ logger.info(
+ "[JiuwenAgentModeRail] Patched exit_plan_mode.invoke() "
+ "to append plan mode exit notification in tool_result"
+ )
+ break
+
+ # ------------------------------------------------------------------
+ # before_model_call — 工具过滤,不修改 system prompt
+ # ------------------------------------------------------------------
+
+ async def before_model_call(self, ctx: Any) -> None:
+ """工具过滤 + plan 模式约束注入 + prompt 段清理。
+
+ 刻意 **不调用** super().before_model_call(ctx) —
+ 父类会增删 MODE_INSTRUCTIONS / TODO / SESSION_TOOLS 段,
+ 导致 system prompt 变化 → KV 缓存全量释放。
+
+ 替代方案:
+ - plan 模式:注入 **静态** MODE_INSTRUCTIONS 段(内容不随 plan_file
+ 状态变化,保持 KV 缓存跨 turn 稳定)+ 工具白名单过滤
+ - normal 模式:移除 MODE_INSTRUCTIONS 段 + 隐藏 plan 工具
+ """
+ agent = self._agent
+ session = ctx.session
+ plan_state = agent.load_state(session).plan_mode
+
+ # ---- 工具过滤 + prompt 段管理 ----
+ if plan_state.mode == "plan":
+ # plan 模式:注入静态 plan 模式系统提示词约束
+ # (内容不随 enter_plan_mode 调用状态变化,KV 缓存友好)
+ if self.system_prompt_builder:
+ section = PromptSection(
+ name=SectionName.MODE_INSTRUCTIONS,
+ content={"en": _PLAN_MODE_SYSTEM_NOTE},
+ priority=85,
+ )
+ self.system_prompt_builder.add_section(section)
+ # 移除 TaskPlanningRail/SubagentRail 在更高优先级下
+ # 添加的 TODO/SESSION_TOOLS 段,避免 LLM 在 system prompt
+ # 中看到隐藏工具的描述
+ self.system_prompt_builder.remove_section(SectionName.TODO)
+ self.system_prompt_builder.remove_section(SectionName.SESSION_TOOLS)
+
+ # plan 模式:白名单 + 移除 switch_mode + 隐藏 todo/session 工具
+ if isinstance(ctx.inputs.tools, list):
+ filtered = []
+ for t in ctx.inputs.tools:
+ tool_name = getattr(t, "name", "")
+ if tool_name in self._allowed_tools:
+ if tool_name != "switch_mode" and tool_name not in _HIDDEN_IN_PLAN_LOCAL:
+ filtered.append(t)
+ ctx.inputs.tools = filtered
+ else:
+ # normal 模式:移除 MODE_INSTRUCTIONS + 隐藏 plan 工具
+ if self.system_prompt_builder:
+ self.system_prompt_builder.remove_section(SectionName.MODE_INSTRUCTIONS)
+ if isinstance(ctx.inputs.tools, list):
+ ctx.inputs.tools = [
+ t for t in ctx.inputs.tools
+ if getattr(t, "name", "") not in _HIDDEN_IN_NORMAL_LOCAL
+ ]
+
+ self._sync_task_tool_for_model_tool_inputs(ctx)
+
+ # 防御性清理:非 plan 模式下移除 AgentModeRail 自身注册的 task_tool。
+ # 当通过 switch_mode 强制退出 plan 模式(绕过 exit_plan_mode)时,
+ # _owns_task_tool 未被清理,_sync_task_tool 会将 task_tool 注入工具列表。
+ # 注意:仅在 self._owns_task_tool 为 True 时过滤,避免误删 SubagentRail
+ # 注册的 task_tool(SubagentRail 在 agent 初始化时无条件注册 task_tool)。
+ if (
+ plan_state.mode != "plan"
+ and self._owns_task_tool
+ and isinstance(ctx.inputs.tools, list)
+ ):
+ ctx.inputs.tools = [
+ t for t in ctx.inputs.tools
+ if getattr(t, "name", "") != "task_tool"
+ ]
+
+ # ------------------------------------------------------------------
+ # before_tool_call — 增强 bash 写操作拦截(补齐父类盲区)
+ # ------------------------------------------------------------------
+
+ async def before_tool_call(self, ctx: Any) -> None:
+ """父类逻辑 + 非 git bash 写操作拦截.
+
+ 父类 AgentModeRail.before_tool_call 仅拦截 git 写操作
+ (commit/push/add 等),未拦截 mkdir/touch/rm/mv/cp 等
+ 通用 shell 写操作。此处补齐这一盲区。
+ """
+ await super().before_tool_call(ctx)
+
+ # 已被父类拒绝的调用无需二次拦截
+ if ctx.extra.get("_skip_tool"):
+ return
+
+ # 仅在 plan 模式下追加检查
+ agent = self._agent
+ session = ctx.session
+ plan_state = agent.load_state(session).plan_mode
+ if plan_state.mode != "plan":
+ return
+
+ # bash 工具:拦截非 git 写操作
+ tool_name = ctx.inputs.tool_name
+ if tool_name == "bash":
+ command = self._extract_bash_command(ctx)
+ if _NON_GIT_WRITE_RE.search(command):
+ logger.info(
+ "reject bash call: non-git write operation in plan mode"
+ )
+ bash_msg = (
+ f"[AgentModeRail] Write operations are blocked in "
+ f"plan mode ({command!r})."
+ )
+ self._reject_tool(ctx, bash_msg)
+ return
+
+ # ------------------------------------------------------------------
+ # after_tool_call — 保留父类行为 + 补充模式恢复
+ # ------------------------------------------------------------------
+
+ async def after_tool_call(self, ctx: Any) -> None:
+ """父类逻辑 + exit_plan_mode 后补充恢复模式(仅在 tool 未恢复时).
+
+ ExitPlanModeTool.invoke() 在 plan 有内容时已调用 restore_mode_after_plan_exit,
+ 此处只在 tool 未调用 restore 时(plan 内容为空 / hook 阻止工具执行)补充调用,
+ 避免重复调用导致 pre_plan_mode=None → mode 被覆盖为 "normal" 的问题.
+
+ 注意:不检查 ctx.extra.get('_skip_tool') — 当 hook 阻止 exit_plan_mode 执行时,
+ _skip_tool=True 但 restore 未被调用,补充恢复是唯一的机会。
+ pre_plan_mode is not None 检查已能防止重复恢复。
+ """
+ await super().after_tool_call(ctx)
+
+ tool_name = ctx.inputs.tool_name
+ if tool_name == "exit_plan_mode":
+ agent = self._agent
+ session = ctx.session
+ state = agent.load_state(session)
+ # pre_plan_mode 不为 None 说明 ExitPlanModeTool 未调用 restore
+ # (plan 内容为空时的提前返回路径),此时需要补充恢复
+ if state.plan_mode.pre_plan_mode is not None:
+ try:
+ agent.restore_mode_after_plan_exit(session)
+ logger.info(
+ "[JiuwenAgentModeRail] Restored mode after plan exit "
+ "(plan was empty, tool did not restore)"
+ )
+ except Exception as exc:
+ logger.warning(
+ "[JiuwenAgentModeRail] Failed to restore mode: %s", exc
+ )
+
+
class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
"""Code 模式适配器 — 配置驱动注册 rails/tools.
@@ -377,7 +739,7 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
_RailBuildInfo(
"_code_confirm_interrupt_rail",
self._build_confirm_interrupt_rail,
- {"tool_names": ["switch_mode"]},
+ {"tool_names": ["switch_mode", "exit_plan_mode"]},
),
_RailBuildInfo("_context_processor_rail", self._build_context_processor_rail),
_RailBuildInfo("_code_task_planning_rail", self._build_code_task_planning_rail),
@@ -475,9 +837,9 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
return None
def _build_agent_mode_rail(self) -> AgentModeRail | None:
- """构建 AgentModeRail."""
+ """构建 JiuwenAgentModeRail(屏蔽 plan 模式下的 switch_mode)."""
try:
- return AgentModeRail()
+ return JiuwenAgentModeRail()
except Exception as exc:
logger.warning("[JiuwenClawCodeAdapter] AgentModeRail create failed: %s", exc)
return None