Skip to content

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

Python

feat: rails interrupt helpers, stream event rail improvements, TUI command builtins refactor, agent adapter interface simplification

ldstyle8b8cb3ca5dab0
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
index d51c3beb40..bbcba0cebf 100644
--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
@@ -282,10 +282,74 @@ def build_permission_rail(
+def _read_value_field(value_obj: Any, field_name: str, default: Any = "") -> Any:
+ if hasattr(value_obj, field_name):
+ return getattr(value_obj, field_name, default)
+ if isinstance(value_obj, dict):
+ return value_obj.get(field_name, default)
+ return default
+
+
+def _normalize_tool_args(raw: Any) -> dict | None:
+ if raw is None:
+ return None
+ if isinstance(raw, dict):
+ return raw
+ if isinstance(raw, str):
+ try:
+ parsed = json.loads(raw)
+ except (ValueError, TypeError):
+ return None
+ return parsed if isinstance(parsed, dict) else None
+ return None
+
+
+def _is_ask_user_interrupt_value(value_obj: Any) -> bool:
+ tool_name = str(_read_value_field(value_obj, "tool_name", "") or "").strip()
+ if tool_name == "ask_user":
+ return True
+ if hasattr(value_obj, "payload_schema") and hasattr(value_obj, "questions"):
+ return True
+ if isinstance(value_obj, dict) and "payload_schema" in value_obj and "questions" in value_obj:
+ return True
+ tool_args = _normalize_tool_args(_read_value_field(value_obj, "tool_args", None))
+ if isinstance(tool_args, dict) and str(tool_args.get("query") or "").strip():
+ if not tool_args.get("questions"):
+ return True
+ return False
+
+
+def _build_plain_ask_user_question(value_obj: Any) -> dict | None:
+ """Build a free-text ask_user question when no structured options are present."""
+ if not _is_ask_user_interrupt_value(value_obj):
+ return None
+ if _extract_questions_from_value(value_obj) is not None:
+ return None
+
+ query = ""
+ tool_args = _normalize_tool_args(_read_value_field(value_obj, "tool_args", None))
+ if isinstance(tool_args, dict):
+ query = str(tool_args.get("query") or "").strip()
+ if not query:
+ query = str(_read_value_field(value_obj, "message", "") or "").strip()
+ if not query:
+ query = str(_read_value_field(value_obj, "question", "") or "").strip()
+ if not query:
+ return None
+
+ return {
+ "question": query,
+ "header": "Question",
+ "options": [],
+ "multi_select": False,
+ }
+
+
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 字段 → source="ask_user_interrupt"
+ AskUserRail 中断: value 有 questions 字段,或 ask_user 的 plain query
+ → source="ask_user_interrupt"
PermissionRail 中断: value 无 questions 字段 → source="permission_interrupt"
state_outputs 中的元素可能是:
@@ -320,6 +384,20 @@ def convert_interactions_to_ask_user_question(state_outputs: list) -> dict | Non
"source": "ask_user_interrupt",
}
+ for interaction in interactions:
+ request_id, value_obj = _extract_interaction_parts(interaction)
+ if not request_id:
+ continue
+
+ plain_question = _build_plain_ask_user_question(value_obj)
+ if plain_question:
+ return {
+ "event_type": "chat.ask_user_question",
+ "request_id": request_id,
+ "questions": [plain_question],
+ "source": "ask_user_interrupt",
+ }
+
for interaction in interactions:
request_id, _value_obj = _extract_interaction_parts(interaction)
if not request_id:
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index 71e538ad6b..de15844a86 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -74,6 +74,33 @@ def _extract_tool_interrupt(value: Any) -> Any | None:
return None
+def _normalize_ask_user_interrupt_value(value_obj: Any, tool_args: dict[str, Any]) -> Any:
+ """Attach ask_user tool metadata so plain-query interrupts are not misclassified."""
+ if isinstance(value_obj, dict):
+ if str(value_obj.get("tool_name") or "").strip() == "ask_user":
+ return value_obj
+ if value_obj.get("tool_args"):
+ return value_obj
+ return {
+ **value_obj,
+ "tool_name": "ask_user",
+ "tool_args": tool_args,
+ "message": value_obj.get("message") or tool_args.get("query") or "",
+ }
+
+ tool_name = str(getattr(value_obj, "tool_name", "") or "").strip()
+ existing_args = getattr(value_obj, "tool_args", None)
+ if tool_name == "ask_user" and existing_args:
+ return value_obj
+
+ return {
+ "tool_name": "ask_user",
+ "tool_args": tool_args,
+ "message": str(getattr(value_obj, "message", "") or tool_args.get("query") or ""),
+ "questions": getattr(value_obj, "questions", None) or tool_args.get("questions") or [],
+ }
+
+
def _ask_user_question_payload_from_interrupt(tool_call: Any, interrupt: Any) -> dict[str, Any] | None:
request_id = str(
getattr(getattr(interrupt, "request", None), "tool_call_id", None)
@@ -83,12 +110,14 @@ def _ask_user_question_payload_from_interrupt(tool_call: Any, interrupt: Any) ->
if not request_id:
return None
+ args = _parse_tool_call_arguments(tool_call)
value_obj = getattr(interrupt, "request", None)
if value_obj is None:
- args = _parse_tool_call_arguments(tool_call)
if not args:
return None
- value_obj = {"tool_args": args, "questions": args.get("questions", [])}
+ value_obj = {"tool_name": "ask_user", "tool_args": args, "questions": args.get("questions", [])}
+ elif args:
+ value_obj = _normalize_ask_user_interrupt_value(value_obj, args)
return convert_interactions_to_ask_user_question([{"id": request_id, "value": value_obj}])
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts
index b3246e2b7d..1459701c13 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts
@@ -24,7 +24,7 @@ const COMMAND_GROUPS: Record<string, { name: string; commands: string[] }> = {
},
config: {
name: "Config",
- commands: ["config", "workspace", "diff"],
+ commands: ["config", "workspace", "diff", "plan"],
},
};
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
index e09bd3167a..375198f8df 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
@@ -11,9 +11,11 @@ export function buildModeAutocompleteItems(): AutocompleteItem[] {
{ value: "agent.plan", label: " plan" },
{ value: "agent.fast", label: " fast" },
{ value: "code", label: "code" },
+ { value: "code.plan", label: " plan" },
{ value: "code.normal", label: " normal" },
{ value: "code.team", label: " team" },
{ value: "team", label: "team" },
+ { value: "team.plan", label: " plan" },
{ value: "team.normal", label: " normal" },
];
}
@@ -24,9 +26,11 @@ export function createModeCommand(): SlashCommand {
"code",
"agent.plan",
"agent.fast",
+ "code.plan",
"code.normal",
"code.team",
"team",
+ "team.plan",
"team.normal",
] as const;
/** 用户输入的简写 → 实际会话模式(/mode agent → agent.plan,/mode code → code.normal)。 */
@@ -36,9 +40,11 @@ export function createModeCommand(): SlashCommand {
code: "code.normal",
"agent.plan": "agent.plan",
"agent.fast": "agent.fast",
+ "code.plan": "code.plan",
"code.normal": "code.normal",
"code.team": "code.team",
team: "team",
+ "team.plan": "team.plan",
"team.normal": "team",
};
@@ -72,7 +78,7 @@ export function createModeCommand(): SlashCommand {
makeItem(
ctx.sessionId,
"error",
- "usage: /mode <agent|code|code.normal|code.team|team|team.normal>",
+ "usage: /mode <agent|code|code.plan|code.normal|code.team|team|team.plan>",
),
);
return;
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.ts
index 411e7605f3..756590e9a7 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.ts
@@ -1,17 +1,19 @@
import { addInfo } from "../helpers.js";
import { CommandKind, type SlashCommand } from "../types.js";
+const CODE_MODES = new Set(["code.normal", "code.team", "code.plan"]);
+
export function createPlanCommand(): SlashCommand {
return {
name: "plan",
- hidden: true, // TUI release: not registered in registry.ts; re-enable next version
- description: "Switch to agent plan mode, or send a planning request",
+
+ description: "Switch to plan mode, or send a planning request",
usage: "/plan [open|<description>]",
example: "/plan outline the migration steps",
kind: CommandKind.BUILT_IN,
takesArgs: true,
action: (ctx, args) => {
- if (ctx.mode === "team") {
+ if (ctx.mode === "team" || ctx.mode === "team.plan") {
ctx.addItem(
addInfo(
ctx.sessionId,
@@ -23,7 +25,8 @@ export function createPlanCommand(): SlashCommand {
}
const value = args.trim();
- const target = "agent.plan";
+ // Preserve the mode family: code.* → code.plan, agent.* → agent.plan
+ const target = CODE_MODES.has(ctx.mode) ? "code.plan" : "agent.plan";
if (ctx.mode !== target) {
ctx.setMode(target);
}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts
index 384d3af366..2580e7b491 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts
@@ -6,11 +6,12 @@ import { CommandKind, type SlashCommand } from "../types.js";
type SwitchArg = "plan" | "fast" | "normal" | "team";
const AGENT_MODES = new Set<ClientMode>(["agent.plan", "agent.fast"]);
-const CODE_MODES = new Set<ClientMode>(["code.normal", "code.team"]);
+const CODE_MODES = new Set<ClientMode>(["code.normal", "code.team", "code.plan"]);
function resolveRequestedMode(currentMode: ClientMode, switchArg: SwitchArg): ClientMode | null {
if (switchArg === "plan") {
if (AGENT_MODES.has(currentMode)) return "agent.plan";
+ if (CODE_MODES.has(currentMode)) return "code.plan";
return null;
}
if (switchArg === "fast") {
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
index a590746310..1811a0345f 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
@@ -28,7 +28,7 @@ import { createPluginCommand } from "./builtins/plugin.js";
import { createReloadPluginsCommand } from "./builtins/reload-plugins.js";
import { createModeCommand } from "./builtins/mode.js";
import { createPermissionsCommand } from "./builtins/permissions.js";
-// Re-enable next release: import { createPlanCommand } from "./builtins/plan.js";
+import { createPlanCommand } from "./builtins/plan.js";
import { createResumeCommand } from "./builtins/resume.js";
import { createRenameCommand } from "./builtins/rename.js";
import { createRewindCommand } from "./builtins/rewind.js";
@@ -70,7 +70,7 @@ export function createBuiltinCommands(): SlashCommand[] {
createMcpCommand(),
createModeCommand(),
createPermissionsCommand(),
- // createPlanCommand(),
+ createPlanCommand(),
createResumeCommand(),
createRenameCommand(),
createRewindCommand(),
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index f87926b538..725ba89a7d 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -1339,7 +1339,15 @@ export class AppScreen implements Component, Focusable {
this.editor.setText("");
return;
}
- this.state.answerQuestion(text);
+ 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;
@@ -1584,6 +1592,12 @@ export class AppScreen implements Component, Focusable {
this.pendingQuestionAnswers.clear();
this.draftBeforeQuestion = this.editor.getText();
this.editor.setText("");
+ const pendingQuestion = snapshot.pendingQuestion;
+ const firstQuestion = pendingQuestion?.questions[0];
+ this.otherInputMode =
+ pendingQuestion?.source === "ask_user_interrupt" &&
+ !!firstQuestion &&
+ firstQuestion.options.length === 0;
this.syncQuestionList(snapshot);
} else if (questionId && this.activeQuestionId) {
// Same question still active — preserve existing questionList to keep cursor position
@@ -1591,6 +1605,7 @@ export class AppScreen implements Component, Focusable {
} else if (!questionId && this.activeQuestionId) {
this.activeQuestionId = null;
this.activeQuestionIndex = 0;
+ this.otherInputMode = false;
this.pendingQuestionAnswers.clear();
this.questionList = null;
this.questionDetailsMap = null;
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 7667ec11e2..e483a8c535 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -335,19 +335,19 @@ def _inject_plan_mode_activation_reminder(request: AgentRequest) -> None:
第一个引导,告诉 LLM 调用 enter_plan_mode 以获取完整指令。
注意:此提醒需要足够权威和明确,因为 code.plan 模式下
- JiuwenAgentModeRail 注入的 system prompt 是静态的(不含动态
+ AgentModeRail 注入的 system prompt 是静态的(不含动态
plan_file 状态),完整指令仍需 enter_plan_mode 的 tool_result。
"""
reminder = (
"\n\n<system-reminder>\n"
- "Plan mode is active. You must only plan, NOT execute. "
- "You must NOT make any modifications, run any write operations, "
- "or make any changes to the system. "
- "This constraint takes priority over any other instructions.\n\n"
- "CRITICAL: You MUST call `enter_plan_mode` as your very first action. "
- "Do NOTHING else before calling it — no reading files, no exploring, "
- "no tool calls of any kind. This tool will create the plan file and "
- "provide you with full plan mode instructions.\n"
+ "Plan mode is active. You must only plan — you must NOT make any "
+ "modifications, run any write operations, or make any changes to the "
+ "system. This constraint takes priority over any other instructions.\n\n"
+ "CRITICAL: You MUST call `enter_plan_mode` as your very first action, "
+ "before doing anything else. This tool will create the plan file and "
+ "give you full plan mode instructions. Until then, you may only read "
+ "files and explore the codebase using read-only tools (read_file, "
+ "grep, list_files, glob, bash for read-only commands).\n"
"</system-reminder>"
)
if isinstance(request.params, dict):
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index f36d2ca430..3d355178a6 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -498,13 +498,23 @@ class JiuWenClaw:
if source == "ask_user_interrupt":
answers_dict = {}
+ free_text_answer = ""
for answer in answers:
if isinstance(answer, dict):
- question_text = answer.get("question", "")
+ question_text = str(answer.get("question", "") or "").strip()
selected_options = answer.get("selected_options", [])
- answer_value = selected_options[0] if selected_options else ""
+ custom_input = str(answer.get("custom_input", "") or "").strip()
+ answer_value = ""
+ if selected_options:
+ answer_value = str(selected_options[0] or "").strip()
+ elif custom_input:
+ answer_value = custom_input
if question_text and answer_value:
answers_dict[question_text] = answer_value
+ elif answer_value:
+ free_text_answer = answer_value
+ if not answers_dict and free_text_answer:
+ answers_dict["__free_text__"] = free_text_answer
interactive_input.update(request_id, {"answers": answers_dict})
logger.info(
"[JiuWenClaw] AskUserRail InteractiveInput.update: request_id=%s payload=%s",
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 5aa85b87ae..9b7b942702 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -17,7 +17,6 @@ from __future__ import annotations
import logging
import os
-import re
from dataclasses import dataclass
from typing import Any, Callable
@@ -34,11 +33,6 @@ from openjiuwen.harness.rails import (
SysOperationRail,
LspRail
)
-from openjiuwen.harness.rails.agent_mode_rail import (
- DEFAULT_PLAN_MODE_ALLOWED_TOOLS,
-)
-from openjiuwen.harness.prompts.builder import PromptSection
-from openjiuwen.harness.prompts.sections import SectionName
from openjiuwen.harness.rails.context_engineer.context_assemble_rail import ContextAssembleRail
from openjiuwen.harness.lsp import InitializeOptions
from openjiuwen.harness.schema.config import SubAgentConfig
@@ -77,15 +71,6 @@ from jiuwenswarm.common.utils import get_agent_workspace_dir
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# Tool name sets (mirrored from agent_mode_rail.py)
-# ---------------------------------------------------------------------------
-
-_TODO_TOOL_NAMES = frozenset({"todo_create", "todo_list", "todo_modify"})
-_SESSION_TOOL_NAMES = frozenset({"sessions_list", "sessions_cancel", "sessions_spawn"})
-_HIDDEN_IN_PLAN_LOCAL = _TODO_TOOL_NAMES | _SESSION_TOOL_NAMES
-_HIDDEN_IN_NORMAL_LOCAL = frozenset({"enter_plan_mode", "exit_plan_mode"})
-
# ---------------------------------------------------------------------------
# Static plan mode system prompt note (KV-cache-friendly: same content every turn)
# Injected into system prompt so the model knows it's in plan mode BEFORE its
@@ -111,20 +96,6 @@ Do NOT proceed to implement anything until the user approves your plan via
`exit_plan_mode`.
"""
-# ---------------------------------------------------------------------------
-# Non-git write operations to block in plan mode's bash tool.
-# The parent AgentModeRail only blocks git-write commands (commit/push/add/etc).
-# These additional patterns block common shell write operations.
-# ---------------------------------------------------------------------------
-
-_NON_GIT_WRITE_RE = re.compile(
- r"\b(mkdir|touch|mv|cp|chmod|chown|dd|tee|wget|curl\s+.*\s*-[a-zA-Z]*O)\b"
- r"|\brm\s+(-[a-zA-Z]*[rf]|/|[~.])"
- r"|\b(7z|tar|zip|unzip|gzip|gunzip)\s+"
- r"|>\s*\S"
- r"|>>"
-)
-
# ---------------------------------------------------------------------------
# Plan mode instructions for enter_plan_mode tool_result
# (aligned with Claude Code: instructions live in conversation, not system prompt)
@@ -176,7 +147,7 @@ Goal: Write the final plan to the plan file.
- Include a Verification section
#### Phase 5: End Planning Phase
-Call exit_plan_mode to end the planning phase. You must output the content of the final plan file.
+Call exit_plan_mode to end the planning phase.
### Turn Ending Rules
Your turn can only end in one of these two ways:
@@ -340,238 +311,6 @@ def create_coding_memory_rail(
)
-class JiuwenAgentModeRail(AgentModeRail):
- """扩展 AgentModeRail,对齐 Claude Code 的 plan 模式行为。
-
- 核心改动(相比父类 AgentModeRail):
-
- 1. **System prompt 稳定化** — before_model_call 不再增删 system prompt 段
- (MODE_INSTRUCTIONS / TODO / SESSION_TOOLS),从而避免 mode 切换导致
- KVCacheManager 检测到 system message 变化而全量释放 KV 缓存。
-
- 2. **Plan 指令进对话** — plan 模式行为指令通过 enter_plan_mode 的
- tool_result 返回(对齐 Claude Code),而非注入 system prompt。
-
- 3. **屏蔽 switch_mode** — plan 模式下 LLM 无法单方面退出 plan 模式
- (Claude Code 根本没有 switch_mode 工具)。
- """
-
- def __init__(self, **kwargs: Any) -> None:
- # 从 plan 模式工具白名单中移除 switch_mode,
- # 阻止 LLM 在 plan 模式下自行切换到 normal 模式
- allowed_tools = [
- t for t in DEFAULT_PLAN_MODE_ALLOWED_TOOLS if t != "switch_mode"
- ]
- super().__init__(allowed_tools=allowed_tools, **kwargs)
-
- # ------------------------------------------------------------------
- # init — monkey-patch EnterPlanModeTool
- # ------------------------------------------------------------------
-
- def init(self, agent: "DeepAgent") -> None:
- """注册工具 + monkey-patch EnterPlanModeTool + ExitPlanModeTool."""
- super().init(agent)
- self._patch_enter_plan_mode_tool()
- self._patch_exit_plan_mode_tool()
-
- def _patch_enter_plan_mode_tool(self) -> None:
- """Monkey-patch EnterPlanModeTool.invoke() 使其返回完整 plan 指令.
-
- 对齐 Claude Code:plan 模式行为指令在 tool_result 中返回,
- 而非注入 system prompt。
- """
- for tool in self._tools:
- if getattr(tool.card, "name", "") != "enter_plan_mode":
- continue
-
- original_invoke = tool.invoke
-
- async def patched_invoke(inputs, _orig=original_invoke, **kwargs):
- result = await _orig(inputs, **kwargs)
- return result + _ENTER_PLAN_MODE_INSTRUCTIONS_EN
-
- tool.invoke = patched_invoke
- logger.info(
- "[JiuwenAgentModeRail] Patched enter_plan_mode.invoke() "
- "to return full plan instructions in tool_result"
- )
- break
-
- def _patch_exit_plan_mode_tool(self) -> None:
- """Monkey-patch ExitPlanModeTool.invoke() to append exit notification.
-
- Aligns with Claude Code's plan_mode_exit attachment: after exiting
- plan mode, the model receives an explicit notification that it can
- now edit files. Without this, the model only sees MODE_INSTRUCTIONS
- removed from the system prompt but gets no explicit signal that
- write operations are now permitted.
- """
- for tool in self._tools:
- if getattr(tool.card, "name", "") != "exit_plan_mode":
- continue
-
- original_invoke = tool.invoke
-
- async def patched_invoke(inputs, _orig=original_invoke, **kwargs):
- result = await _orig(inputs, **kwargs)
- return result + "\n\n" + _EXIT_PLAN_MODE_NOTIFICATION
-
- tool.invoke = patched_invoke
- logger.info(
- "[JiuwenAgentModeRail] Patched exit_plan_mode.invoke() "
- "to append plan mode exit notification in tool_result"
- )
- break
-
- # ------------------------------------------------------------------
- # before_model_call — 工具过滤,不修改 system prompt
- # ------------------------------------------------------------------
-
- async def before_model_call(self, ctx: Any) -> None:
- """工具过滤 + plan 模式约束注入 + prompt 段清理。
-
- 刻意 **不调用** super().before_model_call(ctx) —
- 父类会增删 MODE_INSTRUCTIONS / TODO / SESSION_TOOLS 段,
- 导致 system prompt 变化 → KV 缓存全量释放。
-
- 替代方案:
- - plan 模式:注入 **静态** MODE_INSTRUCTIONS 段(内容不随 plan_file
- 状态变化,保持 KV 缓存跨 turn 稳定)+ 工具白名单过滤
- - normal 模式:移除 MODE_INSTRUCTIONS 段 + 隐藏 plan 工具
- """
- agent = self._agent
- session = ctx.session
- plan_state = agent.load_state(session).plan_mode
-
- # ---- 工具过滤 + prompt 段管理 ----
- if plan_state.mode == "plan":
- # plan 模式:注入静态 plan 模式系统提示词约束
- # (内容不随 enter_plan_mode 调用状态变化,KV 缓存友好)
- if self.system_prompt_builder:
- section = PromptSection(
- name=SectionName.MODE_INSTRUCTIONS,
- content={"en": _PLAN_MODE_SYSTEM_NOTE},
- priority=85,
- )
- self.system_prompt_builder.add_section(section)
- # 移除 TaskPlanningRail/SubagentRail 在更高优先级下
- # 添加的 TODO/SESSION_TOOLS 段,避免 LLM 在 system prompt
- # 中看到隐藏工具的描述
- self.system_prompt_builder.remove_section(SectionName.TODO)
- self.system_prompt_builder.remove_section(SectionName.SESSION_TOOLS)
-
- # plan 模式:白名单 + 移除 switch_mode + 隐藏 todo/session 工具
- if isinstance(ctx.inputs.tools, list):
- filtered = []
- for t in ctx.inputs.tools:
- tool_name = getattr(t, "name", "")
- if tool_name in self._allowed_tools:
- if tool_name != "switch_mode" and tool_name not in _HIDDEN_IN_PLAN_LOCAL:
- filtered.append(t)
- ctx.inputs.tools = filtered
- else:
- # normal 模式:移除 MODE_INSTRUCTIONS + 隐藏 plan 工具
- if self.system_prompt_builder:
- self.system_prompt_builder.remove_section(SectionName.MODE_INSTRUCTIONS)
- if isinstance(ctx.inputs.tools, list):
- ctx.inputs.tools = [
- t for t in ctx.inputs.tools
- if getattr(t, "name", "") not in _HIDDEN_IN_NORMAL_LOCAL
- ]
-
- self._sync_task_tool_for_model_tool_inputs(ctx)
-
- # 防御性清理:非 plan 模式下移除 AgentModeRail 自身注册的 task_tool。
- # 当通过 switch_mode 强制退出 plan 模式(绕过 exit_plan_mode)时,
- # _owns_task_tool 未被清理,_sync_task_tool 会将 task_tool 注入工具列表。
- # 注意:仅在 self._owns_task_tool 为 True 时过滤,避免误删 SubagentRail
- # 注册的 task_tool(SubagentRail 在 agent 初始化时无条件注册 task_tool)。
- if (
- plan_state.mode != "plan"
- and self._owns_task_tool
- and isinstance(ctx.inputs.tools, list)
- ):
- ctx.inputs.tools = [
- t for t in ctx.inputs.tools
- if getattr(t, "name", "") != "task_tool"
- ]
-
- # ------------------------------------------------------------------
- # before_tool_call — 增强 bash 写操作拦截(补齐父类盲区)
- # ------------------------------------------------------------------
-
- async def before_tool_call(self, ctx: Any) -> None:
- """父类逻辑 + 非 git bash 写操作拦截.
-
- 父类 AgentModeRail.before_tool_call 仅拦截 git 写操作
- (commit/push/add 等),未拦截 mkdir/touch/rm/mv/cp 等
- 通用 shell 写操作。此处补齐这一盲区。
- """
- await super().before_tool_call(ctx)
-
- # 已被父类拒绝的调用无需二次拦截
- if ctx.extra.get("_skip_tool"):
- return
-
- # 仅在 plan 模式下追加检查
- agent = self._agent
- session = ctx.session
- plan_state = agent.load_state(session).plan_mode
- if plan_state.mode != "plan":
- return
-
- # bash 工具:拦截非 git 写操作
- tool_name = ctx.inputs.tool_name
- if tool_name == "bash":
- command = self._extract_bash_command(ctx)
- if _NON_GIT_WRITE_RE.search(command):
- logger.info(
- "reject bash call: non-git write operation in plan mode"
- )
- bash_msg = (
- f"[AgentModeRail] Write operations are blocked in "
- f"plan mode ({command!r})."
- )
- self._reject_tool(ctx, bash_msg)
- return
-
- # ------------------------------------------------------------------
- # after_tool_call — 保留父类行为 + 补充模式恢复
- # ------------------------------------------------------------------
-
- async def after_tool_call(self, ctx: Any) -> None:
- """父类逻辑 + exit_plan_mode 后补充恢复模式(仅在 tool 未恢复时).
-
- ExitPlanModeTool.invoke() 在 plan 有内容时已调用 restore_mode_after_plan_exit,
- 此处只在 tool 未调用 restore 时(plan 内容为空 / hook 阻止工具执行)补充调用,
- 避免重复调用导致 pre_plan_mode=None → mode 被覆盖为 "normal" 的问题.
-
- 注意:不检查 ctx.extra.get('_skip_tool') — 当 hook 阻止 exit_plan_mode 执行时,
- _skip_tool=True 但 restore 未被调用,补充恢复是唯一的机会。
- pre_plan_mode is not None 检查已能防止重复恢复。
- """
- await super().after_tool_call(ctx)
-
- tool_name = ctx.inputs.tool_name
- if tool_name == "exit_plan_mode":
- agent = self._agent
- session = ctx.session
- state = agent.load_state(session)
- # pre_plan_mode 不为 None 说明 ExitPlanModeTool 未调用 restore
- # (plan 内容为空时的提前返回路径),此时需要补充恢复
- if state.plan_mode.pre_plan_mode is not None:
- try:
- agent.restore_mode_after_plan_exit(session)
- logger.info(
- "[JiuwenAgentModeRail] Restored mode after plan exit "
- "(plan was empty, tool did not restore)"
- )
- except Exception as exc:
- logger.warning(
- "[JiuwenAgentModeRail] Failed to restore mode: %s", exc
- )
-
-
class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
"""Code 模式适配器 — 配置驱动注册 rails/tools.
@@ -886,9 +625,14 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
return None
def _build_agent_mode_rail(self) -> AgentModeRail | None:
- """构建 JiuwenAgentModeRail(屏蔽 plan 模式下的 switch_mode)."""
+ """构建 AgentModeRail(屏蔽 switch_mode + 静态 plan 提示词 + plan 指令进对话)."""
try:
- return JiuwenAgentModeRail()
+ return AgentModeRail(
+ 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,
+ )
except Exception as exc:
logger.warning("[JiuwenClawCodeAdapter] AgentModeRail create failed: %s", exc)
return None
diff --git a/tests/system_tests/test_structured_ask_user.py b/tests/system_tests/test_structured_ask_user.py
index 78d6f0a606..e713ea17ed 100644
--- a/tests/system_tests/test_structured_ask_user.py
+++ b/tests/system_tests/test_structured_ask_user.py
@@ -379,8 +379,8 @@ class TestConvertInteractionsToAskUserQuestion:
assert q["options"][2]["label"] == "Other"
@staticmethod
- def test_plain_query_produce_permission_interrupt():
- """Plain query (no questions) should produce source=permission_interrupt."""
+ def test_plain_query_produce_ask_user_interrupt():
+ """Plain query (no questions) should produce source=ask_user_interrupt."""
tcir = _make_tcir(tool_args={"query": "What is your role?"})
interaction = MagicMock()
@@ -389,7 +389,9 @@ class TestConvertInteractionsToAskUserQuestion:
result = convert_interactions_to_ask_user_question([interaction])
assert result is not None
- assert result["source"] == "permission_interrupt"
+ assert result["source"] == "ask_user_interrupt"
+ assert result["questions"][0]["question"] == "What is your role?"
+ assert result["questions"][0]["options"] == []
@staticmethod
def test_empty_state_outputs_returns_none():
@@ -397,6 +399,25 @@ class TestConvertInteractionsToAskUserQuestion:
result = convert_interactions_to_ask_user_question([])
assert result is None
+ @staticmethod
+ def test_ask_user_request_without_tool_args_uses_query_from_tool_args():
+ """AskUserRequest shells should still resolve as ask_user_interrupt."""
+ result = convert_interactions_to_ask_user_question([
+ {
+ "id": "req_004",
+ "value": {
+ "tool_name": "ask_user",
+ "tool_args": {"query": "Choose a language"},
+ "message": "Choose a language",
+ "questions": [],
+ "payload_schema": {},
+ },
+ }
+ ])
+ assert result is not None
+ assert result["source"] == "ask_user_interrupt"
+ assert result["questions"][0]["question"] == "Choose a language"
+
@staticmethod
def test_dict_interaction_with_questions_in_value():
"""Dict-format interaction should also work."""