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(plan_mode): refactor the plan mode process
ldstyle80645b62df61d
diff --git a/jiuwenswarm/agents/harness/code/prompt/plan_approval.py b/jiuwenswarm/agents/harness/code/prompt/plan_approval.pynew file mode 100644index 0000000000..9e4b927d06--- /dev/null+++ b/jiuwenswarm/agents/harness/code/prompt/plan_approval.py@@ -0,0 +1,257 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Plan approval definitions — templates and helpers.++Plan approval is text-only: ``exit_plan_mode`` tool_result shows the plan+plus a short marker; the next user message is interpreted by the server+(``_check_and_handle_pending_approval``) as approve or feedback.+"""++from __future__ import annotations++import re+from typing import Literal++# ── Legacy event type (wire compat only; no longer pushed to clients) ───++PLAN_APPROVAL_EVENT_TYPE = "plan.approval_required"++# Pushed to clients after the user approves and server restores normal mode.+PLAN_MODE_EXITED_EVENT_TYPE = "plan.mode_exited"++# ── Approve / Reject command prefixes ───────────────────────────────────+# The frontend sends a new user request with one of these as the query text+# after the user interacts with the approval dialog.++APPROVE_CMD_PREFIX = "plan.approve"+REJECT_CMD_PREFIX = "plan.reject"++# Set on request.params when the user explicitly approved the plan this turn.+# Consumed by ``_ensure_code_mode_state`` to allow plan → normal restoration.+PLAN_USER_APPROVED_FLAG = "_plan_user_approved"++PlanUserIntent = Literal["approve", "revise"]++# ── Pending approval marker (fallback — appended to exit_plan_mode tool_result) ──++_PENDING_APPROVAL_MARKER_CN = (+ "\n\n---\n"+ "**仍在规划模式**,等待你确认计划。直接在输入框回复:\n"+ "- 同意开始执行:回复「好」「可以」「按计划实现」等(批准后将退出规划模式)\n"+ "- 需要修改:直接说明修改意见"+)++_PENDING_APPROVAL_MARKER_EN = (+ "\n\n---\n"+ "**Still in plan mode** — reply in chat to review this plan:\n"+ '- To approve and start implementation: "ok", "approve", "implement the plan", etc.\n'+ "- To revise: describe what to change"+)++PENDING_APPROVAL_MARKER = {+ "cn": _PENDING_APPROVAL_MARKER_CN,+ "en": _PENDING_APPROVAL_MARKER_EN,+}++# ── Approved notification (injected on the NEXT request when user approves) ──++_APPROVED_NOTIFICATION_CN = (+ "\n\n<system-reminder>\n"+ "用户已批准你的计划。立即开始执行。\n"+ "你现在处于 normal 模式,可以编辑文件、运行命令、进行修改。\n"+ "## 已批准的计划:\n{plan_content}\n"+ "</system-reminder>"+)++_APPROVED_NOTIFICATION_EN = (+ "\n\n<system-reminder>\n"+ "User has approved your plan. Proceed with implementation.\n"+ "You are now in normal mode. You can edit files, run commands, and make changes.\n"+ "## Approved Plan:\n{plan_content}\n"+ "</system-reminder>"+)++APPROVED_NOTIFICATION = {+ "cn": _APPROVED_NOTIFICATION_CN,+ "en": _APPROVED_NOTIFICATION_EN,+}++# ── Feedback injection (injected on the NEXT request when user gives feedback) ──++_FEEDBACK_INJECTION_CN = (+ "\n\n<system-reminder>\n"+ "用户要求修订计划(尚未批准执行)。请只修改计划文件,不要实现产品代码。\n"+ "你仍处于 plan 模式:禁止编辑计划文件以外的任何文件,禁止运行写操作。\n"+ "修订完成后,再次调用 exit_plan_mode 提交审批。\n\n"+ "**用户修订意见:**\n{user_message}\n"+ "</system-reminder>"+)++_FEEDBACK_INJECTION_EN = (+ "\n\n<system-reminder>\n"+ "The user wants plan revisions (implementation is NOT approved yet).\n"+ "You are still in plan mode — edit ONLY the plan file. Do NOT implement product code.\n"+ "Once revised, call exit_plan_mode again to submit for approval.\n\n"+ "**User revision request:**\n{user_message}\n"+ "</system-reminder>"+)++FEEDBACK_INJECTION = {+ "cn": _FEEDBACK_INJECTION_CN,+ "en": _FEEDBACK_INJECTION_EN,+}++# ── Intent detection helpers ─────────────────────────────────────────────++_APPROVAL_KEYWORDS_CN = frozenset({+ "好", "可以", "批准", "同意", "行", "没问题", "通过",+ "嗯", "好的", "可以了", "就这样", "ok", "okay", "approve",+})+_APPROVAL_KEYWORDS_EN = frozenset({+ "ok", "okay", "approve", "yes", "yeah", "yep", "good",+ "looks good", "approved", "go ahead", "proceed",+})++_REJECT_PREFIXES_CN = ("不行", "不好", "不要", "别", "不对", "不可以", "不同意")+_REJECT_PREFIXES_EN = ("reject", "no,", "no ", "don't", "do not")++_REVISION_SUBSTRINGS = (+ "修改", "改一下", "改成", "要改", "调整", "补充", "添加", "增加", "删除", "换成",+ "重新", "细化", "重写", "不够", "缺少", "有问题", "不满意", "换一个",+ "revise", "change", "modify", "update the plan", "add more", "remove",+ "instead", "rather than", "should also", "missing", "redo",+)++_IMPLEMENT_PATTERNS = (+ re.compile(r"按.{0,6}计划.{0,4}(实现|执行|做)"),+ re.compile(r"按.{0,6}方案.{0,4}(实现|执行|做)"),+ re.compile(r"开始(实现|执行|写代码|干活|做)"),+ re.compile(r"(可以|去|动手|直接)(实现|执行|做|开工)"),+ re.compile(r"^(实现|执行|开工)吧?[。.!]?$"),+ re.compile(r"就这样(做|执行|实现)"),+ re.compile(r"implement(\s+the)?\s+plan", re.IGNORECASE),+ re.compile(r"(start|go ahead|proceed)\s+(with\s+)?(implement|implementation|execution|building)", re.IGNORECASE),+ re.compile(r"^implement(\s+it)?[.!?]?$", re.IGNORECASE),+ re.compile(r"^(execute|build|ship)(\s+it|\s+the\s+plan)?[.!?]?$", re.IGNORECASE),+ re.compile(r"let'?s\s+(implement|build|execute)", re.IGNORECASE),+)+++def classify_plan_user_intent(user_message: str) -> PlanUserIntent:+ """Classify the user's response after ``exit_plan_mode``.++ Returns:+ ``"approve"`` when the user wants to exit plan mode and implement.+ ``"revise"`` when the user wants to change the plan only.+ """+ text = user_message.strip()+ if not text:+ return "revise"++ if text.startswith(APPROVE_CMD_PREFIX):+ return "approve"+ if text.startswith(REJECT_CMD_PREFIX):+ return "revise"++ lower = text.lower()++ for prefix in _REJECT_PREFIXES_CN:+ if text.startswith(prefix):+ return "revise"+ for prefix in _REJECT_PREFIXES_EN:+ if lower.startswith(prefix):+ return "revise"++ if _has_revision_intent(text, lower):+ return "revise"++ if _has_implementation_intent(text):+ return "approve"++ if _is_pure_approval(lower):+ return "approve"++ return "revise"+++def is_user_approving(user_message: str) -> bool:+ """Return ``True`` when the user message approves the plan."""+ return classify_plan_user_intent(user_message) == "approve"+++def is_direct_plan_implement_request(user_message: str) -> bool:+ """True when the user clearly asks to implement an existing plan via chat.++ Stronger than bare ``好``/``可以`` — used when there is no pending+ ``exit_plan_mode`` gate but a plan file already exists in plan mode.+ """+ text = user_message.strip()+ if not text:+ return False+ if text.startswith(APPROVE_CMD_PREFIX):+ return True+ if classify_plan_user_intent(text) != "approve":+ return False+ return _has_implementation_intent(text)+++def _has_revision_intent(text: str, lower: str) -> bool:+ for kw in _REVISION_SUBSTRINGS:+ if kw in text or kw in lower:+ return True+ return False+++def _has_implementation_intent(text: str) -> bool:+ for pattern in _IMPLEMENT_PATTERNS:+ if pattern.search(text):+ return True+ return False+++def _is_pure_approval(lower: str) -> bool:+ for kw in _APPROVAL_KEYWORDS_CN | _APPROVAL_KEYWORDS_EN:+ if lower == kw or lower.startswith(kw + " ") or lower.startswith(kw + "。"):+ return True++ if len(lower) <= 12:+ for prefix in ("好", "可以", "行", "ok", "yes", "approve", "go", "yep", "proceed"):+ if lower.startswith(prefix):+ return True++ return False+++def extract_feedback_from_reject(user_message: str) -> str:+ """Extract feedback text from a rejection command.++ Handles formats like: ``plan.reject <feedback>`` or plain feedback text.++ Args:+ user_message: The full user message.++ Returns:+ The extracted feedback text, or the full message if no prefix found.+ """+ text = user_message.strip()+ if text.startswith(REJECT_CMD_PREFIX):+ rest = text[len(REJECT_CMD_PREFIX):].strip()+ return rest if rest else text+ return text+++__all__ = [+ "PLAN_APPROVAL_EVENT_TYPE",+ "PLAN_MODE_EXITED_EVENT_TYPE",+ "APPROVE_CMD_PREFIX",+ "REJECT_CMD_PREFIX",+ "PLAN_USER_APPROVED_FLAG",+ "PlanUserIntent",+ "PENDING_APPROVAL_MARKER",+ "APPROVED_NOTIFICATION",+ "FEEDBACK_INJECTION",+ "classify_plan_user_intent",+ "is_direct_plan_implement_request",+ "is_user_approving",+ "extract_feedback_from_reject",+]diff --git a/jiuwenswarm/agents/harness/code/rails/__init__.py b/jiuwenswarm/agents/harness/code/rails/__init__.pyindex 70103ef902..c549246103 100644--- a/jiuwenswarm/agents/harness/code/rails/__init__.py+++ b/jiuwenswarm/agents/harness/code/rails/__init__.py@@ -3,7 +3,11 @@from jiuwenswarm.agents.harness.code.rails.code_task_planning_rail import (CodeTaskPlanningRail,)+from jiuwenswarm.agents.harness.code.rails.code_plan_approval_rail import (+ PlanApprovalRail,+)__all__ = ["CodeTaskPlanningRail",+ "PlanApprovalRail",]diff --git a/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py b/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.pynew file mode 100644index 0000000000..096ab2048c--- /dev/null+++ b/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py@@ -0,0 +1,151 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""CodeAgentModeRail — defer plan-mode exit until the user approves in chat."""++from __future__ import annotations++import json+import re+from typing import TYPE_CHECKING, Any++from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.rails.agent_mode_rail import AgentModeRail++from jiuwenswarm.agents.harness.code.rails.code_plan_approval_rail import (+ PENDING_EXIT_RESULT_PREFIX,+)++if TYPE_CHECKING:+ from openjiuwen.harness.deep_agent import DeepAgent++_EMPTY_EXIT_MSG = {+ "cn": "规划模式已结束。你现在可以结束本轮。\n计划文件:{plan_path}",+ "en": "Plan mode ended. You can now exit the turn.\nPlan file: {plan_path}",+}++_SWITCH_MODE_EXIT_PLAN_MSG = {+ "cn": (+ "[AgentModeRail] plan 模式下不能用 switch_mode 退出。"+ "请先调用 exit_plan_mode 提交计划,再在对话中回复「按计划实现」等批准执行;"+ "或使用 /mode code.normal 切换模式。"+ ),+ "en": (+ "[AgentModeRail] switch_mode cannot exit plan mode. "+ "Call exit_plan_mode, then approve in chat (e.g. implement the plan), "+ "or use /mode code.normal."+ ),+}++_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"|>>"+)+++def _plan_tool_language(language: str | None) -> str:+ return "cn" if language == "cn" else "en"+++class CodeAgentModeRail(AgentModeRail):+ """AgentModeRail variant for jiuwenswarm code mode.++ ``exit_plan_mode`` presents the plan for review but does **not** restore+ normal mode until the user approves via chat (handled by the server-side+ pending-approval gate).+ """++ def init(self, agent: "DeepAgent") -> None:+ """Register tools and patch ``exit_plan_mode`` to defer mode restore."""+ super().init(agent)+ self._patch_exit_plan_mode_tool()++ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:+ """Enforce plan-mode write blocks beyond the parent git-only guard."""+ agent = self._agent+ session = ctx.session+ plan_state = agent.load_state(session).plan_mode+ tool_name = ctx.inputs.tool_name++ if plan_state.mode == "plan" and tool_name == "switch_mode":+ target = self._parse_switch_mode_target(ctx)+ if target in {"normal", "auto"}:+ lang = "cn" if self._language_is_cn() else "en"+ self._reject_tool(ctx, _SWITCH_MODE_EXIT_PLAN_MSG[lang])+ return++ await super().before_tool_call(ctx)+ if ctx.extra.get("_skip_tool"):+ return++ if plan_state.mode != "plan":+ return+ if tool_name == "bash":+ command = self._extract_bash_command(ctx)+ if _NON_GIT_WRITE_RE.search(command):+ if self._language_is_cn():+ msg = f"[AgentModeRail] plan 模式下禁止写操作({command!r})。"+ else:+ msg = (+ f"[AgentModeRail] Write operations are blocked in plan mode "+ f"({command!r})."+ )+ self._reject_tool(ctx, msg)++ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:+ """Skip default exit handling while the plan awaits user approval."""+ if (+ ctx.inputs.tool_name == "exit_plan_mode"+ and not ctx.extra.get("_skip_tool")+ and ctx.inputs.tool_result is not None+ ):+ return+ await super().after_tool_call(ctx)++ def _patch_exit_plan_mode_tool(self) -> None:+ """Read plan for review without calling ``restore_mode_after_plan_exit``."""+ for tool in self._tools:+ if getattr(tool.card, "name", "") != "exit_plan_mode":+ continue++ language = _plan_tool_language(getattr(tool, "_language", "cn"))++ async def patched_invoke(inputs, _tool=tool, _lang=language, **kwargs):+ agent = _tool._agent_ref # pylint: disable=protected-access+ session = kwargs.get("session")+ plan_path = agent.get_plan_file_path(session)+ plan_text = ""+ if plan_path and plan_path.exists():+ plan_text = plan_path.read_text(encoding="utf-8")+ plan_path_str = str(plan_path) if plan_path else ""+ if not plan_text.strip():+ return _EMPTY_EXIT_MSG[_lang].format(plan_path=plan_path_str)+ prefix = PENDING_EXIT_RESULT_PREFIX[_lang].format(+ plan_path=plan_path_str,+ )+ return prefix + plan_text++ tool.invoke = patched_invoke+ break++ @staticmethod+ def _parse_switch_mode_target(ctx: AgentCallbackContext) -> str:+ raw: Any = None+ tool_call = getattr(ctx.inputs, "tool_call", None)+ if tool_call is not None:+ raw = getattr(tool_call, "arguments", None)+ if raw is None:+ raw = getattr(ctx.inputs, "tool_args", None)+ args: dict[str, Any] = {}+ if isinstance(raw, dict):+ args = raw+ elif isinstance(raw, str):+ try:+ parsed = json.loads(raw)+ if isinstance(parsed, dict):+ args = parsed+ except (TypeError, ValueError):+ pass+ return str(args.get("mode") or args.get("target_mode") or "").strip()diff --git a/jiuwenswarm/agents/harness/code/rails/code_confirm_interrupt_rail.py b/jiuwenswarm/agents/harness/code/rails/code_confirm_interrupt_rail.pynew file mode 100644index 0000000000..0ae3010bc3--- /dev/null+++ b/jiuwenswarm/agents/harness/code/rails/code_confirm_interrupt_rail.py@@ -0,0 +1,142 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""CodeConfirmInterruptRail — user-visible confirmation for sensitive control tools."""++from __future__ import annotations++import json+from typing import Any, Optional++from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall+from openjiuwen.core.single_agent.interrupt.response import InterruptRequest+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.rails.interrupt.confirm_rail import ConfirmInterruptRail++_SWITCH_MODE_EXIT_PLAN_MSG_CN = (+ "[AgentModeRail] plan 模式下不能用 switch_mode 退出。"+ "请先调用 exit_plan_mode 提交计划,再在对话中回复「按计划实现」等批准执行;"+ "或使用 /mode code.normal 切换模式。"+)++_SWITCH_MODE_EXIT_PLAN_MSG_EN = (+ "[AgentModeRail] switch_mode cannot exit plan mode. "+ "Call exit_plan_mode, then approve in chat (e.g. implement the plan), "+ "or use /mode code.normal."+)+++def _format_args_preview(tool_args: dict[str, Any]) -> str:+ if not tool_args:+ return ""+ try:+ return json.dumps(tool_args, ensure_ascii=False, indent=2)[:800]+ except (TypeError, ValueError):+ return str(tool_args)[:800]+++def build_confirm_interrupt_message(tool_name: str, tool_args: dict[str, Any] | None = None) -> str:+ """Build a descriptive confirmation prompt for the frontend."""+ args = tool_args or {}+ if tool_name == "switch_mode":+ target_mode = str(args.get("mode") or args.get("target_mode") or "").strip()+ if target_mode == "plan":+ action = "enter plan mode (read-only planning phase)"+ elif target_mode in {"normal", "auto"}:+ action = "exit plan mode and return to execution"+ else:+ action = f"switch agent mode to `{target_mode or 'unknown'}`"+ lines = [+ f"**Agent wants to {action}**",+ "",+ "Tool: `switch_mode`",+ ]+ if target_mode:+ lines.append(f"Target mode: `{target_mode}`")+ lines.append("")+ lines.append("Approve to let the agent continue with this mode change.")+ return "\n".join(lines)++ lines = [+ f"**Tool `{tool_name}` requires your approval**",+ "",+ "The agent is waiting for you to allow or reject this action.",+ ]+ preview = _format_args_preview(args)+ if preview and preview != "{}":+ lines.extend(["", "Arguments:", f"```json\n{preview}\n```"])+ return "\n".join(lines)+++class CodeConfirmInterruptRail(ConfirmInterruptRail):+ """ConfirmInterruptRail with tool-specific confirmation copy for code mode."""++ async def resolve_interrupt(+ self,+ ctx: AgentCallbackContext,+ tool_call: Optional[ToolCall],+ user_input: Optional[Any],+ auto_confirm_config: Optional[dict] = None,+ ):+ rejected = self._reject_switch_mode_exit_in_plan(ctx, tool_call)+ if rejected is not None:+ return rejected++ if user_input is None and tool_call is not None:+ tool_name = tool_call.name or ""+ tool_args = self._parse_tool_args(tool_call)+ message = build_confirm_interrupt_message(tool_name, tool_args)+ return self.interrupt(+ InterruptRequest(+ message=message,+ payload_schema=self.request.payload_schema,+ auto_confirm_key=self._get_auto_confirm_key(tool_call),+ )+ )+ return await super().resolve_interrupt(+ ctx, tool_call, user_input, auto_confirm_config+ )++ def _reject_switch_mode_exit_in_plan(+ self,+ ctx: AgentCallbackContext,+ tool_call: Optional[ToolCall],+ ):+ if tool_call is None or (tool_call.name or "") != "switch_mode":+ return None+ agent = ctx.agent+ if agent is None:+ return None+ plan_state = agent.load_state(ctx.session).plan_mode+ if plan_state.mode != "plan":+ return None+ args = self._parse_tool_args(tool_call)+ target = str(args.get("mode") or args.get("target_mode") or "").strip()+ if target not in {"normal", "auto"}:+ return None+ language = "cn"+ builder = getattr(agent, "system_prompt_builder", None)+ if builder is not None and getattr(builder, "language", "cn") == "en":+ language = "en"+ msg = _SWITCH_MODE_EXIT_PLAN_MSG_EN if language == "en" else _SWITCH_MODE_EXIT_PLAN_MSG_CN+ return self.reject(tool_result={"error": msg})++ @staticmethod+ def _parse_tool_args(tool_call: ToolCall) -> dict[str, Any]:+ raw = getattr(tool_call, "arguments", None)+ if raw is None:+ return {}+ if isinstance(raw, dict):+ return raw+ if isinstance(raw, str):+ try:+ parsed = json.loads(raw)+ except (TypeError, ValueError):+ return {}+ return parsed if isinstance(parsed, dict) else {}+ return {}+++__all__ = [+ "CodeConfirmInterruptRail",+ "build_confirm_interrupt_message",+]diff --git a/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.py b/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.pynew file mode 100644index 0000000000..8e1b86123f--- /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.++Aligns with Claude Code: ``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/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.pyindex bbcba0cebf..cf807b7890 100644--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py@@ -8,6 +8,7 @@ and building permission rails.from __future__ import annotationsimport json+import refrom typing import Anyfrom jiuwenswarm.common.utils import logger@@ -345,12 +346,79 @@ def _build_plain_ask_user_question(value_obj: Any) -> dict | None:}+_PERMISSION_INTERRUPT_MARKERS = (+ "需要授权才能执行",+ "requires permission",+ "Permission denied",+ "安全风险评估",+)+_CONFIRM_INTERRUPT_TOOLS = frozenset({"switch_mode", "exit_plan_mode"})+++def _read_interrupt_fields(value_obj: Any) -> tuple[str, str, dict | None]:+ """Return ``(tool_name, message, tool_args)`` from an interrupt value object."""+ tool_name = ""+ message = ""+ tool_args: dict | None = None++ if hasattr(value_obj, "tool_name"):+ tool_name = str(getattr(value_obj, "tool_name", "") or "").strip()+ if hasattr(value_obj, "message"):+ message = str(getattr(value_obj, "message", "") or "").strip()+ if not message and hasattr(value_obj, "question"):+ message = str(getattr(value_obj, "question", "") or "").strip()+ tool_args = _normalize_tool_args(getattr(value_obj, "tool_args", None))++ if isinstance(value_obj, dict):+ tool_name = tool_name or str(value_obj.get("tool_name", "") or "").strip()+ message = message or str(+ value_obj.get("message", "") or value_obj.get("question", "") or ""+ ).strip()+ if tool_args is None:+ tool_args = _normalize_tool_args(value_obj.get("tool_args"))++ return tool_name, message, tool_args+++def _is_permission_interrupt_message(message: str, tool_name: str) -> bool:+ """Heuristic: PermissionInterruptRail copy vs ConfirmInterruptRail copy."""+ normalized = message.strip()+ if any(marker in normalized for marker in _PERMISSION_INTERRUPT_MARKERS):+ return True+ if normalized.startswith("**工具 `") or normalized.startswith("**Tool `"):+ return True+ if tool_name and tool_name not in _CONFIRM_INTERRUPT_TOOLS:+ return True+ if normalized in {"", "Please approve or reject?"}:+ return tool_name not in _CONFIRM_INTERRUPT_TOOLS+ return False+++def _parse_plan_metadata_from_message(message: str) -> tuple[str, str]:+ plan_path = ""+ plan_slug = ""+ path_match = re.search(r"\*\*Plan file:\*\* `([^`]+)`", message)+ if path_match:+ plan_path = path_match.group(1).strip()+ slug_match = re.search(r"\*\*Plan id:\*\* `([^`]+)`", message)+ if slug_match:+ plan_slug = slug_match.group(1).strip()+ return plan_path, plan_slug+++def _resolve_interrupt_source(tool_name: str, message: str) -> str:+ if _is_permission_interrupt_message(message, tool_name):+ return "permission_interrupt"+ return "confirm_interrupt"++def convert_interactions_to_ask_user_question(state_outputs: list) -> dict | None:"""Convert __interaction__ list to frontend chat.ask_user_question format.AskUserRail 中断: value 有 questions 字段,或 ask_user 的 plain query→ source="ask_user_interrupt"PermissionRail 中断: value 无 questions 字段 → source="permission_interrupt"+ ConfirmInterruptRail 中断: 控制类工具确认 → source="confirm_interrupt"state_outputs 中的元素可能是:- InteractionOutput 对象 (有 id, value 属性, value 是 ToolCallInterruptRequest)@@ -399,7 +467,7 @@ def convert_interactions_to_ask_user_question(state_outputs: list) -> dict | Non}for interaction in interactions:- request_id, _value_obj = _extract_interaction_parts(interaction)+ request_id, value_obj = _extract_interaction_parts(interaction)if not request_id:continue@@ -407,12 +475,22 @@ def convert_interactions_to_ask_user_question(state_outputs: list) -> dict | Nonif not question_data:continue- return {+ tool_name, message, _tool_args = _read_interrupt_fields(value_obj)+ source = _resolve_interrupt_source(tool_name, message)++ payload = {"event_type": "chat.ask_user_question","request_id": request_id,"questions": [question_data],- "source": "permission_interrupt",+ "source": source,}+ plan_path = str(question_data.get("plan_path") or "").strip()+ plan_slug = str(question_data.get("plan_slug") or "").strip()+ if plan_path:+ payload["plan_path"] = plan_path+ if plan_slug:+ payload["plan_slug"] = plan_slug+ return payloadreturn None@@ -513,26 +591,36 @@ def extract_question_from_interaction(payload: Any) -> dict | None:if payload is None:return None- tool_name = ""- message = ""-- if hasattr(payload, 'value'):+ if hasattr(payload, "value"):value_obj = payload.value- message = getattr(value_obj, 'message', '') or getattr(value_obj, 'question', '')- tool_name = getattr(value_obj, 'tool_name', '')elif isinstance(payload, dict):- value_obj = payload.get('value', {})- if isinstance(value_obj, dict):- message = value_obj.get('message', '') or value_obj.get('question', '')- tool_name = value_obj.get('tool_name', '')- else:- message = payload.get('message', '') or payload.get('question', '')+ value_obj = payload.get("value", payload)else:return None+ tool_name, message, tool_args = _read_interrupt_fields(value_obj)+ source = _resolve_interrupt_source(tool_name, message)++ generic_confirm_message = message.strip() in {"", "Please approve or reject?"}+ needs_message = not message or (source == "confirm_interrupt" and generic_confirm_message)+ if tool_name and needs_message:+ if source == "confirm_interrupt":+ from jiuwenswarm.agents.harness.code.rails.code_confirm_interrupt_rail import (+ build_confirm_interrupt_message,+ )++ message = build_confirm_interrupt_message(tool_name, tool_args or {})+ elif not message:+ message = f"工具 `{tool_name}` 需要授权才能执行"++ if source == "confirm_interrupt":+ header = f"操作确认: {tool_name}" if tool_name else "操作确认"+ else:+ header = f"权限审批: {tool_name}" if tool_name else "权限审批"+return {- "question": message or f"工具 `{tool_name}` 需要授权才能执行",- "header": f"权限审批: {tool_name}" if tool_name else "权限审批",+ "question": message,+ "header": header,"options": [{"label": "本次允许", "description": "仅本次授权执行"},{"label": "总是允许", "description": "记住该规则,以后自动放行"},diff --git a/jiuwenswarm/agents/harness/common/tools/command_tools.py b/jiuwenswarm/agents/harness/common/tools/command_tools.pyindex e96d3d4e99..7b6bc11bf7 100644--- a/jiuwenswarm/agents/harness/common/tools/command_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/command_tools.py@@ -5,6 +5,7 @@from __future__ import annotationsimport asyncio+import contextlibimport jsonimport localeimport os@@ -578,6 +579,13 @@ def _run_command_sync(finally:if sid:unregister_shell_process(sid, proc)+ # Close pipe FDs that communicate() would have closed on the+ # normal path. Without this, exception paths (cancel / timeout)+ # leak FDs and trigger ResourceWarning.+ for stream in (proc.stdout, proc.stdin, proc.stderr):+ if stream is not None:+ with contextlib.suppress(Exception):+ stream.close()return subprocess.CompletedProcess(args=plan,returncode=proc.returncode if proc.returncode is not None else -1,diff --git a/jiuwenswarm/agents/swarm/providers/code_rails.py b/jiuwenswarm/agents/swarm/providers/code_rails.pyindex 6692dd8e0a..b46f6e52d5 100644--- a/jiuwenswarm/agents/swarm/providers/code_rails.py+++ b/jiuwenswarm/agents/swarm/providers/code_rails.py@@ -258,11 +258,25 @@ def build_code_coding_memory(params: dict[str, Any], ctx: SwarmBuildContext) ->def build_code_agent_mode(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:"""Build the code plan-mode rail (Claude-Code-aligned AgentModeRail)."""try:- from jiuwenswarm.server.runtime.agent_adapter.interface_code import (- JiuwenAgentModeRail,+ from jiuwenswarm.agents.harness.code.rails.code_agent_mode_rail import (+ CodeAgentModeRail,)- return JiuwenAgentModeRail()+ return CodeAgentModeRail(+ allowed_tools=[+ "enter_plan_mode",+ "exit_plan_mode",+ "ask_user",+ "task_tool",+ "read_file",+ "grep",+ "list_files",+ "glob",+ "bash",+ "write_file",+ "edit_file",+ ],+ )except Exception as exc:logger.warning("[swarm.code_agent_mode] create failed: %s", exc)return Nonediff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 9b19c7c9cb..e081b24f93 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -1241,8 +1241,10 @@ export class CliPiAppState {if (source === "permission_interrupt" ||+ source === "confirm_interrupt" ||source === "ask_user_interrupt") {+ const resumeMode = this.pendingQuestion.resumeMode ?? this.mode;this.sendEventOnly("chat.send",{@@ -1250,10 +1252,11 @@ export class CliPiAppState {request_id: this.pendingQuestion.requestId,answers,source,- mode: this.mode,+ mode: resumeMode,},true,);+ this.streamingState = StreamingState.Responding;} else {const params: Record<string, unknown> = {request_id: this.pendingQuestion.requestId,@@ -1269,7 +1272,9 @@ export class CliPiAppState {);}this.pendingQuestion = null;- this.streamingState = StreamingState.Idle;+ if (this.streamingState !== StreamingState.Responding) {+ this.streamingState = StreamingState.Idle;+ }this.streamingStateBeforeQuestion = null;this.emitChange();}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.tsindex 596e4fb464..818cea5a87 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts@@ -33,6 +33,10 @@ type PreferredLanguage = "zh" | "en";export interface PendingQuestion {requestId: string;source?: string;+ /** Mode active when the interrupt was raised; used when resuming the tool call. */+ resumeMode?: ClientMode;+ planPath?: string;+ planSlug?: string;evolutionMeta?: Record<string, unknown>;questions: PendingQuestionItem[];}@@ -42,6 +46,8 @@ export interface PendingQuestionItem {question: string;options: PendingQuestionOption[];multiSelect?: boolean;+ planPath?: string;+ planSlug?: string;}export interface PendingQuestionOption {@@ -164,14 +170,7 @@ function _handleAgentModeToolResult(if (toolName !== "switch_mode" && toolName !== "exit_plan_mode") return;if (toolName === "exit_plan_mode") {- const existingMode = delegate.getMode();- if (existingMode === "code.plan") {- delegate.setMode("code.normal");- } else if (existingMode === "team.plan") {- delegate.setMode("team");- } else if (existingMode === "agent.plan") {- delegate.setMode("agent.fast");- }+ // Plan exit is deferred until the user approves in chat; keep UI plan mode.return;}@@ -228,7 +227,6 @@ function _getToolResultPayload(payload: Record<string, unknown>): Record<string,}function normalizeVisibleMode(mode: ClientMode): ClientMode {- if (mode === "code.plan") return "code.normal";if (mode === "team.plan") return "team";return mode;}@@ -428,6 +426,8 @@ function normalizePendingQuestion(payload: Record<string, unknown>): PendingQues.map((item) => ({header: typeof item.header === "string" ? item.header : "Question",question: typeof item.question === "string" ? item.question : "",+ planPath: typeof item.plan_path === "string" ? item.plan_path : undefined,+ planSlug: typeof item.plan_slug === "string" ? item.plan_slug : undefined,options: Array.isArray(item.options)? item.options.filter((option): option is Record<string, unknown> =>@@ -1162,6 +1162,18 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFramreturn true;}+ case "plan.approval_required":+ // Text-only plan approval: plan + marker already appear in the chat stream.+ return connectionChanged;++ case "plan.mode_exited": {+ const mode = typeof payload.mode === "string" ? payload.mode : "code.normal";+ if (mode === "code.normal" && delegate.getMode().startsWith("code.")) {+ delegate.setMode("code.normal");+ }+ return true;+ }+case "chat.ask_user_question": {const requestId = typeof payload.request_id === "string" ? payload.request_id : "";const questions = normalizePendingQuestion(payload);@@ -1174,9 +1186,21 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram: payload._evolution_meta && typeof payload._evolution_meta === "object"? (payload._evolution_meta as Record<string, unknown>): undefined;+ const source = typeof payload.source === "string" ? payload.source : undefined;+ const planPath =+ typeof payload.plan_path === "string" && payload.plan_path.trim()+ ? payload.plan_path.trim()+ : questions[0]?.planPath;+ const planSlug =+ typeof payload.plan_slug === "string" && payload.plan_slug.trim()+ ? payload.plan_slug.trim()+ : questions[0]?.planSlug;delegate.setPendingQuestion({requestId,- source: typeof payload.source === "string" ? payload.source : undefined,+ source,+ resumeMode: delegate.getMode(),+ planPath,+ planSlug,evolutionMeta,questions,});diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex 655170fe3f..8f2b07b332 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -78,9 +78,37 @@ const ENABLE_MOUSE_TRACKING = "\x1b[?1000h\x1b[?1006h";const DISABLE_MOUSE_TRACKING = "\x1b[?1000l\x1b[?1006l";const TRANSCRIPT_WHEEL_SCROLL_LINES = 3;const PERMISSION_TOOL_RE = /工具\s+`([^`]+)`\s+需要授权/;+const CONFIRM_TOOL_RE = /(?:Tool|工具)\s*:\s*`([^`]+)`/i;+const CONFIRM_ACTION_RE = /\*\*(?:Agent wants to|Tool `[^`]+` requires your approval)([^*]*)\*\*/i;const PERMISSION_RISK_RE = /安全风险评估:\**\s*([^\s*]+)?\s*\**([^*\n]+?风险)\**/m;const PERMISSION_QUOTE_RE = /^>\s*(.+)$/gm;const PERMISSION_JSON_BLOCK_RE = /```json\s*([\s\S]*?)\s*```/i;+const SGR_MOUSE_RE = /^\x1b\[<(\d+);(\d+);(\d+)([mM])$/;++interface QuestionOptionRowHit {+ row: number;+ value: string;+}++function stripAnsi(text: string): string {+ return text.replace(/\x1b\[[0-9;]*m/g, "");+}++function parseSgrMouseRelease(+ data: string,+): { button: number; col: number; row: number } | null {+ const match = data.match(SGR_MOUSE_RE);+ if (!match || match[4] !== "m") {+ return null;+ }+ const button = Number.parseInt(match[1], 10) & 3;+ const col = Number.parseInt(match[2], 10);+ const row = Number.parseInt(match[3], 10);+ if (!Number.isFinite(col) || !Number.isFinite(row)) {+ return null;+ }+ return { button, col, row };+}function wrapText(text: string, maxWidth: number): string[] {if (maxWidth < 1) return [text];@@ -298,11 +326,21 @@ function resolveFdBinary(): string | null {}function isPermissionRequest(source: string | undefined, questionText: string): boolean {- return source === "permission_interrupt" || PERMISSION_TOOL_RE.test(questionText);+ return (+ source === "permission_interrupt" ||+ source === "confirm_interrupt" ||+ PERMISSION_TOOL_RE.test(questionText) ||+ CONFIRM_TOOL_RE.test(questionText) ||+ CONFIRM_ACTION_RE.test(questionText) ||+ /\*\*Tool `/i.test(questionText)+ );}function parsePermissionSummary(questionText: string): PermissionSummary {- const tool = PERMISSION_TOOL_RE.exec(questionText)?.[1]?.trim();+ const tool =+ PERMISSION_TOOL_RE.exec(questionText)?.[1]?.trim() ||+ CONFIRM_TOOL_RE.exec(questionText)?.[1]?.trim();+ const confirmAction = CONFIRM_ACTION_RE.exec(questionText)?.[1]?.trim();const riskMatch = PERMISSION_RISK_RE.exec(questionText);const risk = riskMatch? `${(riskMatch[1] ?? "").trim()} ${riskMatch[2].trim()}`.trim()@@ -334,7 +372,7 @@ function parsePermissionSummary(questionText: string): PermissionSummary {risk,reason,command,- description,+ description: description ?? confirmAction,};}@@ -657,6 +695,7 @@ export class AppScreen implements Component, Focusable {private pendingQuestionAnswers = new Map<number, string>();private questionList: SelectList | null = null;private questionDetailsMap: Map<string, string[]> | null = null;+ private questionOptionRows: QuestionOptionRowHit[] = [];private otherInputMode = false;private ctrlCPendingForQuestion = false;private ctrlCPendingForQuestionTimer: ReturnType<typeof setTimeout> | null = null;@@ -1009,6 +1048,11 @@ export class AppScreen implements Component, Focusable {return;}+ if (pendingQuestion && this.handlePendingQuestionInput(data, snapshot)) {+ this.tui.requestRender();+ return;+ }+const handled = handleAppScreenKeyInput(data, {interruptTask: () => this.interruptTask(),exitApp: () => this.exit(),@@ -1234,25 +1278,6 @@ export class AppScreen implements Component, Focusable {}}- if (snapshot.pendingQuestion && this.questionList !== null) {- this.questionList.handleInput(data);- this.tui.requestRender();- return;- }-- if (snapshot.pendingQuestion && this.otherInputMode) {- if (matchesKey(data, "escape")) {- this.otherInputMode = false;- this.editor.setText("");- this.syncQuestionList(this.state.getSnapshot());- this.tui.requestRender();- return;- }- this.editor.handleInput(data);- this.tui.requestRender();- return;- }-// Detect pasted file paths (drag-and-drop) in the terminal// When files are dragged in, they arrive as a pasted string.// Windows/PowerShell may not send bracketed paste markers,@@ -1333,7 +1358,7 @@ export class AppScreen implements Component, Focusable {}this.lastTranscriptLineCount = transcriptLineCount;this.lastTranscriptLineWidth = width;- return buildAppScreenLines(snapshot, {+ const screenLines = buildAppScreenLines(snapshot, {width,height: this.tui.terminal.rows,questionLines,@@ -1361,6 +1386,8 @@ export class AppScreen implements Component, Focusable {? Date.now() - this.runningStartedAtMs: undefined,});+ this.updateQuestionOptionRows(screenLines, snapshot);+ return screenLines;}private async handleSubmit(raw: string): Promise<void> {@@ -1391,40 +1418,55 @@ export class AppScreen implements Component, Focusable {const snapshot = this.state.getSnapshot();if (snapshot.pendingQuestion) {- if (this.questionList === null) {- if (this.otherInputMode) {- this.pendingQuestionAnswers.set(this.activeQuestionIndex, text);- this.otherInputMode = false;-- const pendingQuestion = snapshot.pendingQuestion;- if (this.activeQuestionIndex < pendingQuestion.questions.length - 1) {- this.activeQuestionIndex += 1;- this.syncQuestionList(this.state.getSnapshot());- this.editor.setText("");- this.tui.requestRender();- return;- }+ if (this.questionList !== null) {+ const selected = this.questionList.getSelectedItem();+ if (selected) {+ this.handleQuestionSelection(selected.value);+ }+ this.editor.setText("");+ return;+ }+ if (this.otherInputMode) {+ const pendingQuestion = snapshot.pendingQuestion;+ const pickedLabel = this.pendingQuestionAnswers.get(this.activeQuestionIndex) ?? "";+ this.otherInputMode = false;+ this.syncEditorSubmitState(this.state.getSnapshot());- const answers = pendingQuestion.questions.map((question, index) => {- const answerValue = this.pendingQuestionAnswers.get(index) ?? question.options[0]?.label ?? "";- return {- question: question.question,- selected_options: [answerValue],- };- });- this.state.submitQuestionAnswers(answers);+ if (this.activeQuestionIndex < pendingQuestion.questions.length - 1) {+ this.pendingQuestionAnswers.set(this.activeQuestionIndex, pickedLabel || text);+ this.activeQuestionIndex += 1;+ this.syncQuestionList(this.state.getSnapshot());this.editor.setText("");+ this.tui.requestRender();return;}- const question =- snapshot.pendingQuestion.questions[this.activeQuestionIndex]?.question ?? "";- if (question) {- this.state.submitQuestionAnswers([- { selected_options: [text], custom_input: text },- ]);- } else {- this.state.answerQuestion(text);- }++ const answers = pendingQuestion.questions.map((question, index) => {+ const label = this.pendingQuestionAnswers.get(index) ?? "";+ if (label === "Other") {+ return {+ question: question.question,+ selected_options: [label],+ custom_input: index === this.activeQuestionIndex ? text : undefined,+ };+ }+ return {+ question: question.question,+ selected_options: [label || text],+ };+ });+ this.state.submitQuestionAnswers(answers);+ this.editor.setText("");+ return;+ }+ const question =+ snapshot.pendingQuestion.questions[this.activeQuestionIndex]?.question ?? "";+ if (question) {+ this.state.submitQuestionAnswers([+ { selected_options: [text], custom_input: text },+ ]);+ } else {+ this.state.answerQuestion(text);}this.editor.setText("");return;@@ -1700,6 +1742,7 @@ export class AppScreen implements Component, Focusable {this.draftBeforeQuestion = "";this.clearCtrlCPendingForQuestion();}+ this.syncEditorSubmitState(snapshot);this.syncTeamPanelSelection(snapshot);this.refreshSwarmWorkflowsView();this.syncAnimationLoop(snapshot);@@ -4250,7 +4293,14 @@ export class AppScreen implements Component, Focusable {if (permissionRequest) {const summary = parsePermissionSummary(question.question);- const title = progress ? `Permission ${this.activeQuestionIndex + 1}/${total}` : "Permission";+ const title =+ pendingQuestion.source === "confirm_interrupt"+ ? progress+ ? `Confirm ${this.activeQuestionIndex + 1}/${total}`+ : "Confirm action"+ : progress+ ? `Permission ${this.activeQuestionIndex + 1}/${total}`+ : "Permission";lines.push(...renderPermissionBlock(width, summary, title));} else if (this.otherInputMode) {lines.push(@@ -4315,8 +4365,8 @@ export class AppScreen implements Component, Focusable {padToWidth(palette.text.dim(permissionRequest- ? "↑/↓ review · Enter confirm · Esc reject"- : "↑/↓ choose · Enter confirm · Esc reject",+ ? "↑/↓ review · Enter/click confirm · Esc reject"+ : "↑/↓ choose · Enter/click confirm · Esc reject",),width,),@@ -4328,6 +4378,82 @@ export class AppScreen implements Component, Focusable {return lines;}+ private handlePendingQuestionInput(+ data: string,+ snapshot: ReturnType<CliPiAppState["getSnapshot"]>,+ ): boolean {+ if (!snapshot.pendingQuestion) {+ return false;+ }++ const mouse = parseSgrMouseRelease(data);+ if (mouse?.button === 0 && this.questionList !== null) {+ const hit = this.questionOptionRows.find((entry) => entry.row === mouse.row);+ if (hit) {+ this.handleQuestionSelection(hit.value);+ return true;+ }+ }++ if (this.questionList !== null) {+ this.questionList.handleInput(data);+ return true;+ }++ if (this.otherInputMode) {+ if (matchesKey(data, "escape")) {+ this.otherInputMode = false;+ this.editor.setText("");+ this.syncQuestionList(this.state.getSnapshot());+ this.syncEditorSubmitState(snapshot);+ return true;+ }+ this.editor.handleInput(data);+ return true;+ }++ return false;+ }++ private updateQuestionOptionRows(+ screenLines: string[],+ snapshot: ReturnType<CliPiAppState["getSnapshot"]>,+ ): void {+ this.questionOptionRows = [];+ if (!snapshot.pendingQuestion || !this.questionList) {+ return;+ }++ const question =+ snapshot.pendingQuestion.questions[this.activeQuestionIndex] ??+ snapshot.pendingQuestion.questions[0];+ if (!question) {+ return;+ }++ for (const option of question.options) {+ const displayLabel = normalizePermissionOptionLabel(option.label);+ for (let i = 0; i < screenLines.length; i++) {+ const plain = stripAnsi(screenLines[i]);+ if (+ (plain.startsWith("→ ") || plain.startsWith(" ")) &&+ plain.includes(displayLabel)+ ) {+ this.questionOptionRows.push({ row: i + 1, value: option.label });+ break;+ }+ }+ }+ }++ private syncEditorSubmitState(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): void {+ const pendingQuestion = snapshot.pendingQuestion;+ this.editor.disableSubmit =+ !!pendingQuestion &&+ !this.otherInputMode &&+ (this.questionList !== null || (pendingQuestion.questions[0]?.options.length ?? 0) > 0);+ }+private syncQuestionList(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): void {const pendingQuestion = snapshot.pendingQuestion;if (!pendingQuestion) {@@ -4346,7 +4472,8 @@ export class AppScreen implements Component, Focusable {const items: SelectItem[] = question.options.map((option) => ({value: option.label,label:- pendingQuestion.source === "permission_interrupt"+ pendingQuestion.source === "permission_interrupt" ||+ pendingQuestion.source === "confirm_interrupt"? normalizePermissionOptionLabel(option.label): option.label,description: option.description,@@ -4361,7 +4488,11 @@ export class AppScreen implements Component, Focusable {}this.questionDetailsMap = detailsMap;- const maxVisible = pendingQuestion.source === "permission_interrupt" ? 4 : 6;+ const maxVisible =+ pendingQuestion.source === "permission_interrupt" ||+ pendingQuestion.source === "confirm_interrupt"+ ? 4+ : 6;// For questions with details sub-lines (e.g. rewind), use a narrower label column// so the description starts sooner and details can align beneath it.const layout = detailsMap.size > 0@@ -4410,7 +4541,9 @@ export class AppScreen implements Component, Focusable {if (label === "Other") {this.otherInputMode = true;+ this.pendingQuestionAnswers.set(this.activeQuestionIndex, label);this.questionList = null;+ this.syncEditorSubmitState(snapshot);this.tui.requestRender();return;}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 03097fa4b4..4a73512986 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -971,7 +971,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {? { evolution_meta: evolutionMeta }: {};// 如果是需要走 interrupt/interact 的确认,发送 chat.send- if (source === 'permission_interrupt') {+ if (source === 'permission_interrupt' || source === 'confirm_interrupt') {await request('chat.send', {session_id: sessionId,query: '',diff --git a/jiuwenswarm/common/e2a/constants.py b/jiuwenswarm/common/e2a/constants.pyindex bdc17064ed..572d8150ee 100644--- a/jiuwenswarm/common/e2a/constants.py+++ b/jiuwenswarm/common/e2a/constants.py@@ -24,6 +24,7 @@ E2A_RESPONSE_KIND_A2A_TASK = "a2a.task"E2A_RESPONSE_KIND_A2A_MESSAGE = "a2a.message"E2A_RESPONSE_KIND_A2A_STREAM_EVENT = "a2a.stream_event"E2A_RESPONSE_KIND_CRON = "cron"+E2A_RESPONSE_KIND_PLAN_APPROVAL_REQUIRED = "plan.approval_required"E2A_RESPONSE_KIND_EXT = "ext"# 运行时以本元组为准(与 docs §12 一致)@@ -39,6 +40,7 @@ E2A_RESPONSE_KINDS: tuple[str, ...] = (E2A_RESPONSE_KIND_A2A_MESSAGE,E2A_RESPONSE_KIND_A2A_STREAM_EVENT,E2A_RESPONSE_KIND_CRON,+ E2A_RESPONSE_KIND_PLAN_APPROVAL_REQUIRED,E2A_RESPONSE_KIND_EXT,)diff --git a/jiuwenswarm/common/e2a/gateway_normalize.py b/jiuwenswarm/common/e2a/gateway_normalize.pyindex eaba635251..1b2e6321ee 100644--- a/jiuwenswarm/common/e2a/gateway_normalize.py+++ b/jiuwenswarm/common/e2a/gateway_normalize.py@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Anyfrom jiuwenswarm.common.e2a.constants import (E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST,E2A_RESPONSE_KIND_CRON,+ E2A_RESPONSE_KIND_PLAN_APPROVAL_REQUIRED,E2A_RESPONSE_KIND_E2A_CHUNK,E2A_RESPONSE_KIND_E2A_COMPLETE,E2A_RESPONSE_KIND_E2A_ERROR,@@ -564,6 +565,20 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":is_complete=False,)+ if kind == E2A_RESPONSE_KIND_PLAN_APPROVAL_REQUIRED:+ return AgentResponseChunk(+ request_id=rid,+ channel_id=ch,+ payload={+ "event_type": "plan.approval_required",+ "plan_content": body.get("plan_content", ""),+ "plan_slug": body.get("plan_slug", ""),+ "plan_path": body.get("plan_path", ""),+ "session_id": e2a.session_id or "",+ },+ is_complete=True,+ )+raise ValueError(f"e2a_response_to_agent_chunk: unsupported response_kind={kind!r} is_final={e2a.is_final!r}")diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex 6c60f9e775..81b2b538e8 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -202,6 +202,7 @@ class EventType(Enum):CHAT_EVOLUTION_STATUS = "chat.evolution_status"CHAT_SUBTASK_UPDATE = "chat.subtask_update"CHAT_ASK_USER_QUESTION = "chat.ask_user_question"+ PLAN_APPROVAL_REQUIRED = "plan.approval_required"CHAT_SESSION_RESULT = "chat.session_result"TEAM_MEMBER = "team.member"TEAM_TASK = "team.task"diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex c14114d767..151d49c8ad 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -78,10 +78,41 @@ from jiuwenswarm.common.security.ws_origin import (is_origin_check_enabled,is_allowed_browser_origin,)+from jiuwenswarm.agents.harness.code.prompt.plan_approval import (+ APPROVE_CMD_PREFIX,+ APPROVED_NOTIFICATION,+ FEEDBACK_INJECTION,+ PLAN_MODE_EXITED_EVENT_TYPE,+ PLAN_USER_APPROVED_FLAG,+ REJECT_CMD_PREFIX,+ classify_plan_user_intent,+ extract_feedback_from_reject,+ is_direct_plan_implement_request,+)+from jiuwenswarm.common.schema.message import ReqMethodlogger = logging.getLogger(__name__)-# 流式处理心跳间隔:当 Agent 处理时间超过此阈值时,发送心跳 chunk 保持 WebSocket 连接活跃+# ── Plan approval state store (session_id → PlanApprovalState) ────────────+# Populated by PlanApprovalRail.after_tool_call after exit_plan_mode,+# consumed by _handle_pending_plan_approval before the next user turn.+_pending_plan_approvals: dict[str, dict] = {}++# Sessions where the user approved the plan on the latest chat turn.+# Consumed by _ensure_code_mode_state (session-scoped, not request.params) so+# concurrent skills.list RPCs cannot steal the approval flag.+_plan_approved_sessions: set[str] = set()++# Serialize plan-mode restore per session to avoid checkpoint races.+_session_mode_sync_locks: dict[str, asyncio.Lock] = {}++_CODE_MODE_SYNC_METHODS = frozenset({+ ReqMethod.CHAT_SEND,+ ReqMethod.CHAT_RESUME,+ ReqMethod.CHAT_ANSWER,+})++# ── 流式处理心跳间隔:当 Agent 处理时间超过此阈值时,发送心跳 chunk 保持 WebSocket 连接活跃 --# 避免 ping_timeout 导致连接关闭。默认 10 秒,小于服务端 ping_timeout=20s。_STREAM_HEARTBEAT_INTERVAL_SECONDS = 10.0_HISTORY_PAGE_SIZE = 20@@ -226,8 +257,6 @@ def _apply_resolved_mode_to_request(request: AgentRequest) -> tuple[str, str | Ndef _payload_to_request(data: dict[str, Any]) -> AgentRequest:"""将 Gateway 发送的 JSON 载荷解析为 AgentRequest."""- from jiuwenswarm.common.schema.message import ReqMethod-req_method = data.get("req_method")if req_method is not None and isinstance(req_method, str):req_method = ReqMethod(req_method)@@ -365,6 +394,202 @@ def _inject_plan_mode_activation_reminder(request: AgentRequest) -> None:)+# ── Plan approval helpers ──────────────────────────────────────────────+++def _store_pending_approval_from_agent(+ session_id: str,+ agent_instance: Any,+) -> None:+ """Pick up ``_plan_approval_state`` from the agent instance and store it.++ Called after ``agent.process_message`` / ``process_message_stream``+ completes. The rail sets ``agent_instance._plan_approval_state`` during+ ``after_tool_call``; we read it and store it in the session-level dict so+ the next request can inspect it.++ Args:+ session_id: The session identifier.+ agent_instance: The DeepAgent instance that just processed a request.+ """+ approval_state = getattr(agent_instance, "_plan_approval_state", None)+ if approval_state is None:+ return+ # Convert dataclass to dict if needed+ if hasattr(approval_state, "to_dict"):+ _pending_plan_approvals[session_id] = approval_state.to_dict()+ elif isinstance(approval_state, dict):+ _pending_plan_approvals[session_id] = approval_state+ else:+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_slug": getattr(approval_state, "plan_slug", ""),+ "plan_content": getattr(approval_state, "plan_content", ""),+ "plan_path": getattr(approval_state, "plan_path", ""),+ }+ try:+ delattr(agent_instance, "_plan_approval_state")+ except (AttributeError, TypeError):+ pass+ logger.info(+ "[_store_pending_approval] Session %s has pending plan approval",+ session_id,+ )+++def _is_resuming_tool_interrupt(request: AgentRequest) -> bool:+ """Return True when the request resumes a paused tool-call interrupt."""+ params = request.params if isinstance(request.params, dict) else {}+ request_id = str(params.get("request_id") or "").strip()+ answers = params.get("answers")+ if not request_id or not answers:+ return False+ source = str(params.get("source") or "").strip()+ return source in {+ "permission_interrupt",+ "confirm_interrupt",+ "ask_user_interrupt",+ }+++def _check_and_handle_pending_approval(+ request: AgentRequest,+ language: str = "cn",+) -> bool:+ """Check for pending plan approval and handle user's response.++ Must be called BEFORE agent processing (before _ensure_code_mode_state).+ If there is a pending approval and the user's message is a response to it,+ this function will:++ - **On approval**: Return ``True``, having already modified ``request``+ to inject the approval notification into the query (which will be+ visible to the model in normal mode).+ - **On feedback**: Return ``True``, having injected the feedback as a+ ``<system-reminder>`` and kept plan mode active.+ - **No pending approval**: Return ``False`` (no changes).++ Args:+ request: The incoming request (will be mutated if approval is handled).+ language: ``"cn"`` or ``"en"``.++ Returns:+ ``True`` if a pending approval was found and handled; ``False`` otherwise.+ """+ if _is_resuming_tool_interrupt(request):+ return False++ session_id = request.session_id+ if not session_id:+ return False++ pending = _pending_plan_approvals.pop(session_id, None)+ if not pending or not pending.get("pending"):+ return False++ # Read the user's response+ user_msg = ""+ if isinstance(request.params, dict):+ user_msg = (request.params.get("query") or "").strip()+ if not user_msg:+ # Empty user message — keep pending state+ _pending_plan_approvals[session_id] = pending+ return False++ plan_content = pending.get("plan_content", "")+ lang = "cn" if language == "cn" else "en"++ # Classify: approve → exit plan and implement; revise → stay in plan.+ is_reject_cmd = user_msg.startswith(REJECT_CMD_PREFIX)+ intent = classify_plan_user_intent(user_msg)++ if intent == "approve":+ # ── User approves the plan ──+ _plan_approved_sessions.add(session_id)+ if isinstance(request.params, dict):+ request.params["mode"] = "code.normal"+ request.params[PLAN_USER_APPROVED_FLAG] = True+ approval_text = APPROVED_NOTIFICATION[lang].format(plan_content=plan_content)+ if isinstance(request.params, dict):+ request.params["query"] = approval_text+ logger.info(+ "[_check_and_handle_pending_approval] User APPROVED plan for session %s",+ session_id,+ )+ else:+ # ── User wants plan revisions only ──+ feedback_msg = user_msg+ if is_reject_cmd:+ feedback_msg = extract_feedback_from_reject(user_msg)+ feedback_text = FEEDBACK_INJECTION[lang].format(user_message=feedback_msg)+ _plan_approved_sessions.discard(session_id)+ if isinstance(request.params, dict):+ request.params["mode"] = "code.plan"+ request.params.pop(PLAN_USER_APPROVED_FLAG, None)+ request.params["query"] = feedback_text+ logger.info(+ "[_check_and_handle_pending_approval] User REVISE plan for session %s",+ session_id,+ )++ return True+++async def _try_handle_direct_plan_implement(+ request: AgentRequest,+ agent: Any,+ language: str = "cn",+) -> bool:+ """Approve plan via chat when ``exit_plan_mode`` left no pending gate.++ Covers cases where the user says e.g. 「按计划实现」 after rejecting a+ misleading ``switch_mode`` confirm, without re-calling ``exit_plan_mode``.+ """+ if _is_resuming_tool_interrupt(request):+ return False++ session_id = request.session_id+ if not session_id or not isinstance(request.params, dict):+ return False+ if request.params.get(PLAN_USER_APPROVED_FLAG):+ return False+ user_msg = (request.params.get("query") or "").strip()+ if not is_direct_plan_implement_request(user_msg):+ return False++ 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)+ state = agent.get_instance().load_state(session)+ if state.plan_mode.mode != "plan":+ return False++ plan_path = agent.get_instance().get_plan_file_path(session)+ plan_content = ""+ if plan_path and plan_path.exists():+ plan_content = plan_path.read_text(encoding="utf-8")+ if not plan_content.strip():+ return False++ lang = "cn" if language == "cn" else "en"+ _plan_approved_sessions.add(session_id)+ request.params["mode"] = "code.normal"+ request.params[PLAN_USER_APPROVED_FLAG] = True+ request.params["query"] = APPROVED_NOTIFICATION[lang].format(+ plan_content=plan_content,+ )+ logger.info(+ "[_try_handle_direct_plan_implement] User APPROVED plan via chat "+ "for session %s",+ session_id,+ )+ return True++class AgentWebSocketServer:"""Gateway 与 AgentServer 之间的 WebSocket 服务端(单例).@@ -836,8 +1061,6 @@ class AgentWebSocketServer:)try:- from jiuwenswarm.common.schema.message import ReqMethod-if request.channel_id == "acp" and request.req_method != ReqMethod.INITIALIZE:metadata = dict(request.metadata or {})ws_caps = self._get_ws_acp_client_capabilities(ws)@@ -1072,8 +1295,6 @@ class AgentWebSocketServer:@staticmethoddef _should_trigger_before_chat_request_hook(request: AgentRequest) -> bool:- from jiuwenswarm.common.schema.message import ReqMethod-return request.req_method in (ReqMethod.CHAT_SEND,ReqMethod.CHAT_RESUME,@@ -1150,13 +1371,109 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))+ @staticmethod+ def _resolve_code_language() -> str:+ """Determine the display language for code mode plan approval messages.++ Returns ``"cn"`` or ``"en"`` based on configuration.+ Defaults to ``"cn"`` if the config key is missing.+ """+ try:+ config = get_config()+ return config.get("language", "cn")+ except Exception:+ return "cn"++ @staticmethod+ def _should_sync_code_mode_state(request: AgentRequest) -> bool:+ """Only agent chat turns may change plan/normal mode.++ Background RPCs (e.g. ``skills.list``) also send ``mode: code.normal`` but+ must not run plan-mode restore logic or race with an in-flight approval.+ """+ method = request.req_method+ if method is None:+ return True+ return method in _CODE_MODE_SYNC_METHODS++ @staticmethod+ def _session_mode_sync_lock(session_id: str) -> asyncio.Lock:+ lock = _session_mode_sync_locks.get(session_id)+ if lock is None:+ lock = asyncio.Lock()+ _session_mode_sync_locks[session_id] = lock+ return lock++ async def _push_plan_mode_exited(self, request: AgentRequest) -> None:+ """Notify the client that plan mode ended after user approval."""+ session_id = request.session_id+ if not session_id:+ return+ await self.send_push({+ "channel_id": request.channel_id or "default",+ "session_id": session_id,+ "payload": {+ "event_type": PLAN_MODE_EXITED_EVENT_TYPE,+ "mode": "code.normal",+ },+ })++ @staticmethod+ def _is_resuming_tool_interrupt(request: AgentRequest) -> bool:+ """Return True when the request resumes a paused tool-call interrupt."""+ return _is_resuming_tool_interrupt(request)++ async def _prepare_code_mode_chat_turn(+ self,+ request: AgentRequest,+ channel_id: str,+ ) -> tuple[str, str | None, Any]:+ """Plan approval gates, mode resolution, and correct agent instance selection."""+ language = self._resolve_code_language()++ if not _is_resuming_tool_interrupt(request):+ _check_and_handle_pending_approval(request, language=language)++ mode, sub_mode = _apply_resolved_mode_to_request(request)+ agent_mode = "agent" if mode == "auto_harness" else mode+ project_dir = resolve_request_project_dir(request)++ agent = await self._agent_manager.get_agent(+ channel_id=channel_id,+ mode=agent_mode,+ project_dir=project_dir,+ sub_mode=sub_mode,+ )+ if agent is None:+ raise ValueError("Failed to get agent")++ if (+ not _is_resuming_tool_interrupt(request)+ and await _try_handle_direct_plan_implement(+ request, agent, language=language+ )+ ):+ prev_sub_mode = sub_mode+ mode, sub_mode = _apply_resolved_mode_to_request(request)+ if sub_mode != prev_sub_mode:+ agent = await self._agent_manager.get_agent(+ channel_id=channel_id,+ mode=agent_mode,+ project_dir=project_dir,+ sub_mode=sub_mode,+ )+ if agent is None:+ raise ValueError("Failed to get agent")++ return mode, sub_mode, agent+async def _ensure_code_mode_state(self,request: AgentRequest,mode: str,sub_mode: str,agent: Any,- ) -> None:+ ) -> bool:"""code 模式:确保 agent 的 plan_mode 状态正确,必要时执行 switch_mode 并持久化.当 plan 已完成(plan_slug 存在且 mode 不为 "plan")时跳过 switch_mode,@@ -1166,37 +1483,75 @@ class AgentWebSocketServer:切换到 plan 模式且尚未调用 enter_plan_mode 时,注入 <system-reminder>告知 LLM 调用 enter_plan_mode(对齐 Claude Code:plan 指令不进 system prompt)。++ Returns:+ ``True`` if plan mode was restored to normal after user approval."""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)+ return False+ if not self._should_sync_code_mode_state(request):+ return False+ if self._is_resuming_tool_interrupt(request):+ logger.info(+ "[_ensure_code_mode_state] Skip mode sync while resuming tool interrupt "+ "for session=%s source=%s",+ request.session_id,+ (request.params or {}).get("source") if isinstance(request.params, dict) else None,+ )+ return False++ session_id = request.session_id or "default"+ restored_after_approval = False+ async with self._session_mode_sync_lock(session_id):+ 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)+ # 仅在目标模式与当前模式不同时执行模式切换,避免:+ # 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:+ approved_this_turn = session_id in _plan_approved_sessions+ if isinstance(request.params, dict):+ request.params.pop(PLAN_USER_APPROVED_FLAG, None)+ # 仅当用户明确批准计划时才允许 plan → normal。+ if state.plan_mode.mode == "plan" and sub_mode == "normal":+ if approved_this_turn:+ _plan_approved_sessions.discard(session_id)+ agent.get_instance().restore_mode_after_plan_exit(session)+ restored_after_approval = True+ logger.info(+ "[_ensure_code_mode_state] Restored plan→normal after user "+ "approval for session=%s",+ session_id,+ )+ else:+ if isinstance(request.params, dict):+ request.params["mode"] = "code.plan"+ logger.info(+ "[_ensure_code_mode_state] Blocked plan→normal without approval "+ "for session=%s request_id=%s",+ session_id,+ request.request_id,+ )+ else:+ agent.get_instance().switch_mode(session=session, mode=sub_mode)+ # switch_mode/restore 内部已通过 save_state 写入 "deepagent" key,+ # 只需 post_run 持久化到 checkpointer+ await session.post_run()++ # 切换到 plan 模式且尚未调用 enter_plan_mode 时,+ # 注入 <system-reminder> 告知 LLM 调用 enter_plan_mode。+ if sub_mode == "plan" and not state.plan_mode.plan_slug:+ _inject_plan_mode_activation_reminder(request)++ return restored_after_approvalasync def _handle_unary(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:"""非流式处理:调用 process_message,返回一条 E2AResponse 线 JSON。"""- from jiuwenswarm.common.schema.message import ReqMethod-channel_id = request.channel_id or "default"if request.req_method == ReqMethod.INITIALIZE:@@ -1215,21 +1570,22 @@ class AgentWebSocketServer:await self._handle_acp_tool_response(ws, request, send_lock)return- mode, sub_mode = _apply_resolved_mode_to_request(request)- 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,+ mode, sub_mode, agent = await self._prepare_code_mode_chat_turn(+ request, channel_id)- if agent is None:- raise ValueError("Failed to get agent")- await self._ensure_code_mode_state(request, mode, sub_mode, agent)+ restored_plan = await self._ensure_code_mode_state(request, mode, sub_mode, agent)+ if restored_plan:+ await self._push_plan_mode_exited(request)resp = await agent.process_message(request)+ # ── Pick up pending approval state from agent ──+ _store_pending_approval_from_agent(+ request.session_id or "default",+ agent.get_instance(),+ )+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))@@ -1245,18 +1601,14 @@ class AgentWebSocketServer:current_task = asyncio.current_task()if current_task is not None:self._session_stream_tasks[session_id] = current_task- mode, sub_mode = _apply_resolved_mode_to_request(request)- 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,++ mode, sub_mode, agent = await self._prepare_code_mode_chat_turn(+ request, channel_id)- if agent is None:- raise ValueError("Failed to get agent")- await self._ensure_code_mode_state(request, mode, sub_mode, agent)+ restored_plan = await self._ensure_code_mode_state(request, mode, sub_mode, agent)+ if restored_plan:+ await self._push_plan_mode_exited(request)chunk_count = 0# 心跳控制:当有真实 chunk 发送时重置,空闲时发送心跳@@ -1326,6 +1678,12 @@ class AgentWebSocketServer:if self._session_stream_tasks.get(session_id) is current_task:self._session_stream_tasks.pop(session_id, None)+ # ── Pick up pending approval state from agent ──+ _store_pending_approval_from_agent(+ session_id,+ agent.get_instance(),+ )+logger.info("[AgentWebSocketServer] 流式响应已发送: request_id=%s 共 %s 个 chunk",request.request_id,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 3d355178a6..1e47d551ef 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -522,7 +522,10 @@ class JiuWenClaw:)return interactive_input- if source and source != "permission_interrupt":+ if source and source not in {+ "permission_interrupt",+ "confirm_interrupt",+ }:return Noneanswer = answers[0] if answers else {}@@ -531,7 +534,7 @@ class JiuWenClaw:value = selected_options[0] if selected_options else ""- if value in ("approve", "本次允许", "Approve"):+ if value in ("approve", "本次允许", "Approve", "Proceed", "批准", "开始执行"):confirm_payload = {"approved": True, "auto_confirm": False, "feedback": ""}elif value in ("always_allow", "总是允许", "Always Allow"):confirm_payload = {@@ -540,8 +543,13 @@ class JiuWenClaw:"persist_allow": True,"feedback": "",}- elif value in ("reject", "拒绝", "Reject"):- confirm_payload = {"approved": False, "auto_confirm": False, "feedback": custom_input or "用户拒绝"}+ elif value in ("reject", "拒绝", "Reject", "继续规划", "其他意见"):+ feedback = custom_input or (+ "用户希望继续规划" if value in ("Keep planning", "继续规划", "其他意见") else "用户拒绝"+ )+ confirm_payload = {"approved": False, "auto_confirm": False, "feedback": feedback}+ elif custom_input:+ confirm_payload = {"approved": False, "auto_confirm": False, "feedback": custom_input}else:confirm_payload = {"approved": False, "auto_confirm": False, "feedback": f"未知选项: {value}"}diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex bb6b0f87f6..d1a5655b4d 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -28,7 +28,6 @@ from openjiuwen.harness.factory import create_deep_agentfrom openjiuwen.harness.prompts import resolve_languagefrom openjiuwen.harness.rails import (AgentModeRail,- ConfirmInterruptRail,CodingMemoryRail,SysOperationRail,LspRail@@ -54,7 +53,10 @@ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers importfrom jiuwenswarm.agents.harness.code.prompt.code_prompt_builder import (build_code_system_prompt,)-from jiuwenswarm.agents.harness.code.rails import CodeTaskPlanningRail+from jiuwenswarm.agents.harness.code.rails import (+ CodeTaskPlanningRail,+ PlanApprovalRail,+)from jiuwenswarm.agents.harness.common.rails import (ProjectMemoryRail,StructuredAskUserRail,@@ -173,25 +175,6 @@ implementing the approved plan.</system-reminder>"""-class JiuwenAgentModeRail(AgentModeRail):- """AgentModeRail preconfigured with jiuwenswarm's code plan-mode contract.-- Bakes in the Claude-Code-aligned plan-mode behavior (switch_mode disabled,- static plan-mode system note, enter/exit plan instructions) so both the- legacy adapter path and the declarative swarm provider construct an- identical rail without duplicating configuration.- """-- def __init__(self) -> None:- """Initialize the rail with the fixed code plan-mode configuration."""- super().__init__(- allow_switch_mode=False,- plan_mode_system_note=_PLAN_MODE_SYSTEM_NOTE,- enter_plan_instructions=_ENTER_PLAN_MODE_INSTRUCTIONS_EN,- exit_plan_notification=_EXIT_PLAN_MODE_NOTIFICATION,- )--# 名字 → 构建方法映射(rail/tool 名字与类方法名对照)_RAIL_BUILD_NAMES: dict[str, str] = {"SysOperationRail": "_build_filesystem_rail",@@ -208,6 +191,7 @@ _RAIL_BUILD_NAMES: dict[str, str] = {"CodingMemoryRail": "_build_coding_memory_rail","WorktreeRail": "_build_worktree_rail_via_config","CodeAgentRail": "_build_code_agent_rail",+ "PlanApprovalRail": "_build_plan_approval_rail",}_TOOL_BUILD_NAMES: dict[str, str] = {@@ -330,6 +314,24 @@ def create_coding_memory_rail()+# ─── Plan mode allowed tools for code mode ──────────────────────────────+# Excludes switch_mode so the LLM cannot unilaterally exit plan mode.++_CODE_PLAN_ALLOWED_TOOLS: list[str] = [+ "enter_plan_mode",+ "exit_plan_mode",+ "ask_user",+ "task_tool",+ "read_file",+ "grep",+ "list_files",+ "glob",+ "bash",+ "write_file",+ "edit_file",+]++class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):"""Code 模式适配器 — 配置驱动注册 rails/tools.@@ -546,11 +548,12 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):_RailBuildInfo("_code_confirm_interrupt_rail",self._build_confirm_interrupt_rail,- {"tool_names": ["switch_mode", "exit_plan_mode"]},+ {"tool_names": ["switch_mode"]},),_RailBuildInfo("_context_processor_rail", self._build_context_processor_rail),_RailBuildInfo("_code_task_planning_rail", self._build_code_task_planning_rail),_RailBuildInfo("_code_agent_rail", self._build_code_agent_rail),+ _RailBuildInfo("_code_plan_approval_rail", self._build_plan_approval_rail),]# 动态 Rails — 从 config.yaml::modes.code.rails 读取@@ -644,11 +647,17 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):return Nonedef _build_agent_mode_rail(self) -> AgentModeRail | None:- """构建 AgentModeRail(屏蔽 switch_mode + 静态 plan 提示词 + plan 指令进对话)."""+ """构建 CodeAgentModeRail(plan 退出需用户批准后生效)."""try:- return JiuwenAgentModeRail()+ from jiuwenswarm.agents.harness.code.rails.code_agent_mode_rail import (+ CodeAgentModeRail,+ )++ return CodeAgentModeRail(+ allowed_tools=_CODE_PLAN_ALLOWED_TOOLS,+ )except Exception as exc:- logger.warning("[JiuwenClawCodeAdapter] AgentModeRail create failed: %s", exc)+ logger.warning("[JiuwenClawCodeAdapter] CodeAgentModeRail create failed: %s", exc)return None@staticmethod@@ -668,12 +677,18 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):logger.warning("[JiuwenClawCodeAdapter] StructuredAskUserRail create failed: %s", exc)return None- def _build_confirm_interrupt_rail(self, tool_names: list[str] | None = None) -> ConfirmInterruptRail | None:- """构建 ConfirmInterruptRail."""+ def _build_confirm_interrupt_rail(self, tool_names: list[str] | None = None) -> Any | None:+ """构建 CodeConfirmInterruptRail(控制类工具需用户确认,含可读提示)."""try:- return ConfirmInterruptRail(tool_names=tool_names or ["switch_mode"])+ from jiuwenswarm.agents.harness.code.rails.code_confirm_interrupt_rail import (+ CodeConfirmInterruptRail,+ )++ # exit_plan_mode 由 PlanApprovalRail 负责计划审批,不再走 ConfirmInterrupt。+ filtered = [name for name in (tool_names or []) if name != "exit_plan_mode"]+ return CodeConfirmInterruptRail(tool_names=filtered or ["switch_mode"])except Exception as exc:- logger.warning("[JiuwenClawCodeAdapter] ConfirmInterruptRail create failed: %s", exc)+ logger.warning("[JiuwenClawCodeAdapter] CodeConfirmInterruptRail create failed: %s", exc)return Nonedef _build_lsp_rail_via_config(self) -> Any:@@ -1020,18 +1035,30 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):logger.warning("[JiuwenClawCodeAdapter] CodeAgentRail create failed: %s", exc)return None+ def _build_plan_approval_rail(self) -> PlanApprovalRail | None:+ """构建 PlanApprovalRail,管理 plan 审批生命周期。"""+ try:+ rail = PlanApprovalRail()+ logger.info("[JiuwenClawCodeAdapter] PlanApprovalRail created")+ return rail+ except Exception as exc:+ logger.warning("[JiuwenClawCodeAdapter] PlanApprovalRail create failed: %s", exc)+ return None+def _get_current_agent_rails(self, config: dict[str, Any], config_base: dict[str, Any] | None = None) -> list[Any]:- """扩展父类方法,将 CodeAgentRail 纳入热重载范围。+ """扩展父类方法,将 Code/Plan 专属 Rail 纳入热重载范围。父类 _get_current_agent_rails 只返回 skill/context/memory 等 rail,- CodeAgentRail 不在其中。覆盖此方法确保 config reload 时- CodeAgentRail 被正确重新初始化。+ CodeAgentRail 和 PlanApprovalRail 不在其中。覆盖此方法确保 config reload+ 时这些 rail 被正确重新初始化。"""rails_list = super()._get_current_agent_rails(config, config_base)if self._code_agent_rail is not None:rails_list.append(self._code_agent_rail)+ if self._code_plan_approval_rail is not None:+ rails_list.append(self._code_plan_approval_rail)return rails_list# ─── Runtime config ──────────────────────────diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex d81159b940..ca8b8330ba 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -759,7 +759,7 @@ def test_code_member_builds_declaratively_without_post_processing(# Code-specific rails materialized via the normal declarative spec.build.for expected in ("CodeTaskPlanningRail",- "JiuwenAgentModeRail",+ "CodeAgentModeRail","StructuredAskUserRail","WorktreeRail",):diff --git a/tests/system_tests/test_structured_ask_user.py b/tests/system_tests/test_structured_ask_user.pyindex eb59f37538..a333786065 100644--- a/tests/system_tests/test_structured_ask_user.py+++ b/tests/system_tests/test_structured_ask_user.py@@ -32,6 +32,10 @@ from jiuwenswarm.agents.harness.common.rails.ask_user_rail import (from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (_extract_questions_from_value,convert_interactions_to_ask_user_question,+ extract_question_from_interaction,+)+from jiuwenswarm.agents.harness.code.rails.code_confirm_interrupt_rail import (+ build_confirm_interrupt_message,)pytestmark = [pytest.mark.integration, pytest.mark.system]@@ -435,6 +439,77 @@ class TestConvertInteractionsToAskUserQuestion:assert result["source"] == "ask_user_interrupt"+# =====================================================================+# 5b. Confirm vs permission interrupt classification+# =====================================================================++class TestConfirmAndPermissionInterrupts:+ @staticmethod+ def test_confirm_interrupt_message_is_classified():+ message = build_confirm_interrupt_message("switch_mode", {"mode": "plan"})+ result = convert_interactions_to_ask_user_question([+ {+ "id": "req_confirm",+ "value": {+ "tool_name": "switch_mode",+ "message": message,+ "tool_args": {"mode": "plan"},+ },+ }+ ])+ assert result is not None+ assert result["source"] == "confirm_interrupt"+ assert "switch_mode" in result["questions"][0]["question"]+ assert result["questions"][0]["header"].startswith("操作确认")++ @staticmethod+ def test_permission_interrupt_message_is_classified():+ message = "**工具 `write_file` 需要授权才能执行**\n\n请确认是否允许该操作。"+ result = convert_interactions_to_ask_user_question([+ {+ "id": "req_perm",+ "value": {+ "tool_name": "write_file",+ "message": message,+ "tool_args": {"file_path": "foo.py"},+ },+ }+ ])+ assert result is not None+ assert result["source"] == "permission_interrupt"+ assert "write_file" in result["questions"][0]["question"]+ assert result["questions"][0]["header"].startswith("权限审批")++ @staticmethod+ def test_extract_question_falls_back_for_generic_confirm_copy():+ question = extract_question_from_interaction({+ "id": "req_generic",+ "value": {+ "tool_name": "switch_mode",+ "message": "Please approve or reject?",+ "tool_args": {"mode": "normal"},+ },+ })+ assert question is not None+ assert "switch_mode" in question["question"]+ assert question["header"] == "操作确认: switch_mode"++ @staticmethod+ def test_exit_plan_mode_interrupt_uses_confirm_interrupt():+ result = convert_interactions_to_ask_user_question([+ {+ "id": "req_plan_exit",+ "value": {+ "tool_name": "exit_plan_mode",+ "message": "Please approve or reject?",+ "tool_args": {},+ },+ }+ ])+ assert result is not None+ assert result["source"] == "confirm_interrupt"++# =====================================================================# 6. StructuredAskUserRail resolve_interrupt Tests# =====================================================================diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex e25fa93570..cef950182d 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -360,6 +360,9 @@ def test_handle_stream_accepts_team_mode_without_sub_mode(monkeypatch):def __init__(self):self.seen_request = None+ def get_instance(self):+ return self+async def process_message_stream(self, request):self.seen_request = requestyield AgentResponseChunk(@@ -433,6 +436,9 @@ def test_handle_stream_accepts_code_team_sub_mode(monkeypatch):def __init__(self):self.seen_request = None+ def get_instance(self):+ return self+async def process_message_stream(self, request):self.seen_request = requestyield AgentResponseChunk(diff --git a/tests/unit_tests/agentserver/test_code_agent_mode_rail.py b/tests/unit_tests/agentserver/test_code_agent_mode_rail.pynew file mode 100644index 0000000000..8ee4252ec8--- /dev/null+++ b/tests/unit_tests/agentserver/test_code_agent_mode_rail.py@@ -0,0 +1,80 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for CodeAgentModeRail plan-mode enforcement."""++# pylint: disable=protected-access++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from jiuwenswarm.agents.harness.code.rails.code_agent_mode_rail import CodeAgentModeRail+++async def test_before_tool_call_blocks_switch_mode_exit_in_plan_mode() -> None:+ rail = CodeAgentModeRail(allowed_tools=["switch_mode"])+ agent = MagicMock()+ plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")+ agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)+ rail._agent = agent++ parent = AsyncMock()+ with patch.object(CodeAgentModeRail.__bases__[0], "before_tool_call", parent):+ ctx = SimpleNamespace(+ session=SimpleNamespace(),+ inputs=SimpleNamespace(+ tool_name="switch_mode",+ tool_call=SimpleNamespace(+ id="call_1",+ arguments='{"mode": "normal"}',+ ),+ tool_args={"mode": "normal"},+ ),+ extra={},+ )+ await rail.before_tool_call(ctx)++ parent.assert_not_awaited()+ assert ctx.extra.get("_skip_tool") is True+++async def test_before_tool_call_blocks_non_git_write_in_plan_mode() -> None:+ rail = CodeAgentModeRail(allowed_tools=["bash"])+ agent = MagicMock()+ plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")+ agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)+ rail._agent = agent++ parent = AsyncMock()+ with patch.object(CodeAgentModeRail.__bases__[0], "before_tool_call", parent):+ ctx = SimpleNamespace(+ session=SimpleNamespace(),+ inputs=SimpleNamespace(+ tool_name="bash",+ tool_call=SimpleNamespace(id="call_1"),+ tool_args={"command": "mkdir -p src/foo"},+ ),+ extra={},+ )+ await rail.before_tool_call(ctx)++ parent.assert_awaited_once()+ assert ctx.extra.get("_skip_tool") is True+++def test_init_patches_exit_plan_mode_invoke() -> None:+ rail = CodeAgentModeRail(allowed_tools=["exit_plan_mode"])+ tool = MagicMock()+ tool.card.name = "exit_plan_mode"+ tool._language = "cn"+ tool._agent_ref = MagicMock()+ tool._agent_ref.get_plan_file_path.return_value = None+ rail._tools = [tool]++ agent = MagicMock()+ rail.init(agent)++ assert tool.invoke is not rail._patch_exit_plan_mode_tooldiff --git a/tests/unit_tests/agentserver/test_code_confirm_interrupt_rail.py b/tests/unit_tests/agentserver/test_code_confirm_interrupt_rail.pynew file mode 100644index 0000000000..d985d2a755--- /dev/null+++ b/tests/unit_tests/agentserver/test_code_confirm_interrupt_rail.py@@ -0,0 +1,55 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for CodeConfirmInterruptRail plan-mode switch_mode guard."""++from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult++from jiuwenswarm.agents.harness.code.rails.code_confirm_interrupt_rail import (+ CodeConfirmInterruptRail,+)+++async def test_switch_mode_exit_rejected_in_plan_without_confirm_ui() -> None:+ rail = CodeConfirmInterruptRail(tool_names=["switch_mode"])+ agent = MagicMock()+ plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")+ agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)+ agent.system_prompt_builder = SimpleNamespace(language="cn")++ tool_call = SimpleNamespace(+ name="switch_mode",+ arguments='{"mode": "normal"}',+ )+ ctx = SimpleNamespace(agent=agent, session=SimpleNamespace())++ decision = await rail.resolve_interrupt(ctx, tool_call, user_input=None)++ assert isinstance(decision, RejectResult)+ assert "switch_mode" in str(decision.tool_result)+++async def test_switch_mode_exit_rejected_even_after_user_approves_confirm() -> None:+ rail = CodeConfirmInterruptRail(tool_names=["switch_mode"])+ agent = MagicMock()+ plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")+ agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)+ agent.system_prompt_builder = SimpleNamespace(language="cn")++ tool_call = SimpleNamespace(+ name="switch_mode",+ arguments='{"mode": "normal"}',+ )+ ctx = SimpleNamespace(agent=agent, session=SimpleNamespace())++ decision = await rail.resolve_interrupt(+ ctx, tool_call, user_input={"approved": True}+ )++ assert isinstance(decision, RejectResult)diff --git a/tests/unit_tests/agentserver/test_plan_approval.py b/tests/unit_tests/agentserver/test_plan_approval.pynew file mode 100644index 0000000000..42a2de60fe--- /dev/null+++ b/tests/unit_tests/agentserver/test_plan_approval.py@@ -0,0 +1,132 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for text-only plan approval gate."""++# pylint: disable=protected-access++from jiuwenswarm.agents.harness.code.prompt.plan_approval import (+ PLAN_USER_APPROVED_FLAG,+ classify_plan_user_intent,+ is_direct_plan_implement_request,+)+from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server.agent_ws_server import (+ _check_and_handle_pending_approval,+ _pending_plan_approvals,+ _plan_approved_sessions,+ AgentWebSocketServer,+)+++def _make_request(session_id: str, query: str, mode: str = "code.normal") -> AgentRequest:+ return AgentRequest(+ request_id="req_test",+ channel_id="tui",+ session_id=session_id,+ params={"query": query, "mode": mode},+ )+++def setup_function() -> None:+ _pending_plan_approvals.clear()+ _plan_approved_sessions.clear()+++def test_direct_plan_implement_requires_strong_signal() -> None:+ assert is_direct_plan_implement_request("好,那按计划实现吧") is True+ assert is_direct_plan_implement_request("按计划实现") is True+ assert is_direct_plan_implement_request("好") is False+ assert is_direct_plan_implement_request("可以") is False+++def test_classify_implement_intent_as_approve() -> None:+ assert classify_plan_user_intent("按计划实现") == "approve"+ assert classify_plan_user_intent("开始实现吧") == "approve"+ assert classify_plan_user_intent("implement the plan") == "approve"+++def test_classify_revision_intent() -> None:+ assert classify_plan_user_intent("多添加几个边界测试用例") == "revise"+ assert classify_plan_user_intent("第二步改成异步") == "revise"+ assert classify_plan_user_intent("不行,先别做") == "revise"+++def test_classify_mixed_revision_overrides_short_approval() -> None:+ assert classify_plan_user_intent("可以,但是要把第二步改成异步") == "revise"+++def test_pending_approval_accepts_free_text_approve() -> None:+ session_id = "sess_approve"+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_content": "# Plan\n\nDo the thing",+ "plan_slug": "test-plan",+ "plan_path": "/tmp/plan.md",+ }+ request = _make_request(session_id, "可以,开始吧")++ assert _check_and_handle_pending_approval(request, language="cn") is True+ assert session_id not in _pending_plan_approvals+ assert request.params["mode"] == "code.normal"+ assert request.params[PLAN_USER_APPROVED_FLAG] is True+ assert session_id in _plan_approved_sessions+ assert "用户已批准" in request.params["query"]+ assert "Do the thing" in request.params["query"]+++def test_approve_registers_session_level_flag() -> None:+ session_id = "sess_flag"+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_content": "# Plan",+ "plan_slug": "test-plan",+ "plan_path": "/tmp/plan.md",+ }+ request = _make_request(session_id, "按计划实现")++ assert _check_and_handle_pending_approval(request, language="cn") is True+ assert session_id in _plan_approved_sessions+++def test_skills_list_does_not_sync_code_mode() -> None:+ request = AgentRequest(+ request_id="req_skills",+ channel_id="tui",+ session_id="sess_skills",+ req_method=ReqMethod.SKILLS_LIST,+ params={"mode": "code.normal"},+ )+ assert AgentWebSocketServer._should_sync_code_mode_state(request) is False+++def test_pending_approval_accepts_implement_phrase() -> None:+ session_id = "sess_implement"+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_content": "# Plan",+ "plan_slug": "test-plan",+ "plan_path": "/tmp/plan.md",+ }+ request = _make_request(session_id, "按计划实现")++ assert _check_and_handle_pending_approval(request, language="cn") is True+ assert request.params["mode"] == "code.normal"+ assert request.params[PLAN_USER_APPROVED_FLAG] is True+++def test_pending_approval_accepts_feedback_text() -> None:+ session_id = "sess_feedback"+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_content": "# Plan",+ "plan_slug": "test-plan",+ "plan_path": "/tmp/plan.md",+ }+ request = _make_request(session_id, "多添加几个边界测试用例")++ assert _check_and_handle_pending_approval(request, language="cn") is True+ assert request.params["mode"] == "code.plan"+ assert PLAN_USER_APPROVED_FLAG not in request.params+ assert "用户要求修订计划" in request.params["query"]+ assert "多添加几个边界测试用例" in request.params["query"]diff --git a/tests/unit_tests/agentserver/test_plan_approval_rail.py b/tests/unit_tests/agentserver/test_plan_approval_rail.pynew file mode 100644index 0000000000..f56470e4a1--- /dev/null+++ b/tests/unit_tests/agentserver/test_plan_approval_rail.py@@ -0,0 +1,60 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for PlanApprovalRail deferred plan-mode exit."""++# pylint: disable=protected-access++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from jiuwenswarm.agents.harness.code.rails.code_agent_mode_rail import CodeAgentModeRail+from jiuwenswarm.agents.harness.code.rails.code_plan_approval_rail import PlanApprovalRail+++async def test_exit_plan_mode_appends_pending_marker_without_switching_mode() -> None:+ rail = PlanApprovalRail()+ agent = MagicMock()+ plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")+ agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)+ agent.get_plan_file_path.return_value = None++ ctx = SimpleNamespace(+ session=SimpleNamespace(),+ inputs=SimpleNamespace(+ tool_name="exit_plan_mode",+ tool_result={"ok": True},+ tool_msg=SimpleNamespace(+ content="Plan submitted for your review.\n\n## Plan:\nstep 1",+ ),+ ),+ extra={},+ )++ rail._agent = agent+ await rail.after_tool_call(ctx)++ agent.switch_mode.assert_not_called()+ assert getattr(agent, "_plan_approval_state").pending is True+ assert "仍在规划模式" in ctx.inputs.tool_msg.content+++async def test_code_agent_mode_rail_skips_exit_after_tool_call() -> None:+ rail = CodeAgentModeRail(allowed_tools=["exit_plan_mode"])+ rail._agent = MagicMock()+ parent = AsyncMock()+ rail.__class__.__bases__[0].after_tool_call = parent++ ctx = SimpleNamespace(+ inputs=SimpleNamespace(+ tool_name="exit_plan_mode",+ tool_result={"ok": True},+ ),+ extra={},+ )++ await rail.after_tool_call(ctx)+ parent.assert_not_called()diff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.pynew file mode 100644index 0000000000..a5c2f46029--- /dev/null+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py@@ -0,0 +1,350 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""End-to-end orchestration tests for plan mode approval and exit flows."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from jiuwenswarm.agents.harness.code.prompt.plan_approval import PLAN_USER_APPROVED_FLAG+from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server.agent_ws_server import (+ AgentWebSocketServer,+ _check_and_handle_pending_approval,+ _pending_plan_approvals,+ _plan_approved_sessions,+ _try_handle_direct_plan_implement,+)+++def _chat_request(+ session_id: str,+ query: str,+ *,+ mode: str = "code.plan",+ req_method: ReqMethod = ReqMethod.CHAT_SEND,+ extra_params: dict | None = None,+) -> AgentRequest:+ params: dict = {"query": query, "mode": mode}+ if extra_params:+ params.update(extra_params)+ return AgentRequest(+ request_id="req_flow",+ channel_id="tui",+ session_id=session_id,+ req_method=req_method,+ params=params,+ )+++def setup_function() -> None:+ _pending_plan_approvals.clear()+ _plan_approved_sessions.clear()+++async def test_direct_implement_refetches_normal_agent_instance(tmp_path: Path) -> None:+ """TUI still sends code.plan; server must switch to code:normal agent after approval."""+ session_id = "sess_refetch"+ plan_file = tmp_path / "sliding-window.md"+ plan_file.write_text("# Plan\n\nImplement sliding window.", encoding="utf-8")++ plan_agent = MagicMock()+ plan_instance = MagicMock()+ normal_agent = MagicMock()+ normal_instance = MagicMock()+ plan_agent.get_instance.return_value = plan_instance+ normal_agent.get_instance.return_value = normal_instance++ plan_state = SimpleNamespace(mode="plan", plan_slug="sliding-window")+ plan_instance.card = SimpleNamespace(id="code-agent")+ normal_instance.card = SimpleNamespace(id="code-agent")+ plan_instance.load_state.return_value = SimpleNamespace(plan_mode=plan_state)+ plan_instance.get_plan_file_path.return_value = plan_file+ plan_instance.restore_mode_after_plan_exit = MagicMock()++ manager = MagicMock()+ manager.get_agent = AsyncMock(side_effect=[plan_agent, normal_agent])++ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ server._agent_manager = manager+ server._resolve_code_language = MagicMock(return_value="cn")++ request = _chat_request(session_id, "好,那按计划实现吧", mode="code.plan")++ mock_session = MagicMock()+ mock_session.pre_run = AsyncMock()+ with (+ patch(+ "openjiuwen.core.single_agent.create_agent_session",+ MagicMock(return_value=mock_session),+ ),+ patch.object(+ AgentWebSocketServer,+ "_ensure_code_mode_state",+ new_callable=AsyncMock,+ return_value=True,+ ) as ensure_mock,+ ):+ mode, sub_mode, agent = await server._prepare_code_mode_chat_turn(+ request, "tui"+ )++ assert manager.get_agent.await_count == 2+ second_call = manager.get_agent.await_args_list[1].kwargs+ assert second_call["sub_mode"] == "normal"+ assert agent is normal_agent+ assert sub_mode == "normal"+ assert request.params["mode"] == "code.normal"+ assert session_id in _plan_approved_sessions+ assert "用户已批准" in request.params["query"]+ ensure_mock.assert_not_called()+++async def test_pending_approval_uses_normal_agent_without_extra_refetch() -> None:+ session_id = "sess_pending"+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_content": "# Plan\nstep 1",+ "plan_slug": "test",+ "plan_path": "/tmp/plan.md",+ }++ normal_agent = MagicMock()+ manager = MagicMock()+ manager.get_agent = AsyncMock(return_value=normal_agent)++ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ server._agent_manager = manager+ server._resolve_code_language = MagicMock(return_value="cn")++ request = _chat_request(session_id, "按计划实现", mode="code.plan")++ mode, sub_mode, agent = await server._prepare_code_mode_chat_turn(request, "tui")++ assert manager.get_agent.await_count == 1+ assert sub_mode == "normal"+ assert agent is normal_agent+ assert session_id not in _pending_plan_approvals+++async def test_confirm_interrupt_resume_does_not_consume_pending_approval() -> None:+ session_id = "sess_interrupt"+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_content": "# Plan",+ "plan_slug": "test",+ "plan_path": "/tmp/plan.md",+ }++ assert (+ _check_and_handle_pending_approval(+ _chat_request(+ session_id,+ "",+ extra_params={+ "request_id": "tool_req_1",+ "answers": {"approved": False},+ "source": "confirm_interrupt",+ },+ ),+ language="cn",+ )+ is False+ )+ assert session_id in _pending_plan_approvals+++async def test_blocked_plan_to_normal_without_approval(tmp_path: Path) -> None:+ session_id = "sess_block"+ plan_agent = MagicMock()+ plan_instance = MagicMock()+ plan_agent.get_instance.return_value = plan_instance+ plan_instance.card = SimpleNamespace(id="code-agent")+ plan_state = SimpleNamespace(mode="plan", plan_slug="test")+ plan_instance.load_state.return_value = SimpleNamespace(plan_mode=plan_state)++ session = MagicMock()+ create_session = MagicMock(return_value=session)+ pre_run = AsyncMock()+ post_run = AsyncMock()++ server = AgentWebSocketServer.__new__(AgentWebSocketServer)++ request = _chat_request(session_id, "hello", mode="code.normal")++ with patch(+ "openjiuwen.core.single_agent.create_agent_session",+ create_session,+ ):+ session.pre_run = pre_run+ session.post_run = post_run+ restored = await server._ensure_code_mode_state(+ request, "code", "normal", plan_agent+ )++ assert restored is False+ assert request.params["mode"] == "code.plan"+ plan_instance.restore_mode_after_plan_exit.assert_not_called()+++async def test_ensure_restores_plan_to_normal_after_approval(tmp_path: Path) -> None:+ session_id = "sess_restore"+ _plan_approved_sessions.add(session_id)++ plan_agent = MagicMock()+ plan_instance = MagicMock()+ plan_agent.get_instance.return_value = plan_instance+ plan_instance.card = SimpleNamespace(id="code-agent")+ plan_state = SimpleNamespace(mode="plan", plan_slug="test")+ plan_instance.load_state.return_value = SimpleNamespace(plan_mode=plan_state)++ session = MagicMock()+ create_session = MagicMock(return_value=session)+ pre_run = AsyncMock()+ post_run = AsyncMock()++ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ request = _chat_request(session_id, "injected approval", mode="code.normal")+ request.params[PLAN_USER_APPROVED_FLAG] = True++ with patch(+ "openjiuwen.core.single_agent.create_agent_session",+ create_session,+ ):+ session.pre_run = pre_run+ session.post_run = post_run+ restored = await server._ensure_code_mode_state(+ request, "code", "normal", plan_agent+ )++ assert restored is True+ plan_instance.restore_mode_after_plan_exit.assert_called_once_with(session)+ assert session_id not in _plan_approved_sessions+++async def test_direct_implement_reads_plan_file(tmp_path: Path) -> None:+ session_id = "sess_direct"+ plan_file = tmp_path / "plan.md"+ plan_file.write_text("# Direct plan body", encoding="utf-8")++ agent = MagicMock()+ instance = MagicMock()+ agent.get_instance.return_value = instance+ instance.card = SimpleNamespace(id="code-agent")+ instance.load_state.return_value = SimpleNamespace(+ plan_mode=SimpleNamespace(mode="plan", plan_slug="plan")+ )+ instance.get_plan_file_path.return_value = plan_file++ request = _chat_request(session_id, "按计划实现")+ session = MagicMock()+ with patch(+ "openjiuwen.core.single_agent.create_agent_session",+ MagicMock(return_value=session),+ ):+ session.pre_run = AsyncMock()+ handled = await _try_handle_direct_plan_implement(+ request,+ agent,+ language="cn",+ )++ assert handled is True+ assert "Direct plan body" in request.params["query"]+++async def test_reject_switch_mode_then_direct_implement_exits_plan(+ tmp_path: Path,+) -> None:+ """Reproduce stuck scenario: reject switch_mode confirm, then chat approve."""+ session_id = "sess_stuck"+ plan_file = tmp_path / "plan.md"+ plan_file.write_text("# Sliding window plan\nstep 1", encoding="utf-8")++ plan_agent = MagicMock()+ normal_agent = MagicMock()+ plan_instance = MagicMock()+ normal_instance = MagicMock()+ plan_agent.get_instance.return_value = plan_instance+ normal_agent.get_instance.return_value = normal_instance+ plan_instance.card = SimpleNamespace(id="code-agent")+ normal_instance.card = SimpleNamespace(id="code-agent")+ plan_instance.load_state.return_value = SimpleNamespace(+ plan_mode=SimpleNamespace(mode="plan", plan_slug="plan")+ )+ plan_instance.get_plan_file_path.return_value = plan_file++ manager = MagicMock()+ manager.get_agent = AsyncMock(side_effect=[plan_agent, normal_agent])++ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ server._agent_manager = manager+ server._resolve_code_language = MagicMock(return_value="cn")++ # Step 1: user rejects switch_mode — pending must survive (none here).+ reject_req = _chat_request(+ session_id,+ "",+ extra_params={+ "request_id": "sw_1",+ "answers": {"approved": False},+ "source": "confirm_interrupt",+ },+ )+ assert _check_and_handle_pending_approval(reject_req, language="cn") is False++ # Step 2: user approves implementation in chat while TUI still shows plan.+ mock_session = MagicMock()+ mock_session.pre_run = AsyncMock()+ implement_req = _chat_request(session_id, "好,那按计划实现吧", mode="code.plan")++ with patch(+ "openjiuwen.core.single_agent.create_agent_session",+ MagicMock(return_value=mock_session),+ ):+ mode, sub_mode, agent = await server._prepare_code_mode_chat_turn(+ implement_req, "tui"+ )++ assert sub_mode == "normal"+ assert agent is normal_agent+ assert implement_req.params["mode"] == "code.normal"+ assert session_id in _plan_approved_sessions+++async def test_skills_list_does_not_restore_plan_mode() -> None:+ session_id = "sess_skills"+ _plan_approved_sessions.add(session_id)++ plan_agent = MagicMock()+ plan_instance = MagicMock()+ plan_agent.get_instance.return_value = plan_instance++ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ request = AgentRequest(+ request_id="req_skills",+ channel_id="tui",+ session_id=session_id,+ req_method=ReqMethod.SKILLS_LIST,+ params={"mode": "code.normal"},+ )++ restored = await server._ensure_code_mode_state(+ request, "code", "normal", plan_agent+ )++ assert restored is False+ plan_instance.restore_mode_after_plan_exit.assert_not_called()diff --git a/tests/unit_tests/e2a/test_gateway_normalize.py b/tests/unit_tests/e2a/test_gateway_normalize.pyindex a9e1cc785d..426b79474f 100644--- a/tests/unit_tests/e2a/test_gateway_normalize.py+++ b/tests/unit_tests/e2a/test_gateway_normalize.py@@ -3,6 +3,7 @@import timefrom jiuwenswarm.common.e2a.agent_compat import e2a_to_agent_request+from jiuwenswarm.common.e2a.constants import E2A_RESPONSE_KIND_PLAN_APPROVAL_REQUIREDfrom jiuwenswarm.common.e2a.gateway_normalize import (E2A_FALLBACK_FAILED_KEY,E2A_INTERNAL_CONTEXT_KEY,@@ -10,10 +11,11 @@ from jiuwenswarm.common.e2a.gateway_normalize import (build_fallback_e2a,channel_context_for_channel_reply,e2a_from_agent_fields,+ e2a_response_to_agent_chunk,message_to_e2a_or_fallback,message_to_legacy_agent_dict,)-from jiuwenswarm.common.e2a.models import E2AEnvelope+from jiuwenswarm.common.e2a.models import E2AEnvelope, E2AResponsefrom jiuwenswarm.common.schema.message import Message, ReqMethod@@ -107,3 +109,26 @@ def test_build_fallback_and_legacy_keys():inner = env.channel_context[E2A_INTERNAL_CONTEXT_KEY]assert inner[E2A_FALLBACK_FAILED_KEY] is Trueassert inner[E2A_LEGACY_AGENT_REQUEST_KEY]["req_method"] == "history.get"+++def test_e2a_response_to_agent_chunk_plan_approval_required():+ e2a = E2AResponse(+ response_id="req-plan-1",+ request_id="req-plan-1",+ sequence=0,+ is_final=True,+ status="succeeded",+ response_kind=E2A_RESPONSE_KIND_PLAN_APPROVAL_REQUIRED,+ body={+ "plan_content": "## Plan\nDo the thing",+ "plan_slug": "bright-otter",+ "plan_path": "/tmp/.plans/bright-otter.md",+ },+ channel="tui",+ session_id="session-1",+ )+ chunk = e2a_response_to_agent_chunk(e2a)+ assert chunk.payload["event_type"] == "plan.approval_required"+ assert chunk.payload["plan_content"] == "## Plan\nDo the thing"+ assert chunk.payload["plan_slug"] == "bright-otter"+ assert chunk.is_complete is True