Skip to content

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

Python

fix: add StructuredAskUserTool for interacting with users

ldstyle8495d07fbf67f
diff --git a/.gitignore b/.gitignore
index 515234b470..6b9a91aa8c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -49,6 +49,7 @@ pnpm-debug.log*
**/CLAUDE.local.md
**/JIUWENCLAW.local.md
**/JIUWENCLAW.md
+.jiuwen/settings.local.json
workspace/agent-data.json
# reference
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_code.py b/jiuwenclaw/agentserver/deep_agent/interface_code.py
index 42f1f5b8e7..f2cfc300f4 100644
--- a/jiuwenclaw/agentserver/deep_agent/interface_code.py
+++ b/jiuwenclaw/agentserver/deep_agent/interface_code.py
@@ -26,25 +26,16 @@ from openjiuwen.core.runner import Runner
from openjiuwen.core.single_agent import AgentCard
from openjiuwen.harness import DeepAgent
from openjiuwen.harness.factory import create_deep_agent
-from openjiuwen.harness.prompts import resolve_language
from openjiuwen.harness.rails import (
AgentModeRail,
- AskUserRail,
ConfirmInterruptRail,
- SkillUseRail,
- SkillEvolutionRail,
- SecurityRail,
- TaskPlanningRail,
)
from openjiuwen.harness.rails.coding_memory_rail import CodingMemoryRail
from openjiuwen.harness.rails.context_engineer.context_assemble_rail import ContextAssembleRail
from openjiuwen.harness.rails.context_engineer.context_processor_rail import ContextProcessorRail
from openjiuwen.harness.rails.filesystem_rail import FileSystemRail
-from openjiuwen.harness.rails.heartbeat_rail import HeartbeatRail
from openjiuwen.harness.lsp import InitializeOptions
from openjiuwen.harness.rails.lsp_rail import LspRail
-from openjiuwen.harness.rails.memory_rail import MemoryRail
-from openjiuwen.harness.rails.subagent_rail import SubagentRail
from openjiuwen.harness.schema.config import SubAgentConfig
from openjiuwen.harness.subagents.browser_agent import build_browser_agent_config
from openjiuwen.harness.subagents.code_agent import build_code_agent_config
@@ -61,6 +52,7 @@ from jiuwenclaw.agentserver.deep_agent.interrupt.interrupt_helpers import build_
from jiuwenclaw.agentserver.deep_agent.prompt_builder import build_identity_prompt
from jiuwenclaw.agentserver.deep_agent.rails import (
ProjectMemoryRail,
+ StructuredAskUserRail,
)
from jiuwenclaw.agentserver.memory.config import get_memory_mode
from jiuwenclaw.agentserver.permissions.core import init_permission_engine
@@ -113,12 +105,14 @@ def _append_explore_and_plan_subagents(
subagents: list[SubAgentConfig | DeepAgent],
resolved_language: str,
model: Model,
+ workspace: str | None = None,
) -> list[SubAgentConfig | DeepAgent]:
effective = list(subagents)
if not _subagent_list_has_name(effective, "explore_agent"):
effective.append(
build_explore_agent_config(
model=model,
+ workspace=workspace,
language=resolved_language,
max_iterations=25,
)
@@ -127,6 +121,7 @@ def _append_explore_and_plan_subagents(
effective.append(
build_plan_agent_config(
model=model,
+ workspace=workspace,
language=resolved_language,
max_iterations=25,
)
@@ -170,7 +165,9 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
self._agent_name = self._instance_overrides.get(
"agent_name", config.get("agent_name", "main_agent")
)
- self._project_dir = config.get("workspace_dir")
+ self._project_dir = self._instance_overrides.get(
+ "workspace_dir", config.get("workspace_dir")
+ )
model = self._create_model(config_base)
agent_card = AgentCard(name=self._agent_name, id='jiuwenclaw')
@@ -197,6 +194,7 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
raw_subagents,
resolved_language=self._resolve_runtime_language(),
model=model,
+ workspace=self._project_dir or self._workspace_dir or "./",
)
self._instance = create_deep_agent(
@@ -283,7 +281,7 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
),
_RailBuildInfo("_code_filesystem_rail", FileSystemRail, {}),
_RailBuildInfo("_code_agent_mode_rail", AgentModeRail, {}),
- _RailBuildInfo("_code_ask_user_rail", AskUserRail, {}),
+ _RailBuildInfo("_code_ask_user_rail", StructuredAskUserRail, {}),
_RailBuildInfo(
"_code_confirm_interrupt_rail",
ConfirmInterruptRail,
diff --git a/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.py b/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.py
index f5938bafb2..3800632b2f 100644
--- a/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.py
+++ b/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.py
@@ -7,6 +7,7 @@ and building permission rails.
"""
from __future__ import annotations
+import json
from typing import Any
from jiuwenclaw.agentserver.permissions.checker import collect_permission_rail_tool_names
@@ -122,8 +123,12 @@ def _extract_questions_from_value(value_obj: Any) -> list | None:
AskUserRail 的 value (ToolCallInterruptRequest) 有 questions 属性.
如果 questions 存在且非空, 返回列表; 否则返回 None 表示不是 AskUserRail 中断.
+
+ Additional source: StructuredAskUserRail puts `questions` in the tool call
+ arguments, which are preserved in ToolCallInterruptRequest.tool_args.
"""
- if hasattr(value_obj, "questions"):
+ # 1. Direct questions attribute on value_obj
+ if hasattr(value_obj, 'questions'):
qs = value_obj.questions
if qs and len(qs) > 0:
return qs
@@ -131,6 +136,22 @@ def _extract_questions_from_value(value_obj: Any) -> list | None:
qs = value_obj.get("questions", [])
if qs and len(qs) > 0:
return qs
+
+ # 2. questions embedded in tool_args (StructuredAskUserRail path)
+ # ToolCallInterruptRequest.tool_args preserves the original tool call
+ # arguments, including the `questions` parameter.
+ tool_args = getattr(value_obj, 'tool_args', None)
+ if tool_args is not None:
+ if isinstance(tool_args, str):
+ try:
+ tool_args = json.loads(tool_args)
+ except (ValueError, TypeError):
+ pass
+ if isinstance(tool_args, dict):
+ qs = tool_args.get("questions", [])
+ if qs and len(qs) > 0:
+ return qs
+
return None
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/__init__.py b/jiuwenclaw/agentserver/deep_agent/rails/__init__.py
index f6bd3b3f85..5615e8c06d 100644
--- a/jiuwenclaw/agentserver/deep_agent/rails/__init__.py
+++ b/jiuwenclaw/agentserver/deep_agent/rails/__init__.py
@@ -10,6 +10,7 @@ from jiuwenclaw.agentserver.deep_agent.rails.runtime_prompt_rail import RuntimeP
from jiuwenclaw.agentserver.deep_agent.rails.team_member_skill_toolkit_rail import (
MemberSkillToolkitRail,
)
+from jiuwenclaw.agentserver.deep_agent.rails.ask_user_rail import StructuredAskUserRail
from jiuwenclaw.agentserver.deep_agent.rails.stream_event_rail import JiuClawStreamEventRail
__all__ = [
@@ -20,4 +21,5 @@ __all__ = [
"ResponsePromptRail",
"RuntimePromptRail",
"MemberSkillToolkitRail",
+ "StructuredAskUserRail",
]
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/ask_user_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/ask_user_rail.py
new file mode 100644
index 0000000000..431a07d4d0
--- /dev/null
+++ b/jiuwenclaw/agentserver/deep_agent/rails/ask_user_rail.py
@@ -0,0 +1,358 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Extended AskUserRail that supports structured questions with options.
+
+The upstream AskUserRail (from openjiuwen) only accepts a plain `query` string.
+This subclass extends the `ask_user` tool schema with an optional `questions`
+parameter, allowing the LLM to present multi-choice options to the user.
+
+When `questions` is provided, the interrupt payload includes structured
+question data that the frontend TUI renders as clickable options instead
+of a free-text input box.
+
+The key mechanism: ToolCallInterruptRequest.tool_args preserves the original
+tool call arguments (including `questions`). The interrupt_helpers pipeline
+extracts questions from tool_args so the frontend can render them.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import uuid
+from typing import Any, Iterable, Mapping, Optional
+
+from pydantic import BaseModel, Field
+
+from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall
+from openjiuwen.core.foundation.tool import Tool
+from openjiuwen.core.foundation.tool.base import ToolCard
+from openjiuwen.core.single_agent.interrupt import InterruptRequest
+from openjiuwen.core.single_agent.rail import AgentCallbackContext
+from openjiuwen.harness.prompts import resolve_language
+from openjiuwen.harness.rails.interrupt.ask_user_rail import (
+ AskUserPayload,
+ AskUserRail,
+)
+from openjiuwen.harness.rails.interrupt.interrupt_base import (
+ InterruptDecision,
+)
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Extended input schema
+# ---------------------------------------------------------------------------
+
+_QUESTIONS_ITEM_SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "question": {
+ "type": "string",
+ "description": "The question to present to the user.",
+ },
+ "header": {
+ "type": "string",
+ "description": "A short label displayed as a chip/tag (max 12 chars).",
+ },
+ "options": {
+ "type": "array",
+ "description": "Available choices for this question (2-4 items).",
+ "items": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "type": "string",
+ "description": "Display text for this option (1-5 words).",
+ },
+ "description": {
+ "type": "string",
+ "description": "Explanation of what this option means.",
+ },
+ },
+ "required": ["label"],
+ },
+ },
+ "multi_select": {
+ "type": "boolean",
+ "default": False,
+ "description": "Allow multiple selections instead of just one.",
+ },
+ },
+ "required": ["question"],
+}
+
+EXTENDED_INPUT_PARAMS_EN: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "The question to present to the user (required).",
+ },
+ "questions": {
+ "type": "array",
+ "description": (
+ "Structured questions with selectable options. "
+ "Use this when you want the user to choose from predefined options "
+ "instead of typing free text. Each question must have 2-4 options. "
+ "The user can always select 'Other' for custom input."
+ ),
+ "items": _QUESTIONS_ITEM_SCHEMA,
+ },
+ },
+ "required": ["query"],
+}
+
+EXTENDED_INPUT_PARAMS_CN: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "向用户展示的问题(必填)。",
+ },
+ "questions": {
+ "type": "array",
+ "description": (
+ "带选项的结构化问题。当希望用户从预定义选项中选择而非自由输入时使用。"
+ "每个问题必须提供 2-4 个选项。用户始终可以选择「其他」进行自定义输入。"
+ ),
+ "items": _QUESTIONS_ITEM_SCHEMA,
+ },
+ },
+ "required": ["query"],
+}
+
+_EXTENDED_DESCRIPTION_EN: str = (
+ "Interrupts execution and requests input from the user. "
+ "Supports two modes:\n"
+ "1. Plain query (free-text): pass only `query` — the user types their answer.\n"
+ "2. Structured questions (multi-choice): pass `query` + `questions` — "
+ "the user selects from predefined options. "
+ "Use `questions` when you want the user to choose between specific options "
+ "(e.g., 'Apply update' vs 'Skip'). Each question can have 2-4 options."
+)
+
+_EXTENDED_DESCRIPTION_CN: str = (
+ "中断执行并向用户请求输入。支持两种模式:\n"
+ "1. 纯文本查询:只传 `query` —— 用户自由输入回答。\n"
+ "2. 结构化选项:传 `query` + `questions` —— 用户从预定义选项中选择。"
+ "当你希望用户在特定选项间做选择时(如「应用更新」vs「跳过」)使用 `questions`。"
+ "每个问题可提供 2-4 个选项。"
+)
+
+# ---------------------------------------------------------------------------
+# Structured answer payload
+# ---------------------------------------------------------------------------
+
+
+class StructuredAskUserPayload(BaseModel):
+ """Payload for structured user answers."""
+
+ answers: dict[str, str] = Field(
+ default_factory=dict,
+ description="Mapping of question text to selected option label.",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Extended AskUserTool
+# ---------------------------------------------------------------------------
+
+
+class StructuredAskUserTool(Tool):
+ """AskUser tool with extended schema supporting structured questions."""
+
+ def __init__(self, language: str = "cn", agent_id: Optional[str] = None):
+ input_params = (
+ EXTENDED_INPUT_PARAMS_EN
+ if language == "en"
+ else EXTENDED_INPUT_PARAMS_CN
+ )
+ description = (
+ _EXTENDED_DESCRIPTION_EN if language == "en" else _EXTENDED_DESCRIPTION_CN
+ )
+ final_tool_id = (
+ f"ask_user_{agent_id}" if agent_id else f"ask_user_{uuid.uuid4().hex}"
+ )
+ card = ToolCard(
+ id=final_tool_id,
+ name="ask_user",
+ description=description,
+ input_params=input_params,
+ )
+ super().__init__(card)
+
+ async def invoke(self, query, questions=None, **kwargs):
+ return {}
+
+ async def stream(self, query, questions=None, **kwargs):
+ yield {}
+
+
+# ---------------------------------------------------------------------------
+# StructuredAskUserRail
+# ---------------------------------------------------------------------------
+
+
+class StructuredAskUserRail(AskUserRail):
+ """Extended AskUserRail that supports structured questions with options.
+
+ When the LLM calls `ask_user` with a `questions` parameter, this rail
+ injects the structured question data into the interrupt payload so the
+ frontend TUI can render clickable options instead of a free-text input.
+
+ The mechanism relies on ToolCallInterruptRequest.tool_args preserving
+ the original tool call arguments. interrupt_helpers._extract_questions_from_value()
+ checks tool_args for a `questions` field and converts it to frontend format.
+ """
+
+ def __init__(
+ self,
+ tool_names: Optional[Iterable[str]] = None,
+ ):
+ super().__init__(tool_names=tool_names)
+ self._structured_tools: list[StructuredAskUserTool] = []
+
+ def init(self, agent):
+ """Register the extended ask_user tool with structured questions schema."""
+ language = resolve_language()
+ agent_id = getattr(getattr(agent, "card", None), "id", None)
+ tool = StructuredAskUserTool(language=language, agent_id=agent_id)
+ self._structured_tools = [tool]
+
+ from openjiuwen.core.runner.runner import Runner
+ Runner.resource_mgr.add_tool(self._structured_tools)
+
+ for tool in self._structured_tools:
+ agent.ability_manager.add(tool.card)
+
+ def uninit(self, agent):
+ """Remove the extended ask_user tool."""
+ for tool in self._structured_tools:
+ name = getattr(tool.card, "name", None)
+ if name and hasattr(agent, "ability_manager"):
+ agent.ability_manager.remove(name)
+
+ tool_id = tool.card.id
+ if tool_id:
+ from openjiuwen.core.runner.runner import Runner
+ Runner.resource_mgr.remove_tool(tool_id)
+ self._structured_tools = []
+
+ def get_structured_tools(self) -> list[StructuredAskUserTool]:
+ """Return the list of registered structured tools."""
+ return self._structured_tools
+
+ async def resolve_interrupt(
+ self,
+ ctx: AgentCallbackContext,
+ tool_call: Optional[ToolCall],
+ user_input: Optional[Any],
+ auto_confirm_config: Optional[dict] = None,
+ ) -> InterruptDecision:
+ """Handle interrupt resolution with structured answer support.
+
+ For structured questions: user_input contains a dict with an `answers`
+ key mapping question text → selected option label. We convert this to
+ a rejection with the answer text.
+
+ For plain query: delegate to parent class behavior (AskUserPayload).
+ """
+ if user_input is None:
+ return self.interrupt(self._build_ask_request(tool_call))
+
+ # Detect if this was a structured questions call by checking tool_args
+ questions_data = self.extract_questions(tool_call)
+ is_structured = questions_data is not None and len(questions_data) > 0
+
+ if is_structured:
+ try:
+ if isinstance(user_input, StructuredAskUserPayload):
+ payload = user_input
+ elif isinstance(user_input, dict):
+ if "answers" in user_input:
+ payload = StructuredAskUserPayload(
+ answers=user_input.get("answers", {}),
+ )
+ else:
+ # Frontend sends answers as {question: selected_option}
+ payload = StructuredAskUserPayload(answers=user_input)
+ elif isinstance(user_input, AskUserPayload):
+ # Upstream AskUserPayload changed: answer (str) → answers (dict)
+ free_text = getattr(user_input, "answer", None)
+ if free_text is not None:
+ payload = StructuredAskUserPayload(
+ answers={"__free_text__": free_text},
+ )
+ else:
+ payload = StructuredAskUserPayload(
+ answers=user_input.answers,
+ )
+ elif isinstance(user_input, str):
+ payload = StructuredAskUserPayload(
+ answers={"__free_text__": user_input},
+ )
+ else:
+ return self.interrupt(self._build_ask_request(tool_call))
+
+ # Format answer as readable text for the LLM
+ answer_parts = []
+ for q_text, selected in payload.answers.items():
+ if q_text == "__free_text__":
+ answer_parts.append(selected)
+ else:
+ answer_parts.append(f"{q_text}: {selected}")
+ answer_text = "\n".join(answer_parts) if answer_parts else ""
+ logger.info(
+ "[StructuredAskUserRail] Resolved structured answer: %s",
+ answer_text,
+ )
+ return self.reject(tool_result=answer_text)
+
+ except Exception as exc:
+ logger.warning(
+ "[StructuredAskUserRail] Failed to parse structured answer: %s, "
+ "falling back to interrupt",
+ exc,
+ )
+ return self.interrupt(self._build_ask_request(tool_call))
+
+ # Plain query — delegate to parent which handles AskUserPayload.answers
+ if isinstance(user_input, AskUserPayload):
+ return await super().resolve_interrupt(
+ ctx, tool_call, user_input, auto_confirm_config
+ )
+ elif isinstance(user_input, str):
+ return self.reject(tool_result=user_input)
+ return await super().resolve_interrupt(
+ ctx, tool_call, user_input, auto_confirm_config
+ )
+
+ def _build_ask_request(self, tool_call: Optional[ToolCall]) -> InterruptRequest:
+ """Build interrupt request. For structured questions, the questions data
+ flows through ToolCallInterruptRequest.tool_args (preserved by the
+ interrupt handler). No need to attach questions to InterruptRequest
+ itself since from_tool_call() doesn't copy extra fields."""
+ request = super()._build_ask_request(tool_call)
+ return request
+
+ def extract_questions(
+ self, tool_call: Optional[ToolCall]
+ ) -> Optional[list[dict]]:
+ """Extract questions data from tool call arguments."""
+ if tool_call is None:
+ return None
+
+ args = tool_call.arguments
+ if isinstance(args, str):
+ try:
+ args = json.loads(args)
+ except (ValueError, TypeError):
+ return None
+
+ if isinstance(args, Mapping):
+ questions = args.get("questions")
+ if questions and isinstance(questions, list) and len(questions) > 0:
+ return questions
+
+ return None
\ No newline at end of file
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index dbe7835510..6bda831759 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -590,7 +590,18 @@ class GatewayServer:
if session_key is not None:
self._session_to_client[session_key] = ws
- mode = Mode.from_raw(params.get("mode"), default=Mode.AGENT_PLAN)
+ default_mode = Mode.CODE_NORMAL if route.channel_id == "tui" else Mode.AGENT_PLAN
+ mode = Mode.from_raw(params.get("mode"), default=default_mode)
+
+ # 确保 mode 被设置到 params 中,以便后续转发到 AgentServer
+ params = dict(params)
+ params.setdefault("mode", mode.value)
+
+ # 从 params 中提取 cwd,注入到 metadata 中以便 message_handler 解析 @file 引用
+ metadata = {"method": method}
+ cwd = params.get("cwd")
+ if cwd and isinstance(cwd, str) and cwd.strip():
+ metadata["cwd"] = cwd.strip()
msg = Message(
id=req_id,
@@ -602,7 +613,7 @@ class GatewayServer:
ok=True,
req_method=req_method,
mode=mode,
- metadata={"method": method},
+ metadata=metadata,
)
if self._on_message_cb is not None:
diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.py
index a6fc3c5090..be897b3755 100644
--- a/jiuwenclaw/channel/cli_channel.py
+++ b/jiuwenclaw/channel/cli_channel.py
@@ -700,7 +700,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
session_id=target,
channel_id="tui",
title=str(params.get("title") or "").strip(),
- mode=params.get("mode", "unknown"),
+ mode=params.get("mode", "code.normal"),
)
await channel.send_response(ws, req_id, ok=True, payload={"session_id": target})
diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.ts
index d9b8311249..d33e021565 100644
--- a/jiuwenclaw/cli/src/app-state.ts
+++ b/jiuwenclaw/cli/src/app-state.ts
@@ -94,7 +94,7 @@ export class CliPiAppState {
private sessionId: string;
private sessionTitle: string = "";
private mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team" =
- "agent.plan";
+ "code.normal";
private themeName: ThemeName = getCurrentThemeName();
private accentColor: AccentColorName = getCurrentAccentColor();
private transcriptMode: "compact" | "detailed" = "compact";
@@ -417,7 +417,7 @@ export class CliPiAppState {
setTrustedDir: setTrustedDir,
removeTrustedDir: removeTrustedDir,
clearTrustedDirs: clearTrustedDirs,
- getWorkspaceDir: () => process.cwd(),
+ getWorkspaceDir: () => getTrustedDirs()[0] || process.cwd(),
enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.
};
}
@@ -425,6 +425,7 @@ export class CliPiAppState {
readonly sendEventOnly = (method: string, params: Record<string, unknown>): string => {
const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;
const trustedDirs = getTrustedDirs();
+ const workspaceDir = trustedDirs[0] || process.cwd();
this.wsClient.send({
type: "req",
id,
@@ -433,6 +434,7 @@ export class CliPiAppState {
...params,
session_id: (params.session_id as string | undefined) ?? this.sessionId,
...(trustedDirs.length > 0 ? { trusted_dirs: trustedDirs } : {}),
+ ...(workspaceDir ? { cwd: workspaceDir } : {}),
},
});
return id;
@@ -444,9 +446,13 @@ readonly request = async <T = Record<string, unknown>>(
timeoutMs?: number,
): Promise<T> => {
const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;
+ const trustedDirs = getTrustedDirs();
+ const workspaceDir = trustedDirs[0] || process.cwd();
const response = await this.wsClient.request(id, method, {
...params,
session_id: params.session_id ?? this.sessionId,
+ ...(trustedDirs.length > 0 ? { trusted_dirs: trustedDirs } : {}),
+ ...(workspaceDir ? { cwd: workspaceDir } : {}),
}, timeoutMs ?? 30000);
return response.payload as T;
};
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/init.prompts.ts b/jiuwenclaw/cli/src/core/commands/builtins/init.prompts.ts
index 088ae01d38..11caa77a07 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/init.prompts.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/init.prompts.ts
@@ -55,7 +55,7 @@ These files are auto-loaded into every coding-mode session by ProjectMemoryRail,
Never use relative paths. When writing or editing, always construct \`${rootDir}/<filename>\`.
2. **Do NOT use the \`coding_memory_read\` / \`coding_memory_write\` / \`coding_memory_edit\` tools in this command.** Those are for session-level auto-memory, a different system. /init produces static project documents via the file write tools only.
3. **Existing files pre-detected in workspace root**:
- - JIUWENCLAW.md: ${yesNo(existing.jiuwenclawMd)} ${existing.jiuwenclawMd ? "— you MUST read it first, propose a diff, then use \`ask_user\` tool to ask the user whether to apply. Offer options: \"Apply update\" / \"Skip (keep current)\". If user chooses apply, use Edit to apply the diff; if skip, leave the file unchanged and continue. NEVER silently overwrite." : ""}
+ - JIUWENCLAW.md: ${yesNo(existing.jiuwenclawMd)} ${existing.jiuwenclawMd ? "— you MUST read it first, propose a diff, then use `ask_user` with `questions` to ask the user whether to apply. Example: `ask_user(query='Update JIUWENCLAW.md?', questions=[{question: 'JIUWENCLAW.md already exists. What would you like to do?', header: 'Update', options: [{label: 'Apply update', description: 'Merge the proposed changes into the existing file'}, {label: 'Skip (keep current)', description: 'Leave the file unchanged and continue'}], multi_select: false}])`. If user chooses 'Apply update', use Edit to apply the diff; if 'Skip', leave the file unchanged and continue. NEVER silently overwrite." : ""}
- JIUWENCLAW.local.md: ${yesNo(existing.jiuwenclawLocalMd)} ${existing.jiuwenclawLocalMd ? "— propose additions via Edit only, never overwrite." : ""}
- Legacy reference files (do NOT delete or rewrite; you may link to them): CLAUDE.md=${yesNo(existing.claudeMd)}, CLAUDE.local.md=${yesNo(existing.claudeLocalMd)}, AGENTS.md=${yesNo(existing.agentsMd)}, OPENJIUWEN.md=${yesNo(existing.openjiuwenMd)}, .cursorrules=${yesNo(existing.cursorRules)}, .github/copilot-instructions.md=${yesNo(existing.copilotInstructions)}
4. **When the explore sub-agent runs bash commands**, always prefix with \`cd ${rootDir} && ...\` or use \`git -C ${rootDir}\` — sub-agent CWD is not guaranteed to equal \`${rootDir}\`.
@@ -97,9 +97,27 @@ Fallback (no task_tool): do the same yourself with \`glob\` and \`read_file\`; f
## Step 3: Fill gaps + build proposal
-Gather info code can't answer. Preferred: use the \`ask_user\` tool.
-- If \`ask_user\` supports \`questions: [...]\` multi-choice schema, use it.
-- Otherwise, write the questions as plain text in your reply and wait for the user's next turn.
+Gather info code can't answer. Use the \`ask_user\` tool with structured \`questions\` parameter.
+
+The \`ask_user\` tool supports a \`questions\` parameter for presenting selectable options:
+\`\`\`
+ask_user(
+ query="Brief description of what you're asking",
+ questions=[
+ {
+ question: "The full question text",
+ header: "ShortTag",
+ options: [
+ {label: "Option A", description: "What option A means"},
+ {label: "Option B", description: "What option B means"},
+ ],
+ multi_select: false,
+ }
+ ]
+)
+\`\`\`
+
+Use selectable options when they help clarify the question, or ask open-ended questions to gather free-form input. The user can always choose "Other" for custom input.
For scope \`project\` / \`both\`: ask about team practices —
non-obvious commands, branch/PR conventions, env setup, testing quirks, common pitfalls.
@@ -118,7 +136,7 @@ Steps 4–5 consume this queue.
Target: \`${rootDir}/JIUWENCLAW.md\`
-${existing.jiuwenclawMd ? "File EXISTS — read it, propose a merged diff, WAIT for user confirmation, then apply via Edit. DO NOT use Write to overwrite silently." : "File is absent — use Write to create it."}
+${existing.jiuwenclawMd ? "File EXISTS — read it, propose a merged diff, use `ask_user` with `questions` to get user confirmation (options: 'Apply update' / 'Skip (keep current)'), then apply via Edit if confirmed. DO NOT use Write to overwrite silently." : "File is absent — use Write to create it."}
Consume queue entries whose \`target == "JIUWENCLAW.md"\`.
@@ -209,7 +227,7 @@ function buildInitPromptZh({ rootDir, scopeKey, existing }: BuildInitPromptArgs)
永远不要用相对路径。写入或编辑时总是构造 \`${rootDir}/<文件名>\`。
2. **禁止使用 \`coding_memory_read\` / \`coding_memory_write\` / \`coding_memory_edit\` 工具。** 那是会话级自动记忆,和 /init 是两套系统。/init 只通过文件写入工具产出静态项目文档。
3. **工作区根目录现有文件(已预探测)**:
- - JIUWENCLAW.md:${yesNoZh(existing.jiuwenclawMd)} ${existing.jiuwenclawMd ? "—— 必须先读取、生成 diff,然后用 \`ask_user\` 工具询问用户是否应用更新。提供选项:「应用更新」 / 「跳过(保留当前)」。若用户选应用,用 Edit 执行 diff;若选跳过,保持文件不变继续后续步骤。严禁静默覆盖。" : ""}
+ - JIUWENCLAW.md:${yesNoZh(existing.jiuwenclawMd)} ${existing.jiuwenclawMd ? "—— 必须先读取、生成 diff,然后用 \`ask_user\` 的 \`questions\` 参数让用户选择。示例:\`ask_user(query='更新 JIUWENCLAW.md?', questions=[{question: 'JIUWENCLAW.md 已存在,你想怎么处理?', header: '更新', options: [{label: '应用更新', description: '把提议的变更合并到现有文件'}, {label: '跳过(保留当前)', description: '保持文件不变,继续后续步骤'}], multi_select: false}])\`。若用户选「应用更新」,用 Edit 执行 diff;若选「跳过」,保持文件不变继续。严禁静默覆盖。" : ""}
- JIUWENCLAW.local.md:${yesNoZh(existing.jiuwenclawLocalMd)} ${existing.jiuwenclawLocalMd ? "— 只能通过 Edit 追加,不要覆盖。" : ""}
- 遗留参考文件(不要删改,可用 markdown 链接引用):CLAUDE.md=${yesNoZh(existing.claudeMd)}, CLAUDE.local.md=${yesNoZh(existing.claudeLocalMd)}, AGENTS.md=${yesNoZh(existing.agentsMd)}, OPENJIUWEN.md=${yesNoZh(existing.openjiuwenMd)}, .cursorrules=${yesNoZh(existing.cursorRules)}, .github/copilot-instructions.md=${yesNoZh(existing.copilotInstructions)}
4. **子代理 bash 命令必须加前缀**:\`cd ${rootDir} && ...\` 或用 \`git -C ${rootDir}\`,因为子代理的 CWD 不保证等于 \`${rootDir}\`。
@@ -251,9 +269,26 @@ task_description: |
## 步骤 3:补齐信息 + 生成提案
-收集代码无法回答的问题。优先用 \`ask_user\` 工具:
-- 若 \`ask_user\` 支持 \`questions: [...]\` 多选 schema,就用它;
-- 否则把问题写进你的回复里,等用户下一轮回答。
+收集代码无法回答的问题。用 \`ask_user\` 工具的 \`questions\` 参数提供可选项:
+
+\`\`\`
+ask_user(
+ query="简要说明你在问什么",
+ questions=[
+ {
+ question: "完整的问题文本",
+ header: "短标签",
+ options: [
+ {label: "选项 A", description: "选项 A 的含义"},
+ {label: "选项 B", description: "选项 B 的含义"},
+ ],
+ multi_select: false,
+ }
+ ]
+)
+\`\`\`
+
+根据问题性质选择选项式提问或直接输入式提问;用户始终可以选择「其他」进行自定义输入。
对 \`project\` / \`both\` 范围:询问团队实践 —
非显而易见的命令、分支 / PR 约定、环境初始化、测试习惯、常见坑位。
@@ -272,7 +307,7 @@ task_description: |
目标:\`${rootDir}/JIUWENCLAW.md\`
-${existing.jiuwenclawMd ? "文件已存在 —— 先读取,生成合并 diff,等用户确认,然后用 Edit 应用。绝不要用 Write 静默覆盖。" : "文件不存在 —— 用 Write 创建。"}
+${existing.jiuwenclawMd ? "文件已存在 —— 先读取,生成合并 diff,用 \`ask_user\` 的 \`questions\` 参数获取用户确认(选项:「应用更新」 / 「跳过(保留当前)」),确认后用 Edit 应用。绝不要用 Write 静默覆盖。" : "文件不存在 —— 用 Write 创建。"}
消费队列中 \`target == "JIUWENCLAW.md"\` 的条目。
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/init.ts b/jiuwenclaw/cli/src/core/commands/builtins/init.ts
index 69f85cdd12..0fd5eab877 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/init.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/init.ts
@@ -106,6 +106,7 @@ export function createInitCommand(): SlashCommand {
}
// ---- Guard 3: workspace root ----
+ // ctx.getWorkspaceDir() 现在优先返回 trustedDirs[0],fallback process.cwd()
const rootDir =
ctx.getWorkspaceDir() ||
(typeof process !== "undefined" ? process.cwd() : "");
@@ -114,8 +115,8 @@ export function createInitCommand(): SlashCommand {
addError(
ctx.sessionId,
language === "zh"
- ? "无法识别工作目录,请先用 /workspace-dir <path> 指定。"
- : "Cannot resolve workspace directory. Use /workspace-dir <path> first.",
+ ? "无法识别工作目录,请先用 /workspace set <path> 指定。"
+ : "Cannot resolve workspace directory. Use /workspace set <path> first.",
),
);
return;
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/mode.ts b/jiuwenclaw/cli/src/core/commands/builtins/mode.ts
index 0384a870c0..2cf282f9cf 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/mode.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/mode.ts
@@ -50,6 +50,19 @@ export function createModeCommand(): SlashCommand {
completion: async () => [...directModes],
action: async (ctx, args) => {
const requestedMode = args.trim();
+ // 无参数时显示当前 mode
+ if (!requestedMode) {
+ const currentMode = ctx.mode ?? "unknown";
+ ctx.addItem(
+ makeItem(
+ ctx.sessionId,
+ "info",
+ `Current mode: ${currentMode}`,
+ "m",
+ ),
+ );
+ return;
+ }
const nextMode = modeAlias[requestedMode];
if (!nextMode) {
ctx.addItem(
diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.ts
index ef595f4644..f553c256f2 100644
--- a/jiuwenclaw/cli/src/ui/app-screen.ts
+++ b/jiuwenclaw/cli/src/ui/app-screen.ts
@@ -32,7 +32,7 @@ import {
import type { SessionListPayload, SessionMeta } from "../core/commands/builtins/resume.js";
import type { ConfigItemSchema } from "../core/commands/builtins/config.js";
import { buildModeAutocompleteItems } from "../core/commands/builtins/mode.js";
-import { addTrustedDir } from "../core/tui-trusted-dirs-store.js";
+import { addTrustedDir, getTrustedDirs, isTrustedDir } from "../core/tui-trusted-dirs-store.js";
import { handleAppScreenKeyInput } from "./keymap.js";
import { buildAppScreenLines } from "./screen-layout.js";
import {
@@ -365,7 +365,7 @@ export class AppScreen implements Component, Focusable {
this.editor = new Editor(tui, editorTheme, { paddingX: 1, autocompleteMaxVisible: 6 });
this.composerAutocompleteProvider = new CombinedAutocompleteProvider(
this.buildSlashCommands(),
- process.cwd(),
+ getTrustedDirs()[0] || process.cwd(),
resolveFdBinary(),
);
this.editor.setAutocompleteProvider(this.composerAutocompleteProvider);
@@ -384,6 +384,9 @@ export class AppScreen implements Component, Focusable {
private initStartupPrompt(): void {
const cwd = process.cwd();
+ if (isTrustedDir(cwd)) {
+ return;
+ }
const items: SelectItem[] = [
{
label: "Yes, I trust this folder",
@@ -1404,7 +1407,9 @@ export class AppScreen implements Component, Focusable {
}
private collectComposerAttachments(text: string): FileAttachment[] {
+ const cwd = getTrustedDirs()[0] || process.cwd();
return extractAttachmentsFromText(text, {
+ cwd,
classifyAttachment: (path) => (this.isAcceptedAttachment(path) ? (isImageAttachment(path) ? "image" : "file") : null),
}).map(({ resolvedPath, ...attachment }) => attachment);
}
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.json b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.json
index 26c743b804..31df0162bd 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.json
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.json
@@ -227,6 +227,13 @@
"isMarkdown": true
}
],
+ "jiuwenclaw_workspace/skills/llm-wiki": [
+ {
+ "name": "SKILL.md",
+ "path": "agent/jiuwenclaw_workspace/skills/llm-wiki/SKILL.md",
+ "isMarkdown": true
+ }
+ ],
"jiuwenclaw_workspace/skills/openJiuwen-DeepSearch": [
{
"name": "README.md",
@@ -457,5 +464,24 @@
"path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/wechat_article.py",
"isMarkdown": false
}
+ ],
+ "jiuwenclaw_workspace/skills/skvm-general": [
+ {
+ "name": "SKILL.md",
+ "path": "agent/jiuwenclaw_workspace/skills/skvm-general/SKILL.md",
+ "isMarkdown": true
+ }
+ ],
+ "jiuwenclaw_workspace/skills/skvm-jit": [
+ {
+ "name": "adapter-skill-paths.md",
+ "path": "agent/jiuwenclaw_workspace/skills/skvm-jit/adapter-skill-paths.md",
+ "isMarkdown": true
+ },
+ {
+ "name": "SKILL.md",
+ "path": "agent/jiuwenclaw_workspace/skills/skvm-jit/SKILL.md",
+ "isMarkdown": true
+ }
]
}
\ No newline at end of file
diff --git a/tests/system_tests/test_project_memory.py b/tests/system_tests/test_project_memory.py
index 3d68cfdb4c..9ebce0f2e8 100644
--- a/tests/system_tests/test_project_memory.py
+++ b/tests/system_tests/test_project_memory.py
@@ -300,6 +300,7 @@ class TestCodeModeIntegration:
with tempfile.TemporaryDirectory() as td:
adapter = JiuwenClawCodeAdapter()
adapter._workspace_dir = td
+ adapter._project_dir = td
adapter._instance_overrides = {}
adapter._config_cache = {}
@@ -322,6 +323,7 @@ class TestCodeModeIntegration:
adapter = JiuwenClawCodeAdapter()
adapter._workspace_dir = td
+ adapter._project_dir = td
adapter._instance_overrides = {}
adapter._config_cache = {}
@@ -375,6 +377,7 @@ class TestExploreAgentSubagentIntegration:
adapter = JiuwenClawCodeAdapter()
adapter._workspace_dir = "/tmp/test-workspace"
+ adapter._project_dir = "/tmp/test-workspace"
monkeypatch.setattr(
JiuwenClawCodeAdapter,
"_browser_runtime_enabled",
@@ -406,6 +409,7 @@ class TestExploreAgentSubagentIntegration:
adapter = JiuwenClawCodeAdapter()
adapter._workspace_dir = "/tmp/test-workspace"
+ adapter._project_dir = "/tmp/test-workspace"
monkeypatch.setattr(
JiuwenClawCodeAdapter,
"_browser_runtime_enabled",
@@ -439,6 +443,7 @@ class TestExploreAgentSubagentIntegration:
adapter = JiuwenClawCodeAdapter()
adapter._workspace_dir = "/tmp/test-workspace"
+ adapter._project_dir = "/tmp/test-workspace"
monkeypatch.setattr(
JiuwenClawCodeAdapter,
"_browser_runtime_enabled",
@@ -558,6 +563,7 @@ class TestProjectMemoryRailModeSwitching:
with tempfile.TemporaryDirectory() as td:
adapter = JiuwenClawCodeAdapter()
adapter._workspace_dir = td
+ adapter._project_dir = td
adapter._instance_overrides = {}
adapter._config_cache = {}
diff --git a/tests/system_tests/test_structured_ask_user.py b/tests/system_tests/test_structured_ask_user.py
new file mode 100644
index 0000000000..450465aa27
--- /dev/null
+++ b/tests/system_tests/test_structured_ask_user.py
@@ -0,0 +1,598 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""System tests for StructuredAskUserRail and interrupt_helpers questions extraction.
+
+Tests the integration of:
+1. StructuredAskUserRail — init/uninit lifecycle, tool card schema, resolve_interrupt
+2. interrupt_helpers._extract_questions_from_value — extraction from tool_args
+3. interrupt_helpers.convert_interactions_to_ask_user_question — full conversion pipeline
+4. init.prompts.ts prompt text — structured ask_user instructions present
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall
+from openjiuwen.core.single_agent.interrupt.response import (
+ ToolCallInterruptRequest,
+)
+from openjiuwen.harness.rails.interrupt.ask_user_rail import AskUserPayload
+
+from jiuwenclaw.agentserver.deep_agent.rails.ask_user_rail import (
+ EXTENDED_INPUT_PARAMS_CN,
+ EXTENDED_INPUT_PARAMS_EN,
+ StructuredAskUserRail,
+ StructuredAskUserTool,
+)
+from jiuwenclaw.agentserver.deep_agent.interrupt.interrupt_helpers import (
+ _extract_questions_from_value,
+ convert_interactions_to_ask_user_question,
+)
+
+pytestmark = [pytest.mark.integration, pytest.mark.system]
+
+
+# =====================================================================
+# Helpers
+# =====================================================================
+
+def _make_tool_call(
+ tool_call_id: str = "tc_001",
+ arguments: dict | str | None = None,
+) -> ToolCall:
+ """Create a ToolCall with given arguments."""
+ if arguments is None:
+ arguments = {"query": "Update?"}
+ if isinstance(arguments, dict):
+ arguments = json.dumps(arguments)
+ return ToolCall(id=tool_call_id, type="function", name="ask_user", arguments=arguments)
+
+
+def _make_tcir(
+ message: str = "Update?",
+ tool_args: dict | str | None = None,
+) -> ToolCallInterruptRequest:
+ """Create a ToolCallInterruptRequest for testing."""
+ if tool_args is None:
+ tool_args = {"query": message}
+ return ToolCallInterruptRequest(
+ message=message,
+ payload_schema={},
+ tool_name="ask_user",
+ tool_call_id="tc_001",
+ tool_args=tool_args,
+ )
+
+
+def _make_mock_agent() -> MagicMock:
+ """Create a mock agent with ability_manager and card."""
+ agent = MagicMock()
+ agent.ability_manager = MagicMock()
+ agent.card = MagicMock()
+ agent.card.id = "test_agent_001"
+ return agent
+
+
+# =====================================================================
+# 1. StructuredAskUserTool Schema Tests
+# =====================================================================
+
+class TestStructuredAskUserToolSchema:
+ """Verify the extended tool card schema for ask_user."""
+
+ @staticmethod
+ def test_en_schema_has_query_and_questions():
+ """English schema must include both `query` and `questions` properties."""
+ props = EXTENDED_INPUT_PARAMS_EN["properties"]
+ assert "query" in props
+ assert "questions" in props
+ assert props["query"]["type"] == "string"
+ assert props["questions"]["type"] == "array"
+
+ @staticmethod
+ def test_cn_schema_has_query_and_questions():
+ """Chinese schema must include both `query` and `questions` properties."""
+ props = EXTENDED_INPUT_PARAMS_CN["properties"]
+ assert "query" in props
+ assert "questions" in props
+
+ @staticmethod
+ def test_required_fields_only_query():
+ """Only `query` is required; `questions` is optional."""
+ assert EXTENDED_INPUT_PARAMS_EN["required"] == ["query"]
+ assert EXTENDED_INPUT_PARAMS_CN["required"] == ["query"]
+
+ @staticmethod
+ def test_questions_item_schema_structure():
+ """Each question item must have `question` (required) and optional
+ `header`, `options`, `multi_select`.
+ """
+
+ from jiuwenclaw.agentserver.deep_agent.rails.ask_user_rail import (
+ _QUESTIONS_ITEM_SCHEMA,
+ )
+ props = _QUESTIONS_ITEM_SCHEMA["properties"]
+ assert "question" in props
+ assert "header" in props
+ assert "options" in props
+ assert "multi_select" in props
+ assert _QUESTIONS_ITEM_SCHEMA["required"] == ["question"]
+
+ @staticmethod
+ def test_tool_card_name_is_ask_user():
+ """Tool card name must be `ask_user` (same as original for compat)."""
+ tool = StructuredAskUserTool(language="en")
+ assert tool.card.name == "ask_user"
+
+ @staticmethod
+ def test_tool_card_input_params_match_en():
+ """Tool card input_params should match EXTENDED_INPUT_PARAMS_EN."""
+ tool = StructuredAskUserTool(language="en")
+ assert tool.card.input_params == EXTENDED_INPUT_PARAMS_EN
+
+ @staticmethod
+ def test_tool_card_input_params_match_cn():
+ """Tool card input_params should match EXTENDED_INPUT_PARAMS_CN."""
+ tool = StructuredAskUserTool(language="cn")
+ assert tool.card.input_params == EXTENDED_INPUT_PARAMS_CN
+
+
+# =====================================================================
+# 2. StructuredAskUserRail Lifecycle Tests
+# =====================================================================
+
+class TestStructuredAskUserRailLifecycle:
+ """Verify rail init/uninit lifecycle with mock agent."""
+
+ @staticmethod
+ def test_init_registers_tool_in_ability_manager():
+ """init() must register the tool card in agent.ability_manager."""
+ rail = StructuredAskUserRail()
+ agent = _make_mock_agent()
+
+ with patch("openjiuwen.harness.rails.interrupt.ask_user_rail.resolve_language", return_value="en"):
+ rail.init(agent)
+
+ agent.ability_manager.add.assert_called_once()
+ added_card = agent.ability_manager.add.call_args[0][0]
+ assert added_card.name == "ask_user"
+
+ @staticmethod
+ def test_uninit_removes_tool_from_ability_manager():
+ """uninit() must remove the tool from agent.ability_manager."""
+ rail = StructuredAskUserRail()
+ agent = _make_mock_agent()
+
+ with patch("openjiuwen.harness.rails.interrupt.ask_user_rail.resolve_language", return_value="en"):
+ rail.init(agent)
+ rail.uninit(agent)
+
+ agent.ability_manager.remove.assert_called_once_with("ask_user")
+
+ @staticmethod
+ def test_init_uninit_clears_structured_tools():
+ """uninit() must clear the internal _structured_tools list."""
+ rail = StructuredAskUserRail()
+ agent = _make_mock_agent()
+
+ with patch("openjiuwen.harness.rails.interrupt.ask_user_rail.resolve_language", return_value="en"):
+ rail.init(agent)
+ assert len(rail.get_structured_tools()) == 1
+
+ rail.uninit(agent)
+ assert len(rail.get_structured_tools()) == 0
+
+ @staticmethod
+ def test_tool_names_default_is_ask_user():
+ """Default tool_names should be {'ask_user'}."""
+ rail = StructuredAskUserRail()
+ assert rail.get_tools() == {"ask_user"}
+
+
+# =====================================================================
+# 3. StructuredAskUserRail _extract_questions Tests
+# =====================================================================
+
+class TestStructuredAskUserRailExtractQuestions:
+ """Verify _extract_questions method parses tool call arguments correctly."""
+
+ @staticmethod
+ def test_extract_questions_from_dict_args():
+ """Should extract questions from dict arguments."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={
+ "query": "Update?",
+ "questions": [
+ {"question": "Apply update?", "header": "Update",
+ "options": [{"label": "Apply", "description": "apply"}]},
+ ],
+ })
+ result = rail.extract_questions(tc)
+ assert result is not None
+ assert len(result) == 1
+ assert result[0]["question"] == "Apply update?"
+
+ @staticmethod
+ def test_extract_questions_from_string_args():
+ """Should extract questions from JSON string arguments."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments=json.dumps({
+ "query": "Update?",
+ "questions": [{"question": "Q1", "header": "H1"}],
+ }))
+ result = rail.extract_questions(tc)
+ assert result is not None
+ assert len(result) == 1
+
+ @staticmethod
+ def test_extract_questions_returns_none_for_plain_query():
+ """Should return None for a plain query (no questions)."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={"query": "What is your role?"})
+ result = rail.extract_questions(tc)
+ assert result is None
+
+ @staticmethod
+ def test_extract_questions_returns_none_for_none_tool_call():
+ """Should return None when tool_call is None."""
+ rail = StructuredAskUserRail()
+ result = rail.extract_questions(None)
+ assert result is None
+
+
+# =====================================================================
+# 4. interrupt_helpers._extract_questions_from_value Tests
+# =====================================================================
+
+class TestExtractQuestionsFromValue:
+ """Verify _extract_questions_from_value handles all extraction paths."""
+
+ @staticmethod
+ def test_dict_value_obj_with_questions():
+ """Should extract questions from a dict value_obj."""
+ result = _extract_questions_from_value({
+ "questions": [{"question": "Q1", "header": "H1"}],
+ })
+ assert result is not None
+ assert len(result) == 1
+
+ @staticmethod
+ def test_tcir_with_questions_in_tool_args_dict():
+ """Should extract questions from ToolCallInterruptRequest.tool_args (dict)."""
+ tcir = _make_tcir(tool_args={
+ "query": "Update?",
+ "questions": [
+ {"question": "Apply?", "header": "Update",
+ "options": [{"label": "Apply", "description": "apply"}]},
+ ],
+ })
+ result = _extract_questions_from_value(tcir)
+ assert result is not None
+ assert result[0]["question"] == "Apply?"
+
+ @staticmethod
+ def test_tcir_with_questions_in_tool_args_json_string():
+ """Should extract questions from ToolCallInterruptRequest.tool_args (JSON string)."""
+ tcir = _make_tcir(tool_args=json.dumps({
+ "query": "Update?",
+ "questions": [{"question": "Apply?", "header": "Update"}],
+ }))
+ result = _extract_questions_from_value(tcir)
+ assert result is not None
+ assert result[0]["question"] == "Apply?"
+
+ @staticmethod
+ def test_tcir_plain_query_returns_none():
+ """Should return None for plain query (no questions in tool_args)."""
+ tcir = _make_tcir(tool_args={"query": "What is your role?"})
+ result = _extract_questions_from_value(tcir)
+ assert result is None
+
+ @staticmethod
+ def test_tcir_invalid_json_string_returns_none():
+ """Should return None for tool_args that is invalid JSON."""
+ tcir = _make_tcir(tool_args="not valid json{{{")
+ result = _extract_questions_from_value(tcir)
+ assert result is None
+
+ @staticmethod
+ def test_tcir_json_string_without_questions_returns_none():
+ """Should return None for JSON string tool_args without questions field."""
+ tcir = _make_tcir(tool_args=json.dumps({"query": "role?"}))
+ result = _extract_questions_from_value(tcir)
+ assert result is None
+
+ @staticmethod
+ def test_empty_questions_list_returns_none():
+ """Should return None for an empty questions list."""
+ tcir = _make_tcir(tool_args={"query": "Q?", "questions": []})
+ result = _extract_questions_from_value(tcir)
+ assert result is None
+
+ @staticmethod
+ def test_direct_questions_attribute_on_object():
+ """Should extract questions from hasattr path (questions attribute)."""
+ obj = MagicMock()
+ obj.questions = [{"question": "Q1", "header": "H1"}]
+ # Remove tool_args to ensure it goes through the hasattr path
+ del obj.tool_args
+ result = _extract_questions_from_value(obj)
+ assert result is not None
+ assert len(result) == 1
+
+ @staticmethod
+ def test_tool_args_takes_priority_over_direct_attribute():
+ """If both direct questions and tool_args.questions exist, direct path wins."""
+ tcir = _make_tcir(tool_args={
+ "query": "Q?",
+ "questions": [{"question": "from_tool_args", "header": "TA"}],
+ })
+ # ToolCallInterruptRequest does NOT have .questions attribute
+ # so only tool_args path will be hit
+ result = _extract_questions_from_value(tcir)
+ assert result is not None
+ assert result[0]["question"] == "from_tool_args"
+
+
+# =====================================================================
+# 5. convert_interactions_to_ask_user_question Full Pipeline
+# =====================================================================
+
+class TestConvertInteractionsToAskUserQuestion:
+ """Verify the full conversion pipeline from TCIR to frontend event."""
+
+ @staticmethod
+ def test_structured_questions_produce_ask_user_interrupt():
+ """Structured questions in tool_args should produce source=ask_user_interrupt."""
+ tcir = _make_tcir(tool_args={
+ "query": "Update?",
+ "questions": [
+ {"question": "Apply update?", "header": "Update",
+ "options": [{"label": "Apply", "description": "apply"},
+ {"label": "Skip", "description": "skip"}],
+ "multi_select": False},
+ ],
+ })
+
+ # Wrap in InteractionOutput-like structure
+ interaction = MagicMock()
+ interaction.id = "req_001"
+ interaction.value = tcir
+
+ result = convert_interactions_to_ask_user_question([interaction])
+ assert result is not None
+ assert result["event_type"] == "chat.ask_user_question"
+ assert result["source"] == "ask_user_interrupt"
+ assert len(result["questions"]) == 1
+ q = result["questions"][0]
+ assert q["question"] == "Apply update?"
+ assert q["header"] == "Update"
+ # Options should include original 2 + "Other" appended by _build_multi_questions
+ assert len(q["options"]) == 3
+ assert q["options"][0]["label"] == "Apply"
+ assert q["options"][1]["label"] == "Skip"
+ assert q["options"][2]["label"] == "Other"
+
+ @staticmethod
+ def test_plain_query_produce_permission_interrupt():
+ """Plain query (no questions) should produce source=permission_interrupt."""
+ tcir = _make_tcir(tool_args={"query": "What is your role?"})
+
+ interaction = MagicMock()
+ interaction.id = "req_002"
+ interaction.value = tcir
+
+ result = convert_interactions_to_ask_user_question([interaction])
+ assert result is not None
+ assert result["source"] == "permission_interrupt"
+
+ @staticmethod
+ def test_empty_state_outputs_returns_none():
+ """Empty state_outputs should return None."""
+ result = convert_interactions_to_ask_user_question([])
+ assert result is None
+
+ @staticmethod
+ def test_dict_interaction_with_questions_in_value():
+ """Dict-format interaction should also work."""
+ result = convert_interactions_to_ask_user_question([
+ {
+ "id": "req_003",
+ "value": {
+ "query": "Update?",
+ "questions": [{"question": "Apply?", "header": "Upd",
+ "options": [{"label": "Yes"}]}],
+ },
+ }
+ ])
+ assert result is not None
+ assert result["source"] == "ask_user_interrupt"
+
+
+# =====================================================================
+# 6. StructuredAskUserRail resolve_interrupt Tests
+# =====================================================================
+
+class TestStructuredAskUserRailResolveInterrupt:
+ """Verify resolve_interrupt handles structured and plain answers."""
+
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_none_user_input_returns_interrupt():
+ """When user_input is None, should return interrupt (first-time call)."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={
+ "query": "Update?",
+ "questions": [{"question": "Apply?", "header": "Upd",
+ "options": [{"label": "Apply"}]}],
+ })
+ ctx = MagicMock()
+
+ decision = await rail.resolve_interrupt(ctx, tc, None)
+
+ # Should be an InterruptResult
+ from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult
+ assert isinstance(decision, InterruptResult)
+
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_structured_answer_dict_returns_reject():
+ """Structured answer as dict should return RejectResult with formatted text."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={
+ "query": "Update?",
+ "questions": [{"question": "Apply update?", "header": "Update",
+ "options": [{"label": "Apply update"}, {"label": "Skip"}]}],
+ })
+ ctx = MagicMock()
+
+ # Simulate user selecting "Apply update"
+ user_input = {"answers": {"Apply update?": "Apply update"}}
+ decision = await rail.resolve_interrupt(ctx, tc, user_input)
+
+ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult
+ assert isinstance(decision, RejectResult)
+ assert "Apply update" in decision.tool_result
+
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_structured_answer_string_fallback():
+ """String answer for a structured question should be handled as free-text."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={
+ "query": "Update?",
+ "questions": [{"question": "Apply?", "header": "Upd"}],
+ })
+ ctx = MagicMock()
+
+ decision = await rail.resolve_interrupt(ctx, tc, "I want to customize")
+
+ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult
+ assert isinstance(decision, RejectResult)
+ assert "I want to customize" in decision.tool_result
+
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_plain_query_delegates_to_parent():
+ """Plain query (no questions) should delegate to parent AskUserRail."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={"query": "What is your role?"})
+ ctx = MagicMock()
+
+ # AskUserPayload changed: answer (str) → answers (dict)
+ # Construct payload compatible with both old and new upstream versions
+ if "answer" in AskUserPayload.model_fields:
+ user_input = AskUserPayload(answer="I am a developer")
+ else:
+ user_input = AskUserPayload(answers={"What is your role?": "I am a developer"})
+ decision = await rail.resolve_interrupt(ctx, tc, user_input)
+
+ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult
+ assert isinstance(decision, RejectResult)
+ assert "I am a developer" in decision.tool_result
+
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_structured_answer_with_multiple_questions():
+ """Multiple structured questions answered should format all answers."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={
+ "query": "Setup info",
+ "questions": [
+ {"question": "Branch naming?", "header": "Branch"},
+ {"question": "Test runner?", "header": "Test"},
+ ],
+ })
+ ctx = MagicMock()
+
+ user_input = {
+ "answers": {
+ "Branch naming?": "feature/*",
+ "Test runner?": "pytest",
+ },
+ }
+ decision = await rail.resolve_interrupt(ctx, tc, user_input)
+
+ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult
+ assert isinstance(decision, RejectResult)
+ assert "Branch naming?" in decision.tool_result
+ assert "feature/*" in decision.tool_result
+ assert "Test runner?" in decision.tool_result
+ assert "pytest" in decision.tool_result
+
+
+# =====================================================================
+# 7. init.prompts.ts Prompt Text Tests (read source file directly)
+# =====================================================================
+
+_INIT_PROMPTS_TS_PATH = (
+ Path(__file__).parent.parent.parent
+ / "jiuwenclaw"
+ / "cli"
+ / "src"
+ / "core"
+ / "commands"
+ / "builtins"
+ / "init.prompts.ts"
+)
+
+
+class TestInitPromptStructuredAskUser:
+ """Verify the /init prompt text instructs structured ask_user usage.
+
+ These tests read the TypeScript source file directly rather than importing,
+ since init.prompts.ts is a TypeScript module not importable by Python.
+ """
+
+ @staticmethod
+ def _read_prompts_ts() -> str:
+ """Read the init.prompts.ts source file."""
+ if not _INIT_PROMPTS_TS_PATH.exists():
+ pytest.skip("init.prompts.ts not found at expected path")
+ return _INIT_PROMPTS_TS_PATH.read_text(encoding="utf-8")
+
+ def test_en_prompt_contains_ask_user_questions_parameter(self):
+ """EN prompt must instruct LLM to use `ask_user` with `questions`."""
+ content = self._read_prompts_ts()
+ assert "questions" in content
+ assert "ask_user" in content
+ # Must NOT contain the old conditional language
+ assert "If `ask_user` supports" not in content
+
+ def test_zh_prompt_contains_ask_user_questions_parameter(self):
+ """ZH prompt must instruct LLM to use `ask_user` with `questions`."""
+ content = self._read_prompts_ts()
+ assert "questions" in content
+ assert "ask_user" in content
+ # Must NOT contain the old conditional language
+ assert "若 `ask_user` 支持" not in content
+
+ def test_en_prompt_contains_apply_update_skip_options(self):
+ """EN prompt must mention 'Apply update' / 'Skip' as concrete options."""
+ content = self._read_prompts_ts()
+ assert "Apply update" in content
+ assert "Skip (keep current)" in content
+
+ def test_zh_prompt_contains_apply_update_skip_options(self):
+ """ZH prompt must mention '应用更新' / '跳过' as concrete options."""
+ content = self._read_prompts_ts()
+ assert "应用更新" in content
+ assert "跳过" in content
+
+ def test_en_step3_has_questions_usage_example(self):
+ """EN Step 3 must include ask_user questions usage example."""
+ content = self._read_prompts_ts()
+ assert "multi_select" in content
+ # The example should show the questions parameter structure
+ assert "header" in content
+
+ def test_zh_step3_has_questions_usage_example(self):
+ """ZH Step 3 must include ask_user questions usage example."""
+ content = self._read_prompts_ts()
+ assert "multi_select" in content
+ assert "header" in content
\ No newline at end of file