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:企业版系统提示词workspace目录异常问题
hanjiahuic2993eee14e9
diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.pyindex f9aeee6644..7a932f8e98 100644--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py@@ -1,7 +1,6 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.import sysfrom enum import IntEnum-from pathlib import Pathfrom typing import Optionalfrom openjiuwen.harness.prompts import SystemPromptBuilder, PromptSection, resolve_language@@ -9,16 +8,10 @@ from jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shefrom jiuwenswarm.common.config import get_sandbox_runtimefrom jiuwenswarm.common.utils import logger-from jiuwenswarm.common.utils import (- get_user_workspace_dir,- get_agent_memory_dir,- get_agent_skills_dir,- get_agent_workspace_dir,- get_deepagent_todo_dir,-)+from jiuwenswarm.common.utils import get_user_workspace_dir-def _get_config_dir() -> "Path":+def _get_config_dir():return get_user_workspace_dir() / "config"@@ -247,10 +240,6 @@ def _identity_prompt(language: str,) -> PromptSection:config_dir = _get_config_dir()- agent_workspace_dir = get_agent_workspace_dir()- memory_dir = get_agent_memory_dir()- skills_dir = get_agent_skills_dir()- todo_dir = get_deepagent_todo_dir()os_type = sys.platformshell_env_prompt = build_shell_environment_prompt(language, os_type)@@ -296,17 +285,17 @@ JiuwenSwarm 使用独立的内部数据目录保存启动配置、Agent 身份这些内部数据目录不等于用户当前处理的项目目录,也不是用户任务中相对路径的默认含义。-| 路径 | 类型 | 用途 | 操作建议 |+| 逻辑路径 | 类型 | 用途 | 操作建议 ||------|------|------|----------|-| `{config_dir}` | JiuwenSwarm 启动配置目录 | 保存 `config.yaml` 和 `.env` | 只有用户明确要求修改 JiuwenSwarm 自身配置时才访问 |-| `{agent_workspace_dir}` | Agent 内部数据目录 | 保存身份、记忆、技能、待办和运行状态 | 不要在其中搜索或运行用户项目文件 |-| `{memory_dir}` | Agent 记忆目录 | 保存持久化记忆 | 将其视为 Agent 记忆的一部分 |-| `{skills_dir}` | Agent 技能目录 | 保存和读取技能 | 可以读取和调用,不要作为项目目录使用 |-| `{todo_dir}` | Agent 待办目录 | 保存任务和待办状态 | 用于任务状态管理 |+| JiuwenSwarm 启动配置目录 | JiuwenSwarm 启动配置目录 | 保存 `config.yaml` 和 `.env` | 只有用户明确要求修改 JiuwenSwarm 自身配置时才访问;绝对路径见「运行时目录上下文」 |+| Agent 内部数据目录 | Agent 内部数据目录 | 保存身份、记忆、技能、待办和运行状态 | 不要在其中搜索或运行用户项目文件;绝对路径见「运行时目录上下文」 |+| Agent 内部数据目录/memory | Agent 记忆目录 | 保存持久化记忆 | 将其视为 Agent 记忆的一部分 |+| Agent 内部数据目录/skills | Agent 技能目录 | 保存和读取技能 | 可以读取和调用,不要作为项目目录使用 |+| Agent 内部数据目录/todo | Agent 待办目录 | 保存任务和待办状态 | 用于任务状态管理 |## 目录理解规则-- 当前项目目录和当前工作目录由后面的“运行时目录上下文”提供。+- 当前项目目录、当前工作目录以及 Agent 内部数据目录的**绝对路径**,由后面的「运行时目录上下文」提供;不要使用本节逻辑路径名去猜测或拼接盘符路径。- 当前项目目录是用户项目的根目录,也是本次任务的 workspace 操作边界。- 当前工作目录(cwd)是 Bash 默认执行目录,也是用户任务中相对路径的解析基准。- Agent 内部数据目录只保存 Agent 自身数据,不是用户项目。@@ -378,7 +367,7 @@ JiuwenSwarm 使用独立的内部数据目录保存启动配置、Agent 身份- 非项目型通用产物:当前未绑定项目时,报告、导出文件、图片、数据文件等非项目型产物应放在当前工作目录中的合理位置。- Agent 内部数据:Agent 身份、记忆、技能、待办和运行状态,只能保存在 Agent 内部数据目录的对应位置。- 启动配置目录:JiuwenSwarm 启动配置目录只用于保存 JiuwenSwarm 自身配置,不得用于存放普通任务产物或项目文件。-- 不要仅因为 `{agent_workspace_dir}` 的物理目录名包含 `workspace`,就把它当作用户项目的输出目录。+- 不要仅因为 Agent 内部数据目录的物理路径名包含 `workspace`,就把它当作用户项目的输出目录。## 文件发送@@ -412,17 +401,19 @@ Agent identity, memory, skills, todos, and runtime state.These internal data directories are not the project currently being handled for the user.They are not the default meaning of relative paths in user tasks.-| Path | Type | Purpose | Guidance |+| Logical path | Type | Purpose | Guidance ||------|------|---------|----------|-| `{config_dir}` | Startup config | Stores `config.yaml` and `.env` | Access only for JiuwenSwarm config tasks |-| `{agent_workspace_dir}` | Agent data | Stores identity, memory, skills, todos | Not for user project files |-| `{memory_dir}` | Agent memory directory | Stores persistent memory | Treat it as part of the Agent's memory |-| `{skills_dir}` | Agent skills | Stores and provides skills | May be read/invoked; not a project directory |-| `{todo_dir}` | Agent todo directory | Stores tasks and todo state | Use it for task-state management |+| Startup config directory | Startup config | `config.yaml` / `.env` | Config only; abs path in runtime context |+| Agent internal data directory | Agent data | identity/memory/skills/todos | Not project files; see runtime context |+| Agent internal data directory/memory | Agent memory | Persistent memory | Part of Agent memory |+| Agent internal data directory/skills | Agent skills | Skill storage | Read/invoke; not a project dir |+| Agent internal data directory/todo | Agent todo | Tasks and todo state | For task-state management |## Directory Interpretation Rules-- The current project directory and current working directory are provided later in the runtime directory context.+- Absolute paths for the current project directory, current working directory, and Agent+ internal data directory are provided later in the runtime directory context.+ Do not invent absolute paths from the logical names in this section.- The current project directory is the root of the user's project and the workspace boundary for the current task.- The current working directory (`cwd`) is Bash's default execution directoryand the base directory for resolving relative paths in user tasks.@@ -513,8 +504,8 @@ If the user does not specify a location, follow these rules:in their designated locations inside the Agent internal data directory.- Startup configuration directory: The JiuwenSwarm startup configuration directory is reservedfor JiuwenSwarm's own configuration, not ordinary task artifacts or project files.-- Do not treat `{agent_workspace_dir}` as the user's project output directory merely because- its physical directory name contains the word `workspace`.+- Do not treat the Agent internal data directory as the user's project output directory merely because+ its physical path name contains the word `workspace`.## Sending Filesdiff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex c69fb83572..d36fcd2a50 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -7,7 +7,6 @@ every model call by reading runtime_state.yaml in Python, so the LLM alwayssees the current values without needing to call any tool."""from __future__ import annotations-from jiuwenswarm.edition import is_enterpriseimport osimport sys@@ -26,7 +25,10 @@ from openjiuwen.harness.prompts.prompt_attachment_manager import (from openjiuwen.harness.rails.base import DeepAgentRailfrom jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shell_environment_promptfrom jiuwenswarm.common.utils import (+ get_agent_memory_dir,+ get_agent_skills_dir,get_agent_workspace_dir,+ get_deepagent_todo_dir,get_runtime_state_path,get_user_workspace_dir,logger,@@ -157,19 +159,63 @@ class RuntimePromptRail(DeepAgentRail):self._request_system_prompt = valuedef _resolve_agent_workspace_and_config(self) -> tuple[str, str]:- """Resolve agent workspace / config dirs; enterprise uses workspace_key paths."""- if self._workspace_dir and is_enterprise():- workspace_root = Path(self._workspace_dir)- base_workspace = workspace_root.parent.parent- return str(workspace_root), str(base_workspace / "config")+ """Resolve agent workspace and JiuwenSwarm startup config dirs.++ Agent workspace may be tenant-scoped (enterprise ``workspace_{key}``).+ Startup config is always the process-wide ``~/.jiuwenswarm/config``,+ never ``workspace_{key}/config``.+ """+ config_dir = str(get_user_workspace_dir() / "config")if self._workspace_dir:+ return str(Path(self._workspace_dir)), config_dir+ return str(get_agent_workspace_dir()), config_dir++ @staticmethod+ def _format_agent_data_paths(+ agent_workspace_dir: str,+ config_dir: str,+ *,+ language: str,+ ) -> str:+ """Absolute agent-internal paths for the runtime directory context.++ Identity prompt only describes logical layout; this block is the sole+ source of absolute paths for agent data (skills/memory/todo).++ When ``agent_workspace_dir`` matches the bound+ :func:`get_agent_workspace_dir`, resolve skills/memory/todo via the+ PathProvider-aware getters so custom deployments stay consistent with+ tools. An explicit alternate workspace root keeps the standard layout+ contract (``<workspace>/{skills,memory,todo}``).+ """+ root = Path(agent_workspace_dir)+ bound_ws = os.path.abspath(str(get_agent_workspace_dir()))+ same_as_bound = os.path.normcase(os.path.abspath(str(root))) == os.path.normcase(+ bound_ws+ )+ if same_as_bound:+ skills = str(get_agent_skills_dir())+ memory = str(get_agent_memory_dir())+ todo = str(get_deepagent_todo_dir())+ else:+ # Explicit non-bound workspace: assume standard subdir layout.+ skills = str(root / "skills")+ memory = str(root / "memory")+ todo = str(root / "todo")+ if language == "cn":return (- str(Path(self._workspace_dir)),- str(get_user_workspace_dir() / "config"),+ f"- Agent 内部数据目录:{agent_workspace_dir}\n"+ f"- Agent 技能目录:{skills}\n"+ f"- Agent 记忆目录:{memory}\n"+ f"- Agent 待办目录:{todo}\n"+ f"- JiuwenSwarm 启动配置目录:{config_dir}\n")return (- str(get_agent_workspace_dir()),- str(get_user_workspace_dir() / "config"),+ f"- Agent internal data directory: {agent_workspace_dir}\n"+ f"- Agent skills directory: {skills}\n"+ f"- Agent memory directory: {memory}\n"+ f"- Agent todo directory: {todo}\n"+ f"- JiuwenSwarm startup configuration directory: {config_dir}\n")@staticmethod@@ -565,7 +611,12 @@ class RuntimePromptRail(DeepAgentRail):trusted_dirs = self._existing_dirs(self._trusted_dirs)# Prefer explicit per-agent workspace; enterprise uses multi-tenant paths.resolved_ws, config_dir = self._resolve_agent_workspace_and_config()- agent_workspace_dir = self._existing_dir(self._workspace_dir) or resolved_ws+ if self._workspace_dir and str(self._workspace_dir).strip():+ agent_workspace_dir = os.path.abspath(+ os.path.expanduser(str(self._workspace_dir).strip())+ )+ else:+ agent_workspace_dir = resolved_wsproject_dir = self._existing_dir(self._project_dir)runtime_cwd = (self._existing_dir(self._cwd)@@ -584,6 +635,12 @@ class RuntimePromptRail(DeepAgentRail):other_dirs.append(path)cn_dirs_display = ", ".join(other_dirs) if other_dirs else "无"en_dirs_display = ", ".join(other_dirs) if other_dirs else "none"+ cn_agent_paths = self._format_agent_data_paths(+ agent_workspace_dir, config_dir, language="cn"+ )+ en_agent_paths = self._format_agent_data_paths(+ agent_workspace_dir, config_dir, language="en"+ )logger.info("[RuntimePromptRail] directory context: channel=%s project_dir=%s ""cwd=%s agent_workspace=%s has_project=%s",@@ -600,8 +657,7 @@ class RuntimePromptRail(DeepAgentRail):"# 运行时目录上下文\n\n"f"- 当前项目目录(项目根目录,也是本次任务的 workspace 边界):{project_dir}\n"f"- 当前工作目录(cwd,也是 Bash 默认执行目录):{runtime_cwd}\n"- f"- Agent 内部数据目录:{agent_workspace_dir}\n"- f"- JiuwenSwarm 启动配置目录:{config_dir}\n\n"+ f"{cn_agent_paths}\n""目录含义:\n""- 当前项目目录是用户正在处理的项目根目录,也是本次任务文件操作的主要边界。\n""- 当前工作目录是 Bash 未显式传入 `workdir` 时的默认执行目录,也是相对路径的解析基准。\n"@@ -634,8 +690,7 @@ class RuntimePromptRail(DeepAgentRail):"# 运行时目录上下文\n\n""- 当前项目目录:未设置\n"f"- 当前工作目录(cwd,也是 Bash 默认执行目录):{runtime_cwd}\n"- f"- Agent 内部数据目录:{agent_workspace_dir}\n"- f"- JiuwenSwarm 启动配置目录:{config_dir}\n\n"+ f"{cn_agent_paths}\n""当前没有绑定用户项目,也没有传入独立的任务工作路径。""当前工作目录暂时回退到 Agent 内部数据目录。\n\n""重要规则:\n"@@ -660,8 +715,7 @@ class RuntimePromptRail(DeepAgentRail):"# 运行时目录上下文\n\n""- 当前项目目录:未设置\n"f"- 当前工作目录(cwd,也是 Bash 默认执行目录):{runtime_cwd}\n"- f"- Agent 内部数据目录:{agent_workspace_dir}\n"- f"- JiuwenSwarm 启动配置目录:{config_dir}\n\n"+ f"{cn_agent_paths}\n""当前没有绑定用户项目。\n\n""目录含义:\n""- 当前工作目录是本次任务的文件操作目录和相对路径解析基准,但不要称其为项目目录。\n"@@ -687,8 +741,7 @@ class RuntimePromptRail(DeepAgentRail):"# Runtime Directory Context\n\n"f"- Current project directory (project root and workspace boundary): {project_dir}\n"f"- Current working directory (cwd and Bash default directory): {runtime_cwd}\n"- f"- Agent internal data directory: {agent_workspace_dir}\n"- f"- JiuwenSwarm startup configuration directory: {config_dir}\n\n"+ f"{en_agent_paths}\n""Directory semantics:\n""- The current project directory is the user project's root ""and the main file-operation boundary.\n"@@ -732,8 +785,7 @@ class RuntimePromptRail(DeepAgentRail):"# Runtime Directory Context\n\n""- Current project directory: not set\n"f"- Current working directory (cwd and Bash default directory): {runtime_cwd}\n"- f"- Agent internal data directory: {agent_workspace_dir}\n"- f"- JiuwenSwarm startup configuration directory: {config_dir}\n\n"+ f"{en_agent_paths}\n""No user project or independent task path is currently bound. ""The current working directory has temporarily fallen back to ""the Agent internal data directory.\n\n"@@ -763,8 +815,7 @@ class RuntimePromptRail(DeepAgentRail):"# Runtime Directory Context\n\n""- Current project directory: not set\n"f"- Current working directory (cwd and Bash default directory): {runtime_cwd}\n"- f"- Agent internal data directory: {agent_workspace_dir}\n"- f"- JiuwenSwarm startup configuration directory: {config_dir}\n\n"+ f"{en_agent_paths}\n""No user project is currently bound.\n\n""Directory semantics:\n""- The current working directory is this task's file-operation directory "diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 7792c16bda..7f38522bcc 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -1373,6 +1373,8 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):self._runtime_prompt_rail.set_runtime_paths(cwd=task_cwd,project_dir=runtime_config.project_dir or self._project_dir,+ # Agent data root (skills/memory/todo), not project context.+ workspace_dir=self._agent_workspace_dir,)self._runtime_prompt_rail.set_session_id(runtime_config.session_id)self._runtime_prompt_rail.set_request_system_prompt(diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex aaf5dbe863..713c35029f 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -12882,6 +12882,7 @@ class JiuWenSwarmDeepAdapter:self._runtime_prompt_rail.set_runtime_paths(cwd=task_cwd,project_dir=runtime_config.project_dir or self._project_dir,+ workspace_dir=self._workspace_dir,)self._runtime_prompt_rail.set_model_name(self._resolve_model_name())self._runtime_prompt_rail.set_mode(runtime_config.mode)diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 4529cbe055..011e12eb1b 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -168,6 +168,20 @@ def test_build_agent_identity_prompt_contains_identity_section_only():assert "## Symphony Orchestration" not in promptassert "`symphony_compose_score`" not in promptassert "# 消息说明" not in prompt+ # Agent-internal dirs must stay logical; absolute tenant paths belong in runtime context.+ assert "Agent 内部数据目录/skills" in prompt+ assert "workspace_default" not in prompt+ assert "运行时目录上下文" in prompt+ assert "绝对路径" in prompt+++def test_build_agent_identity_prompt_english_uses_logical_paths():+ prompt = build_agent_identity_prompt(language="en")++ assert "# JiuwenSwarm Internal Data" in prompt+ assert "Agent internal data directory/skills" in prompt+ assert "workspace_default" not in prompt+ assert "runtime directory context" in prompt@pytest.mark.asyncio@@ -1239,11 +1253,12 @@ def test_deep_adapter_subagents_omits_research_without_explicit_enable():@pytest.mark.asyncioasync def test_runtime_rail_multi_tenant_workspace_dirs(monkeypatch):- """测试注入 workspace_dir 时 _resolve_agent_workspace_and_config 返回正确路径。"""+ """workspace_dir 驱动租户内部数据路径;启动配置仍用全局 ~/.jiuwenswarm/config。"""monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")builder = SystemPromptBuilder(language="cn")workspace_root = Path("/tmp/test_jiuwenswarm/workspace_abc/agent/jiuwenclaw_workspace")+ global_root = Path("/tmp/test_jiuwenswarm_home")runtime_rail = RuntimePromptRail(language="cn",channel="web",@@ -1253,8 +1268,12 @@ async def test_runtime_rail_multi_tenant_workspace_dirs(monkeypatch):runtime_rail.set_runtime_paths(workspace_dir=str(workspace_root))runtime_rail.init(SimpleNamespace(system_prompt_builder=builder))- ctx = AgentCallbackContext(agent=None, inputs=None, session=None)- await runtime_rail.before_model_call(ctx)+ with patch(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_user_workspace_dir",+ return_value=global_root,+ ):+ ctx = AgentCallbackContext(agent=None, inputs=None, session=None)+ await runtime_rail.before_model_call(ctx)prompt = builder.build()@@ -1262,18 +1281,29 @@ async def test_runtime_rail_multi_tenant_workspace_dirs(monkeypatch):assert "workspace" in promptassert "workspace_abc" in promptassert "Agent 内部数据目录" in prompt+ assert "Agent 技能目录" in prompt- expected_base = workspace_root.parent.parent- expected_config = str(expected_base / "config")+ expected_config = str(global_root / "config")expected_workspace = str(workspace_root)+ expected_skills = str(workspace_root / "skills")+ expected_tenant_config = str(workspace_root.parent.parent / "config")expected_config_win = expected_config.replace("/", "\\")expected_workspace_win = expected_workspace.replace("/", "\\")+ expected_skills_win = expected_skills.replace("/", "\\")+ expected_tenant_config_win = expected_tenant_config.replace("/", "\\")assert (expected_config in prompt or expected_config_win in prompt), f"Config path not found: {expected_config}"assert (expected_workspace in prompt or expected_workspace_win in prompt), f"Workspace path not found: {expected_workspace}"+ assert (+ expected_skills in prompt or expected_skills_win in prompt+ ), f"Skills path not found: {expected_skills}"+ assert (+ expected_tenant_config not in prompt+ and expected_tenant_config_win not in prompt+ ), f"Tenant-scoped config must not appear: {expected_tenant_config}"@pytest.mark.asyncio@@ -1321,6 +1351,64 @@ async def test_runtime_rail_single_tenant_workspace_dirs():), f"Workspace path not found: {expected_workspace}"+async def test_runtime_rail_path_provider_memory_override(tmp_path):+ """Bound workspace 下 memory 走 PathProvider,不得硬拼 workspace/memory。"""+ from jiuwenswarm.common import path_provider as providers++ providers.reset_path_provider()+ custom_memory = tmp_path / "shared" / "memory"+ custom_memory.mkdir(parents=True)+ bound_ws = tmp_path / "agent" / "jiuwenclaw_workspace"+ bound_ws.mkdir(parents=True)++ class MemoryProvider(providers.PathProvider):+ name = "memory-override"++ def resolve_path(self, category, ctx, **kwargs):+ if category == providers.PathCategory.MEMORY:+ return custom_memory+ return None++ providers.register_path_provider(MemoryProvider())+ try:+ builder = SystemPromptBuilder(language="cn")+ runtime_rail = RuntimePromptRail(language="cn", channel="web")+ # Match bound workspace so PathProvider-aware getters are used.+ runtime_rail.set_runtime_paths(workspace_dir=str(bound_ws))+ runtime_rail.init(SimpleNamespace(system_prompt_builder=builder))++ with (+ patch(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_agent_workspace_dir",+ return_value=bound_ws,+ ),+ patch(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_user_workspace_dir",+ return_value=tmp_path,+ ),+ # get_agent_memory_dir() reads workspace via utils; keep fallback root+ # aligned so only MEMORY is remapped by the registered provider.+ patch.object(_utils_mod, "get_agent_workspace_dir", return_value=bound_ws),+ ):+ ctx = AgentCallbackContext(agent=None, inputs=None, session=None)+ await runtime_rail.before_model_call(ctx)++ prompt = builder.build()+ expected_memory = str(custom_memory)+ expected_memory_win = expected_memory.replace("/", "\\")+ hard_joined = str(bound_ws / "memory")+ hard_joined_win = hard_joined.replace("/", "\\")+ assert (+ expected_memory in prompt or expected_memory_win in prompt+ ), f"Provider memory path not found: {expected_memory}"+ assert (+ hard_joined not in prompt and hard_joined_win not in prompt+ ), f"Hard-joined memory must not appear when PathProvider overrides: {hard_joined}"+ finally:+ providers.reset_path_provider()++def test_interface_deep_skill_rail_uses_multi_tenant_paths():"""测试 get_multi_tenant_skill_dirs 按 workspace_key 解析路径。"""from jiuwenswarm.common.utils import get_multi_tenant_skill_dirs