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(tui): fix and improve /workspace slash command
ray_le3130bb428a68
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdnew file mode 100644index 0000000000..7547c11ab4--- /dev/null+++ b/docs/en/SlashCommands.md@@ -0,0 +1,152 @@+# Slash Commands Reference++This document categorizes commands by **parsing location**: `TUI Local Parsing` and `Gateway / Agent Parsing`.+For quick reference of current behavior; final implementation follows the code.++---++## Overview: By Parsing Side++### TUI Local Parsing (CLI Built-in)++Executed locally in the terminal UI, not through Gateway control pipeline.++| Command | Description |+|---|---|+| `/clear` | Clear screen |+| `/color` | Adjust TUI color scheme |+| `/copy` | Copy last message |+| `/exit` | Exit |+| `/help` | Show available commands |+| `/theme` | Switch theme |+| `/config` | Modify configuration (currently local, planned to unify with Gateway) |+| `/workspace` | Manage trusted directories (see below) |++> Note: `/mode` controlled switching logic is primarily on Gateway side, see "`/mode` and `/switch`" below.++### Gateway / Agent Parsing (Controlled Channel)++Identified by Gateway and forwarded to AgentServer and other backend capabilities.++| Command | Description |+|---|---|+| `/plan` | Switch to planning sub-mode |+| `/resume` | Resume historical session (see below) |+| `/new_session` | Create new session (IM only) |+| `/mode` | Mode switching (supports first-level entry and direct syntax) |+| `/switch` | Switch second-level mode within current mode family |+| `/skills` | Skills list (see "IM vs TUI Differences") |+| `/model` | Model view, add, switch (see below) |+| `/diff` | View session changes by turn (see below) |++---++## Key Command Details++### `/workspace` (TUI Trusted Directory Management)++Manages directories AI can access for file read, edit, and execute operations.++#### Subcommands++| Command | Description |+|---|---|+| `/workspace` or `/workspace get` | Show system default workspace and current trusted directories list |+| `/workspace add [path]` | Add trusted directory (defaults to cwd; error if path doesn't exist) |+| `/workspace set <path>` | Reset trusted dirs to single path (confirmation required if dirs exist) |+| `/workspace remove <path>` | Remove specified trusted directory |+| `/workspace clear` | Clear all trusted directories (use default workspace only) |++#### Concepts++- **System default workspace**: Fixed path `~/.jiuwenclaw/agent/jiuwenclaw_workspace`, always available+- **Trusted directories (`trusted_dirs`)**: User-authorized accessible directories, managed by TUI, passed to backend Agent++#### Control Logic++1. **Startup confirmation**: TUI prompts user whether to trust current directory+ - "Trust" → add current directory as trusted+ - "Don't trust" → use default workspace only++2. **Session-level management**: Trusted directories are effective for current CLI session, not persisted to file++3. **Backend passing**: TUI passes `trusted_dirs` via request params; Agent restricts file operations accordingly++4. **Path restriction**: Agent limits file operations within trusted directories; operations outside require user confirmation++5. **Path validation**: `add` and `set` validate path existence; error shown if invalid++#### Aliases++`/workspace_dir`, `/workspace-dir`++### `/mode` and `/switch` (Controlled Channel)++- First-level entry mapping:+ - `/mode agent` -> `agent.plan`+ - `/mode code` -> `code.normal`+ - `/mode team` -> `team`+- Direct syntax:+ - `/mode agent.plan` -> `agent.plan`+ - `/mode agent.fast` -> `agent.fast`+ - `/mode code.plan` -> `code.plan`+ - `/mode code.normal` -> `code.normal`+- Second-level switching:+ - agent family: `/switch plan` <-> `agent.plan`, `/switch fast` <-> `agent.fast`+ - code family: `/switch plan` <-> `code.plan`, `/switch normal` <-> `code.normal`+- Invalid combinations (e.g., `/switch fast` under `code.*`) return: `Invalid command`.+- Note: Standalone `/team` command removed, use `/mode team` instead.++### `/resume`++- `/resume list`: List historical sessions.+- `/resume <conversation_id>`: Resume specified session.++### `/model` (View / Add / Switch Model)++- Usage:+ - `/model` or `/model list`: List switchable models (with current model marker);+ - `/model <name>`: Switch to specified model;+ - `/model add <name> key=value ...`: Add model config (e.g., `model=...`, `provider=...`, `api_base=...`, `api_key=...`).+- Limitation: `video` / `audio` / `vision` cannot be set as default chat model via `/model <name>`, use `/config edit` or `/config set` instead.+- Config write behavior:+ - Adding model writes to `config.yaml` `models.defaults` (compatible with old structure), triggers Agent config reload;+ - Switching model validates config and environment variable placeholders, updates `MODEL_NAME` / `MODEL_PROVIDER` / `API_BASE` / `API_KEY`, writes back to `.env`.+- Secure display: Sensitive fields like `api_key`, `token` are masked.++### `/diff` (Session Change Review)++- Usage: `/diff` (no subcommands).+- Data source: TUI requests Agent diff service via `command.diff`, returns `turns` (change sets per turn) for current `session_id`.+- Display rules:+ - With changes: Shows `Found N turn(s) with file changes` with structured `turns`;+ - Without changes: Shows `No file changes in this session`.+- Scope: For viewing uncommitted per-turn change traces in current session, not a replacement for `git diff` full version control perspective.++---++## `/skills`: IM vs TUI Differences++Both ultimately request `skills.list`, but trigger methods and display differ.++| Side | Trigger Method | Behavior |+|---|---|---|+| IM (Feishu etc. controlled channel) | Exact match `/skills list` (whitespace normalized first) | Gateway intercepts control message and requests `skills.list`, results shown as IM notification/card; standalone `/skills` doesn't go through this control path. |+| TUI (CLI built-in) | Input `/skills` | Locally executes built-in command and calls `skills.list`, displays as list view in session (title `Skills`); shows `No skills returned` when empty. |++Conclusion: IM uses `/skills list`, TUI uses `/skills`, current syntax differs (known status).++---++## Planned Features++| Command | Description |+|---|---|+| `/compact` | Compress current context |+| `/init` | Project initialization |+| `/btw` | Ask question |+| `/context` | Context status view |+| `/export` | Export related files |+| `/mcp` | MCP management |+| `/memory` | Memory management |+| `/permissions` | Permission management |\ No newline at end of filediff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"index 3d1d2b9cca..3130149fc3 100644--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"@@ -20,7 +20,7 @@| `/help` | 查看可用命令 || `/theme` | 切换主题 || `/config` | 修改配置(当前为本地实现,后续计划统一到 Gateway) |-| `/workspace` | 管理工作区路径与目录授权(见下文) |+| `/workspace` | 管理可信目录(见下文) |> 说明:`/mode` 的受控切换逻辑以 Gateway 侧行为为主,详见下文「`/mode` 与 `/switch`」。@@ -30,7 +30,6 @@| 命令 | 说明 ||---|---|-| `/add_dir` | 目录授权为可读写(TUI 侧建议改用 `/workspace add`) || `/plan` | 切换规划子模式 || `/resume` | 历史会话恢复(见下文) || `/new_session` | 新建会话(仅 IM 生效) |@@ -44,21 +43,42 @@## 重点命令说明-### `/workspace`(TUI 工作区目录、待开发)--- 常用子命令:- - `/workspace` 或 `/workspace get`:查看当前路径;- - `/workspace set <path>`:设置工作区路径(支持如 `./` 的相对路径,按 TUI 启动目录解析);- - `/workspace clear`:清空工作区路径;- - `/workspace add <path>`:迁移自原 `/add-dir`,底层调用 `command.add_dir`。-- 兼容别名:`/workspace_dir`、`/workspace-dir`。-- 持久化文件:`~/.jiuwenclaw/tui-workspace-dir`(单行文本)。-- 默认值:若本地未保存,TUI 启动时默认取 `process.cwd()`。-- 与 Gateway 关系:当存在非空工作区路径时,TUI 通过 `sendEventOnly` 发送请求会在 `params` 中附带 `workspace_dir`,供 Gateway / AgentServer 使用。-- 切换路径与会话隔离:- - 仅当新旧路径(规范化后)不同才触发处理;- - 当前会话已发生 `chat.send` 时,`/workspace set` 才进入“确认 ->(必要时)中断 -> 新建会话”流程;- - 若尚未 `chat.send`,仅更新 `workspace_dir`,不新建会话。+### `/workspace`(TUI 可信目录管理)++管理 AI 可访问的目录范围,用于文件读取、编辑、执行等操作。++#### 子命令++| 命令 | 说明 |+|---|---|+| `/workspace` 或 `/workspace get` | 查看系统默认工作空间与当前可信目录列表 |+| `/workspace add [path]` | 添加可信目录(默认为当前目录,路径不存在时提示错误) |+| `/workspace set <path>` | 重置可信目录为单个路径(已有可信目录时需确认) |+| `/workspace remove <path>` | 移除指定可信目录 |+| `/workspace clear` | 清空所有可信目录(仅使用默认工作空间) |++#### 概念说明++- **系统默认工作空间(workspace)**:固定路径 `~/.jiuwenclaw/agent/jiuwenclaw_workspace`,始终可用+- **可信目录(trusted_dirs)**:用户授权的可访问目录,由 TUI 管理,传递给后端 Agent++#### 控制逻辑++1. **启动确认**:TUI 启动时询问用户是否信任当前目录+ - 选择「信任」:将当前目录添加为可信目录+ - 选择「不信任」:仅使用默认工作空间++2. **会话级管理**:可信目录在当前 CLI 会话有效,不持久化到文件++3. **后端传递**:TUI 通过请求参数 `trusted_dirs` 传递可信目录列表,Agent 据此限制文件操作范围++4. **路径限制**:Agent 收到可信目录后,文件操作需限制在可信目录范围内;超出范围需向用户确认++5. **路径校验**:`add` 和 `set` 操作会校验路径是否存在,不存在则提示错误++#### 兼容别名++`/workspace_dir`、`/workspace-dir`### `/mode` 与 `/switch`(受控通道)diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex b0ae1631c5..5b39cbf171 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -2033,14 +2033,17 @@ class JiuWenClawDeepAdapter:if self._instance.deep_config is not None:self._instance.deep_config.language = resolved_language- async def _update_runtime_config(- self,- session_id: str | None,- mode: str = "agent.plan",- request_id: str | None = None,- channel_id: str | None = None,- request_metadata: dict[str, Any] | None = None,- ) -> None:+ @dataclass+ class _RuntimeConfig:+ """Per-request runtime config bundle for _update_runtime_config."""+ session_id: str | None = None+ mode: str = "agent.plan"+ request_id: str | None = None+ channel_id: str | None = None+ request_metadata: dict[str, Any] | None = None+ trusted_dirs: list[str] | None = None++ async def _update_runtime_config(self, runtime_config: "_RuntimeConfig") -> None:"""Register per-request tools for current agent execution."""if self._instance is None:raise RuntimeError("JiuWenClawDeepAdapter 未初始化,请先调用 create_instance()")@@ -2048,14 +2051,15 @@ class JiuWenClawDeepAdapter:resolved_language = self._resolve_runtime_language()if self._runtime_prompt_rail:self._runtime_prompt_rail.set_language(resolved_language)- resolved_channel = str(channel_id or self._resolve_prompt_channel(session_id) or "web").strip() or "web"+ resolved_channel = str(runtime_config.channel_id or self._resolve_prompt_channel(runtime_config.session_id) or "web").strip() or "web"self._runtime_prompt_rail.set_channel(resolved_channel)+ self._runtime_prompt_rail.set_trusted_dirs(runtime_config.trusted_dirs)- await self._update_rails_for_mode(mode)- await self._update_tools_for_mode(mode, session_id, request_id)- await self._update_session_tools(session_id, request_id, channel_id=channel_id)- self._refresh_acp_runtime_tools(session_id, request_id, channel_id, request_metadata)- self._update_prompt_for_mode(mode, resolved_language)+ await self._update_rails_for_mode(runtime_config.mode)+ await self._update_tools_for_mode(runtime_config.mode, runtime_config.session_id, runtime_config.request_id)+ await self._update_session_tools(runtime_config.session_id, runtime_config.request_id, channel_id=runtime_config.channel_id)+ self._refresh_acp_runtime_tools(runtime_config.session_id, runtime_config.request_id, runtime_config.channel_id, runtime_config.request_metadata)+ self._update_prompt_for_mode(runtime_config.mode, resolved_language)# user_todos 工具注册(工具只注册一次,channel_id 每次请求由 ContextVar 更新)try:@@ -2936,13 +2940,14 @@ class JiuWenClawDeepAdapter:resolved_model = self._resolve_model_for_request(request)self._apply_model_to_react_agent(resolved_model)try:- await self._update_runtime_config(- request.session_id,- mode,+ await self._update_runtime_config(self._RuntimeConfig(+ session_id=request.session_id,+ mode=mode,request_id=request.request_id,channel_id=request.channel_id,request_metadata=request.metadata,- )+ trusted_dirs=inputs.get("trusted_dirs"),+ ))result = await Runner.run_agent(agent=self._instance, inputs=inputs)except asyncio.CancelledError:logger.info("[JiuWenClawDeepAdapter] Agent 任务被取消: request_id=%s session_id=%s", request.request_id,@@ -3059,13 +3064,14 @@ class JiuWenClawDeepAdapter:resolved_model = self._resolve_model_for_request(request)self._apply_model_to_react_agent(resolved_model)try:- await self._update_runtime_config(- request.session_id,- mode,+ await self._update_runtime_config(self._RuntimeConfig(+ session_id=request.session_id,+ mode=mode,request_id=request.request_id,channel_id=request.channel_id,request_metadata=request.metadata,- )+ trusted_dirs=inputs.get("trusted_dirs"),+ ))if self._stream_event_rail is not None:self._stream_event_rail.reset_abort()async for chunk in Runner.run_agent_streaming(self._instance, inputs):diff --git a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.pyindex a117e1aabb..68d4273f1b 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py@@ -39,6 +39,7 @@ class RuntimePromptRail(DeepAgentRail):self._tz = timezone(timedelta(hours=timezone_offset))self._agent_name = agent_nameself._model_name = model_name+ self._trusted_dirs: list[str] | None = Nonedef init(self, agent) -> None:"""从 agent 获取 system_prompt_builder 引用。"""@@ -50,6 +51,7 @@ class RuntimePromptRail(DeepAgentRail):self.system_prompt_builder.remove_section("time")self.system_prompt_builder.remove_section("runtime")self.system_prompt_builder.remove_section("browser_tool_policy")+ self.system_prompt_builder.remove_section("trusted_dirs_policy")self.system_prompt_builder = Nonedef set_language(self, language: str) -> None:@@ -60,6 +62,10 @@ class RuntimePromptRail(DeepAgentRail):"""per-request 更新频道。"""self._channel = channel+ def set_trusted_dirs(self, trusted_dirs: list[str] | None) -> None:+ """per-request 更新可信目录。"""+ self._trusted_dirs = trusted_dirs+@staticmethoddef _get_git_branch() -> str:"""获取当前 git 分支名,失败时返回 N/A。"""@@ -165,3 +171,36 @@ class RuntimePromptRail(DeepAgentRail):content={"cn": browser_tool_policy, "en": browser_tool_policy},priority=98,))++ if self._channel == "tui":+ # Trusted directories policy for TUI mode+ if self._trusted_dirs and len(self._trusted_dirs) > 0:+ workspace_dir = "~/.jiuwenclaw/agent/jiuwenclaw_workspace"+ dirs_display = ", ".join(self._trusted_dirs)+ if self._language == "cn":+ trusted_dirs_content = (+ "# 可信目录策略\n\n"+ f"- 默认工作空间:{workspace_dir}\n"+ f"- 用户可信目录:{dirs_display}\n"+ "- 文件操作(读取、编辑、执行)必须限制在上述目录范围内\n"+ "- 若用户请求的操作涉及超出可信目录范围的路径,必须先向用户确认是否允许此次操作\n"+ "- 确认时需明确告知:操作的完整路径、操作类型(读取/编辑/执行)、潜在风险\n"+ )+ else:+ trusted_dirs_content = (+ "# Trusted Directories Policy\n\n"+ f"- Default workspace: {workspace_dir}\n"+ f"- User trusted directories: {dirs_display}\n"+ "- File operations (read, edit, execute) must be limited to the above directories\n"+ "- If the user requests an operation involving paths outside trusted directories, "+ "you must first ask the user to confirm whether to allow this operation\n"+ "- When confirming, clearly state: the full path, operation type (read/edit/execute), "+ "potential risks\n"+ )+ self.system_prompt_builder.add_section(PromptSection(+ name="trusted_dirs_policy",+ content={"cn": trusted_dirs_content, "en": trusted_dirs_content},+ priority=90,+ ))+ else:+ self.system_prompt_builder.remove_section("trusted_dirs_policy")diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex b6497ecb73..0f1a088243 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -76,7 +76,10 @@ _SKILL_ROUTES: dict[ReqMethod, str] = {}-def build_user_prompt(content: str, files: dict, channel: str, language: str) -> str:+def build_user_prompt(+ content: str, files: dict, channel: str,+ language: str, trusted_dirs: list[str] | None = None+ ) -> str:"""Build user prompt for the agent."""if language == "zh":prompt = "你收到一条消息:\n"@@ -95,19 +98,18 @@ def build_user_prompt(content: str, files: dict, channel: str, language: str) ->now = datetime.now(timezone(timedelta(hours=8)))now_str = now.strftime("%Y-%m-%d %H:%M:%S")-- return prompt + json.dumps(- {- "source": channel,- "timezone": "Asia/Shanghai",- "timestamp": now_str,- "preferred_response_language": language,- "content": content,- "files_updated_by_user": json.dumps(files, ensure_ascii=False),- "type": "user input",- },- ensure_ascii=False,- )+ user_message_context = {+ "source": channel,+ "timezone": "Asia/Shanghai",+ "timestamp": now_str,+ "preferred_response_language": language,+ "content": content,+ "files_updated_by_user": json.dumps(files, ensure_ascii=False),+ "type": "user input"+ }+ if trusted_dirs:+ user_message_context["trusted_dirs"] = json.dumps(trusted_dirs, ensure_ascii=False)+ return prompt + json.dumps(user_message_context, ensure_ascii=False)class JiuWenClaw:@@ -199,7 +201,7 @@ class JiuWenClaw:await adapter.reload_agent_config(config_base, env_overrides)logger.info("[JiuWenClaw] Agent config reloaded: sdk=%s", self._sdk_name)- def _build_inputs(self, request: AgentRequest) -> Tuple[dict[str, Any], str]:+ def _build_inputs(self, request: AgentRequest) -> Tuple[dict[str, Any], str, str]:"""构建 adapter 所需的 inputs 字典."""from openjiuwen.core.session.interaction.interactive_input import InteractiveInput@@ -209,6 +211,14 @@ class JiuWenClaw:channel = request.session_id.split('_')[0] if request.session_id else "web"language = config_base.get("preferred_language", "zh")+ # Get trusted directories from request params (passed by TUI)+ trusted_dirs: list[str] = []+ raw_trusted_dirs = request.params.get("trusted_dirs")+ if isinstance(raw_trusted_dirs, list):+ for d in raw_trusted_dirs:+ if isinstance(d, str) and d.strip():+ trusted_dirs.append(d.strip())+if isinstance(query, InteractiveInput):final_query = queryelse:@@ -220,14 +230,16 @@ class JiuWenClaw:query,files=request.params.get("files", {}),channel=channel,- language=language+ language=language,+ trusted_dirs=trusted_dirs,)else:final_query = build_user_prompt(query,files=request.params.get("files", {}),channel=channel,- language=language+ language=language,+ trusted_dirs=trusted_dirs,)inputs: dict[str, Any] = {@@ -241,6 +253,10 @@ class JiuWenClaw:enable_memory = request.metadata.get("enable_memory", True) if request.metadata else Trueinputs["enable_memory"] = enable_memory+ # 传递 trusted_dirs 参数(用于 RuntimePromptRail 添加路径限制策略)+ if trusted_dirs:+ inputs["trusted_dirs"] = trusted_dirs+run = request.params.get("run")if run:inputs["run"] = rundiff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.tsindex d3d0b5d614..3c5e706e93 100644--- a/jiuwenclaw/cli/src/app-state.ts+++ b/jiuwenclaw/cli/src/app-state.ts@@ -45,7 +45,13 @@ import {type ThemeName,} from "./ui/theme.js";import { type ConnectionStatus, WsClient } from "./core/ws-client.js";-import { loadTuiWorkspaceDir, saveTuiWorkspaceDir } from "./core/tui-workspace-dir-store.js";+import {+ getTrustedDirs,+ addTrustedDir,+ setTrustedDir,+ removeTrustedDir,+ clearTrustedDirs,+} from "./core/tui-trusted-dirs-store.js";export interface AppSnapshot {connectionStatus: ConnectionStatus;@@ -131,7 +137,6 @@ export class CliPiAppState {model: "",version: "",};- private workspaceDir: string = loadTuiWorkspaceDir();/** 当 closeUi 中 cancelBeforeExit 调 cancel({showNotice:false}) 时置 true,抑制 chat.interrupt_result 的 UI 通知。 */private suppressInterruptResult = false;private readonly eventDelegate: AppEventDelegate = {@@ -396,21 +401,18 @@ export class CliPiAppState {expandToolGroups: this.expandToolGroups,sessionTitle: snapshot.sessionTitle,setSessionTitle: this.setSessionTitle,- getWorkspaceDir: () => this.workspaceDir,- setWorkspaceDir: this.setWorkspaceDir,+ getTrustedDirs: getTrustedDirs,+ addTrustedDir: addTrustedDir,+ setTrustedDir: setTrustedDir,+ removeTrustedDir: removeTrustedDir,+ clearTrustedDirs: clearTrustedDirs,enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.};}- readonly setWorkspaceDir = (path: string): void => {- this.workspaceDir = path.trim();- saveTuiWorkspaceDir(this.workspaceDir);- this.emitChange();- };-readonly sendEventOnly = (method: string, params: Record<string, unknown>): string => {const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;- const wd = this.workspaceDir.trim();+ const trustedDirs = getTrustedDirs();this.wsClient.send({type: "req",id,@@ -418,7 +420,7 @@ export class CliPiAppState {params: {...params,session_id: (params.session_id as string | undefined) ?? this.sessionId,- ...(wd ? { workspace_dir: wd } : {}),+ ...(trustedDirs.length > 0 ? { trusted_dirs: trustedDirs } : {}),},});return id;diff --git a/jiuwenclaw/cli/src/core/commands/builtins/add-dir.ts b/jiuwenclaw/cli/src/core/commands/builtins/add-dir.tsdeleted file mode 100644index ed792e57a7..0000000000--- a/jiuwenclaw/cli/src/core/commands/builtins/add-dir.ts+++ /dev/null@@ -1,48 +0,0 @@-import { addError, addInfo } from "../helpers.js";-import { CommandKind, type SlashCommand } from "../types.js";--export function createAddDirCommand(): SlashCommand {- return {- name: "add-dir",- description: "Add a new working directory",- usage: "/add-dir <path>",- example: "/add-dir ../another-repo",- kind: CommandKind.BUILT_IN,- takesArgs: true,- action: async (ctx, args) => {- const directoryPath = args.trim();- try {- const payload = await ctx.request<{ path?: string; remember?: boolean }>(- "command.add_dir",- {- ...(directoryPath ? { path: directoryPath } : {}),- remember: false,- },- );- ctx.addItem(- addInfo(- ctx.sessionId,- payload?.path- ? `Requested working directory: ${payload.path}`- : "Requested add-dir flow without explicit path",- "i",- {- view: "kv",- title: "Add Directory",- items: [- {- label: "path",- value: typeof payload?.path === "string" ? payload.path : "(interactive)",- },- { label: "remember", value: String(Boolean(payload?.remember)) },- ],- },- ),- );- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- ctx.addItem(addError(ctx.sessionId, `add-dir failed: ${message}`));- }- },- };-}diff --git a/jiuwenclaw/cli/src/core/commands/builtins/workspace-dir.ts b/jiuwenclaw/cli/src/core/commands/builtins/workspace-dir.tsindex a290d8df50..fab29e762e 100644--- a/jiuwenclaw/cli/src/core/commands/builtins/workspace-dir.ts+++ b/jiuwenclaw/cli/src/core/commands/builtins/workspace-dir.ts@@ -1,74 +1,212 @@import { addError, addInfo } from "../helpers.js";import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";-function showCurrent(ctx: CommandContext): void {- const v = ctx.getWorkspaceDir();+function showAllTrustedPaths(ctx: CommandContext): void {+ const trustedDirs = ctx.getTrustedDirs();++ const items: Array<{ label: string; value: string }> = [];++ // Show system default workspace (fixed)+ items.push({+ label: "workspace (system)",+ value: "~/.jiuwenclaw/agent/jiuwenclaw_workspace",+ });++ // Show trusted directories+ if (trustedDirs.length > 0) {+ trustedDirs.forEach((dir, index) => {+ items.push({+ label: `trusted[${index}]`,+ value: dir,+ });+ });+ } else {+ items.push({+ label: "trusted",+ value: "(none - using workspace only)",+ });+ }+ctx.addItem(- addInfo(ctx.sessionId, v ? "Workspace directory" : "Workspace directory (not set)", "c", {+ addInfo(ctx.sessionId, "Trusted paths for file operations", "c", {view: "kv",- title: "workspace_dir",- items: [{ label: "path", value: v || "(empty)" }],+ title: "Trusted Paths",+ items,}),);}-export function createWorkspaceDirCommand(): SlashCommand {+/**+ * Ask user for Yes/No confirmation.+ * @returns true if user selected Yes, false if No or cancelled+ */+async function askYesNo(+ ctx: CommandContext,+ header: string,+ question: string,+ yesLabel: string,+ noLabel: string,+): Promise<boolean> {+ const answers = await ctx.askQuestions(+ [+ {+ header,+ question,+ options: [{ label: yesLabel }, { label: noLabel }],+ },+ ],+ "local_command",+ );+ const answer = answers[0];+ if (!answer) return false;+ const selected = answer.selected_options[0] ?? "";+ return selected === yesLabel;+}++export function createWorkspaceCommand(): SlashCommand {return {- name: "workspace_dir",- altNames: ["workspace-dir"],- description: "Set or show workspace directory (sent with each chat to gateway)",- usage: "/workspace_dir [get|set <path>|clear]",- example: "/workspace_dir set C:\\Projects\\my-app",+ name: "workspace",+ altNames: ["workspace_dir", "workspace-dir"],+ description: "Manage trusted directories for file operations",+ usage: "/workspace [get|add <path>|set <path>|remove <path>|clear]",+ example: "/workspace add ./",kind: CommandKind.BUILT_IN,takesArgs: true,subCommands: [+ {+ name: "get",+ description: "Show all trusted paths (workspace + trusted directories)",+ kind: CommandKind.BUILT_IN,+ takesArgs: false,+ action: async (ctx) => {+ showAllTrustedPaths(ctx);+ },+ },+ {+ name: "add",+ description: "Add a trusted directory (cwd by default)",+ usage: "/workspace add [path]",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ action: async (ctx, args) => {+ const directoryPath = args.trim();+ // Default to cwd if no path specified+ const resolvedPath = directoryPath || process.cwd();+ if (!resolvedPath) {+ ctx.addItem(addError(ctx.sessionId, "usage: /workspace add [path]"));+ return;+ }+ const result = ctx.addTrustedDir(resolvedPath);+ if (result === "added") {+ ctx.addItem(+ addInfo(ctx.sessionId, `Trusted directory added: ${resolvedPath}`, "c", {+ view: "kv",+ title: "Add Trusted Dir",+ items: [{ label: "path", value: resolvedPath }],+ }),+ );+ } else if (result === "exists") {+ ctx.addItem(addInfo(ctx.sessionId, `Path already set as trusted dir: ${resolvedPath}`, "c"));+ } else if (result === "not_found") {+ ctx.addItem(addError(ctx.sessionId, `Path does not exist: ${resolvedPath}`));+ } else {+ ctx.addItem(addError(ctx.sessionId, `Invalid path: ${resolvedPath}`));+ }+ },+ },{name: "set",- description: "Save workspace directory for this TUI",- usage: "/workspace_dir set <path>",+ description: "Reset trusted dirs and set a single path",+ usage: "/workspace set <path>",kind: CommandKind.BUILT_IN,takesArgs: true,action: async (ctx, args) => {- const path = args.trim();- if (!path) {- ctx.addItem(addError(ctx.sessionId, "usage: /workspace_dir set <path>"));+ const directoryPath = args.trim();+ if (!directoryPath) {+ ctx.addItem(addError(ctx.sessionId, "usage: /workspace set <path>"));return;}- ctx.setWorkspaceDir(path);- ctx.addItem(addInfo(ctx.sessionId, `Workspace directory set: ${path}`, "c"));++ // Check if path exists first+ const result = ctx.setTrustedDir(directoryPath);+ if (result === "not_found") {+ ctx.addItem(addError(ctx.sessionId, `Path does not exist: ${directoryPath}`));+ return;+ }+ if (result === "invalid") {+ ctx.addItem(addError(ctx.sessionId, `Invalid path: ${directoryPath}`));+ return;+ }++ // If trusted dirs already has content, ask for confirmation+ const currentDirs = ctx.getTrustedDirs();+ if (currentDirs.length > 0) {+ const confirmed = await askYesNo(+ ctx,+ "Confirm Reset",+ `This will clear all existing trusted directories and set "${directoryPath}" as the only trusted path.\nCurrent trusted dirs will be removed: ${currentDirs.join(", ")}`,+ "Yes, reset and set",+ "No, keep current",+ );+ if (!confirmed) {+ ctx.addItem(addInfo(ctx.sessionId, "Operation cancelled. Current trusted dirs unchanged.", "c"));+ return;+ }+ }++ // Execute the set operation+ ctx.setTrustedDir(directoryPath);+ ctx.addItem(+ addInfo(ctx.sessionId, `Trusted directory set: ${directoryPath}`, "c", {+ view: "kv",+ title: "Set Trusted Dir",+ items: [{ label: "path", value: directoryPath }],+ }),+ );},},{- name: "get",- description: "Show saved workspace directory",+ name: "remove",+ description: "Remove a trusted directory",+ usage: "/workspace remove <path>",kind: CommandKind.BUILT_IN,- takesArgs: false,- action: async (ctx) => {- showCurrent(ctx);+ takesArgs: true,+ action: async (ctx, args) => {+ const directoryPath = args.trim();+ if (!directoryPath) {+ ctx.addItem(addError(ctx.sessionId, "usage: /workspace remove <path>"));+ return;+ }+ const removed = ctx.removeTrustedDir(directoryPath);+ if (removed) {+ ctx.addItem(addInfo(ctx.sessionId, `Trusted directory removed: ${directoryPath}`, "c"));+ } else {+ ctx.addItem(addInfo(ctx.sessionId, `Path not in trusted dirs: ${directoryPath}`, "c"));+ }},},{name: "clear",- description: "Clear saved workspace directory",+ description: "Clear all trusted directories (will use default workspace only)",kind: CommandKind.BUILT_IN,takesArgs: false,action: async (ctx) => {- ctx.setWorkspaceDir("");- ctx.addItem(addInfo(ctx.sessionId, "Workspace directory cleared.", "c"));+ ctx.clearTrustedDirs();+ ctx.addItem(addInfo(ctx.sessionId, "Trusted directories cleared. Using default workspace only.", "c"));},},],action: async (ctx, args) => {if (!args.trim()) {- showCurrent(ctx);+ showAllTrustedPaths(ctx);return;}ctx.addItem(addError(ctx.sessionId,- "usage: /workspace_dir [get|set <path>|clear] — use subcommands, or /workspace_dir alone to show current",+ "usage: /workspace [get|add [path]|set <path>|remove <path>|clear] — use subcommands",),);},};-}+}\ No newline at end of filediff --git a/jiuwenclaw/cli/src/core/commands/registry.ts b/jiuwenclaw/cli/src/core/commands/registry.tsindex 2d0c8711c3..13225dda99 100644--- a/jiuwenclaw/cli/src/core/commands/registry.ts+++ b/jiuwenclaw/cli/src/core/commands/registry.ts@@ -1,6 +1,5 @@/** 内置 slash 与 Gateway 受控指令对齐时参见仓库 `jiuwenclaw/gateway/slash_command.py`(SSOT)与 `docs/zh/CLI_COMMANDS.md`。 */import type { SlashCommand } from "./types.js";-import { createAddDirCommand } from "./builtins/add-dir.js";import { createClearCommand } from "./builtins/clear.js";import { createColorCommand } from "./builtins/color.js";import { createCompactCommand } from "./builtins/compact.js";@@ -25,12 +24,11 @@ import { createRenameCommand } from "./builtins/rename.js";import { createSessionCommand } from "./builtins/session.js";import { createSkillsCommand } from "./builtins/skills.js";import { createThemeCommand } from "./builtins/theme.js";-import { createWorkspaceDirCommand } from "./builtins/workspace-dir.js";+import { createWorkspaceCommand } from "./builtins/workspace-dir.js";export function createBuiltinCommands(): SlashCommand[] {const commands: SlashCommand[] = [createHelpCommand(() => commands),- createAddDirCommand(),createClearCommand(),createInitCommand(),createColorCommand(),@@ -51,7 +49,7 @@ export function createBuiltinCommands(): SlashCommand[] {createSessionCommand(),createSkillsCommand(),createThemeCommand(),- createWorkspaceDirCommand(),+ createWorkspaceCommand(),createHotkeyCommand(),];diff --git a/jiuwenclaw/cli/src/core/commands/types.ts b/jiuwenclaw/cli/src/core/commands/types.tsindex a6f1e07963..57b8553820 100644--- a/jiuwenclaw/cli/src/core/commands/types.ts+++ b/jiuwenclaw/cli/src/core/commands/types.ts@@ -55,8 +55,12 @@ export interface CommandContext {expandToolGroups: (scope: "last" | "all") => void;sessionTitle: string;setSessionTitle: (title: string) => void;- getWorkspaceDir: () => string;- setWorkspaceDir: (path: string) => void;+ // Trusted directories management (global, not session-specific)+ getTrustedDirs: () => string[];+ addTrustedDir: (path: string) => "added" | "exists" | "not_found" | "invalid";+ setTrustedDir: (path: string) => "set" | "not_found" | "invalid";+ removeTrustedDir: (path: string) => boolean;+ clearTrustedDirs: () => void;enterConfigEditor?: (focusKey?: string,configPayload?: Record<string, unknown> & { schema?: ConfigItemSchema[] },diff --git a/jiuwenclaw/cli/src/core/tui-trusted-dirs-store.ts b/jiuwenclaw/cli/src/core/tui-trusted-dirs-store.tsnew file mode 100644index 0000000000..5863204a46--- /dev/null+++ b/jiuwenclaw/cli/src/core/tui-trusted-dirs-store.ts@@ -0,0 +1,112 @@+import { existsSync } from "node:fs";+import { resolve } from "node:path";++/**+ * In-memory trusted directories storage (session-based, no persistence).+ * Managed at CLI startup and via /workspace commands.+ */+let _trustedDirs: string[] = [];++/**+ * Normalize a path for comparison (handle trailing separators, case on Windows)+ */+function normalizePath(path: string): string {+ const trimmed = path.trim();+ if (!trimmed) {+ return "";+ }+ const resolved = resolve(trimmed);+ // On Windows, normalize case+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;+}++/**+ * Get all trusted directories.+ * Returns empty array if no dirs set (will use default workspace).+ * @returns Array of trusted directory paths (normalized)+ */+export function getTrustedDirs(): string[] {+ return [..._trustedDirs];+}++/**+ * Add a trusted directory.+ * @param path - Directory path to add+ * @returns "added" if added, "exists" if already trusted, "not_found" if path doesn't exist, "invalid" if invalid path+ */+export function addTrustedDir(path: string): "added" | "exists" | "not_found" | "invalid" {+ const normalized = normalizePath(path);+ if (!normalized) {+ return "invalid";+ }+ if (!existsSync(normalized)) {+ return "not_found";+ }+ if (_trustedDirs.includes(normalized)) {+ return "exists";+ }+ _trustedDirs.push(normalized);+ return "added";+}++/**+ * Reset trusted dirs and set a single path.+ * @param path - Directory path to set as the only trusted dir+ * @returns "set" if set successfully, "not_found" if path doesn't exist, "invalid" if invalid path+ */+export function setTrustedDir(path: string): "set" | "not_found" | "invalid" {+ const normalized = normalizePath(path);+ if (!normalized) {+ return "invalid";+ }+ if (!existsSync(normalized)) {+ return "not_found";+ }+ _trustedDirs = [normalized];+ return "set";+}++/**+ * Remove a trusted directory.+ * @param path - Directory path to remove+ * @returns true if removed, false if not found+ */+export function removeTrustedDir(path: string): boolean {+ const normalized = normalizePath(path);+ if (!normalized) {+ return false;+ }+ const index = _trustedDirs.indexOf(normalized);+ if (index === -1) {+ return false;+ }+ _trustedDirs.splice(index, 1);+ return true;+}++/**+ * Clear all trusted directories (will use default workspace only).+ */+export function clearTrustedDirs(): void {+ _trustedDirs = [];+}++/**+ * Check if a path is a trusted directory.+ * @param path - Directory path to check+ * @returns true if trusted+ */+export function isTrustedDir(path: string): boolean {+ const normalized = normalizePath(path);+ if (!normalized) {+ return false;+ }+ return _trustedDirs.includes(normalized);+}++/**+ * Get the default workspace path.+ */+export function getDefaultWorkspacePath(): string {+ return resolve("~/.jiuwenclaw/agent/jiuwenclaw_workspace");+}\ No newline at end of filediff --git a/jiuwenclaw/cli/src/core/tui-workspace-dir-store.ts b/jiuwenclaw/cli/src/core/tui-workspace-dir-store.tsdeleted file mode 100644index cf2bb3a600..0000000000--- a/jiuwenclaw/cli/src/core/tui-workspace-dir-store.ts+++ /dev/null@@ -1,23 +0,0 @@-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";--const STATE_DIR = join(homedir(), ".jiuwenclaw");-const STATE_FILE = join(STATE_DIR, "tui-workspace-dir");--export function loadTuiWorkspaceDir(): string {- try {- if (!existsSync(STATE_FILE)) {- return "";- }- return readFileSync(STATE_FILE, "utf8").trim();- } catch {- return "";- }-}--export function saveTuiWorkspaceDir(value: string): void {- mkdirSync(STATE_DIR, { recursive: true });- const trimmed = value.trim();- writeFileSync(STATE_FILE, trimmed ? `${trimmed}\n` : "", "utf8");-}diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.tsindex 4a5cecd0c4..f84f4bc2d0 100644--- a/jiuwenclaw/cli/src/ui/app-screen.ts+++ b/jiuwenclaw/cli/src/ui/app-screen.ts@@ -32,6 +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 { handleAppScreenKeyInput } from "./keymap.js";import { buildAppScreenLines } from "./screen-layout.js";import {@@ -338,6 +339,7 @@ export class AppScreen implements Component, Focusable {private resumeSessionList: ResumeSessionListState | null = null;private modelList: ModelListState | null = null;private configEditorState: ConfigEditorState | null = null;+ private startupPromptList: SelectList | null = null;private showTodos = true;private showTeamPanel = false;private selectedTeamMemberId: string | null = null;@@ -375,6 +377,40 @@ export class AppScreen implements Component, Focusable {this.unsubscribe = this.state.onChange(() => {this.handleStateChange();});+ // Initialize startup prompt for workspace trust+ this.initStartupPrompt();+ }++ private initStartupPrompt(): void {+ const cwd = process.cwd();+ const items: SelectItem[] = [+ {+ label: "Yes, I trust this folder",+ value: "yes",+ description: "JiuwenClaw will be able to read, edit, and execute files here",+ },+ {+ label: "No, use default workspace",+ value: "no",+ description: "Only ~/.jiuwenclaw/agent/jiuwenclaw_workspace will be accessible",+ },+ ];+ this.startupPromptList = new SelectList(items, 2, selectListTheme, {+ minPrimaryColumnWidth: 40,+ maxPrimaryColumnWidth: 60,+ });+ this.startupPromptList.onSelect = (item) => {+ if (item.value === "yes") {+ addTrustedDir(cwd);+ }+ this.startupPromptList = null;+ this.tui.requestRender();+ };+ this.startupPromptList.onCancel = () => {+ // Same as "No" - use default workspace+ this.startupPromptList = null;+ this.tui.requestRender();+ };}get focused(): boolean {@@ -482,6 +518,13 @@ export class AppScreen implements Component, Focusable {}}+ // Startup prompt for workspace trust (shown first)+ if (this.startupPromptList !== null) {+ this.startupPromptList.handleInput(data);+ this.tui.requestRender();+ return;+ }+if (!snapshot.pendingQuestion && this.resumeSessionList !== null) {this.resumeSessionList.list.handleInput(data);this.tui.requestRender();@@ -579,6 +622,7 @@ export class AppScreen implements Component, Focusable {const editorLines = this.applySlashCommandHint(this.editor.render(width), width);const composerPreviewLines: string[] = [];const questionLines = [+ ...this.buildStartupPromptLines(width),...this.buildConfigEditorLines(width),...this.buildResumeSessionListLines(width),...this.buildModelListLines(width),@@ -839,6 +883,26 @@ export class AppScreen implements Component, Focusable {this.tui.requestRender();}+ private buildStartupPromptLines(width: number): string[] {+ if (!this.startupPromptList) {+ return [];+ }+ const cwd = process.cwd();+ return [+ "",+ padToWidth(palette.status.warning("Safety Check"), width),+ "",+ padToWidth(palette.text.primary(`Current folder: ${cwd}`), width),+ "",+ padToWidth(palette.text.dim("Is this a project you created or one you trust?"), width),+ padToWidth(palette.text.dim("(e.g. your own code, well-known open source, or team project)"), width),+ padToWidth(palette.text.dim("If unfamiliar, please review the folder contents before proceeding."), width),+ "",+ ...this.startupPromptList.render(width),+ padToWidth(palette.text.dim("↑/↓ choose · Enter confirm · Esc use default workspace"), width),+ ];+ }+private buildResumeSessionListLines(width: number): string[] {if (!this.resumeSessionList) {return [];diff --git a/jiuwenclaw/web/src/utils/formatters.ts b/jiuwenclaw/web/src/utils/formatters.tsindex b443122be1..d7869050cd 100644--- a/jiuwenclaw/web/src/utils/formatters.ts+++ b/jiuwenclaw/web/src/utils/formatters.ts@@ -68,7 +68,7 @@ export function formatToolArguments(args: Record<string, unknown>): string {/*** 格式化工具结果(截断长结果)*/-export function formatToolResult(result: string, maxLength = 500): string {+export function formatToolResult(result: string, maxLength = 10000): string {if (result.length <= maxLength) return result;return result.slice(0, maxLength) + `\n... (${i18n.t('chatUi.toolResult.truncated')})`;}