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

# 支持动态调整工作空间路径

cyz95e0f73968cee9
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index c40cc90fc9..0983cba02f 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -88,7 +88,7 @@ from jiuwenclaw.agentserver.permissions import (
get_permission_engine,
PermissionLevel,
)
-from jiuwenclaw.agentserver.skill_manager import SkillManager, _SKILLS_DIR
+from jiuwenclaw.agentserver.skill_manager import SkillManager, _get_skills_dir
from jiuwenclaw.evolution.service import EvolutionService
from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk
from jiuwenclaw.agentserver.memory import get_memory_manager
@@ -302,7 +302,7 @@ class JiuWenClaw:
# register installed skills (compatible with openjiuwen variants).
if hasattr(self._instance, "_skill_util"):
try:
- await self._instance.register_skill(str(_SKILLS_DIR))
+ await self._instance.register_skill(str(_get_skills_dir()))
except Exception as exc:
logger.warning("[JiuWenClaw] register_skill failed, continue without skills: %s", exc)
@@ -339,7 +339,7 @@ class JiuWenClaw:
evo_service = EvolutionService(
llm=self._instance._get_llm(),
model=agent_config.model_name,
- skills_base_dir=str(_SKILLS_DIR),
+ skills_base_dir=str(_get_skills_dir()),
auto_scan=evolution_auto_scan,
)
self._instance.set_evolution_service(evo_service)
diff --git a/jiuwenclaw/agentserver/prompt_builder.py b/jiuwenclaw/agentserver/prompt_builder.py
index 39cc364ac5..f72f4c6c92 100644
--- a/jiuwenclaw/agentserver/prompt_builder.py
+++ b/jiuwenclaw/agentserver/prompt_builder.py
@@ -5,15 +5,36 @@ import os
from datetime import datetime, timezone, timedelta
from typing import Optional
-from jiuwenclaw.utils import USER_WORKSPACE_DIR
+from jiuwenclaw.utils import (
+ get_user_workspace_dir,
+ get_agent_home_dir,
+ get_agent_memory_dir,
+ get_agent_skills_dir,
+ get_agent_workspace_dir,
+)
logger = logging.getLogger(__name__)
-CONFIG_DIR = USER_WORKSPACE_DIR / "config"
-HOME_DIR = USER_WORKSPACE_DIR / "agent" / "home"
-MEMORY_DIR = USER_WORKSPACE_DIR / "agent" / "memory"
-SKILL_DIR = USER_WORKSPACE_DIR / "agent" / "skills"
-WORKSPACE_DIR = USER_WORKSPACE_DIR / "agent" / "workspace"
+
+
+def _get_config_dir() -> "Path":
+ return get_user_workspace_dir() / "config"
+
+
+def _get_home_dir() -> "Path":
+ return get_agent_home_dir()
+
+
+def _get_memory_dir() -> "Path":
+ return get_agent_memory_dir()
+
+
+def _get_skill_dir() -> "Path":
+ return get_agent_skills_dir()
+
+
+def _get_workspace_dir() -> "Path":
+ return get_agent_workspace_dir()
def _memory_prompt(language: str, is_cron: bool = False) -> str:
@@ -48,14 +69,14 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
sections.append(memory_prompt)
sections.append("")
- profile_content = _read_file(MEMORY_DIR / "USER.md")
+ profile_content = _read_file(_get_memory_dir() / "USER.md")
if profile_content:
sections.append("## 当前身份与用户资料")
sections.append("这是你对自己和用户的了解:")
sections.append(profile_content)
sections.append("")
- memory_content = _read_file(MEMORY_DIR / "MEMORY.md")
+ memory_content = _read_file(_get_memory_dir() / "MEMORY.md")
if memory_content:
sections.append("## 长期记忆")
sections.append("之前会话的重要信息:")
@@ -64,7 +85,7 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
beijing_tz = timezone(timedelta(hours=8))
today = datetime.now(tz=beijing_tz).strftime("%Y-%m-%d")
- today_content = _read_file(MEMORY_DIR / f"{today}.md")
+ today_content = _read_file(_get_memory_dir() / f"{today}.md")
if today_content:
sections.append("## 今日会话记录")
sections.append(today_content)
@@ -94,14 +115,14 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
sections.append(memory_prompt)
sections.append("")
- profile_content = _read_file(MEMORY_DIR / "USER.md")
+ profile_content = _read_file(_get_memory_dir() / "USER.md")
if profile_content:
sections.append("## Current Identity and User Profile")
sections.append("What you know about yourself and the user:")
sections.append(profile_content)
sections.append("")
- memory_content = _read_file(MEMORY_DIR / "MEMORY.md")
+ memory_content = _read_file(_get_memory_dir() / "MEMORY.md")
if memory_content:
sections.append("## Long-term Memory")
sections.append("Important information from previous sessions:")
@@ -110,7 +131,7 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
beijing_tz = timezone(timedelta(hours=8))
today = datetime.now(tz=beijing_tz).strftime("%Y-%m-%d")
- today_content = _read_file(MEMORY_DIR / f"{today}.md")
+ today_content = _read_file(_get_memory_dir() / f"{today}.md")
if today_content:
sections.append("## Today's Session Record")
sections.append(today_content)
@@ -187,14 +208,14 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
sections.append(memory_prompt)
sections.append("")
- profile_content = _read_file(MEMORY_DIR / "USER.md")
+ profile_content = _read_file(_get_memory_dir() / "USER.md")
if profile_content:
sections.append("## 当前身份与用户资料")
sections.append("这是你对自己和用户的了解:")
sections.append(profile_content)
sections.append("")
- memory_content = _read_file(MEMORY_DIR / "MEMORY.md")
+ memory_content = _read_file(_get_memory_dir() / "MEMORY.md")
if memory_content:
sections.append("## 长期记忆")
sections.append("之前会话的重要信息:")
@@ -203,7 +224,7 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
beijing_tz = timezone(timedelta(hours=8))
today = datetime.now(tz=beijing_tz).strftime("%Y-%m-%d")
- today_content = _read_file(MEMORY_DIR / f"{today}.md")
+ today_content = _read_file(_get_memory_dir() / f"{today}.md")
if today_content:
sections.append("## 今日会话记录")
sections.append(today_content)
@@ -287,14 +308,14 @@ Before outputting final response text, **you must call the following tools first
sections.append(memory_prompt)
sections.append("")
- profile_content = _read_file(MEMORY_DIR / "USER.md")
+ profile_content = _read_file(_get_memory_dir() / "USER.md")
if profile_content:
sections.append("## Current Identity and User Profile")
sections.append("What you know about yourself and the user:")
sections.append(profile_content)
sections.append("")
- memory_content = _read_file(MEMORY_DIR / "MEMORY.md")
+ memory_content = _read_file(_get_memory_dir() / "MEMORY.md")
if memory_content:
sections.append("## Long-term Memory")
sections.append("Important information from previous sessions:")
@@ -303,7 +324,7 @@ Before outputting final response text, **you must call the following tools first
beijing_tz = timezone(timedelta(hours=8))
today = datetime.now(tz=beijing_tz).strftime("%Y-%m-%d")
- today_content = _read_file(MEMORY_DIR / f"{today}.md")
+ today_content = _read_file(_get_memory_dir() / f"{today}.md")
if today_content:
sections.append("## Today's Session Record")
sections.append(today_content)
@@ -538,12 +559,12 @@ When the user requests code/scripts/config/tests that must be delivered **as fil
def _skills_prompt(language: str) -> str:
- skills = os.listdir(SKILL_DIR)
+ skills = os.listdir(_get_skill_dir())
skills_str = "\n".join(skills)
if language == "zh":
return f"""## 技能
-技能存放在 `{SKILL_DIR}` 目录下。
+技能存放在 `{_get_skill_dir()}` 目录下。
当前可用技能:
{skills_str}
@@ -551,7 +572,7 @@ def _skills_prompt(language: str) -> str:
else:
return f"""## Skills
-Skills live under `{SKILL_DIR}`.
+Skills live under `{_get_skill_dir()}`.
Available skills:
{skills_str}
@@ -604,20 +625,20 @@ def _workspace_prompt(language: str) -> str:
if language == "zh":
return f"""## 工作区
-你当前的工作路径为:{WORKSPACE_DIR}.
+你当前的工作路径为:{_get_workspace_dir()}.
你可以自由在这个路径里操作文件,他们都属于你。如果用户没有要求在其他路径操作,默认将文件保存在此目录下。
"""
else:
return f"""## Workspace
-You are working under the dir:{WORKSPACE_DIR}.
+You are working under the dir:{_get_workspace_dir()}.
Write or save all files under this dir, unless user ask you to operate in other dirs.
"""
def _principle_prompt(language: str) -> str:
"""优先从 ~/.jiuwenclaw/agent/home/PRINCIPLE.md 读取;缺失时回退内置文案。"""
- file_content = _read_file(str(HOME_DIR / "PRINCIPLE.md"))
+ file_content = _read_file(str(_get_home_dir() / "PRINCIPLE.md"))
if file_content:
return file_content
if language == "zh":
@@ -695,7 +716,7 @@ def _time_prompt(language: str) -> str:
def _tone_prompt(language: str) -> str:
"""优先从 ~/.jiuwenclaw/agent/home/TONE.md 读取;缺失时回退内置文案。"""
- file_content = _read_file(str(HOME_DIR / "TONE.md"))
+ file_content = _read_file(str(_get_home_dir() / "TONE.md"))
if file_content:
return file_content
if language == "zh":
@@ -848,19 +869,19 @@ def _start_prompt(language: str) -> str:
| 路径 | 用途 | 操作建议 |
|------|------|----------|
-| `{CONFIG_DIR}` | 配置信息 | 不要轻易改动,错误配置可能导致异常 |
-| `{HOME_DIR}` | 身份与任务信息 | 可适当更新,以更好地服务用户 |
-| `{MEMORY_DIR}` | 持久化记忆 | 将其视为你记忆的一部分,随时查阅 |
-| `{SKILL_DIR}` | 技能库 | 可随时翻阅、调用,不可修改 |
-| `{WORKSPACE_DIR}` | 工作区 | 你的安全屋,可自由读写,注意不要影响系统其他部分 |
+| `{_get_config_dir()}` | 配置信息 | 不要轻易改动,错误配置可能导致异常 |
+| `{_get_home_dir()}` | 身份与任务信息 | 可适当更新,以更好地服务用户 |
+| `{_get_memory_dir()}` | 持久化记忆 | 将其视为你记忆的一部分,随时查阅 |
+| `{_get_skill_dir()}` | 技能库 | 可随时翻阅、调用,不可修改 |
+| `{_get_workspace_dir()}` | 工作区 | 你的安全屋,可自由读写,注意不要影响系统其他部分 |
## 配置信息
谨慎对待你的配置信息,如果用户要求你修改,请在修改后重启自己的服务,以保证改动生效
| 路径 | 用途 |
|------|------|----------|
-| `{CONFIG_DIR}/config.yaml` | 配置信息 |
-| `{CONFIG_DIR}/.env` | 环境变量 |
+| `{_get_config_dir()}/config.yaml` | 配置信息 |
+| `{_get_config_dir()}/.env` | 环境变量 |
"""
else:
return f"""You are a personal assistant created and run by JiuwenClaw.
@@ -874,19 +895,19 @@ Everything starts from the `.jiuwenclaw` directory.
| Path | Purpose | Guidelines |
|------|---------|------------|
-| `{CONFIG_DIR}` | Configuration | Do not modify lightly; bad config can cause failures |
-| `{HOME_DIR}` | Identity and task info | You may update this to better serve your user |
-| `{MEMORY_DIR}` | Persistent memory | Treat it as part of your memory; consult it anytime |
-| `{SKILL_DIR}` | Skill library | Read and invoke freely; do not modify |
-| `{WORKSPACE_DIR}` | Workspace | Your safe space; read and write freely, but avoid affecting other parts of the system |
+| `{_get_config_dir()}` | Configuration | Do not modify lightly; bad config can cause failures |
+| `{_get_home_dir()}` | Identity and task info | You may update this to better serve your user |
+| `{_get_memory_dir()}` | Persistent memory | Treat it as part of your memory; consult it anytime |
+| `{_get_skill_dir()}` | Skill library | Read and invoke freely; do not modify |
+| `{_get_workspace_dir()}` | Workspace | Your safe space; read and write freely, but avoid affecting other parts of the system |
## Configuration
Be careful with your configuration, if changes are required, remember to restart your service to ensure the changes are configured.
| Path | Purpose |
|------|------|----------|
-| `{CONFIG_DIR}/config.yaml` | Config Infos |
-| `{CONFIG_DIR}/.env` | Environment Variables |
+| `{_get_config_dir()}/config.yaml` | Config Infos |
+| `{_get_config_dir()}/.env` | Environment Variables |
"""
diff --git a/jiuwenclaw/agentserver/skill_manager.py b/jiuwenclaw/agentserver/skill_manager.py
index 3ca440c065..51dadbc542 100644
--- a/jiuwenclaw/agentserver/skill_manager.py
+++ b/jiuwenclaw/agentserver/skill_manager.py
@@ -28,13 +28,24 @@ logger = logging.getLogger(__name__)
_SKILLNET_DOWNLOAD_TIMEOUT: int = int(os.environ.get("SKILLNET_DOWNLOAD_TIMEOUT", "60"))
_SKILLNET_MAX_RETRIES: int = int(os.environ.get("SKILLNET_MAX_RETRIES", "3"))
+
# ---------------------------------------------------------------------------
# 默认路径
# ---------------------------------------------------------------------------
-_SKILLS_DIR = get_agent_skills_dir()
-_AGENT_ROOT = get_agent_root_dir()
-_MARKETPLACE_DIR = _SKILLS_DIR / "_marketplace"
-_STATE_FILE = _SKILLS_DIR / "skills_state.json"
+def _get_skills_dir() -> "Path":
+ return get_agent_skills_dir()
+
+
+def _get_agent_root_dir() -> "Path":
+ return get_agent_root_dir()
+
+
+def _get_marketplace_dir() -> "Path":
+ return _get_skills_dir() / "_marketplace"
+
+
+def _get_state_file() -> "Path":
+ return _get_skills_dir() / "skills_state.json"
class SkillNetEmptyDownloadError(Exception):
@@ -128,14 +139,14 @@ class SkillManager:
"""Skill 管理器,对应 skills.* 请求方法."""
def __init__(self) -> None:
- _SKILLS_DIR.mkdir(parents=True, exist_ok=True)
+ _get_skills_dir().mkdir(parents=True, exist_ok=True)
self._state: dict[str, Any] = self._load_state()
# SkillNet 异步安装:install 立即返回 install_id,后台下载;完成后调用 hook 重载 Agent
self._skillnet_install_jobs: dict[str, dict[str, Any]] = {}
self._skillnet_install_complete_hook: Callable[[], Awaitable[None]] | None = None
def set_skillnet_install_complete_hook(
- self, hook: Callable[[], Awaitable[None]] | None
+ self, hook: Callable[[], Awaitable[None]] | None
) -> None:
"""安装成功落盘后回调(通常为重载 Agent 实例)."""
self._skillnet_install_complete_hook = hook
@@ -201,7 +212,7 @@ class SkillManager:
raise ValueError("缺少参数: name")
# 先在本地 skills 目录中查找
- for child in _SKILLS_DIR.iterdir():
+ for child in _get_skills_dir().iterdir():
if child.name.startswith("_") or not child.is_dir():
continue
md = self._try_find_skill_file(child)
@@ -217,8 +228,8 @@ class SkillManager:
return meta
# 再在 marketplace 目录中查找
- if _MARKETPLACE_DIR.exists():
- for repo_dir in _MARKETPLACE_DIR.iterdir():
+ if _get_marketplace_dir().exists():
+ for repo_dir in _get_marketplace_dir().iterdir():
if not repo_dir.is_dir():
continue
for plugin_dir in repo_dir.iterdir():
@@ -290,7 +301,7 @@ class SkillManager:
return {"success": False, "detail": f"marketplace {marketplace_name} 缺少 url"}
# 确保 marketplace 仓库已 clone
- repo_dir = _MARKETPLACE_DIR / marketplace_name
+ repo_dir = _get_marketplace_dir() / marketplace_name
if repo_dir.exists():
await self._git_pull(repo_dir)
else:
@@ -300,7 +311,7 @@ class SkillManager:
# 在仓库中查找 plugin 目录
plugin_src = repo_dir / "skills" / plugin_name
-
+
# 兼容单skill模式
if not plugin_src.exists() or not plugin_src.is_dir():
plugin_src = repo_dir
@@ -312,7 +323,7 @@ class SkillManager:
return {"success": False, "detail": f"plugin {plugin_name} 缺少 SKILL.md"}
# 复制到本地 skills 目录
- dest = _SKILLS_DIR / plugin_name
+ dest = _get_skills_dir() / plugin_name
if dest.exists():
if not force:
return {"success": False, "detail": f"skill {plugin_name} 已存在"}
@@ -631,7 +642,7 @@ class SkillManager:
force = bool(params.get("force", False))
# 检查 skill 是否已安装
- dest = _SKILLS_DIR / slug
+ dest = _get_skills_dir() / slug
if dest.exists() and not force:
return {
"success": False,
@@ -754,11 +765,11 @@ class SkillManager:
}
async def _skillnet_install_background(
- self,
- install_id: str,
- skill_url: str,
- force: bool,
- mirror_url: str | None = None,
+ self,
+ install_id: str,
+ skill_url: str,
+ force: bool,
+ mirror_url: str | None = None,
) -> None:
try:
result = await asyncio.to_thread(
@@ -839,7 +850,7 @@ class SkillManager:
}
def _skillnet_install_files_sync(
- self, skill_url: str, force: bool, mirror_url: str | None = None
+ self, skill_url: str, force: bool, mirror_url: str | None = None
) -> dict[str, Any]:
"""在工作线程中下载并拷贝到 skills 目录;返回 ok / skill_name / meta / skill_url."""
try:
@@ -875,7 +886,7 @@ class SkillManager:
}
skill_name = str(meta.get("name", skill_dir.name)).strip() or skill_dir.name
- dest = _SKILLS_DIR / skill_name
+ dest = _get_skills_dir() / skill_name
if dest.exists():
if not force:
return {
@@ -934,7 +945,7 @@ class SkillManager:
if self._is_builtin_skill(name, self._get_installed_plugins(), dest):
return {"success": False, "detail": "内置技能不允许删除"}
- dest = _SKILLS_DIR / name
+ dest = _get_skills_dir() / name
if dest.exists() and dest.is_dir():
_safe_rmtree(dest)
for mirror_root in self._get_mirror_skills_dirs():
@@ -969,7 +980,7 @@ class SkillManager:
if meta is None:
return {"success": False, "detail": "无法解析 skill 文件"}
skill_name = meta.get("name", src.stem)
- dest = _SKILLS_DIR / skill_name
+ dest = _get_skills_dir() / skill_name
if dest.exists():
if not force:
return {"success": False, "detail": f"skill {skill_name} 已存在"}
@@ -982,7 +993,7 @@ class SkillManager:
return {"success": False, "detail": f"目录中未找到 SKILL.md: {raw_path}"}
meta = self._parse_skill_md(md) or {}
skill_name = meta.get("name", src.name)
- dest = _SKILLS_DIR / skill_name
+ dest = _get_skills_dir() / skill_name
if dest.exists():
if not force:
return {"success": False, "detail": f"skill {skill_name} 已存在"}
@@ -1034,7 +1045,7 @@ class SkillManager:
cache_removed = False
if bool(remove_cache):
- repo_dir = _MARKETPLACE_DIR / name
+ repo_dir = _get_marketplace_dir() / name
if repo_dir.exists() and repo_dir.is_dir():
try:
_safe_rmtree(repo_dir)
@@ -1070,7 +1081,7 @@ class SkillManager:
return {"success": False, "detail": f"marketplace 不存在: {name}"}
if enabled:
- repo_dir = _MARKETPLACE_DIR / name
+ repo_dir = _get_marketplace_dir() / name
url = marketplace.get("url", "")
if not url:
return {"success": False, "detail": f"marketplace {name} 缺少 url"}
@@ -1092,7 +1103,7 @@ class SkillManager:
return {"success": True, "name": name, "enabled": True, "detail": detail}
# 禁用:删除本地缓存目录,不卸载已安装 skill。
- repo_dir = _MARKETPLACE_DIR / name
+ repo_dir = _get_marketplace_dir() / name
cache_removed = False
if repo_dir.exists() and repo_dir.is_dir():
cache_removed = _safe_rmtree(repo_dir)
@@ -1251,10 +1262,10 @@ class SkillManager:
def _scan_local_skills(self) -> list[dict]:
"""扫描 agent/skills/ 下的本地 skill(跳过 _marketplace)."""
results: list[dict] = []
- if not _SKILLS_DIR.exists():
+ if not _get_skills_dir().exists():
return results
- for child in _SKILLS_DIR.iterdir():
+ for child in _get_skills_dir().iterdir():
if not child.is_dir() or child.name.startswith("_"):
continue
md = self._try_find_skill_file(child)
@@ -1321,7 +1332,7 @@ class SkillManager:
扫描路径:_marketplace/{marketplace_name}/skills/{plugin_name}
"""
results: list[dict] = []
- if not _MARKETPLACE_DIR.exists():
+ if not _get_marketplace_dir().exists():
return results
installed_names = {p.get("name") for p in self._get_installed_plugins()}
@@ -1332,7 +1343,7 @@ class SkillManager:
if bool(m.get("enabled", True)) and m.get("name")
}
- for repo_dir in _MARKETPLACE_DIR.iterdir():
+ for repo_dir in _get_marketplace_dir().iterdir():
if not repo_dir.is_dir():
continue
marketplace_name = repo_dir.name
@@ -1345,7 +1356,7 @@ class SkillManager:
is_skills_dir = True
if not skills_dir.exists() or not skills_dir.is_dir():
# 如果没有 skills 子目录,尝试直接扫描 repo_dir(兼容旧结构)
- skills_dir = repo_dir / _MARKETPLACE_DIR
+ skills_dir = repo_dir / _get_marketplace_dir()
is_skills_dir = False
for plugin_dir in skills_dir.iterdir():
@@ -1387,14 +1398,14 @@ class SkillManager:
try:
source_repo_root = Path(__file__).resolve().parents[2]
source_resources_skills_dir = (
- source_repo_root / "jiuwenclaw" / "resources" / "agent" / "skills"
+ source_repo_root / "jiuwenclaw" / "resources" / "agent" / "skills"
)
# 开发模式下不将源码目录作为镜像目标
# 这样用户下载的skill只保存在用户目录,不会污染源码目录
if (
- source_resources_skills_dir.exists()
- and source_resources_skills_dir.resolve() != _SKILLS_DIR.resolve()
- and source_resources_skills_dir.resolve() != get_builtin_skills_dir().resolve()
+ source_resources_skills_dir.exists()
+ and source_resources_skills_dir.resolve() != _get_skills_dir().resolve()
+ and source_resources_skills_dir.resolve() != get_builtin_skills_dir().resolve()
):
mirrors.append(source_resources_skills_dir)
except Exception:
@@ -1469,7 +1480,7 @@ class SkillManager:
def _refresh_agent_data_indexes(self) -> None:
"""Refresh agent-data.json for runtime and mirror workspaces."""
- workspace_roots: set[Path] = {_AGENT_ROOT.resolve()}
+ workspace_roots: set[Path] = {_get_agent_root_dir().resolve()}
for mirror_root in self._get_mirror_skills_dirs():
try:
# mirror_root = .../agent/skills → agent 根目录为其 parent
@@ -1630,7 +1641,7 @@ class SkillManager:
parts.append(f"HTTP {r.status_code}: {raw}")
if r.status_code == 403 or any(
- "rate limit" in p.lower() for p in parts
+ "rate limit" in p.lower() for p in parts
):
try:
rl = dl.session.get("https://api.github.com/rate_limit", timeout=12)
@@ -1650,10 +1661,9 @@ class SkillManager:
return " | ".join(parts) if parts else ""
-
@staticmethod
def _skillnet_download_sync(
- skill_url: str, target_dir: str, mirror_url: str | None = None
+ skill_url: str, target_dir: str, mirror_url: str | None = None
) -> str:
"""同步调用 skillnet-ai download;失败时附带 GitHub API 返回说明(如前端的限流文案)。"""
try:
@@ -1745,7 +1755,7 @@ class SkillManager:
if not marketplaces:
return
- _MARKETPLACE_DIR.mkdir(parents=True, exist_ok=True)
+ _get_marketplace_dir().mkdir(parents=True, exist_ok=True)
for marketplace in marketplaces:
name = marketplace.get("name", "")
@@ -1753,7 +1763,7 @@ class SkillManager:
if not name or not url:
continue
- repo_dir = _MARKETPLACE_DIR / name
+ repo_dir = _get_marketplace_dir() / name
try:
if repo_dir.exists():
await self._git_pull(repo_dir)
@@ -1774,8 +1784,8 @@ class SkillManager:
def _load_state(self) -> dict[str, Any]:
"""加载 skills_state.json,失败时返回默认空状态."""
try:
- if _STATE_FILE.exists():
- state = json.loads(_STATE_FILE.read_text(encoding="utf-8"))
+ if _get_state_file().exists():
+ state = json.loads(_get_state_file().read_text(encoding="utf-8"))
self._normalize_state(state)
return state
except Exception:
@@ -1787,8 +1797,8 @@ class SkillManager:
def _save_state(self) -> None:
"""持久化状态到 skills_state.json."""
try:
- _STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
- _STATE_FILE.write_text(
+ _get_state_file().parent.mkdir(parents=True, exist_ok=True)
+ _get_state_file().write_text(
json.dumps(self._state, ensure_ascii=False, indent=2),
encoding="utf-8",
)
diff --git a/jiuwenclaw/agentserver/tools/task_tools.py b/jiuwenclaw/agentserver/tools/task_tools.py
index 538dce64f5..0b3cc3ae2b 100644
--- a/jiuwenclaw/agentserver/tools/task_tools.py
+++ b/jiuwenclaw/agentserver/tools/task_tools.py
@@ -16,7 +16,7 @@ from jiuwenclaw.agentserver.tools import (
tool,
)
-from jiuwenclaw.utils import USER_WORKSPACE_DIR
+from jiuwenclaw.utils import get_user_workspace_dir
logger = logging.getLogger(__name__)
@@ -34,7 +34,10 @@ class TaskAddParams:
# Path for persisting task_add entries
-_TASK_DATA_PATH = str(USER_WORKSPACE_DIR / "agent" / "workspace" / "task-data.json")
+def _get_task_data_path() -> str:
+ return str(get_user_workspace_dir() / "agent" / "workspace" / "task-data.json")
+
+
_connector = JSONFileConnector(indent=2)
_service: Optional[Any] = None # TaskMemoryService instance
@@ -215,8 +218,8 @@ async def experience_retrieve(
persisted_memories: List[Dict[str, Any]] = []
persisted_lines: List[str] = []
try:
- if _connector.exists(_TASK_DATA_PATH):
- data = _connector.load_from_file(_TASK_DATA_PATH)
+ if _connector.exists(_get_task_data_path()):
+ data = _connector.load_from_file(_get_task_data_path())
for entry in data.get("entries", []):
mem = {
"id": entry.get("memory_id", ""),
@@ -318,8 +321,8 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
# Step 2: persist new entry to task-data.json
try:
existing = (
- _connector.load_from_file(_TASK_DATA_PATH)
- if _connector.exists(_TASK_DATA_PATH)
+ _connector.load_from_file(_get_task_data_path())
+ if _connector.exists(_get_task_data_path())
else {"entries": []}
)
entry: Dict[str, Any] = {
@@ -339,7 +342,7 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
if params.label is not None:
entry["label"] = params.label
existing.setdefault("entries", []).append(entry)
- _connector.save_to_file(_TASK_DATA_PATH, existing)
+ _connector.save_to_file(_get_task_data_path(), existing)
except Exception as persist_exc:
logger.warning(
"[Experience] experience_learn: failed to persist to task-data.json: %s", persist_exc,
@@ -352,8 +355,8 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
# Step 3: summarize all entries in task-data.json
raw_entries: List[Dict[str, Any]] = []
try:
- if _connector.exists(_TASK_DATA_PATH):
- data = _connector.load_from_file(_TASK_DATA_PATH)
+ if _connector.exists(_get_task_data_path()):
+ data = _connector.load_from_file(_get_task_data_path())
raw_entries = data.get("entries", [])
except Exception as load_exc:
logger.warning("[Experience] experience_learn: failed to reload task-data.json: %s", load_exc)
@@ -394,8 +397,8 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
for mem in memories
]
existing = (
- _connector.load_from_file(_TASK_DATA_PATH)
- if _connector.exists(_TASK_DATA_PATH)
+ _connector.load_from_file(_get_task_data_path())
+ if _connector.exists(_get_task_data_path())
else {"entries": []}
)
existing_ids = {
@@ -407,7 +410,7 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
existing.setdefault("entries", []).append(s_entry)
existing_ids.add(s_entry.get("memory_id"))
added += 1
- _connector.save_to_file(_TASK_DATA_PATH, existing)
+ _connector.save_to_file(_get_task_data_path(), existing)
logger.info(
"[Experience] experience_learn: merged %d summarized entries (total=%d)",
added, len(existing.get("entries", [])),
@@ -444,7 +447,7 @@ async def experience_clear() -> Dict[str, Any]:
Dictionary with status message.
"""
try:
- _connector.save_to_file(_TASK_DATA_PATH, {"entries": []})
+ _connector.save_to_file(_get_task_data_path(), {"entries": []})
logger.info("[Experience] experience_clear: task-data.json wiped")
return {"status": "success", "message": "task-data.json cleared"}
except Exception as exc:
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index 9fac4587b4..4f8bfb2698 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -13,9 +13,10 @@ import time
from dotenv import load_dotenv
-from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_env_file, prepare_workspace
+from jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace
-_config_file = USER_WORKSPACE_DIR / "config" / "config.yaml"
+
+_config_file = get_user_workspace_dir() / "config" / "config.yaml"
if not _config_file.exists():
prepare_workspace(overwrite=False)
diff --git a/jiuwenclaw/app_agentserver.py b/jiuwenclaw/app_agentserver.py
index b0fe928a03..8e1130d73d 100644
--- a/jiuwenclaw/app_agentserver.py
+++ b/jiuwenclaw/app_agentserver.py
@@ -20,12 +20,12 @@ from dotenv import load_dotenv
from openjiuwen.core.common.logging import LogManager
from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patch
-from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_env_file, prepare_workspace, logger
+from jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace, logger
apply_openai_model_client_patch()
# Ensure workspace initialized
-_config_file = USER_WORKSPACE_DIR / "config" / "config.yaml"
+_config_file = get_user_workspace_dir() / "config" / "config.yaml"
if not _config_file.exists():
prepare_workspace(overwrite=False)
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index e9ed9afcd1..411e6140a4 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -24,12 +24,12 @@ from dotenv import load_dotenv
from openjiuwen.core.common.logging import LogManager
from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patch
-from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_env_file, prepare_workspace
+from jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace
apply_openai_model_client_patch()
# Ensure workspace initialized
-_config_file = USER_WORKSPACE_DIR / "config" / "config.yaml"
+_config_file = get_user_workspace_dir() / "config" / "config.yaml"
if not _config_file.exists():
prepare_workspace(overwrite=False)
diff --git a/jiuwenclaw/desktop_app.py b/jiuwenclaw/desktop_app.py
index ad135ee1bb..d009e5ce85 100644
--- a/jiuwenclaw/desktop_app.py
+++ b/jiuwenclaw/desktop_app.py
@@ -15,7 +15,7 @@ from logging.handlers import RotatingFileHandler
import webview
-from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_logs_dir
+from jiuwenclaw.utils import get_user_workspace_dir, get_logs_dir
BACKEND_HOST = "127.0.0.1"
@@ -543,7 +543,7 @@ class DesktopRuntime:
def run(self, window_title: str, width: int, height: int, debug: bool) -> None:
self.start_services()
- storage_path = USER_WORKSPACE_DIR / "tmp" / "webview"
+ storage_path = get_user_workspace_dir() / "tmp" / "webview"
storage_path.mkdir(parents=True, exist_ok=True)
self.window = webview.create_window(
diff --git a/jiuwenclaw/updater.py b/jiuwenclaw/updater.py
index 846c274895..bbb599a922 100644
--- a/jiuwenclaw/updater.py
+++ b/jiuwenclaw/updater.py
@@ -15,7 +15,7 @@ from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from jiuwenclaw.config import get_config_raw
-from jiuwenclaw.utils import USER_WORKSPACE_DIR
+from jiuwenclaw.utils import get_user_workspace_dir
from jiuwenclaw.version import __version__
@@ -27,7 +27,7 @@ DOWNLOAD_CHUNK_SIZE = 1024 * 512
def _updates_dir() -> Path:
- path = USER_WORKSPACE_DIR / ".updates"
+ path = get_user_workspace_dir() / ".updates"
path.mkdir(parents=True, exist_ok=True)
return path
diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.py
index ac2f2e7902..125b163562 100644
--- a/jiuwenclaw/utils.py
+++ b/jiuwenclaw/utils.py
@@ -206,9 +206,40 @@ def _resolve_logging_levels(
-# User home directory
-USER_HOME = Path.home()
-USER_WORKSPACE_DIR = USER_HOME / ".jiuwenclaw"
+_user_home: Path | None = None
+
+
+def get_user_home() -> Path:
+ """Get the current user home directory."""
+ global _user_home
+ if _user_home is None:
+ _user_home = Path.home()
+ return _user_home
+
+
+def set_user_home(path: Path, initialized: bool = False) -> None:
+ """Set a custom user home directory.
+
+ After calling this function, all path getters will return paths based on the new home directory.
+
+ Args:
+ path: The new user home directory path.
+ initialized: If True, skip cache reset (use when paths are already initialized elsewhere).
+ """
+ global _user_home, _initialized, _config_dir, _workspace_dir, _root_dir
+ _user_home = Path(path)
+ if initialized:
+ return
+ _initialized = False
+ _config_dir = None
+ _workspace_dir = None
+ _root_dir = None
+
+
+def get_user_workspace_dir() -> Path:
+ """Get the user workspace directory path (~/.jiuwenclaw or custom path)."""
+ return get_user_home() / ".jiuwenclaw"
+
# Cache for resolved paths
_config_dir: Path | None = None
@@ -323,7 +354,8 @@ def prepare_workspace(overwrite: bool = True, preferred_language: Optional[str]
if not package_root:
raise RuntimeError("package root not found")
- USER_WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)
+ workspace_dir = get_user_workspace_dir()
+ workspace_dir.mkdir(parents=True, exist_ok=True)
# ----- config: copy config.yaml -----
resources_dir = package_root / "resources"
@@ -340,7 +372,7 @@ def prepare_workspace(overwrite: bool = True, preferred_language: Optional[str]
+ ", ".join(str(p) for p in config_yaml_src_candidates)
)
- config_dest_dir = USER_WORKSPACE_DIR / "config"
+ config_dest_dir = workspace_dir / "config"
config_dest_dir.mkdir(parents=True, exist_ok=True)
config_yaml_dest = config_dest_dir / "config.yaml"
@@ -366,18 +398,18 @@ def prepare_workspace(overwrite: bool = True, preferred_language: Optional[str]
"env template source not found; tried: "
+ ", ".join(str(p) for p in env_template_src_candidates)
)
- env_dest = USER_WORKSPACE_DIR / "config" / ".env"
+ env_dest = workspace_dir / "config" / ".env"
if overwrite or not env_dest.exists():
shutil.copy2(env_template_src, env_dest)
# ----- copy runtime dirs (new layout) -----
- agent_root = USER_WORKSPACE_DIR / "agent"
+ agent_root = workspace_dir / "agent"
agent_home = agent_root / "home"
agent_skills = agent_root / "skills"
agent_memory = agent_root / "memory"
agent_sessions = agent_root / "sessions"
- (USER_WORKSPACE_DIR / ".checkpoint").mkdir(parents=True, exist_ok=True)
- (USER_WORKSPACE_DIR / ".logs").mkdir(parents=True, exist_ok=True)
+ (workspace_dir / ".checkpoint").mkdir(parents=True, exist_ok=True)
+ (workspace_dir / ".logs").mkdir(parents=True, exist_ok=True)
template_agent_workspace = template_agent_dir / "workspace"
template_agent_memory = template_agent_dir / "memory"
@@ -451,7 +483,8 @@ def init_user_workspace(overwrite: bool = True) -> Path | Literal["cancelled"]:
交互式 init 会先询问语言;首次启动 app 时非交互 prepare_workspace 则沿用模板 config 中的语言。
"""
- if USER_WORKSPACE_DIR.exists():
+ workspace_dir = get_user_workspace_dir()
+ if workspace_dir.exists():
# Warn user about data loss and ask for confirmation
print("[jiuwenclaw-init] WARNING: This will delete all historical configuration and memory information.")
print("[jiuwenclaw-init] This action cannot be undone.")
@@ -468,7 +501,7 @@ def init_user_workspace(overwrite: bool = True) -> Path | Literal["cancelled"]:
print(f"[jiuwenclaw-init] 将使用语言 / Language: {lang}")
prepare_workspace(overwrite, preferred_language=lang)
- return USER_WORKSPACE_DIR
+ return workspace_dir
def _resolve_paths() -> None:
@@ -478,12 +511,13 @@ def _resolve_paths() -> None:
if _initialized:
return
+ workspace_dir = get_user_workspace_dir()
# 优先使用已初始化的用户工作区 (~/.jiuwenclaw),
# 保证源码运行与安装包运行后的读写路径完全一致。
- user_config_dir = USER_WORKSPACE_DIR / "config"
- user_workspace_dir = USER_WORKSPACE_DIR / "agent" / "workspace"
+ user_config_dir = workspace_dir / "config"
+ user_workspace_dir = workspace_dir / "agent" / "workspace"
if user_config_dir.exists():
- _root_dir = USER_WORKSPACE_DIR
+ _root_dir = workspace_dir
_config_dir = user_config_dir
_workspace_dir = user_workspace_dir
else:
@@ -527,11 +561,11 @@ def get_root_dir() -> Path:
def get_agent_workspace_dir() -> Path:
"""Get the agent workspace directory path."""
- return USER_WORKSPACE_DIR / "agent" / "workspace"
+ return get_user_workspace_dir() / "agent" / "workspace"
def get_agent_root_dir() -> Path:
- return USER_WORKSPACE_DIR / "agent"
+ return get_user_workspace_dir() / "agent"
def get_agent_home_dir() -> Path:
@@ -557,15 +591,16 @@ def get_agent_sessions_dir() -> Path:
def get_checkpoint_dir() -> Path:
- return USER_WORKSPACE_DIR / ".checkpoint"
+ return get_user_workspace_dir() / ".checkpoint"
def get_logs_dir() -> Path:
- return USER_WORKSPACE_DIR / ".logs"
+ return get_user_workspace_dir() / ".logs"
def get_xy_tmp_dir() -> Path:
- xy_tmp_dir = USER_WORKSPACE_DIR / "tmp" / "xiaoyi"
+ workspace_dir = get_user_workspace_dir()
+ xy_tmp_dir = workspace_dir / "tmp" / "xiaoyi"
xy_tmp_dir.mkdir(parents=True, exist_ok=True)
return xy_tmp_dir
diff --git a/tests/system_tests/conftest.py b/tests/system_tests/conftest.py
index 20cfbf1819..4f5a8e2860 100644
--- a/tests/system_tests/conftest.py
+++ b/tests/system_tests/conftest.py
@@ -36,7 +36,7 @@ def clean_environment(temp_home: Path, monkeypatch: pytest.MonkeyPatch) -> None:
1. Overrides HOME to use a temporary directory
2. Clears any cached configuration
3. Resets module-level caches in utils.py
- 4. Directly patches USER_WORKSPACE_DIR to point to temp home
+ 4. Uses set_user_home to set custom home directory
Use this fixture when testing initialization to ensure tests are isolated.
"""
@@ -48,11 +48,8 @@ def clean_environment(temp_home: Path, monkeypatch: pytest.MonkeyPatch) -> None:
# Clear any cached configuration
monkeypatch.delenv("JIUWENCLAW_CONFIG_DIR", raising=False)
- # Directly monkeypatch USER_HOME and USER_WORKSPACE_DIR
- # These are computed at module import time, so we need to override them directly
- temp_workspace = temp_home / ".jiuwenclaw"
- monkeypatch.setattr(utils_module, "USER_HOME", temp_home)
- monkeypatch.setattr(utils_module, "USER_WORKSPACE_DIR", temp_workspace)
+ # Use set_user_home to set custom home directory
+ utils_module.set_user_home(temp_home)
# Reset cache variables
monkeypatch.setattr(utils_module, "_initialized", False)
diff --git a/tests/unit_tests/test_utils.py b/tests/unit_tests/test_utils.py
index f300302f23..ebaada034b 100644
--- a/tests/unit_tests/test_utils.py
+++ b/tests/unit_tests/test_utils.py
@@ -103,12 +103,12 @@ class TestLoggerSetup:
class TestUserWorkspace:
"""Test user workspace functions."""
- @patch("jiuwenclaw.utils.USER_WORKSPACE_DIR")
+ @patch("jiuwenclaw.utils.get_user_workspace_dir")
@patch("jiuwenclaw.utils._find_package_root")
@patch("pathlib.Path.exists")
@patch("builtins.input")
def test_init_user_workspace_cancelled(
- self, mock_input, mock_exists, mock_find_root, mock_workspace_dir, temp_workspace
+ self, mock_input, mock_exists, mock_find_root, mock_get_workspace_dir, temp_workspace
):
"""Test user workspace initialization when user cancels."""
# This test requires more complex mocking due to file operations
@@ -120,14 +120,14 @@ class TestConstants:
"""Test module constants."""
@staticmethod
- def test_user_home_defined():
- """Test USER_HOME is defined and is a Path."""
- assert hasattr(utils, "USER_HOME")
- assert isinstance(utils.USER_HOME, Path)
+ def test_get_user_home_defined():
+ """Test get_user_home is defined and returns a Path."""
+ assert hasattr(utils, "get_user_home")
+ assert isinstance(utils.get_user_home(), Path)
@staticmethod
- def test_user_workspace_dir_defined():
- """Test USER_WORKSPACE_DIR is defined."""
- assert hasattr(utils, "USER_WORKSPACE_DIR")
- assert isinstance(utils.USER_WORKSPACE_DIR, Path)
- assert ".jiuwenclaw" in str(utils.USER_WORKSPACE_DIR)
+ def test_get_user_workspace_dir_defined():
+ """Test get_user_workspace_dir is defined."""
+ assert hasattr(utils, "get_user_workspace_dir")
+ assert isinstance(utils.get_user_workspace_dir(), Path)
+ assert ".jiuwenclaw" in str(utils.get_user_workspace_dir())