JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(tui): add workspace_dir slash_command.py
douran9bf4b510a2dc
diff --git a/docs/en/CLI.md b/docs/en/CLI.mdindex c6d8f28f06..50ac21ef07 100644--- a/docs/en/CLI.md+++ b/docs/en/CLI.md@@ -74,3 +74,24 @@ The Gateway will:- Stored **per channel** (`channel_id` → `mode`). All later messages on that channel use the current mode.- Initial value can come from `default_mode` in config; `MessageHandler` reads it on startup.+---++### 3. TUI: `/workspace_dir` — workspace path for outbound requests++**Scope:** terminal UI (`jiuwenclaw-cli`) only; parsed locally, not by the Gateway control pipeline.++**Behavior**++- **`/workspace_dir`** or **`/workspace_dir get`**: show the saved workspace directory (if any).+- **`/workspace_dir set <path>`**: save a path (spaces allowed). Example: `/workspace_dir set C:\Projects\my-app`+- **`/workspace_dir clear`**: clear the saved value.+- Alias: **`/workspace-dir`**.++**Persistence**++- Stored as a single-line file: **`~/.jiuwenclaw/tui-workspace-dir`**.++**Gateway / Agent**++- When a non-empty path is set, TUI includes **`workspace_dir`** in the WebSocket **`params`** for fire-and-forget requests built by `sendEventOnly` (e.g. `chat.send`), so Gateway and AgentServer can read it from `Message.params` / `AgentRequest.params`. Downstream usage depends on the agent and extensions.+diff --git a/docs/zh/SLASH_COMMAND_ARCHITECTURE.md b/docs/zh/SLASH_COMMAND_ARCHITECTURE.mdindex 3784be8732..25aa362e91 100644--- a/docs/zh/SLASH_COMMAND_ARCHITECTURE.md+++ b/docs/zh/SLASH_COMMAND_ARCHITECTURE.md@@ -140,4 +140,4 @@## 10. 当前命令现状表(基于 `gateway/slash_command.py`)-当前命令清单已拆分到独立文档:[`Slash命令表.md`](./当前Slash命令现状表.md)。+当前命令清单已拆分到独立文档:[`Slash命令表.md`](./Slash命令表.md)。diff --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 f1b886a270..2d7d237279 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"@@ -18,6 +18,14 @@| `/theme` | 切换主题 || `/mode` | 切换当前模式(支持一级入口与直达值;**仅 IM 通道生效**) || `/config` | 修改配置(当前为 TUI 本地实现;规划改为走 Gateway 统一接口) |+| `/workspace_dir` | 设置、查看或清空 **TUI 工作区路径**(见下方说明) |++**`/workspace_dir`(TUI 工作区目录)**++- **子命令**:`/workspace_dir` 或 `/workspace_dir get` 查看当前值;`/workspace_dir set <path>` 保存路径(路径可含空格);`/workspace_dir clear` 清空。+- **别名**:`/workspace-dir`。+- **持久化**:写入用户目录下 `~/.jiuwenclaw/tui-workspace-dir`(单行文本)。+- **与 Gateway 的关系**:在已保存非空路径时,TUI 通过 `sendEventOnly` 发往 Gateway 的请求 **`params` 会附带 `workspace_dir`**(与普通对话、部分中断/权限相关请求一致),供 Gateway / AgentServer 在 `Message.params` / `AgentRequest.params` 中使用;具体消费逻辑以 Agent 与扩展为准。---diff --git a/jiuwenclaw/agentserver/agent_manager.py b/jiuwenclaw/agentserver/agent_manager.pyindex 26319348a7..7e7a562097 100644--- a/jiuwenclaw/agentserver/agent_manager.py+++ b/jiuwenclaw/agentserver/agent_manager.py@@ -141,7 +141,12 @@ class AgentManager:return session_idreturn "default"- async def get_agent(self, channel_id: str = "", mode: str = "agent") -> "JiuWenClaw | None":+ async def get_agent(+ self,+ channel_id: str = "",+ mode: str = "agent",+ workspace_dir: str = None+ ) -> "JiuWenClaw | None":"""获取 Agent 实例(自动创建).如果 agent 不存在,会自动创建(仅用于非 ACP 场景)。@@ -149,6 +154,7 @@ class AgentManager:Args:channel_id: 通道 IDmode: 每个模式对应的实例+ workspace_dir: project dirReturns:JiuWenClaw | None: Agent 实例@@ -156,9 +162,12 @@ class AgentManager:if channel_id in self.agents and mode in self.agents[channel_id]:return self.agents[channel_id][mode]else:- config: dict[str, Any] | None = None+ config = {"workspace_dir": workspace_dir} if workspace_dir else {}if channel_id == "acp":- config = _build_acp_agent_config()+ config = {+ **config,+ **_build_acp_agent_config()+ }await self._create_agent(channel_id, mode, config)return self.agents.get(channel_id, {}).get(mode)diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.pyindex 507689ef80..5ca6388cdf 100644--- a/jiuwenclaw/agentserver/agent_ws_server.py+++ b/jiuwenclaw/agentserver/agent_ws_server.py@@ -431,7 +431,11 @@ class AgentWebSocketServer:returnmode = request.params.get("mode", "agent.plan").split(".")[0]- agent = await self._agent_manager.get_agent(channel_id=channel_id, mode=mode)+ agent = await self._agent_manager.get_agent(+ channel_id=channel_id,+ mode=mode,+ workspace_dir=request.params.get("workspace_dir", None)+ )if agent is None:raise ValueError("Failed to get agent")@@ -461,7 +465,11 @@ class AgentWebSocketServer:"""流式处理:调用 process_message_stream,逐条发送 E2AResponse 线 JSON。"""channel_id = request.channel_id or "default"mode = request.params.get("mode", "agent.plan").split(".")[0]- agent = await self._agent_manager.get_agent(channel_id=channel_id, mode=mode)+ agent = await self._agent_manager.get_agent(+ channel_id=channel_id,+ mode=mode,+ workspace_dir=request.params.get("workspace_dir", None)+ )if agent is None:raise ValueError("Failed to get agent")diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex 1df58b73d6..65c0783d7e 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -1407,6 +1407,7 @@ class JiuWenClawDeepAdapter:config = config_base.get('react', {}).copy()self._config_cache = config.copy()self._agent_name = self._instance_overrides.get("agent_name", config.get("agent_name", "main_agent"))+ self._workspace_dir = self._instance_overrides.get("workspace_dir", config.get("workspace_dir", "workspace"))model = self._create_model(config_base)agent_card = AgentCard(name=self._agent_name, id='jiuwenclaw')diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.tsindex 2d6601d2f6..34289c37ce 100644--- a/jiuwenclaw/cli/src/app-state.ts+++ b/jiuwenclaw/cli/src/app-state.ts@@ -41,6 +41,7 @@ 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";export interface AppSnapshot {connectionStatus: ConnectionStatus;@@ -116,6 +117,7 @@ export class CliPiAppState {model: "",version: "",};+ private workspaceDir: string = loadTuiWorkspaceDir();private readonly eventDelegate: AppEventDelegate = {getConnectionStatus: () => this.connectionStatus,getSessionId: () => this.sessionId,@@ -330,17 +332,30 @@ export class CliPiAppState {expandToolGroups: this.expandToolGroups,sessionTitle: snapshot.sessionTitle,setSessionTitle: this.setSessionTitle,+ getWorkspaceDir: () => this.workspaceDir,+ setWorkspaceDir: this.setWorkspaceDir,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();this.wsClient.send({type: "req",id,method,- params: { ...params, session_id: (params.session_id as string | undefined) ?? this.sessionId },+ params: {+ ...params,+ session_id: (params.session_id as string | undefined) ?? this.sessionId,+ ...(wd ? { workspace_dir: wd } : {}),+ },});return id;};diff --git a/jiuwenclaw/cli/src/core/commands/builtins/workspace-dir.ts b/jiuwenclaw/cli/src/core/commands/builtins/workspace-dir.tsnew file mode 100644index 0000000000..a290d8df50--- /dev/null+++ b/jiuwenclaw/cli/src/core/commands/builtins/workspace-dir.ts@@ -0,0 +1,74 @@+import { addError, addInfo } from "../helpers.js";+import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";++function showCurrent(ctx: CommandContext): void {+ const v = ctx.getWorkspaceDir();+ ctx.addItem(+ addInfo(ctx.sessionId, v ? "Workspace directory" : "Workspace directory (not set)", "c", {+ view: "kv",+ title: "workspace_dir",+ items: [{ label: "path", value: v || "(empty)" }],+ }),+ );+}++export function createWorkspaceDirCommand(): 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",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ subCommands: [+ {+ name: "set",+ description: "Save workspace directory for this TUI",+ usage: "/workspace_dir 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>"));+ return;+ }+ ctx.setWorkspaceDir(path);+ ctx.addItem(addInfo(ctx.sessionId, `Workspace directory set: ${path}`, "c"));+ },+ },+ {+ name: "get",+ description: "Show saved workspace directory",+ kind: CommandKind.BUILT_IN,+ takesArgs: false,+ action: async (ctx) => {+ showCurrent(ctx);+ },+ },+ {+ name: "clear",+ description: "Clear saved workspace directory",+ kind: CommandKind.BUILT_IN,+ takesArgs: false,+ action: async (ctx) => {+ ctx.setWorkspaceDir("");+ ctx.addItem(addInfo(ctx.sessionId, "Workspace directory cleared.", "c"));+ },+ },+ ],+ action: async (ctx, args) => {+ if (!args.trim()) {+ showCurrent(ctx);+ return;+ }+ ctx.addItem(+ addError(+ ctx.sessionId,+ "usage: /workspace_dir [get|set <path>|clear] — use subcommands, or /workspace_dir alone to show current",+ ),+ );+ },+ };+}diff --git a/jiuwenclaw/cli/src/core/commands/registry.ts b/jiuwenclaw/cli/src/core/commands/registry.tsindex 3615926e31..636df9f21b 100644--- a/jiuwenclaw/cli/src/core/commands/registry.ts+++ b/jiuwenclaw/cli/src/core/commands/registry.ts@@ -25,6 +25,7 @@ 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";export function createBuiltinCommands(): SlashCommand[] {const commands: SlashCommand[] = [@@ -50,6 +51,7 @@ export function createBuiltinCommands(): SlashCommand[] {createSessionCommand(),createSkillsCommand(),createThemeCommand(),+ createWorkspaceDirCommand(),createHotkeyCommand(),];diff --git a/jiuwenclaw/cli/src/core/commands/types.ts b/jiuwenclaw/cli/src/core/commands/types.tsindex 4342b71b8d..c44ea23f20 100644--- a/jiuwenclaw/cli/src/core/commands/types.ts+++ b/jiuwenclaw/cli/src/core/commands/types.ts@@ -54,6 +54,8 @@ export interface CommandContext {expandToolGroups: (scope: "last" | "all") => void;sessionTitle: string;setSessionTitle: (title: string) => void;+ getWorkspaceDir: () => string;+ setWorkspaceDir: (path: string) => void;enterConfigEditor?: (focusKey?: string,configPayload?: Record<string, unknown> & { schema?: ConfigItemSchema[] },diff --git a/jiuwenclaw/cli/src/core/tui-workspace-dir-store.ts b/jiuwenclaw/cli/src/core/tui-workspace-dir-store.tsnew file mode 100644index 0000000000..cf2bb3a600--- /dev/null+++ b/jiuwenclaw/cli/src/core/tui-workspace-dir-store.ts@@ -0,0 +1,23 @@+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/gateway/slash_command.py b/jiuwenclaw/gateway/slash_command.pyindex ab7a331971..fabdd4a205 100644--- a/jiuwenclaw/gateway/slash_command.py+++ b/jiuwenclaw/gateway/slash_command.py@@ -204,6 +204,13 @@ FIRST_BATCH_REGISTRY: tuple[SlashCommandEntry, ...] = (req_method="command.resume",notes="CLI 会话恢复;另用 session.list。IM 受控通道本阶段不解析,后续可扩展。",),+ SlashCommandEntry(+ id="workspace_dir",+ canonical_text="/workspace_dir [get|set <path>|clear]",+ scope="client",+ req_method=None,+ notes="TUI 本地保存工作区路径;随 chat.send params.workspace_dir 发往 Gateway/AgentServer。",+ ),)diff --git a/jiuwenclaw/schema/agent.py b/jiuwenclaw/schema/agent.pyindex 223ce97376..181de61015 100644--- a/jiuwenclaw/schema/agent.py+++ b/jiuwenclaw/schema/agent.py@@ -78,6 +78,7 @@ class AgentRequest:metadata: dict[str, Any] | None = Noneenable_memory: bool | None = Nonepermission_context: PermissionContext | None = None+ workspace_dir: str = None@dataclassdiff --git a/tests/unit_tests/gateway/test_slash_command.py b/tests/unit_tests/gateway/test_slash_command.pyindex 66ba705b84..cbacb7e6a9 100644--- a/tests/unit_tests/gateway/test_slash_command.py+++ b/tests/unit_tests/gateway/test_slash_command.py@@ -112,4 +112,4 @@ def test_format_skills_list_for_notice() -> None:def test_first_batch_registry_ids() -> None:ids = {e.id for e in FIRST_BATCH_REGISTRY}- assert ids == {"new_session", "mode", "switch", "skills", "resume"}+ assert ids == {"new_session", "mode", "switch", "skills", "resume", "workspace_dir"}