Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(skill): expand user-home paths (#2053)
Todd914b6ac09176
diff --git a/src/agentscope/_utils/_common.py b/src/agentscope/_utils/_common.pyindex 41c585db1..256d9d7fb 100644--- a/src/agentscope/_utils/_common.py+++ b/src/agentscope/_utils/_common.py@@ -57,6 +57,11 @@ def _generate_id() -> str:return _id_factory()+def _normalize_local_path(path: str) -> str:+ """Expand user-home shorthand and return an absolute local path."""+ return os.path.abspath(os.path.expanduser(path))++def _json_loads_with_repair(json_str: str,schema: dict | None = None,diff --git a/src/agentscope/skill/_local_loader.py b/src/agentscope/skill/_local_loader.pyindex 04f3205e3..917ba5eaa 100644--- a/src/agentscope/skill/_local_loader.py+++ b/src/agentscope/skill/_local_loader.py@@ -9,6 +9,7 @@ import frontmatterfrom ._base import SkillLoaderBasefrom .._logging import logger+from .._utils._common import _normalize_local_pathfrom ..skill import Skill@@ -25,7 +26,7 @@ class LocalSkillLoader(SkillLoaderBase):Whether to scan subdirectories. Defaults to False (onlyscan current directory)."""- self.directory = os.path.abspath(directory)+ self.directory = _normalize_local_path(directory)self.scan_subdir = scan_subdirself._cache: dict[str, Skill] = {}diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.pyindex 9e5ee7d74..305c950a1 100644--- a/src/agentscope/workspace/_base.py+++ b/src/agentscope/workspace/_base.py@@ -61,7 +61,7 @@ from typing import Selffrom pydantic import AnyUrlfrom .._logging import logger-from .._utils._common import _generate_id+from .._utils._common import _generate_id, _normalize_local_pathfrom ..mcp import MCPClientfrom ..message import (Base64Source,@@ -191,7 +191,9 @@ class WorkspaceBase:self._backend = Noneself.default_mcps = list(default_mcps or [])- self.skill_paths = list(skill_paths or [])+ self.skill_paths = [+ _normalize_local_path(path) for path in skill_paths or []+ ]self._mcps = []self._mcp_lock = asyncio.Lock()diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.pyindex 1e4468ddb..92e0fdaee 100644--- a/src/agentscope/workspace/_local_workspace.py+++ b/src/agentscope/workspace/_local_workspace.py@@ -13,6 +13,7 @@ import frontmatterfrom ._utils import DEFAULT_WORKSPACE_INSTRUCTIONSfrom .._logging import logger+from .._utils._common import _normalize_local_pathfrom ..mcp import MCPClientfrom ..skill import Skillfrom ..tool import ToolBase@@ -110,7 +111,9 @@ class LocalWorkspace(WorkspaceBase):# ── seed-only ───────────────────────────────────────────self.default_mcps: list[MCPClient] = list(default_mcps or [])- self.skill_paths: list[str] = list(skill_paths or [])+ self.skill_paths: list[str] = [+ _normalize_local_path(path) for path in skill_paths or []+ ]# ── runtime state ───────────────────────────────────────self._backend = LocalBackend()@@ -724,6 +727,7 @@ class LocalWorkspace(WorkspaceBase):ValueError: If the skill at ``skill_path`` is invalid (missing ormalformed ``SKILL.md``)."""+ skill_path = _normalize_local_path(skill_path)skills_dir = os.path.join(self.workdir, "skills")async with self._skill_lock:os.makedirs(skills_dir, exist_ok=True)diff --git a/tests/skill_loader_test.py b/tests/skill_loader_test.pyindex 101be4ade..84e332921 100644--- a/tests/skill_loader_test.py+++ b/tests/skill_loader_test.py@@ -6,6 +6,7 @@ import tempfileimport shutilimport timefrom unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import patchfrom agentscope.skill import LocalSkillLoader@@ -85,6 +86,60 @@ This is the subdir2 skill content.finally:shutil.rmtree(empty_dir)+ async def test_expanduser_directory(self) -> None:+ """Test that ``~`` is expanded before loading skills."""+ with tempfile.TemporaryDirectory() as home_dir:+ skill_dir = os.path.join(home_dir, "tilde_skill")+ os.makedirs(skill_dir)+ with open(+ os.path.join(skill_dir, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(+ """---+name: tilde_skill+description: A skill under the user home directory+---++This skill is loaded through a tilde path.+""",+ )++ env = {"HOME": home_dir, "USERPROFILE": home_dir}+ drive, tail = os.path.splitdrive(home_dir)+ if drive:+ env["HOMEDRIVE"] = drive+ env["HOMEPATH"] = tail++ with patch.dict(os.environ, env, clear=False):+ loader = LocalSkillLoader(+ os.path.join("~", "tilde_skill"),+ scan_subdir=False,+ )+ self.assertEqual(loader.directory, os.path.abspath(skill_dir))+ skills = await loader.list_skills()++ self.assertListEqual(+ [+ {+ "name": skill.name,+ "description": skill.description,+ "dir": skill.dir,+ }+ for skill in skills+ ],+ [+ {+ "name": "tilde_skill",+ "description": (+ "A skill under the user home directory"+ ),+ "dir": os.path.abspath(skill_dir),+ },+ ],+ )+async def test_scan_subdir_flag_controls_subdirectory_scanning(self,) -> None:diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.pyindex 1d6071f34..7700c6b4a 100644--- a/tests/workspace_local_test.py+++ b/tests/workspace_local_test.py@@ -651,6 +651,88 @@ description: {description}{"test_skill_1": "test_skill_1", "test_skill_2": "test_skill_2"},)+ async def test_initialize_with_tilde_skill_path(self) -> None:+ """Test that ``skill_paths`` expands user-home shorthand."""+ with tempfile.TemporaryDirectory() as home_dir:+ skill_dir = os.path.join(home_dir, "tilde_skill")+ os.makedirs(skill_dir)+ with open(+ os.path.join(skill_dir, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(+ """---+name: tilde_skill+description: A skill under the user home directory+---++This skill is seeded through a tilde path.+""",+ )++ env = {"HOME": home_dir, "USERPROFILE": home_dir}+ drive, tail = os.path.splitdrive(home_dir)+ if drive:+ env["HOMEDRIVE"] = drive+ env["HOMEPATH"] = tail++ with patch.dict(os.environ, env, clear=False):+ workspace = LocalWorkspace(+ workdir=self.temp_dir.name,+ skill_paths=[os.path.join("~", "tilde_skill")],+ )+ self.assertEqual(+ workspace.skill_paths,+ [os.path.abspath(skill_dir)],+ )+ await workspace.initialize()++ skill_target = os.path.join(+ self.temp_dir.name,+ "skills",+ "tilde_skill",+ )+ self.assertTrue(os.path.exists(os.path.join(skill_target, "SKILL.md")))++ async def test_add_skill_with_tilde_path(self) -> None:+ """Test that ``add_skill`` expands user-home shorthand."""+ with tempfile.TemporaryDirectory() as home_dir:+ skill_dir = os.path.join(home_dir, "tilde_skill")+ os.makedirs(skill_dir)+ with open(+ os.path.join(skill_dir, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(+ """---+name: tilde_skill+description: A skill under the user home directory+---++This skill is added through a tilde path.+""",+ )++ env = {"HOME": home_dir, "USERPROFILE": home_dir}+ drive, tail = os.path.splitdrive(home_dir)+ if drive:+ env["HOMEDRIVE"] = drive+ env["HOMEPATH"] = tail++ workspace = LocalWorkspace(workdir=self.temp_dir.name)+ await workspace.initialize()+ with patch.dict(os.environ, env, clear=False):+ await workspace.add_skill(os.path.join("~", "tilde_skill"))++ skill_target = os.path.join(+ self.temp_dir.name,+ "skills",+ "tilde_skill",+ )+ self.assertTrue(os.path.exists(os.path.join(skill_target, "SKILL.md")))+async def test_initialize_skip_duplicate_skills(self) -> None:"""Test that duplicate skills are not copied again.