Skip to content

Build and run agents you can see, understand and trust.

feat(workspace): built the workspace module in agentscope 2.0 (#1586)

DavdGao9f6980ce663b
diff --git a/src/agentscope/offload/__init__.py b/src/agentscope/offload/__init__.py
deleted file mode 100644
index 1ecb033b4..000000000
--- a/src/agentscope/offload/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The offload module in agentscope."""
-
-from ._base import OffloadBase
-
-__all__ = [
- "OffloadBase",
-]
diff --git a/src/agentscope/offload/_base.py b/src/agentscope/offload/_base.py
deleted file mode 100644
index 8daaf5a6a..000000000
--- a/src/agentscope/offload/_base.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The base class for offloading."""
-from abc import abstractmethod, ABC
-from typing import Any
-
-from ..message import Msg, ToolResultBlock, DataBlock, TextBlock
-
-
-class OffloadBase(ABC):
- """The offload base class for agentic retrieval, e.g. offload the
- compressed context into accessible Markdown files so that the agent
- can read them by file reading tools.
- """
-
- @abstractmethod
- async def offload_context(self, msgs: list[Msg], **kwargs: Any) -> None:
- """Offload the compressed context into agent accessible content."""
-
- @abstractmethod
- async def offload_tool_result(
- self,
- blocks: list[ToolResultBlock],
- **kwargs: Any,
- ) -> None:
- """Offload the tool results into agent accessible content."""
-
- @abstractmethod
- async def offload_plan(self, plan: str, **kwargs: Any) -> None:
- """Offload the finished or deprecated plan."""
-
- @abstractmethod
- async def offload_summary(
- self,
- summary: list[TextBlock | DataBlock],
- **kwargs: Any,
- ) -> None:
- """Offload the outdated context summary."""
diff --git a/src/agentscope/workspace/__init__.py b/src/agentscope/workspace/__init__.py
new file mode 100644
index 000000000..a221a9663
--- /dev/null
+++ b/src/agentscope/workspace/__init__.py
@@ -0,0 +1,10 @@
+# -*- coding: utf-8 -*-
+"""The workspace module in agentscope."""
+
+from ._base import WorkspaceBase
+from ._local_workspace import LocalWorkspace
+
+__all__ = [
+ "WorkspaceBase",
+ "LocalWorkspace",
+]
diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.py
new file mode 100644
index 000000000..ef678262f
--- /dev/null
+++ b/src/agentscope/workspace/_base.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+"""The workspace base class."""
+from abc import abstractmethod, ABC
+from typing import Any
+
+from ..skill import Skill
+from ..message import Msg, ToolResultBlock
+from ..tool import ToolBase
+
+
+class WorkspaceBase(ABC):
+ """Abstract base class representing the execution environment of an agent.
+
+ A workspace defines where and how an agent operates, and is
+ responsible for:
+
+ - Providing tools scoped to this environment (e.g. Bash, file I/O tools)
+ - Offloading compressed context to support agentic retrieval
+ """
+
+ @abstractmethod
+ async def initialize(self) -> None:
+ """Initialize the workspace, e.g. initialize the MCPs, copy the skills
+ into the workspace and so on."""
+
+ @abstractmethod
+ async def close(self) -> None:
+ """Close the workspace and clean up resource."""
+
+ @abstractmethod
+ async def get_instructions(self) -> str:
+ """Retrieve the workspace instructions. The instructions will be
+ appended to the system prompt to guide the agent on how to
+ interact with this workspace.
+
+ Returns:
+ `str`:
+ The workspace instructions.
+ """
+
+ @abstractmethod
+ async def list_tools(self) -> list[ToolBase]:
+ """List all tools available in the workspace.
+
+ Returns:
+ `list[ToolBase]`:
+ The list of tools available in the workspace.
+ """
+
+ @abstractmethod
+ async def list_skills(self) -> list[Skill]:
+ """List all skills available in the workspace.
+
+ Returns:
+ `list[Skill]`:
+ The list of skills available in the workspace.
+ """
+
+ @abstractmethod
+ async def offload_context(
+ self,
+ session_id: str,
+ msgs: list[Msg],
+ **kwargs: Any,
+ ) -> str:
+ """Offload the compressed context into agent accessible content."""
+
+ @abstractmethod
+ async def offload_tool_result(
+ self,
+ session_id: str,
+ tool_result: ToolResultBlock,
+ **kwargs: Any,
+ ) -> str:
+ """Offload the tool results into agent accessible content."""
diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.py
new file mode 100644
index 000000000..68e342753
--- /dev/null
+++ b/src/agentscope/workspace/_local_workspace.py
@@ -0,0 +1,789 @@
+# -*- coding: utf-8 -*-
+"""The local workspace class."""
+import asyncio
+import base64
+import hashlib
+import json
+import mimetypes
+import os
+import re
+import shutil
+from copy import deepcopy
+from pathlib import Path
+from typing import Any, TypedDict
+
+import aiofiles
+import aiofiles.ospath
+import frontmatter
+from pydantic import AnyUrl
+
+from ._base import WorkspaceBase
+from ..mcp import MCPClient
+from ..message import (
+ TextBlock,
+ DataBlock,
+ ToolResultBlock,
+ Msg,
+ URLSource,
+ Base64Source,
+)
+from ..skill import Skill
+from ..tool import (
+ ToolBase,
+ Bash,
+ Edit,
+ Glob,
+ Grep,
+ Read,
+ Write,
+)
+from .._logging import logger
+
+
+class _SkillEntry(TypedDict):
+ """A single entry in the .skills index file."""
+
+ hash: str
+ """SHA-256 hash of the skill's SKILL.md content."""
+ skill_name: str
+ """The name exposed to the agent (may differ from the directory name)."""
+
+
+class _SkillsFile(TypedDict):
+ """Schema of the .skills index file stored inside skills_dir."""
+
+ skills_dir_mtime: float
+ """mtime of skills_dir at the time the index was last written."""
+ skills: dict[str, _SkillEntry]
+ """Mapping from directory name (relative to skills_dir) to skill entry."""
+
+
+def _sanitize_dir_name(name: str) -> str:
+ """Sanitize a skill name into a safe directory name.
+
+ Allowed characters: ASCII letters, digits, CJK unified ideographs,
+ hyphens, and underscores. Everything else is replaced with ``_``.
+
+ Args:
+ name (`str`):
+ The raw skill name from SKILL.md frontmatter.
+
+ Returns:
+ `str`:
+ A sanitized string safe to use as a directory name on Windows,
+ macOS, and Linux.
+ """
+ return re.sub(r"[^\w一-鿿-]", "_", name)
+
+
+_DEFAULT_WORKSPACE_INSTRUCTIONS = """<workspace>
+You have access to a local workspace at {workdir} with the following structure:
+
+```
+{workdir}
+├── data/ # offloaded multimodal files (images, etc.)
+├── skills/ # reusable skills, each in its own subdirectory
+└── sessions/ # session context and tool results
+```
+
+This workspace is your personal working environment for completing various tasks.
+You are responsible for keeping it clean, structured, and easy to navigate over time.
+
+### Project Directory
+- Create a dedicated subdirectory for each task or project under the workspace root.
+- Name the directory concisely and descriptively, e.g. `20240315_web-scraper`, so it remains identifiable long after creation.
+- Always create a `README.md` at the project root documenting:
+ - What the project is about
+ - When it was created
+ - Key decisions or context that would help you resume work later
+ - The changes you have made (and when)
+
+### Version Control
+- It is recommended to initialize a `git` repository in each project directory
+ to track changes and allow rollbacks.
+- Always create a `.gitignore` before the first commit to exclude unwanted files
+ (e.g. virtual environments, cache, secrets).
+
+### Python Environment
+- If a project requires Python, use `uv` to create an isolated virtual environment
+ inside the project directory:
+ ```shell
+ uv venv && uv pip install ...
+ ```
+- Never install packages into a shared or global environment — each project must
+ manage its own dependencies to avoid conflicts.
+</workspace>""" # noqa: E501
+
+
+class LocalWorkspace(WorkspaceBase):
+ # pylint: disable=line-too-long
+ """The local workspace class, which chooses a local directory as the
+ agent workspace. It's organized as
+
+ ```
+ {workdir}
+ ├── data/ # the offloaded multimodal files, e.g. images
+ ├── skills/ # the skill directories, each skill has a subdirectory under skills/
+ │ ├── {skill_name}/ # the skill directory
+ │ │ ├── {skill_files} # the files for the skill
+ └── sessions/ # the session directories, each session has a subdirectory under sessions/
+ └── {session_id}/ # the session directory
+ ├── context.jsonl # the offloaded context for the session, in jsonl format
+ └── tool_result-{id}.txt # the offloaded tool results for the session, in txt format
+ ```
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ workdir: str,
+ skill_paths: list[str] | None = None,
+ mcps: list[MCPClient] | None = None,
+ instructions: str = _DEFAULT_WORKSPACE_INSTRUCTIONS,
+ ) -> None:
+ """Initialize the local workspace.
+
+ Args:
+ workdir (`str`):
+ The agent workdir, used to offload the compressed context for
+ agentic retrieval.
+ skill_paths (`list[str] | None`, optional):
+ A list of skill paths that will be copied into the target
+ skill directory when the workspace is first initialized.
+ Defaults to `None`.
+ instructions (`str`, optional):
+ The workspace instructions to guide the agent how to use it.
+ """
+ self._workdir = os.path.abspath(workdir)
+ # Deduplicate skill paths by absolute path
+ self._skill_paths = list(
+ dict.fromkeys(os.path.abspath(p) for p in (skill_paths or [])),
+ )
+ self._instructions = instructions
+ self._mcps = mcps or []
+
+ async def initialize(self) -> None:
+ """Initialize the local workspace by copying skills to the target
+ directory.
+
+ Skills are processed sequentially to guarantee correct deduplication:
+ 1. Validate each skill and compute its SKILL.md hash
+ 2. Skip if the hash already exists in the workspace
+ 3. Resolve directory-name and agent-name conflicts with numeric
+ suffixes
+ 4. Copy the skill, then update the .skills index
+ """
+ # Initialize the MCP connections
+ for mcp in self._mcps:
+ if (
+ mcp.is_stateful or mcp.mcp_config.type == "stdio_mcp"
+ ) and not mcp.is_connected:
+ await mcp.connect()
+
+ # Copy the skills
+ skills_dir = os.path.join(self._workdir, "skills")
+ os.makedirs(skills_dir, exist_ok=True)
+
+ skills_file = await self._load_skills_file(skills_dir)
+ existing: dict[str, _SkillEntry] = skills_file["skills"]
+
+ # Build fast-lookup sets from the current index
+ existing_hashes: set[str] = {e["hash"] for e in existing.values()}
+ existing_agent_names: set[str] = {
+ e["skill_name"] for e in existing.values()
+ }
+ existing_dir_names: set[str] = set(existing.keys())
+
+ updated = False
+ for skill_path in self._skill_paths:
+ result = await self._validate_and_hash_skill(skill_path)
+ if result is None:
+ continue
+
+ _, raw_name, skill_hash = result
+
+ # Skip if already present (by content hash)
+ if skill_hash in existing_hashes:
+ logger.info(
+ "Skill '%s' (hash: %s...) already exists, skipping",
+ raw_name,
+ skill_hash[:8],
+ )
+ continue
+
+ # Resolve agent-facing name conflict
+ agent_name = raw_name
+ counter = 1
+ while agent_name in existing_agent_names:
+ agent_name = f"{raw_name} ({counter})"
+ counter += 1
+
+ # Resolve directory name conflict
+ base_dir = _sanitize_dir_name(raw_name)
+ dir_name = base_dir
+ counter = 1
+ while dir_name in existing_dir_names:
+ dir_name = f"{base_dir}_{counter}"
+ counter += 1
+
+ dest_path = os.path.join(skills_dir, dir_name)
+
+ # Defensive path-traversal check
+ if not os.path.realpath(dest_path).startswith(
+ os.path.realpath(skills_dir) + os.sep,
+ ):
+ logger.warning(
+ "Skill '%s' resolves outside skills_dir, skipping",
+ raw_name,
+ )
+ continue
+
+ try:
+ await asyncio.to_thread(
+ shutil.copytree,
+ skill_path,
+ dest_path,
+ dirs_exist_ok=False,
+ )
+ except Exception as e:
+ logger.warning(
+ "Failed to copy skill '%s' from %s: %s",
+ raw_name,
+ skill_path,
+ str(e),
+ )
+ continue
+
+ logger.info(
+ "Copied skill '%s' (agent name: '%s') from %s to %s",
+ raw_name,
+ agent_name,
+ skill_path,
+ dest_path,
+ )
+
+ entry: _SkillEntry = {"hash": skill_hash, "skill_name": agent_name}
+ existing[dir_name] = entry
+ existing_hashes.add(skill_hash)
+ existing_agent_names.add(agent_name)
+ existing_dir_names.add(dir_name)
+ updated = True
+
+ if updated:
+ skills_file["skills"] = existing
+ skills_file["skills_dir_mtime"] = await aiofiles.ospath.getmtime(
+ skills_dir,
+ )
+ await self._save_skills_file(skills_dir, skills_file)
+
+ async def get_instructions(self) -> str:
+ """Get the workspace instructions."""
+ return self._instructions.format(workdir=self._workdir)
+
+ async def _load_skills_file(self, skills_dir: str) -> _SkillsFile:
+ """Load the .skills index file, returning an empty structure if absent.
+
+ Args:
+ skills_dir (`str`): The skills directory path.
+
+ Returns:
+ `_SkillsFile`: The parsed index, or a fresh empty structure.
+ """
+ path = os.path.join(skills_dir, ".skills")
+ if not await aiofiles.ospath.exists(path):
+ return {"skills_dir_mtime": 0.0, "skills": {}}
+
+ try:
+ async with aiofiles.open(path, "r", encoding="utf-8") as f:
+ data = json.loads(await f.read())
+ return _SkillsFile(
+ skills_dir_mtime=float(data.get("skills_dir_mtime", 0.0)),
+ skills=data.get("skills", {}),
+ )
+ except Exception as e:
+ logger.warning("Failed to load .skills from %s: %s", path, str(e))
+ return {"skills_dir_mtime": 0.0, "skills": {}}
+
+ async def _save_skills_file(
+ self,
+ skills_dir: str,
+ data: _SkillsFile,
+ ) -> None:
+ """Persist the .skills index file.
+
+ Args:
+ skills_dir (`str`): The skills directory path.
+ data (`_SkillsFile`): The index to write.
+ """
+ path = os.path.join(skills_dir, ".skills")
+ try:
+ async with aiofiles.open(path, "w", encoding="utf-8") as f:
+ await f.write(json.dumps(data, indent=2, ensure_ascii=False))
+ except Exception as e:
+ logger.warning("Failed to save .skills to %s: %s", path, str(e))
+
+ async def _validate_skill(
+ self,
+ skill_path: str,
+ ) -> tuple[str, str, str] | None:
+ """Validate if a skill path contains a valid SKILL.md file.
+
+ Args:
+ skill_path (`str`):
+ The path to the skill directory.
+
+ Returns:
+ `tuple[str, str, str] | None`:
+ A tuple of (name, description, skill_md_content) if valid,
+ None otherwise.
+ """
+ skill_md_path = os.path.join(skill_path, "SKILL.md")
+
+ try:
+ # Check if SKILL.md exists
+ if not await aiofiles.ospath.isfile(skill_md_path):
+ logger.warning(
+ "Invalid skill at %s: SKILL.md not found",
+ skill_path,
+ )
+ return None
+
+ # Read and parse SKILL.md
+ async with aiofiles.open(
+ skill_md_path,
+ "r",
+ encoding="utf-8",
+ ) as f:
+ content_str = await f.read()
+
+ # Parse frontmatter
+ content = frontmatter.loads(content_str)
+ name = content.get("name")
+ description = content.get("description")
+
+ if not name or not description:
+ logger.warning(
+ "Invalid skill at %s: SKILL.md missing required "
+ "fields (name or description)",
+ skill_path,
+ )
+ return None
+
+ return str(name), str(description), content_str
+
+ except Exception as e:
+ logger.warning(
+ "Failed to validate skill at %s: %s",
+ skill_path,
+ str(e),
+ )
+ return None
+
+ async def _validate_and_hash_skill(
+ self,
+ skill_path: str,
+ ) -> tuple[str, str, str] | None:
+ """Validate a skill and compute its hash.
+
+ Args:
+ skill_path (`str`):
+ The path to the skill directory.
+
+ Returns:
+ `tuple[str, str, str] | None`:
+ A tuple of (skill_path, skill_name, skill_hash) if valid,
+ None otherwise.
+ """
+ validation_result = await self._validate_skill(skill_path)
+ if validation_result is None:
+ return None
+
+ skill_name, _, skill_md_content = validation_result
+
+ # Compute hash
+ skill_hash = hashlib.sha256(
+ skill_md_content.encode("utf-8"),
+ ).hexdigest()
+
+ return skill_path, skill_name, skill_hash
+
+ async def _offload_data_block(self, data_block: DataBlock) -> DataBlock:
+ """Offload the data block by persisting it as local files. This avoids
+ embedding large base64-encoded data directly in the offload files,
+ keeping them lightweight and readable.
+
+ Args:
+ data_block (`DataBlock`):
+ The data block with base64 source.
+
+ Returns:
+ `DataBlock`:
+ A new data block with the same metadata but with the source
+ replaced by the local file path where the data is stored.
+ """
+ if isinstance(data_block.source, URLSource):
+ return data_block
+
+ # Use the full SHA-256 hex digest (256-bit) as the filename stem.
+ # A full hash collision is computationally infeasible, so an existing
+ # file with the same name is guaranteed to have identical content —
+ # no need to read and compare bytes.
+ hash_str = hashlib.sha256(data_block.source.data.encode()).hexdigest()
+ ext = mimetypes.guess_extension(data_block.source.media_type) or ".bin"
+ path = os.path.join(self._workdir, "data", f"{hash_str}{ext}")
+
+ # Reuse the existing file directly — same hash ⟹ same content.
+ if not await aiofiles.ospath.exists(path):
+ # Write decoded bytes to disk and return a URL-source DataBlock.
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ async with aiofiles.open(path, "wb") as f:
+ await f.write(base64.b64decode(data_block.source.data))
+
+ return DataBlock(
+ id=data_block.id,
+ name=data_block.name,
+ source=URLSource(
+ url=AnyUrl(Path(path).as_uri()),
+ media_type=data_block.source.media_type,
+ ),
+ )
+
+ async def offload_context(
+ self,
+ session_id: str,
+ msgs: list[Msg],
+ **kwargs: Any,
+ ) -> str:
+ """Offload the compressed messages into the local directory for
+ further processing.
+
+ Args:
+ session_id (`str`):
+ The session id.
+ msgs (`list[Msg]`):
+ The messages to offload.
+
+ Returns:
+ `str`:
+ The file path to the offloaded message.
+ """
+ path = os.path.join(
+ self._workdir,
+ "sessions",
+ session_id,
+ "context.jsonl",
+ )
+
+ copied_msgs = deepcopy(msgs)
+ msgs_strs = []
+ for msg in copied_msgs:
+ if not isinstance(msg.content, str):
+ content = []
+ for block in msg.content:
+ if isinstance(block, DataBlock) and isinstance(
+ block.source,
+ Base64Source,
+ ):
+ content.append(await self._offload_data_block(block))
+ else:
+ content.append(block)
+ msg.content = content
+ msgs_strs.append(msg.model_dump_json())
+
+ msgs_str = "\n".join(msgs_strs)
+ # Create parent directory if it doesn't exist
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ # Offload the context into the local file
+ # Always end with a newline to ensure proper JSONL format when
+ # appending
+ async with aiofiles.open(
+ path,
+ mode="a",
+ encoding="utf-8",
+ ) as file:
+ await file.write(msgs_str + "\n")
+ return path
+
+ async def offload_tool_result(
+ self,
+ session_id: str,
+ tool_result: ToolResultBlock,
+ **kwargs: Any,
+ ) -> str:
+ """Offload the tool results into the local directory for agentic
+ retrieval.
+
+ Args:
+ session_id (`str`):
+ The session id.
+ tool_result (`ToolResultBlock`):
+ The tool result.
+
+ Returns:
+ `str`:
+ The file path to the offloaded tool results.
+ """
+ path = os.path.join(
+ self._workdir,
+ "sessions",
+ session_id,
+ f"tool_result-{tool_result.id}.txt",
+ )
+
+ res_strs = []
+ if isinstance(tool_result.output, str):
+ res_strs.append(tool_result.output)
+ else:
+ for block in tool_result.output:
+ if isinstance(block, TextBlock):
+ res_strs.append(block.text)
+ elif isinstance(block, DataBlock):
+ if isinstance(block.source, Base64Source):
+ data_block = await self._offload_data_block(block)
+ url = data_block.source.url
+ else:
+ url = block.source.url
+ res_strs.append(
+ f"<data url='{url}' name='{block.name}' "
+ f"media_type='{block.source.media_type}'/>",
+ )
+
+ # Create parent directory if it doesn't exist
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ async with aiofiles.open(path, mode="w", encoding="utf-8") as file:
+ await file.write("".join(res_strs))
+
+ return path
+
+ async def close(self) -> None:
+ """Close the workspace and clean up resources.
+
+ For LocalWorkspace, this is a no-op as there are no persistent
+ connections or resources to clean up.
+ """
+ # Close the MCP connection
+ for mcp in self._mcps:
+ if (
+ mcp.is_stateful or mcp.mcp_config.type == "stdio_mcp"
+ ) and mcp.is_connected:
+ await mcp.close()
+
+ async def list_tools(self) -> list[ToolBase]:
+ """List all tools available in the workspace."""
+ return [
+ Bash(),
+ Edit(),
+ Glob(),
+ Grep(),
+ Read(),
+ Write(),
+ ]
+
+ async def list_skills(self) -> list[Skill]:
+ """List all skills available in the workspace.
+
+ The method uses the .skills index for agent-facing names, compares the
+ skills directory mtime to detect manual additions/removals since the
+ last write, and reconciles the index when a change is found.
+
+ Returns:
+ `list[Skill]`:
+ A list of Skill objects found in the workspace.
+ """
+ skills_dir = os.path.join(self._workdir, "skills")
+
+ if not await aiofiles.ospath.isdir(skills_dir):
+ return []
+
+ skills_file = await self._load_skills_file(skills_dir)
+ current_mtime = await aiofiles.ospath.getmtime(skills_dir)
+
+ # Detect whether the skills directory has changed since last indexing
+ if current_mtime != skills_file["skills_dir_mtime"]:
+ skills_file = await self._reconcile_skills_dir(
+ skills_dir,
+ skills_file,
+ current_mtime,
+ )
+
+ # Load each skill from disk using the index for the agent-facing name
+ tasks = [
+ self._load_single_skill(
+ os.path.join(skills_dir, dir_name),
+ entry["skill_name"],
+ )
+ for dir_name, entry in skills_file["skills"].items()
+ ]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ skills: list = []
+ for dir_name, result in zip(skills_file["skills"], results):
+ if isinstance(result, Exception):
+ logger.warning(
+ "Failed to load skill from %s: %s",
+ dir_name,
+ str(result),
+ )
+ elif result is not None:
+ skills.append(result)
+
+ return skills
+
+ async def _reconcile_skills_dir(
+ self,
+ skills_dir: str,
+ skills_file: _SkillsFile,
+ current_mtime: float,
+ ) -> _SkillsFile:
+ """Reconcile the .skills index after the skills directory has changed.
+
+ Handles:
+ - Manually deleted subdirectories: removed from the index.
+ - Manually added subdirectories: validated and added with conflict
+ resolution for both directory name and agent-facing skill name.
+
+ Args:
+ skills_dir (`str`): Path to the skills directory.
+ skills_file (`_SkillsFile`): The current (stale) index.
+ current_mtime (`float`): The freshly-read mtime of skills_dir.
+
+ Returns:
+ `_SkillsFile`: The updated index (also persisted to disk).
+ """
+ existing: dict[str, _SkillEntry] = skills_file["skills"]
+ original_mtime = skills_file["skills_dir_mtime"]
+
+ # Collect actual subdirectories on disk
+ def _list_dirs() -> set[str]:
+ return {
+ d
+ for d in os.listdir(skills_dir)
+ if os.path.isdir(os.path.join(skills_dir, d))
+ }
+
+ actual_dirs = await asyncio.to_thread(_list_dirs)
+ indexed_dirs = set(existing.keys())
+
+ updated = False
+
+ # Remove entries for directories that no longer exist
+ for removed in indexed_dirs - actual_dirs:
+ logger.info(
+ "Skill directory '%s' removed, updating index",
+ removed,
+ )
+ del existing[removed]
+ updated = True
+
+ # Add entries for directories not yet in the index
+ existing_agent_names: set[str] = {
+ e["skill_name"] for e in existing.values()
+ }
+ existing_hashes: set[str] = {e["hash"] for e in existing.values()}
+
+ for new_dir in actual_dirs - indexed_dirs:
+ skill_path = os.path.join(skills_dir, new_dir)
+ result = await self._validate_and_hash_skill(skill_path)
+ if result is None:
+ continue
+
+ _, raw_name, skill_hash = result
+
+ if skill_hash in existing_hashes:
+ logger.info(
+ "Manually added skill '%s' already tracked by hash, "
+ "skipping",
+ new_dir,
+ )
+ continue
+
+ agent_name = raw_name
+ counter = 1
+ while agent_name in existing_agent_names:
+ agent_name = f"{raw_name} ({counter})"
+ counter += 1
+
+ entry: _SkillEntry = {"hash": skill_hash, "skill_name": agent_name}
+ existing[new_dir] = entry
+ existing_agent_names.add(agent_name)
+ existing_hashes.add(skill_hash)
+ updated = True
+ logger.info(
+ "Manually added skill '%s' indexed as agent name '%s'",
+ new_dir,
+ agent_name,
+ )
+
+ skills_file["skills"] = existing
+ skills_file["skills_dir_mtime"] = current_mtime
+
+ # Save if index changed OR if mtime needs updating
+ # (mtime change without index change means non-skill files were
+ # added/removed, we still need to record the new mtime to avoid
+ # re-reconciling on every list_skills call)
+ if updated or current_mtime != original_mtime:
+ await self._save_skills_file(skills_dir, skills_file)
+
+ return skills_file
+
+ async def _load_single_skill(
+ self,
+ skill_dir: str,
+ skill_name: str,
+ ) -> Skill | None:
+ """Load a single skill from disk using the agent-facing name from
+ the index.
+
+ Args:
+ skill_dir (`str`):
+ The skill directory path containing SKILL.md.
+ skill_name (`str`):
+ The agent-facing name stored in the .skills index.
+
+ Returns:
+ `Skill | None`:
+ A Skill object or None if the SKILL.md is missing/invalid.
+ """
+ skill_md_path = os.path.join(skill_dir, "SKILL.md")
+
+ try:
+ if not await aiofiles.ospath.isfile(skill_md_path):
+ return None
+
+ updated_at = await aiofiles.ospath.getmtime(skill_md_path)
+
+ async with aiofiles.open(
+ skill_md_path,
+ "r",
+ encoding="utf-8",
+ ) as f:
+ content_str = await f.read()
+ content = frontmatter.loads(content_str)
+
+ description = content.get("description")
+ if not description:
+ logger.warning(
+ "SKILL.md in %s is missing 'description'. Skipping.",
+ skill_dir,
+ )
+ return None
+
+ return Skill(
+ name=skill_name,
+ description=str(description),
+ dir=skill_dir,
+ markdown=content.content,
+ updated_at=updated_at,
+ )
+
+ except Exception as e:
+ logger.warning(
+ "Failed to load skill from %s: %s",
+ skill_dir,
+ str(e),
+ )
+ return None
+
+ async def list_mcps(self) -> list[MCPClient]:
+ """The workspace doesn't need to handle the MCP servers. Just leave
+ it empty."""
+ return self._mcps
diff --git a/tests/toolkit_skill_test.py b/tests/toolkit_skill_test.py
index 41a25ba76..3017d6328 100644
--- a/tests/toolkit_skill_test.py
+++ b/tests/toolkit_skill_test.py
@@ -34,6 +34,7 @@ class MockSkillLoader(SkillLoaderBase):
self._skills = skills
async def list_skills(self) -> list[Skill]:
+ """Return a list of all skills."""
return self._skills
diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.py
new file mode 100644
index 000000000..5b5107cd8
--- /dev/null
+++ b/tests/workspace_local_test.py
@@ -0,0 +1,751 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Test cases for LocalWorkspace."""
+import os
+import json
+import base64
+import tempfile
+from unittest.async_case import IsolatedAsyncioTestCase
+from dataclasses import asdict
+from urllib.parse import urlparse
+from urllib.request import url2pathname
+
+import aiofiles
+
+from agentscope.workspace import LocalWorkspace
+from agentscope.message import (
+ Msg,
+ UserMsg,
+ AssistantMsg,
+ DataBlock,
+ Base64Source,
+ URLSource,
+ TextBlock,
+ ToolResultBlock,
+ ToolResultState,
+)
+
+
+class TestLocalWorkspaceOffload(IsolatedAsyncioTestCase):
+ """Test cases for LocalWorkspace offload functionality."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up test fixtures."""
+ # pylint: disable=consider-using-with
+ self.temp_dir = tempfile.TemporaryDirectory()
+ self.workspace = LocalWorkspace(workdir=self.temp_dir.name)
+
+ async def asyncTearDown(self) -> None:
+ """Clean up test fixtures."""
+ self.temp_dir.cleanup()
+
+ async def test_offload_context_pure_text(self) -> None:
+ """Test offloading messages with pure text content.
+
+ This test verifies that:
+ 1. Messages with string content are correctly offloaded
+ 2. The offloaded file is created at the expected path
+ 3. The file contains valid JSONL with all message fields preserved
+ """
+ session_id = "test_session_pure_text"
+ msgs = [
+ UserMsg(name="user", content="Hello, world!"),
+ AssistantMsg(name="assistant", content="Hi there!"),
+ ]
+
+ # Offload the messages
+ file_path = await self.workspace.offload_context(session_id, msgs)
+
+ # Verify the file was created at the expected path
+ expected_path = os.path.join(
+ self.temp_dir.name,
+ "sessions",
+ session_id,
+ "context.jsonl",
+ )
+ self.assertEqual(file_path, expected_path)
+ self.assertTrue(os.path.exists(file_path))
+
+ # Read and verify the offloaded messages
+ async with aiofiles.open(file_path, "r") as f:
+ content = await f.read()
+
+ lines = content.strip().split("\n")
+ self.assertEqual(len(lines), 2)
+
+ # Compare with expected JSON strings
+ expected_lines = [msg.model_dump_json() for msg in msgs]
+ self.assertListEqual(lines, expected_lines)
+
+ async def test_offload_context_multiple_calls(self) -> None:
+ """Test multiple calls to offload_context for the same session.
+
+ This test verifies that:
+ 1. Multiple calls to offload_context append correctly to the file
+ 2. Each message is on its own line (proper JSONL format)
+ 3. No lines are concatenated together
+ """
+ session_id = "test_session_multiple"
+
+ # First batch of messages
+ msgs1 = [
+ UserMsg(name="user", content="First message"),
+ AssistantMsg(name="assistant", content="First response"),
+ ]
+
+ # Second batch of messages
+ msgs2 = [
+ UserMsg(name="user", content="Second message"),
+ AssistantMsg(name="assistant", content="Second response"),
+ ]
+
+ # Offload first batch
+ file_path = await self.workspace.offload_context(session_id, msgs1)
+
+ # Offload second batch
+ file_path2 = await self.workspace.offload_context(session_id, msgs2)
+
+ # Verify both calls return the same path
+ self.assertEqual(file_path, file_path2)
+
+ # Read and verify the offloaded messages
+ async with aiofiles.open(file_path, "r") as f:
+ content = await f.read()
+
+ lines = content.strip().split("\n")
+ self.assertEqual(len(lines), 4)
+
+ # Compare with expected JSON strings
+ expected_lines = [msg.model_dump_json() for msg in msgs1 + msgs2]
+ self.assertListEqual(lines, expected_lines)
+
+ # Verify each line is valid JSON
+ for line in lines:
+ msg = Msg.model_validate_json(line)
+ self.assertIsNotNone(msg)
+
+ async def test_offload_context_with_datablock(self) -> None:
+ """Test offloading messages with DataBlock content.
+
+ This test verifies that:
+ 1. Messages with DataBlock (Base64Source) are correctly offloaded
+ 2. DataBlock data is persisted to separate files
+ 3. DataBlock source is converted from Base64Source to URLSource
+ 4. The offloaded message file contains the updated DataBlock
+ """
+ session_id = "test_session_datablock"
+
+ # Create a test image data (1x1 red pixel PNG)
+ test_data = base64.b64encode(
+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01"
+ b"\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde",
+ ).decode()
+
+ data_block = DataBlock(
+ source=Base64Source(data=test_data, media_type="image/png"),
+ name="test_image",
+ )
+
+ msgs = [
+ UserMsg(
+ name="user",
+ content=[TextBlock(text="Check this image:"), data_block],
+ ),
+ ]
+
+ # Offload the messages
+ file_path = await self.workspace.offload_context(session_id, msgs)
+
+ # Verify the message file was created
+ self.assertTrue(os.path.exists(file_path))
+
+ # Read and verify the offloaded message
+ async with aiofiles.open(file_path, "r") as f:
+ content = await f.read()
+
+ loaded_msg = Msg.model_validate_json(content.strip())
+
+ # Verify the data file was created and extract the URL
+ self.assertIsInstance(loaded_msg.content, list)
+ self.assertEqual(len(loaded_msg.content), 2)
+ data_url = str(loaded_msg.content[1].source.url)
+ self.assertTrue(data_url.startswith("file://"))
+ # Convert file URL to local path (works on both Windows and Unix)
+ data_file_path = url2pathname(urlparse(data_url).path)
+ self.assertTrue(os.path.exists(data_file_path))
+
+ # Verify the data file contains the correct content
+ async with aiofiles.open(data_file_path, "rb") as f:
+ saved_data = await f.read()
+ self.assertEqual(saved_data, base64.b64decode(test_data))
+
+ # Build expected message with URLSource for comparison
+ # Use the actual IDs from loaded message to avoid UUID mismatch
+ expected_msg = UserMsg(
+ name="user",
+ content=[
+ TextBlock(
+ text="Check this image:",
+ id=loaded_msg.content[0].id,
+ ),
+ DataBlock(
+ id=loaded_msg.content[1].id,
+ source=loaded_msg.content[1].source,
+ name="test_image",
+ ),
+ ],
+ id=loaded_msg.id,
+ created_at=loaded_msg.created_at,
+ )
+ self.assertEqual(
+ loaded_msg.model_dump_json(),
+ expected_msg.model_dump_json(),
+ )
+
+ async def test_offload_data_block_deduplication(self) -> None:
+ """Test that duplicate DataBlocks are deduplicated.
+
+ This test verifies that:
+ 1. Multiple DataBlocks with the same content share the same file
+ 2. Only one file is created for duplicate data
+ 3. Both DataBlocks point to the same file path
+ """
+ # Create two DataBlocks with identical data
+ test_data = base64.b64encode(b"test content").decode()
+
+ data_block1 = DataBlock(
+ source=Base64Source(data=test_data, media_type="text/plain"),
+ name="file1",
+ )
+ data_block2 = DataBlock(
+ source=Base64Source(data=test_data, media_type="text/plain"),
+ name="file2",
+ )
+
+ # Offload both data blocks
+ result1 = await self.workspace._offload_data_block(data_block1)
+ result2 = await self.workspace._offload_data_block(data_block2)
+
+ # Verify both point to the same file by comparing source URLs
+ self.assertEqual(str(result1.source.url), str(result2.source.url))
+
+ # Verify the file exists
+ data_url = str(result1.source.url)
+ # Convert file URL to local path (works on both Windows and Unix)
+ data_file_path = url2pathname(urlparse(data_url).path)
+ self.assertTrue(os.path.exists(data_file_path))
+
+ # Verify only one file was created in the data directory
+ data_dir = os.path.join(self.temp_dir.name, "data")
+ files = os.listdir(data_dir)
+ self.assertEqual(len(files), 1)
+
+ async def test_offload_data_block_url_source(self) -> None:
+ """Test offloading DataBlock with URLSource.
+
+ This test verifies that:
+ 1. DataBlock with URLSource is returned as-is
+ 2. No file is created for URLSource DataBlocks
+ """
+ from pydantic import AnyUrl
+
+ data_block = DataBlock(
+ source=URLSource(
+ url=AnyUrl("https://example.com/image.png"),
+ media_type="image/png",
+ ),
+ name="remote_image",
+ )
+
+ # Offload the data block
+ result = await self.workspace._offload_data_block(data_block)
+
+ # Verify the data block is returned as-is by comparing full objects
+ self.assertDictEqual(result.model_dump(), data_block.model_dump())
+
+ # Verify no file was created in the data directory
+ data_dir = os.path.join(self.temp_dir.name, "data")
+ if os.path.exists(data_dir):
+ files = os.listdir(data_dir)
+ self.assertEqual(len(files), 0)
+
+ async def test_offload_tool_result_string(self) -> None:
+ """Test offloading tool result with string output.
+
+ This test verifies that:
+ 1. Tool result with string output is correctly offloaded
+ 2. The offloaded file is created at the expected path
+ 3. The file contains the correct string content
+ """
+ session_id = "test_session_tool_result"
+ tool_result = ToolResultBlock(
+ id="tool_123",
+ name="test_tool",
+ output="Tool execution successful!",
+ state=ToolResultState.SUCCESS,
+ )
+
+ # Offload the tool result
+ file_path = await self.workspace.offload_tool_result(
+ session_id,
+ tool_result,
+ )
+
+ # Verify the file was created at the expected path
+ expected_path = os.path.join(
+ self.temp_dir.name,
+ "sessions",
+ session_id,
+ f"tool_result-{tool_result.id}.txt",
+ )
+ self.assertEqual(file_path, expected_path)
+ self.assertTrue(os.path.exists(file_path))
+
+ # Read and verify the content
+ async with aiofiles.open(file_path, "r") as f:
+ content = await f.read()
+
+ expected_content = "Tool execution successful!"
+ self.assertEqual(content, expected_content)
+
+ async def test_offload_tool_result_with_blocks(self) -> None:
+ """Test offloading tool result with TextBlock and DataBlock output.
+
+ This test verifies that:
+ 1. Tool result with list of blocks is correctly offloaded
+ 2. TextBlock content is extracted and written to file
+ 3. DataBlock is offloaded and referenced in the output file
+ 4. The output file contains the correct format
+ """
+ session_id = "test_session_tool_result_blocks"
+
+ # Create test data
+ test_data = base64.b64encode(b"test file content").decode()
+ data_block = DataBlock(
+ source=Base64Source(data=test_data, media_type="text/plain"),
+ name="output.txt",
+ )
+
+ tool_result = ToolResultBlock(
+ id="tool_456",
+ name="file_tool",
+ output=[
+ TextBlock(text="File created successfully: "),
+ data_block,
+ ],
+ state=ToolResultState.SUCCESS,
+ )
+
+ # Offload the tool result
+ file_path = await self.workspace.offload_tool_result(
+ session_id,
+ tool_result,
+ )
+
+ # Verify the file was created
+ self.assertTrue(os.path.exists(file_path))
+
+ # Read and verify the content
+ async with aiofiles.open(file_path, "r") as f:
+ content = await f.read()
+
+ # Verify the content structure (URL format varies by platform)
+ self.assertTrue(content.startswith("File created successfully: "))
+ self.assertIn("<data url='file://", content)
+ self.assertIn("name='output.txt'", content)
+ self.assertIn("media_type='text/plain'", content)
+ self.assertTrue(content.endswith("/>"))
+
+ # Extract and verify the data file exists
+ # Parse the URL from the content
+ import re
+
+ url_match = re.search(r"url='([^']+)'", content)
+ self.assertIsNotNone(url_match)
+ data_url = url_match.group(1)
+ # Convert file URL to local path (works on both Windows and Unix)
+ data_file_path = url2pathname(urlparse(data_url).path)
+ self.assertTrue(os.path.exists(data_file_path))
+
+
+class TestLocalWorkspaceSkills(IsolatedAsyncioTestCase):
+ """Test cases for LocalWorkspace skill management functionality."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up test fixtures."""
+ # pylint: disable=consider-using-with
+ self.temp_dir = tempfile.TemporaryDirectory()
+ # pylint: disable=consider-using-with
+ self.test_skills_dir = tempfile.TemporaryDirectory()
+
+ async def asyncTearDown(self) -> None:
+ """Clean up test fixtures."""
+ self.temp_dir.cleanup()
+ self.test_skills_dir.cleanup()
+
+ def _create_test_skill(
+ self,
+ skill_name: str,
+ description: str,
+ additional_files: dict[str, str] | None = None,
+ ) -> str:
+ """Create a test skill directory with SKILL.md.
+
+ Args:
+ skill_name (`str`):
+ The name of the skill.
+ description (`str`):
+ The description of the skill.
+ additional_files (`dict[str, str] | None`, optional):
+ Additional files to create in the skill directory.
+ Keys are file names, values are file contents.
+
+ Returns:
+ `str`:
+ The path to the created skill directory.
+ """
+ skill_dir = os.path.join(self.test_skills_dir.name, skill_name)
+ os.makedirs(skill_dir, exist_ok=True)
+
+ # Create SKILL.md with frontmatter
+ skill_md_content = f"""---
+name: {skill_name}
+description: {description}
+---
+
+# {skill_name}
+
+{description}
+"""
+ with open(
+ os.path.join(skill_dir, "SKILL.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(skill_md_content)
+
+ # Create additional files if provided
+ if additional_files:
+ for filename, content in additional_files.items():
+ with open(
+ os.path.join(skill_dir, filename),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(content)
+
+ return skill_dir
+
+ async def test_initialize_copy_skills(self) -> None:
+ """Test copying skills to workspace.
+
+ This test verifies that:
+ 1. Skills are correctly copied from source paths to workspace
+ 2. The .skills file is created with correct hash mappings
+ 3. All skill files are preserved during copying
+ """
+ # Create test skills
+ skill1_dir = self._create_test_skill(
+ "test_skill_1",
+ "A test skill for testing",
+ {"tool.py": "def test_tool():\n pass\n"},
+ )
+ skill2_dir = self._create_test_skill(
+ "test_skill_2",
+ "Another test skill",
+ {"helper.py": "def helper():\n return 42\n"},
+ )
+
+ # Create workspace with skill paths
+ workspace = LocalWorkspace(
+ workdir=self.temp_dir.name,
+ skill_paths=[skill1_dir, skill2_dir],
+ )
+
+ # Initialize the workspace
+ await workspace.initialize()
+
+ # Verify skills were copied
+ skills_dir = os.path.join(self.temp_dir.name, "skills")
+ self.assertTrue(os.path.exists(skills_dir))
+
+ # Verify skill directories exist
+ skill1_target = os.path.join(skills_dir, "test_skill_1")
+ skill2_target = os.path.join(skills_dir, "test_skill_2")
+ self.assertTrue(os.path.exists(skill1_target))
+ self.assertTrue(os.path.exists(skill2_target))
+
+ # Verify SKILL.md files exist
+ self.assertTrue(
+ os.path.exists(os.path.join(skill1_target, "SKILL.md")),
+ )
+ self.assertTrue(
+ os.path.exists(os.path.join(skill2_target, "SKILL.md")),
+ )
+
+ # Verify additional files were copied
+ self.assertTrue(os.path.exists(os.path.join(skill1_target, "tool.py")))
+ self.assertTrue(
+ os.path.exists(os.path.join(skill2_target, "helper.py")),
+ )
+
+ # Verify .skills file was created with correct new structure
+ skills_hash_file = os.path.join(skills_dir, ".skills")
+ self.assertTrue(os.path.exists(skills_hash_file))
+
+ async with aiofiles.open(skills_hash_file, "r") as f:
+ skills_data = json.loads(await f.read())
+
+ # Verify top-level structure
+ self.assertIn("skills_dir_mtime", skills_data)
+ self.assertIn("skills", skills_data)
+
+ skills_index = skills_data["skills"]
+ self.assertEqual(len(skills_index), 2)
+
+ # Verify each entry has the correct structure
+ self.assertIn("test_skill_1", skills_index)
+ self.assertIn("test_skill_2", skills_index)
+ self.assertDictEqual(
+ {k: v["skill_name"] for k, v in skills_index.items()},
+ {"test_skill_1": "test_skill_1", "test_skill_2": "test_skill_2"},
+ )
+
+ async def test_initialize_skip_duplicate_skills(self) -> None:
+ """Test that duplicate skills are not copied again.
+
+ This test verifies that:
+ 1. Skills are copied on first initialization
+ 2. Running initialize again does not copy duplicate skills
+ 3. The .skills file is not modified on second initialization
+ """
+ # Create test skill
+ skill_dir = self._create_test_skill(
+ "test_skill_dup",
+ "A test skill for duplication testing",
+ )
+
+ # Create workspace and initialize
+ workspace = LocalWorkspace(
+ workdir=self.temp_dir.name,
+ skill_paths=[skill_dir],
+ )
+ await workspace.initialize()
+
+ # Get the .skills file content after first initialization
+ skills_hash_file = os.path.join(
+ self.temp_dir.name,
+ "skills",
+ ".skills",
+ )
+ async with aiofiles.open(skills_hash_file, "r") as f:
+ hash_data_first = await f.read()
+
+ # Get modification time of the skill directory
+ skill_target = os.path.join(
+ self.temp_dir.name,
+ "skills",
+ "test_skill_dup",
+ )
+ mtime_first = os.path.getmtime(skill_target)
+
+ # Initialize again
+ await workspace.initialize()
+
+ # Verify .skills file is unchanged
+ async with aiofiles.open(skills_hash_file, "r") as f:
+ hash_data_second = await f.read()
+ self.assertEqual(hash_data_first, hash_data_second)
+
+ # Verify skill directory was not modified
+ mtime_second = os.path.getmtime(skill_target)
+ self.assertEqual(mtime_first, mtime_second)
+
+ async def test_initialize_deduplicate_skills(self) -> None:
+ """Test that duplicate skills in skill_paths are deduplicated.
+
+ This test verifies that:
+ 1. When skill_paths contains duplicates (same hash), only one is copied
+ 2. No concurrent copy conflicts occur
+ 3. The .skills file contains only one entry for the duplicated skill
+ """
+ # Create a test skill
+ skill_dir = self._create_test_skill(
+ "test_skill_dedup",
+ "A test skill for deduplication testing",
+ )
+
+ # Create workspace with the same skill path listed multiple times
+ workspace = LocalWorkspace(
+ workdir=self.temp_dir.name,
+ skill_paths=[skill_dir, skill_dir, skill_dir], # Same path 3 times
+ )
+
+ # Initialize the workspace
+ await workspace.initialize()
+
+ # Verify only one skill was copied
+ skills_dir = os.path.join(self.temp_dir.name, "skills")
+ skill_target = os.path.join(skills_dir, "test_skill_dedup")
+ self.assertTrue(os.path.exists(skill_target))
+
+ # Verify .skills file contains only one entry
+ skills_hash_file = os.path.join(skills_dir, ".skills")
+ self.assertTrue(os.path.exists(skills_hash_file))
+
+ async with aiofiles.open(skills_hash_file, "r") as f:
+ skills_data = json.loads(await f.read())
+
+ # Should have exactly one entry in the skills index
+ skills_index = skills_data["skills"]
+ self.assertEqual(len(skills_index), 1)
+ self.assertIn("test_skill_dedup", skills_index)
+ self.assertEqual(
+ skills_index["test_skill_dedup"]["skill_name"],
+ "test_skill_dedup",
+ )
+
+ async def test_initialize_invalid_skill(self) -> None:
+ """Test handling of invalid skills.
+
+ This test verifies that:
+ 1. Skills without SKILL.md are not copied
+ 2. Skills with invalid frontmatter are not copied
+ 3. Valid skills are still copied correctly
+ """
+ # Create a valid skill
+ valid_skill_dir = self._create_test_skill(
+ "valid_skill",
+ "A valid test skill",
+ )
+
+ # Create an invalid skill without SKILL.md
+ invalid_skill_no_md = os.path.join(
+ self.test_skills_dir.name,
+ "invalid_no_md",
+ )
+ os.makedirs(invalid_skill_no_md, exist_ok=True)
+ with open(
+ os.path.join(invalid_skill_no_md, "tool.py"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write("def tool():\n pass\n")
+
+ # Create an invalid skill with malformed frontmatter
+ invalid_skill_bad_fm = os.path.join(
+ self.test_skills_dir.name,
+ "invalid_bad_fm",
+ )
+ os.makedirs(invalid_skill_bad_fm, exist_ok=True)
+ with open(
+ os.path.join(invalid_skill_bad_fm, "SKILL.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(
+ "---\nname: missing_description\n---\n\nNo description field!",
+ )
+
+ # Create workspace with all skill paths
+ workspace = LocalWorkspace(
+ workdir=self.temp_dir.name,
+ skill_paths=[
+ valid_skill_dir,
+ invalid_skill_no_md,
+ invalid_skill_bad_fm,
+ ],
+ )
+
+ # Initialize the workspace
+ await workspace.initialize()
+
+ # Verify only the valid skill was copied
+ skills_dir = os.path.join(self.temp_dir.name, "skills")
+ self.assertTrue(os.path.exists(skills_dir))
+
+ # Verify valid skill exists
+ valid_target = os.path.join(skills_dir, "valid_skill")
+ self.assertTrue(os.path.exists(valid_target))
+
+ # Verify invalid skills do not exist
+ invalid_target_no_md = os.path.join(skills_dir, "invalid_no_md")
+ invalid_target_bad_fm = os.path.join(skills_dir, "invalid_bad_fm")
+ self.assertFalse(os.path.exists(invalid_target_no_md))
+ self.assertFalse(os.path.exists(invalid_target_bad_fm))
+
+ async def test_list_skills(self) -> None:
+ """Test listing skills from workspace.
+
+ This test verifies that:
+ 1. All skills in the workspace are correctly listed
+ 2. Each skill has the correct name, description, and directory
+ 3. The returned list matches the expected skills
+ """
+ # Create test skills
+ skill1_dir = self._create_test_skill(
+ "list_skill_1",
+ "First skill for listing",
+ )
+ skill2_dir = self._create_test_skill(
+ "list_skill_2",
+ "Second skill for listing",
+ )
+
+ # Create workspace and initialize
+ workspace = LocalWorkspace(
+ workdir=self.temp_dir.name,
+ skill_paths=[skill1_dir, skill2_dir],
+ )
+ await workspace.initialize()
+
+ # List skills
+ skills = await workspace.list_skills()
+
+ # Verify the number of skills
+ self.assertEqual(len(skills), 2)
+
+ # Sort skills by name for consistent comparison
+ skills_sorted = sorted(skills, key=lambda s: s.name)
+
+ # Build expected skills for comparison
+ expected_skills = [
+ {
+ "name": "list_skill_1",
+ "description": "First skill for listing",
+ "dir": skills_sorted[0].dir, # Use actual dir path
+ "markdown": skills_sorted[0].markdown, # Use actual markdown
+ "updated_at": skills_sorted[
+ 0
+ ].updated_at, # Use actual timestamp
+ },
+ {
+ "name": "list_skill_2",
+ "description": "Second skill for listing",
+ "dir": skills_sorted[1].dir, # Use actual dir path
+ "markdown": skills_sorted[1].markdown, # Use actual markdown
+ "updated_at": skills_sorted[
+ 1
+ ].updated_at, # Use actual timestamp
+ },
+ ]
+
+ # Compare full skill objects using dataclasses.asdict
+ actual_skills = [asdict(skill) for skill in skills_sorted]
+ self.assertListEqual(actual_skills, expected_skills)
+
+ async def test_list_skills_empty(self) -> None:
+ """Test listing skills when no skills exist.
+
+ This test verifies that:
+ 1. An empty list is returned when no skills are in the workspace
+ 2. No errors are raised when the skills directory doesn't exist
+ """
+ # Create workspace without initializing
+ workspace = LocalWorkspace(workdir=self.temp_dir.name)
+
+ # List skills (should return empty list)
+ skills = await workspace.list_skills()
+
+ # Verify empty list is returned
+ self.assertListEqual(skills, [])