Skip to content

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

feat(workspace): isolate skills per agent, select them per session (#2283)

DavdGao1d97e9647d2e
diff --git a/src/agentscope/app/_router/_workspace.py b/src/agentscope/app/_router/_workspace.py
index 1426aa972..90f1e7235 100644
--- a/src/agentscope/app/_router/_workspace.py
+++ b/src/agentscope/app/_router/_workspace.py
@@ -234,7 +234,7 @@ async def list_skills(
agent_id,
session_id,
)
- return await workspace.list_skills()
+ return await workspace.list_skills(agent_id=agent_id)
@workspace_router.post(
@@ -261,7 +261,7 @@ async def add_skill(
agent_id,
session_id,
)
- await workspace.add_skill(body.skill_path)
+ await workspace.add_skill(body.skill_path, agent_id=agent_id)
@workspace_router.post(
@@ -310,6 +310,7 @@ async def upload_skill(
workspace_service.tar_stream(parsed, files),
"tar",
"skill",
+ agent_id=agent_id,
)
except (SkillUploadError, ValueError) as e:
raise HTTPException(
@@ -367,6 +368,7 @@ async def add_skills_from_library(
archive.stream,
archive.format,
record.name,
+ agent_id=agent_id,
)
except Exception as e: # pylint: disable=broad-except
failed[record.name] = _describe_exception(e)
@@ -393,7 +395,7 @@ async def remove_skill(
agent_id,
session_id,
)
- await workspace.remove_skill(skill_name)
+ await workspace.remove_skill(skill_name, agent_id=agent_id)
# ---------------------------------------------------------------------------
diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.py
index f0bd06688..1bc6b2a08 100644
--- a/src/agentscope/app/_service/_session.py
+++ b/src/agentscope/app/_service/_session.py
@@ -505,7 +505,12 @@ class SessionService:
`bool`:
``True`` if the agent record existed and was deleted.
"""
+ # Collected before the sessions go, since a deleted session can
+ # no longer tell us which workspace held the agent's skills.
+ workspaces: dict[str, str] = {}
for session in await self._storage.list_sessions(user_id, agent_id):
+ if session.config.workspace_id:
+ workspaces[session.config.workspace_id] = session.id
if session.team_id is not None:
team = await self._storage.get_team(
user_id,
@@ -537,6 +542,27 @@ class SessionService:
if schedule.agent_id == agent_id:
await self.delete_schedule(user_id, schedule.id)
+ # Best-effort: a workspace that cannot be resolved (backend
+ # down, sandbox gone) must not fail a committed deletion.
+ for workspace_id, session_id in workspaces.items():
+ if not self._workspace_manager:
+ break
+ try:
+ workspace = await self._workspace_manager.get_workspace(
+ user_id,
+ agent_id,
+ session_id,
+ workspace_id,
+ )
+ await workspace.purge_agent(agent_id=agent_id)
+ except Exception as e:
+ logger.warning(
+ "Failed to purge workspace %r for agent %r: %s",
+ workspace_id,
+ agent_id,
+ e,
+ )
+
# storage.delete_agent re-iterates sessions and schedules —
# those re-runs are idempotent no-ops because the records were
# already removed above. What remains is the agent record,
diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.py
index 9db971ff6..7da740f09 100644
--- a/src/agentscope/app/_service/_toolkit.py
+++ b/src/agentscope/app/_service/_toolkit.py
@@ -267,7 +267,9 @@ time or interval"
return Toolkit(
tools=tools,
- skills_or_loaders=await workspace.list_skills(),
+ skills_or_loaders=await workspace.list_skills(
+ agent_id=agent_record.id,
+ ),
mcps=await workspace.list_mcps(
agent_id=agent_record.id,
session_id=session_record.id,
diff --git a/src/agentscope/app/_service/_workspace.py b/src/agentscope/app/_service/_workspace.py
index 8ab968c4b..32f03b6a7 100644
--- a/src/agentscope/app/_service/_workspace.py
+++ b/src/agentscope/app/_service/_workspace.py
@@ -464,6 +464,8 @@ class WorkspaceService:
stream: AsyncIterator[bytes],
archive_format: Literal["zip", "tar", "tar.gz"],
name: str,
+ *,
+ agent_id: str | None = None,
) -> None:
"""Pipe a skill archive into a workspace, one install at a time.
@@ -476,9 +478,16 @@ class WorkspaceService:
archive_format (`Literal["zip", "tar", "tar.gz"]`): How the
stream is packed.
name (`str`): The skill's name, for the backend's logging.
+ agent_id (`str | None`, optional): The agent taking
+ ownership. ``None`` installs into the shared partition.
"""
async with self._install_slots:
- await workspace.add_skill_archive(stream, archive_format, name)
+ await workspace.add_skill_archive(
+ stream,
+ archive_format,
+ name,
+ agent_id=agent_id,
+ )
@staticmethod
async def tar_stream(
diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.py
index 3f00ed73a..c80965633 100644
--- a/src/agentscope/workspace/_base.py
+++ b/src/agentscope/workspace/_base.py
@@ -38,7 +38,7 @@ the workspace's :class:`BackendBase` plus a fixed layout derived from
{workdir}/
├── .mcp # declared MCP configs, per agent and session
├── data/ # offloaded multimodal payloads
- ├── skills/ # skill subdirectories
+ ├── skills/ # .seed template, plus one partition per agent
└── sessions/ # per-session context and tool-result files
MCPs are declared per agent and session, and instantiated lazily:
@@ -47,6 +47,13 @@ each session gets its own instances so stateful MCP state never leaks
across agents or sessions. ``.mcp`` holds only the declarations, and
only for sessions that diverged from ``default_mcps``.
+Skills are partitioned per agent, one directory level under
+``skills/``. Skills are editable in place — an agent may improve its
+own — so the partition is what keeps one agent's edits off another's.
+An agent's first skill call equips its partition from ``skills/.seed``,
+the template holding ``skill_paths``; the partition existing afterwards
+is what stops a seed the agent deleted from coming back.
+
Subclasses only set ``self.workdir`` (the agent-visible root); all
other directory paths are derived via :meth:`BackendBase.join_path`,
keeping path semantics consistent with whichever backend is bound.
@@ -92,8 +99,65 @@ from ._utils import (
#: specs with no ids; it is read back under the legacy empty ids.
MCP_FILE_VERSION = 2
+#: Partition under ``skills/`` used when a caller names no agent — an
+#: ordinary partition, read and written like any other, that the SDK
+#: reaches when it is driven without agents at all.
+DEFAULT_SKILL_PARTITION = "default"
+
+#: Template under ``skills/`` copied into a partition the first time
+#: its agent shows up. Not a partition, and never read directly.
+SKILL_SEED_DIR = ".seed"
+
_DEFAULT_MAX_LIVE_STATEFUL_MCPS = 40
+#: Moves a pre-partition ``skills/`` into the seed template, so the
+#: content a shared workspace already had equips every agent that
+#: shows up. Idempotent: a migrated ``skills/`` holds only
+#: directories. Argv: skills dir, seed dir name.
+_MIGRATE_SKILLS_SHIM = (
+ "import os, shutil, sys\n"
+ "skills, seed = sys.argv[1], sys.argv[2]\n"
+ "if not os.path.isdir(skills):\n"
+ " sys.exit(0)\n"
+ "stale = []\n"
+ "for entry in os.listdir(skills):\n"
+ " if entry == seed:\n"
+ " continue\n"
+ " path = os.path.join(skills, entry)\n"
+ " if entry == '.skills' and os.path.isfile(path):\n"
+ " stale.append((entry, '.index'))\n"
+ " elif os.path.isfile(os.path.join(path, 'SKILL.md')):\n"
+ " stale.append((entry, entry))\n"
+ "if not stale:\n"
+ " sys.exit(0)\n"
+ "dst = os.path.join(skills, seed)\n"
+ "os.makedirs(dst, exist_ok=True)\n"
+ "for entry, name in stale:\n"
+ " shutil.move(os.path.join(skills, entry), os.path.join(dst, name))\n"
+ "print(len(stale))\n"
+)
+
+#: Equips one partition from the seed template, once. The rename is
+#: what makes it safe against a concurrent first touch: the loser
+#: fails and drops its copy. Argv: seed dir, partition dir.
+_EQUIP_PARTITION_SHIM = (
+ "import os, shutil, sys\n"
+ "seed, partition = sys.argv[1], sys.argv[2]\n"
+ "if os.path.isdir(partition):\n"
+ " sys.exit(0)\n"
+ "os.makedirs(os.path.dirname(partition), exist_ok=True)\n"
+ "staging = partition + '.equipping-' + str(os.getpid())\n"
+ "if os.path.isdir(seed):\n"
+ " shutil.copytree(seed, staging)\n"
+ "else:\n"
+ " os.makedirs(staging)\n"
+ "try:\n"
+ " os.rename(staging, partition)\n"
+ "except OSError:\n"
+ " shutil.rmtree(staging, ignore_errors=True)\n"
+ "print('equipped')\n"
+)
+
_EXTRACT_TAR_SHIM = (
"import tarfile, sys, os\n"
"src, dst = sys.argv[1], sys.argv[2]\n"
@@ -210,6 +274,10 @@ class WorkspaceBase:
_mcp_lock: asyncio.Lock
"""Guards mutation of the MCP dicts and the ``.mcp`` file."""
+ _equipped_partitions: set[str]
+ """Partitions already equipped from the seed template, so the
+ check costs nothing after an agent's first skill call."""
+
_skill_lock: asyncio.Lock
"""Guards mutation of the ``skills/`` directory."""
@@ -271,6 +339,7 @@ class WorkspaceBase:
self._mcp_specs = {}
self._mcp_instances = {}
self._mcp_last_used = {}
+ self._equipped_partitions = set()
self._mcp_lock = asyncio.Lock()
self._skill_lock = asyncio.Lock()
@@ -289,6 +358,96 @@ class WorkspaceBase:
DEFAULT_SKILLS_DIR,
)
+ @property
+ def _python_command(self) -> str:
+ """Interpreter that runs the shims below through the backend.
+
+ Sandbox images all ship ``python3``. A backend executing on the
+ host does not get that guarantee — Windows has ``python`` or a
+ Store stub — so those workspaces override this.
+ """
+ return "python3"
+
+ @property
+ def _skill_seed_dir(self) -> str:
+ """``skills/.seed`` — the template every partition starts from."""
+ return self.get_backend().join_path(
+ self._skills_dir,
+ SKILL_SEED_DIR,
+ )
+
+ def _skill_partition(self, agent_id: str | None) -> str:
+ """``skills/<agent_id>`` — where one agent's skills live.
+
+ Skills are writable in place, so the partition is the boundary
+ that keeps one agent's edits off another's. ``None`` maps to
+ :data:`DEFAULT_SKILL_PARTITION`, an ordinary partition like any
+ other — nobody else reads it.
+
+ Args:
+ agent_id (`str | None`):
+ The owning agent, or ``None`` for the default one.
+
+ Returns:
+ `str`:
+ Absolute path of the partition directory.
+
+ Raises:
+ ValueError:
+ If ``agent_id`` cannot be used as a directory name.
+ """
+ # A leading dot would collide with ``.seed`` and with ``.``
+ # and ``..``, which is the whole of the escaping problem.
+ if agent_id and (
+ agent_id.startswith(".") or "/" in agent_id or "\\" in agent_id
+ ):
+ raise ValueError(
+ f"Agent id {agent_id!r} is not usable as a skill partition "
+ f"name.",
+ )
+ return self.get_backend().join_path(
+ self._skills_dir,
+ agent_id or DEFAULT_SKILL_PARTITION,
+ )
+
+ async def _equip_partition(self, agent_id: str | None) -> str:
+ """Return the agent's partition, creating it on first sight.
+
+ A partition that does not exist yet is copied from
+ :attr:`_skill_seed_dir`, which is how ``skill_paths`` reach a
+ new agent. Its existence afterwards is the "already equipped"
+ marker, so a seed the agent later deletes stays deleted — the
+ same rule that keeps ``default_mcps`` from coming back.
+
+ Args:
+ agent_id (`str | None`):
+ The agent to equip, or ``None`` for the default one.
+
+ Returns:
+ `str`:
+ Absolute path of the partition directory.
+ """
+ partition = self._skill_partition(agent_id)
+ if partition in self._equipped_partitions:
+ return partition
+ backend = self.get_backend()
+ result = await backend.exec_shell(
+ [
+ self._python_command,
+ "-c",
+ _EQUIP_PARTITION_SHIM,
+ self._skill_seed_dir,
+ partition,
+ ],
+ )
+ if not result.ok():
+ raise RuntimeError(
+ f"Failed to equip skill partition {partition!r}: "
+ f"{result.stderr.decode('utf-8', 'replace')}",
+ )
+ self._equipped_partitions.add(partition)
+ return partition
+
@property
def _sessions_dir(self) -> str:
"""``${workdir}/sessions`` — per-session offload files."""
@@ -600,6 +759,33 @@ class WorkspaceBase:
e,
)
+ async def purge_agent(self, *, agent_id: str) -> None:
+ """Drop everything this workspace holds for one agent.
+
+ Deletes the agent's skill partition. MCP declarations are
+ keyed by session and cleared by :meth:`purge_session` as those
+ sessions are deleted.
+
+ Best-effort — failures are logged, never raised, so a purge
+ cannot block agent deletion.
+
+ Args:
+ agent_id (`str`):
+ The agent being deleted.
+ """
+ if self._backend is None or not agent_id:
+ return
+ try:
+ partition = self._skill_partition(agent_id)
+ self._equipped_partitions.discard(partition)
+ await self._backend.delete_path(partition)
+ except Exception as e:
+ logger.warning(
+ "Failed to delete the skill partition of agent %r: %s",
+ agent_id,
+ e,
+ )
+
# ── instance lifecycle ─────────────────────────────────────────
@staticmethod
@@ -981,33 +1167,49 @@ class WorkspaceBase:
# ── skill management (shared, simple) ──────────────────────────
- async def list_skills(self) -> list[Skill]:
- """Enumerate skills under ``${workdir}/skills``.
+ async def list_skills(
+ self,
+ *,
+ agent_id: str | None = None,
+ ) -> list[Skill]:
+ """Enumerate the skills one agent can use.
- Walks ``skills/`` recursively, parses every ``SKILL.md``'s
- YAML front matter, and yields one :class:`Skill` per file
- that has both ``name`` and ``description``.
+ Reads the agent's own partition — equipping it from the seed
+ template if this is the agent's first appearance — parses
+ every ``skills/<agent_id>/<dir>/SKILL.md``'s YAML front
+ matter, and yields one :class:`Skill` per file that has both
+ ``name`` and ``description``.
Subclasses with richer indexing (e.g.
- :class:`LocalWorkspace` with its ``.skills`` hash index)
+ :class:`LocalWorkspace` with its ``.index`` hash index)
override this method.
+ Args:
+ agent_id (`str | None`, optional):
+ The agent asking. ``None`` reads the default
+ partition, which is where an SDK caller driving the
+ workspace without agents puts everything.
+
Returns:
`list[Skill]`:
- Skills available to the agent. Empty when ``skills/``
- is missing or contains no parseable ``SKILL.md``.
+ Skills available to the agent. Empty when the
+ partition holds no parseable ``SKILL.md``.
"""
import frontmatter as fm
backend = self.get_backend()
- if not await backend.is_dir(self._skills_dir):
- return []
-
- entries = await backend.list_dir(self._skills_dir, recursive=True)
+ partition = await self._equip_partition(agent_id)
skills: list[Skill] = []
+ entries = await backend.list_dir(partition, recursive=True)
for md_path in entries:
- if backend.basename(md_path) != "SKILL.md":
+ skill_dir = backend.dirname(md_path)
+ # Exactly ``<partition>/<dir>/SKILL.md`` — a SKILL.md a
+ # skill ships in a subfolder is not a second skill.
+ if (
+ backend.basename(md_path) != "SKILL.md"
+ or backend.dirname(skill_dir) != partition
+ ):
continue
try:
raw = await backend.read_file(md_path)
@@ -1020,7 +1222,7 @@ class WorkspaceBase:
Skill(
name=str(name),
description=str(desc),
- dir=backend.dirname(md_path),
+ dir=skill_dir,
markdown=doc.content or "",
updated_at=0.0,
),
@@ -1029,8 +1231,13 @@ class WorkspaceBase:
logger.warning("Failed to load skill %s: %s", md_path, e)
return skills
- async def add_skill(self, skill_path: str) -> None:
- """Copy a local skill directory into ``${workdir}/skills``.
+ async def add_skill(
+ self,
+ skill_path: str,
+ *,
+ agent_id: str | None = None,
+ ) -> None:
+ """Copy a local skill directory into an agent's partition.
Tars the directory on the host, writes the archive to the
backend's tmp area, and extracts it via ``python3 -c`` inside
@@ -1044,11 +1251,14 @@ class WorkspaceBase:
Args:
skill_path (`str`):
Path to a skill directory on the local filesystem.
+ agent_id (`str | None`, optional):
+ The agent taking ownership. ``None`` installs into the
+ default partition.
Raises:
ValueError:
If ``SKILL.md`` is missing or a directory with the
- same basename already exists in ``skills/``.
+ same basename already exists in the partition.
RuntimeError:
If extraction inside the sandbox fails.
"""
@@ -1059,15 +1269,16 @@ class WorkspaceBase:
)
backend = self.get_backend()
+ partition = await self._equip_partition(agent_id)
async with self._skill_lock:
dir_name = os.path.basename(os.path.abspath(skill_path))
- remote_dir = backend.join_path(self._skills_dir, dir_name)
+ remote_dir = backend.join_path(partition, dir_name)
if await backend.file_exists(remote_dir):
raise ValueError(
f"Skill directory {dir_name!r} already exists in "
- f"{self._skills_dir}",
+ f"{partition}",
)
buf = io.BytesIO()
@@ -1079,15 +1290,15 @@ class WorkspaceBase:
await backend.write_file(tmp_path, tar_bytes)
await backend.exec_shell(
- ["mkdir", "-p", self._skills_dir],
+ ["mkdir", "-p", partition],
)
result = await backend.exec_shell(
[
- "python3",
+ self._python_command,
"-c",
_EXTRACT_TAR_SHIM,
tmp_path,
- self._skills_dir,
+ partition,
],
)
if not result.ok():
@@ -1104,8 +1315,10 @@ class WorkspaceBase:
fmt: Literal["zip", "tar", "tar.gz"],
dir_name: str,
max_extracted_bytes: int = DEFAULT_MAX_EXTRACTED_BYTES,
+ *,
+ agent_id: str | None = None,
) -> None:
- """Install a skill from an archive stream into ``skills/``.
+ """Install a skill from an archive stream into a partition.
The archive is piped straight into the sandbox and expanded
there, so the server never holds it whole. Expansion lands in a
@@ -1123,6 +1336,9 @@ class WorkspaceBase:
appended when it is taken.
max_extracted_bytes (`int`):
Ceiling on the archive's expanded size.
+ agent_id (`str | None`, optional):
+ The agent taking ownership. ``None`` installs into the
+ default partition.
Raises:
ValueError:
@@ -1138,11 +1354,12 @@ class WorkspaceBase:
)
backend = self.get_backend()
+ partition = await self._equip_partition(agent_id)
suffix = "tar.gz" if fmt == "tar.gz" else fmt
archive_path = f"/tmp/skill-{_generate_id()}.{suffix}"
async with self._skill_lock:
- await backend.exec_shell(["mkdir", "-p", self._skills_dir])
+ await backend.exec_shell(["mkdir", "-p", partition])
# Staged beside ``skills/`` rather than inside it: the same
# filesystem keeps the final rename atomic, while
# ``list_skills`` never sees a half-expanded archive.
@@ -1154,7 +1371,7 @@ class WorkspaceBase:
try:
result = await backend.exec_shell(
[
- "python3",
+ self._python_command,
"-c",
_EXTRACT_ARCHIVE_SHIM,
archive_path,
@@ -1170,12 +1387,12 @@ class WorkspaceBase:
)
root = await self._find_skill_root(staging)
- installed = await self._free_skill_dir(dir_name)
+ installed = await self._free_skill_dir(dir_name, partition)
move = await backend.exec_shell(
[
"mv",
root,
- backend.join_path(self._skills_dir, installed),
+ backend.join_path(partition, installed),
],
)
if not move.ok():
@@ -1187,7 +1404,7 @@ class WorkspaceBase:
await backend.delete_path(staging)
await backend.delete_path(archive_path)
- logger.info("Added skill %r to %s", installed, self._skills_dir)
+ logger.info("Added skill %r to %s", installed, partition)
async def _find_skill_root(self, staging: str) -> str:
"""Return the directory under ``staging`` holding ``SKILL.md``.
@@ -1220,42 +1437,53 @@ class WorkspaceBase:
raise ValueError("The skill archive contains no SKILL.md")
- async def _free_skill_dir(self, dir_name: str) -> str:
+ async def _free_skill_dir(self, dir_name: str, partition: str) -> str:
"""Return ``dir_name``, suffixed until it is unused.
Args:
dir_name (`str`):
The preferred directory name.
+ partition (`str`):
+ The partition directory the name must be free in.
Returns:
`str`:
- A directory name not present in ``skills/``.
+ A directory name not present in ``partition``.
"""
backend = self.get_backend()
candidate, counter = dir_name, 1
while await backend.file_exists(
- backend.join_path(self._skills_dir, candidate),
+ backend.join_path(partition, candidate),
):
candidate = f"{dir_name}-{counter}"
counter += 1
return candidate
- async def remove_skill(self, name: str) -> None:
+ async def remove_skill(
+ self,
+ name: str,
+ *,
+ agent_id: str | None = None,
+ ) -> None:
"""Remove a skill by its agent-facing ``name`` (front matter).
Looks up the skill via :meth:`list_skills` and ``rm -rf``-style
- deletes its directory through the backend.
+ deletes its directory through the backend. An agent can remove
+ a shared skill: the partitions bound who *owns* a skill, not
+ who may delete one.
Args:
name (`str`):
The agent-facing name of the skill to remove.
+ agent_id (`str | None`, optional):
+ The agent asking. ``None`` searches every partition.
Raises:
KeyError:
If the skill is not found in the workspace.
"""
backend = self.get_backend()
- skills = await self.list_skills()
+ skills = await self.list_skills(agent_id=agent_id)
target_dir: str | None = None
for s in skills:
if s.name == name:
@@ -1269,33 +1497,85 @@ class WorkspaceBase:
await backend.delete_path(target_dir)
logger.info("Removed skill %r at %s", name, target_dir)
+ async def _migrate_skill_layout(self) -> None:
+ """Move a pre-partition ``skills/`` into the seed template.
+
+ Runs once per :meth:`initialize`; idempotent, since a migrated
+ ``skills/`` holds nothing but partition directories. Failures
+ are logged, not raised.
+ """
+ backend = self._backend
+ if backend is None:
+ return
+ try:
+ result = await backend.exec_shell(
+ [
+ self._python_command,
+ "-c",
+ _MIGRATE_SKILLS_SHIM,
+ self._skills_dir,
+ SKILL_SEED_DIR,
+ ],
+ )
+ moved = result.stdout.decode("utf-8", "replace").strip()
+ if result.ok() and moved:
+ logger.info(
+ "Moved %s pre-partition skill entries into %s/.",
+ moved,
+ SKILL_SEED_DIR,
+ )
+ elif not result.ok():
+ logger.warning(
+ "Failed to partition %s: %s",
+ self._skills_dir,
+ result.stderr.decode("utf-8", "replace"),
+ )
+ except Exception as e:
+ logger.warning("Failed to partition %s: %s", self._skills_dir, e)
+
async def _setup_skills(self) -> None:
- """Copy :attr:`skill_paths` into ``${workdir}/skills`` once.
+ """Copy :attr:`skill_paths` into the seed template once.
+ Seeds carry no owning agent, so they are not installed
+ anywhere: they become the template each agent's partition is
+ equipped from on first sight. One archive covers all of them,
+ so a sandbox takes the upload once rather than once per agent.
Skips seeding when:
- :attr:`skill_paths` is empty;
- the backend is not bound; or
- - ``skills/`` already contains entries (assume the prior
- run, or the user, is the source of truth).
+ - the template already contains entries (assume the prior run,
+ or the user, is the source of truth).
- Individual failures are logged and skipped — a single bad
- skill cannot block startup.
+ A skill without ``SKILL.md`` is logged and skipped — one bad
+ path cannot block startup.
"""
if not self.skill_paths:
return
backend = self._backend
if backend is None:
return
- entries = await backend.list_dir(self._skills_dir)
- if entries:
+ seed = self._skill_seed_dir
+ if await backend.is_dir(seed) and await backend.list_dir(seed):
return
- for path in self.skill_paths:
- try:
- await self.add_skill(path)
- except Exception as e:
- logger.warning(
- "Skip skill %r: %s",
- path,
- e,
- )
+
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w") as tf:
+ for path in self.skill_paths:
+ if not os.path.isfile(os.path.join(path, "SKILL.md")):
+ logger.warning("Skip skill %r: SKILL.md not found", path)
+ continue
+ tf.add(path, arcname=os.path.basename(os.path.abspath(path)))
+ tar_bytes = buf.getvalue()
+
+ tmp_path = f"/tmp/skill-seed-{_generate_id()}.tar"
+ await backend.write_file(tmp_path, tar_bytes)
+ result = await backend.exec_shell(
+ [self._python_command, "-c", _EXTRACT_TAR_SHIM, tmp_path, seed],
+ )
+ if not result.ok():
+ logger.warning(
+ "Failed to seed %s: %s",
+ seed,
+ result.stderr.decode("utf-8", "replace"),
+ )
diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.py
index 82c10ee27..49f2b72f5 100644
--- a/src/agentscope/workspace/_local_workspace.py
+++ b/src/agentscope/workspace/_local_workspace.py
@@ -7,6 +7,7 @@ import json
import os
import re
import shutil
+import sys
from typing import AsyncIterator, Literal, TypedDict
import frontmatter
@@ -35,12 +36,12 @@ class _SkillEntry(TypedDict):
class _SkillsFile(TypedDict):
- """Schema of the .skills index file stored inside skills_dir."""
+ """Schema of the .skills index file stored inside a partition."""
skills_dir_mtime: float
- """mtime of skills_dir at the time the index was last written."""
+ """mtime of the partition at the time the index was last written."""
skills: dict[str, _SkillEntry]
- """Mapping from directory name (relative to skills_dir) to skill entry."""
+ """Mapping from directory name (relative to the partition) to entry."""
def _sanitize_dir_name(name: str) -> str:
@@ -69,7 +70,7 @@ class LocalWorkspace(WorkspaceBase):
{workdir}/
├── .mcp # declared MCP configs per agent/session
├── data/ # offloaded multimodal files
- ├── skills/ # skill subdirectories
+ ├── skills/ # .seed template, plus one partition per agent
└── sessions/ # per-session context and tool-result files
"""
@@ -96,8 +97,9 @@ class LocalWorkspace(WorkspaceBase):
MCP clients seeded into every agent/session that has
not added or removed one of its own.
skill_paths (`list[str] | None`, optional):
- Local skill directories seeded into
- ``<workdir>/skills`` on first :meth:`initialize`.
+ Local skill directories written to the seed template
+ on first :meth:`initialize`, from which every agent's
+ partition is equipped.
instructions (`str`, defaults to \
`DEFAULT_WORKSPACE_INSTRUCTIONS`):
System-prompt fragment template returned by
@@ -127,6 +129,15 @@ class LocalWorkspace(WorkspaceBase):
self._skill_lock = asyncio.Lock()
self._mcp_lock = asyncio.Lock()
+ @property
+ def _python_command(self) -> str:
+ """The running interpreter, since the shims execute on the host.
+
+ ``python3`` is only a safe name inside a sandbox image; on
+ Windows it is absent or a Store stub that opens a web page.
+ """
+ return sys.executable or "python3"
+
async def list_tools(self) -> list[ToolBase]:
"""Return builtin tools, using PowerShell as the shell on Windows."""
from ..tool import Bash, Edit, Glob, Grep, PowerShell, Read, Write
@@ -156,7 +167,8 @@ class LocalWorkspace(WorkspaceBase):
MCP *declarations* are restored from ``.mcp``; sessions absent
from it fall back to ``default_mcps``. Nothing is connected
here — clients are built on the first ``list_mcps`` for a given
- agent/session. ``skill_paths`` are seeded on first use.
+ agent/session. ``skill_paths`` become the seed template each
+ agent's partition is equipped from on its first skill call.
Idempotent: a no-op when the workspace is already alive.
"""
@@ -167,8 +179,10 @@ class LocalWorkspace(WorkspaceBase):
self._mcp_specs = await self._restore_mcp_specs()
- # Seed skills
- skills_dir = os.path.join(self.workdir, "skills")
+ # Seeds have no owning agent, so they go to the template
+ os.makedirs(self._skills_dir, exist_ok=True)
+ await self._migrate_skill_layout()
+ skills_dir = self._skill_seed_dir
os.makedirs(skills_dir, exist_ok=True)
skills_file = await self._load_skills_file(skills_dir)
@@ -271,15 +285,15 @@ class LocalWorkspace(WorkspaceBase):
return self.instructions
async def _load_skills_file(self, skills_dir: str) -> _SkillsFile:
- """Load the .skills index file, returning an empty structure if absent.
+ """Load the .index file, returning an empty structure if absent.
Args:
- skills_dir (`str`): The skills directory path.
+ skills_dir (`str`): The partition directory path.
Returns:
`_SkillsFile`: The parsed index, or a fresh empty structure.
"""
- path = os.path.join(skills_dir, ".skills")
+ path = os.path.join(skills_dir, ".index")
if not await self._backend.file_exists(path):
return {"skills_dir_mtime": 0.0, "skills": {}}
@@ -299,13 +313,13 @@ class LocalWorkspace(WorkspaceBase):
skills_dir: str,
data: _SkillsFile,
) -> None:
- """Persist the .skills index file.
+ """Persist the .index file.
Args:
- skills_dir (`str`): The skills directory path.
+ skills_dir (`str`): The partition directory path.
data (`_SkillsFile`): The index to write.
"""
- path = os.path.join(skills_dir, ".skills")
+ path = os.path.join(skills_dir, ".index")
try:
await self._backend.write_file(
path,
@@ -424,6 +438,7 @@ class LocalWorkspace(WorkspaceBase):
await self._backend.delete_path(mcp_file)
async with self._skill_lock:
+ self._equipped_partitions.clear()
skills_path = os.path.join(self.workdir, "skills")
await self._backend.delete_path(skills_path)
@@ -431,57 +446,84 @@ class LocalWorkspace(WorkspaceBase):
path = os.path.join(self.workdir, sub)
await self._backend.delete_path(path)
- async def list_skills(self) -> list[Skill]:
- """List all skills available in the workspace.
+ async def list_skills(
+ self,
+ *,
+ agent_id: str | None = None,
+ ) -> list[Skill]:
+ """List the skills one agent can use.
+
+ Reads the agent's own partition — equipping it from the seed
+ template on the agent's first appearance — using the
+ partition's ``.index`` for agent-facing names.
- 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.
+ Args:
+ agent_id (`str | None`, optional):
+ The agent asking. ``None`` reads the default
+ partition, which is where an SDK caller driving the
+ workspace without agents puts everything.
Returns:
`list[Skill]`:
A list of Skill objects found in the workspace.
"""
- skills_dir = os.path.join(self.workdir, "skills")
+ partition = await self._equip_partition(agent_id)
async with self._skill_lock:
- if not await self._backend.is_dir(skills_dir):
- return []
+ return await self._list_partition_skills(partition)
- skills_file = await self._load_skills_file(skills_dir)
- current_mtime = await self._backend.stat_mtime(skills_dir)
- if current_mtime is None:
- current_mtime = 0.0
-
- # Detect if 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,
- )
+ async def _list_partition_skills(self, skills_dir: str) -> list[Skill]:
+ """List the skills held by one partition.
- # Load skills 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)
+ Compares the partition's mtime against its ``.index`` to
+ detect additions/removals made behind the workspace's back, and
+ reconciles the index when they differ.
+
+ Args:
+ skills_dir (`str`):
+ The partition directory to read.
+
+ Returns:
+ `list[Skill]`:
+ The partition's skills, empty when it does not exist.
+ """
+ if not await self._backend.is_dir(skills_dir):
+ return []
+
+ skills_file = await self._load_skills_file(skills_dir)
+ current_mtime = await self._backend.stat_mtime(skills_dir)
+ if current_mtime is None:
+ current_mtime = 0.0
+
+ # Detect if the partition 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 skills 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)
+ 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
+ return skills
async def _reconcile_skills_dir(
self,
@@ -718,25 +760,35 @@ class LocalWorkspace(WorkspaceBase):
]
await self._save_mcp_file()
- async def add_skill(self, skill_path: str) -> None:
- """Add a skill to the workspace by copying from the given path.
+ async def add_skill(
+ self,
+ skill_path: str,
+ *,
+ agent_id: str | None = None,
+ ) -> None:
+ """Add a skill to an agent's partition by copying from a path.
The skill directory must contain a valid ``SKILL.md`` file with
``name`` and ``description`` frontmatter fields. Duplicate skills
(identified by the SHA-256 hash of ``SKILL.md``) are silently skipped.
Name and directory conflicts are resolved by appending a numeric
- suffix.
+ suffix. All three are scoped to the partition: what another agent
+ installed neither collides with this one nor dedups against it,
+ since either agent may later edit its own copy.
Args:
skill_path (`str`):
Absolute or relative path to the skill directory to copy.
+ agent_id (`str | None`, optional):
+ The agent taking ownership. ``None`` installs into the
+ default partition.
Raises:
ValueError: If the skill at ``skill_path`` is invalid (missing or
malformed ``SKILL.md``).
"""
skill_path = _normalize_local_path(skill_path)
- skills_dir = os.path.join(self.workdir, "skills")
+ skills_dir = await self._equip_partition(agent_id)
async with self._skill_lock:
os.makedirs(skills_dir, exist_ok=True)
@@ -819,6 +871,8 @@ class LocalWorkspace(WorkspaceBase):
fmt: Literal["zip", "tar", "tar.gz"],
dir_name: str,
max_extracted_bytes: int = DEFAULT_MAX_EXTRACTED_BYTES,
+ *,
+ agent_id: str | None = None,
) -> None:
"""Expand a skill archive, then install it as a local directory.
@@ -837,6 +891,9 @@ class LocalWorkspace(WorkspaceBase):
Unused; kept for interface compatibility.
max_extracted_bytes (`int`):
Ceiling on the archive's expanded size.
+ agent_id (`str | None`, optional):
+ The agent taking ownership. ``None`` installs into the
+ default partition.
Raises:
ValueError:
@@ -853,7 +910,7 @@ class LocalWorkspace(WorkspaceBase):
await self._backend.write_stream(archive_path, stream)
result = await self._backend.exec_shell(
[
- "python3",
+ self._python_command,
"-c",
_EXTRACT_ARCHIVE_SHIM,
archive_path,
@@ -867,33 +924,37 @@ class LocalWorkspace(WorkspaceBase):
f"Failed to expand skill archive: "
f"{result.stderr.decode('utf-8', 'replace')}",
)
- await self.add_skill(await self._find_skill_root(staging))
+ await self.add_skill(
+ await self._find_skill_root(staging),
+ agent_id=agent_id,
+ )
finally:
await self._backend.delete_path(staging)
await self._backend.delete_path(archive_path)
- async def remove_skill(self, name: str) -> None:
+ async def remove_skill(
+ self,
+ name: str,
+ *,
+ agent_id: str | None = None,
+ ) -> None:
"""Remove a skill from the workspace by its agent-facing name.
- The skill directory is deleted from disk and the ``.skills`` index is
- updated. If no skill with the given name is found, a warning is
- logged and the method returns without error.
+ The skill directory is deleted from the agent's partition and
+ that partition's ``.index`` is updated. If no skill with the given
+ name is found, a warning is logged and the method returns without
+ error.
Args:
name (`str`):
The agent-facing name of the skill to remove (as stored in the
- ``.skills`` index, i.e. the ``name`` field from ``SKILL.md``
+ ``.index``, i.e. the ``name`` field from ``SKILL.md``
possibly with a numeric suffix for de-duplication).
+ agent_id (`str | None`, optional):
+ The agent asking. ``None`` uses the default partition.
"""
- skills_dir = os.path.join(self.workdir, "skills")
+ skills_dir = await self._equip_partition(agent_id)
async with self._skill_lock:
- if not await self._backend.is_dir(skills_dir):
- logger.warning(
- "Skills directory does not exist; cannot remove skill %r",
- name,
- )
- return
-
skills_file = await self._load_skills_file(skills_dir)
existing: dict[str, _SkillEntry] = skills_file["skills"]
diff --git a/src/agentscope/workspace/_sandboxed_base.py b/src/agentscope/workspace/_sandboxed_base.py
index 230b0241d..19e970c80 100644
--- a/src/agentscope/workspace/_sandboxed_base.py
+++ b/src/agentscope/workspace/_sandboxed_base.py
@@ -202,6 +202,7 @@ class SandboxedWorkspaceBase(WorkspaceBase):
await self._setup_mcp_gateway()
# Set up the skills if not exists
+ await self._migrate_skill_layout()
await self._setup_skills()
self.is_alive = True
@@ -248,6 +249,7 @@ class SandboxedWorkspaceBase(WorkspaceBase):
async with self._mcp_lock, self._skill_lock:
await self._close_all_mcp_instances()
self._mcp_specs.clear()
+ self._equipped_partitions.clear()
for path in (
self._sessions_dir,
diff --git a/src/agentscope/workspace/_utils.py b/src/agentscope/workspace/_utils.py
index b72cde355..8dc45dafc 100644
--- a/src/agentscope/workspace/_utils.py
+++ b/src/agentscope/workspace/_utils.py
@@ -21,7 +21,7 @@ workspace at {workdir} with the following structure:
```
{workdir}
├── data/ # offloaded multimodal files (images, etc.) — system-managed
-├── skills/ # reusable skills, each in its own subdirectory
+├── skills/ # reusable skills, grouped by the agent that owns them
└── sessions/ # offloaded session context and tool results — system-managed
```
diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.py
index 1c38381a9..8275260f0 100644
--- a/tests/service_toolkit_test.py
+++ b/tests/service_toolkit_test.py
@@ -57,7 +57,10 @@ class _FakeWorkspace:
"""Return the configured workspace tools."""
return list(self._tools)
- async def list_skills(self) -> list:
+ async def list_skills(
+ self,
+ agent_id: str, # pylint: disable=unused-argument
+ ) -> list:
"""Return the configured workspace skills."""
return list(self._skills)
diff --git a/tests/workspace_bubblewrap_test.py b/tests/workspace_bubblewrap_test.py
index e7cdc7cee..523d0410d 100644
--- a/tests/workspace_bubblewrap_test.py
+++ b/tests/workspace_bubblewrap_test.py
@@ -937,7 +937,10 @@ class TestBubblewrapWorkspace(IsolatedAsyncioTestCase):
skills = await self.workspace.list_skills()
self.assertEqual(len(skills), 1)
self.assertEqual(skills[0].name, "greeter")
- self.assertEqual(skills[0].dir, f"{SANDBOX_WORKDIR}/skills/greeter")
+ self.assertEqual(
+ skills[0].dir,
+ f"{SANDBOX_WORKDIR}/skills/default/greeter",
+ )
await self.workspace.remove_skill("greeter")
self.assertListEqual(await self.workspace.list_skills(), [])
diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.py
index a7b75b30d..5b888e395 100644
--- a/tests/workspace_daytona_test.py
+++ b/tests/workspace_daytona_test.py
@@ -1170,7 +1170,7 @@ class TestDaytonaWorkspaceBuiltinToolsMock(IsolatedAsyncioTestCase):
self.assertEqual([skill.name for skill in skills], ["demo-skill"])
self.assertEqual(
skills[0].dir,
- "/home/daytona/skills/local-skill",
+ "/home/daytona/skills/default/local-skill",
)
await self.workspace.remove_skill("demo-skill")
@@ -1491,8 +1491,8 @@ class TestDaytonaWorkspaceLive(IsolatedAsyncioTestCase):
self.assertEqual(
[skill.dir for skill in seeded],
[
- f"{workspace.workdir}/skills/live_seed_one",
- f"{workspace.workdir}/skills/live_seed_two",
+ f"{workspace.workdir}/skills/default/live_seed_one",
+ f"{workspace.workdir}/skills/default/live_seed_two",
],
)
diff --git a/tests/workspace_docker_test.py b/tests/workspace_docker_test.py
index 0efb80715..eec2613b7 100644
--- a/tests/workspace_docker_test.py
+++ b/tests/workspace_docker_test.py
@@ -520,11 +520,11 @@ class TestDockerWorkspaceSkills(IsolatedAsyncioTestCase):
return skill_dir
async def test_initialize_copy_skills(self) -> None:
- """``skill_paths`` are copied into the container's ``skills/``.
+ """``skill_paths`` are copied into the container's seed template.
Verifies:
- 1. Both seed skills appear under ``<workdir>/skills/`` (host
- mirror) — directory + SKILL.md + supplementary files.
+ 1. Both seed skills appear under ``<workdir>/skills/.seed/``
+ (host mirror) — directory + SKILL.md + supplementary files.
"""
skill1 = self._create_test_skill(
"test_skill_1",
@@ -544,7 +544,7 @@ class TestDockerWorkspaceSkills(IsolatedAsyncioTestCase):
)
await self.workspace.initialize()
- skills_host = os.path.join(self.temp_dir.name, "skills")
+ skills_host = os.path.join(self.temp_dir.name, "skills", ".seed")
self.assertTrue(os.path.isdir(skills_host))
for name, extra in (
("test_skill_1", "tool.py"),
@@ -562,7 +562,8 @@ class TestDockerWorkspaceSkills(IsolatedAsyncioTestCase):
Verifies:
1. Every seeded skill is returned with the right name + dir.
- 2. The dir field uses the *container-side* path.
+ 2. The dir field uses the *container-side* path, inside the
+ partition the caller was equipped with.
"""
skill1 = self._create_test_skill(
"list_skill_1",
@@ -591,7 +592,7 @@ class TestDockerWorkspaceSkills(IsolatedAsyncioTestCase):
)
self.assertEqual(
skills_sorted[0].dir,
- f"{CONTAINER_SKILLS_DIR}/list_skill_1",
+ f"{CONTAINER_SKILLS_DIR}/default/list_skill_1",
)
self.assertEqual(skills_sorted[1].name, "list_skill_2")
@@ -601,7 +602,7 @@ class TestDockerWorkspaceSkills(IsolatedAsyncioTestCase):
)
self.assertEqual(
skills_sorted[1].dir,
- f"{CONTAINER_SKILLS_DIR}/list_skill_2",
+ f"{CONTAINER_SKILLS_DIR}/default/list_skill_2",
)
async def test_list_skills_empty(self) -> None:
diff --git a/tests/workspace_k8s_test.py b/tests/workspace_k8s_test.py
index a4d21a661..fad5ade31 100644
--- a/tests/workspace_k8s_test.py
+++ b/tests/workspace_k8s_test.py
@@ -182,7 +182,7 @@ class TestK8sWorkspaceHappyPath(IsolatedAsyncioTestCase):
self.assertEqual(len(skills), 1)
self.assertEqual(
(skills[0].name, skills[0].description, skills[0].dir),
- ("greeter", "Says hi.", f"{POD_WORKDIR}/skills/greeter"),
+ ("greeter", "Says hi.", f"{POD_WORKDIR}/skills/default/greeter"),
)
await ws.remove_skill("greeter")
diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.py
index a2d3b2dbe..03f6474cf 100644
--- a/tests/workspace_local_test.py
+++ b/tests/workspace_local_test.py
@@ -615,7 +615,7 @@ description: {description}
await workspace.initialize()
# Verify skills were copied
- skills_dir = os.path.join(self.temp_dir.name, "skills")
+ skills_dir = os.path.join(self.temp_dir.name, "skills", ".seed")
self.assertTrue(os.path.exists(skills_dir))
# Verify skill directories exist
@@ -639,7 +639,7 @@ description: {description}
)
# Verify .skills file was created with correct new structure
- skills_hash_file = os.path.join(skills_dir, ".skills")
+ skills_hash_file = os.path.join(skills_dir, ".index")
self.assertTrue(os.path.exists(skills_hash_file))
async with aiofiles.open(skills_hash_file, "r") as f:
@@ -700,6 +700,7 @@ This skill is seeded through a tilde path.
skill_target = os.path.join(
self.temp_dir.name,
"skills",
+ ".seed",
"tilde_skill",
)
self.assertTrue(os.path.exists(os.path.join(skill_target, "SKILL.md")))
@@ -738,6 +739,7 @@ This skill is added through a tilde path.
skill_target = os.path.join(
self.temp_dir.name,
"skills",
+ "default",
"tilde_skill",
)
self.assertTrue(os.path.exists(os.path.join(skill_target, "SKILL.md")))
@@ -767,7 +769,8 @@ This skill is added through a tilde path.
skills_hash_file = os.path.join(
self.temp_dir.name,
"skills",
- ".skills",
+ ".seed",
+ ".index",
)
async with aiofiles.open(skills_hash_file, "r") as f:
hash_data_first = await f.read()
@@ -776,6 +779,7 @@ This skill is added through a tilde path.
skill_target = os.path.join(
self.temp_dir.name,
"skills",
+ ".seed",
"test_skill_dup",
)
mtime_first = os.path.getmtime(skill_target)
@@ -816,12 +820,12 @@ This skill is added through a tilde path.
await workspace.initialize()
# Verify only one skill was copied
- skills_dir = os.path.join(self.temp_dir.name, "skills")
+ skills_dir = os.path.join(self.temp_dir.name, "skills", ".seed")
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")
+ skills_hash_file = os.path.join(skills_dir, ".index")
self.assertTrue(os.path.exists(skills_hash_file))
async with aiofiles.open(skills_hash_file, "r") as f:
@@ -892,7 +896,7 @@ This skill is added through a tilde path.
await workspace.initialize()
# Verify only the valid skill was copied
- skills_dir = os.path.join(self.temp_dir.name, "skills")
+ skills_dir = os.path.join(self.temp_dir.name, "skills", ".seed")
self.assertTrue(os.path.exists(skills_dir))
# Verify valid skill exists
@@ -1835,3 +1839,161 @@ class TestLocalWorkspaceMCPScoping(IsolatedAsyncioTestCase):
again = await ws.list_mcps(agent_id="agent-A", session_id="s1")
self.assertEqual([m.name for m in again], ["a", "b"])
self.assertEqual(len(connected), 6)
+
+
+class TestLocalWorkspaceSkillPartitions(IsolatedAsyncioTestCase):
+ """Per-agent skill partitions under ``skills/``.
+
+ Covers:
+ - an agent's installs stay out of every other agent's listing
+ - ``skill_paths`` equip each agent with its own copy, once
+ - a caller that names no agent gets the default partition
+ - a pre-partition ``skills/`` becomes the seed template
+ - an agent id that would escape ``skills/`` is refused
+ """
+
+ async def asyncSetUp(self) -> None:
+ """Set up test fixtures."""
+ # pylint: disable=consider-using-with
+ self.temp_dir = tempfile.TemporaryDirectory()
+ self.src_dir = tempfile.TemporaryDirectory()
+ self.skills_dir = os.path.join(self.temp_dir.name, "skills")
+
+ async def asyncTearDown(self) -> None:
+ """Clean up test fixtures."""
+ self.temp_dir.cleanup()
+ self.src_dir.cleanup()
+
+ def _make_skill(self, dir_name: str, skill_name: str) -> str:
+ """Write a minimal skill directory outside the workspace."""
+ path = os.path.join(self.src_dir.name, dir_name)
+ os.makedirs(path, exist_ok=True)
+ with open(
+ os.path.join(path, "SKILL.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(
+ f"---\nname: {skill_name}\ndescription: d\n---\n\nbody\n",
+ )
+ return path
+
+ async def _workspace(self, **kwargs: Any) -> LocalWorkspace:
+ """Build and initialise a workspace over the temp workdir."""
+ ws = LocalWorkspace(workdir=self.temp_dir.name, **kwargs)
+ await ws.initialize()
+ self.addAsyncCleanup(ws.close)
+ return ws
+
+ async def test_agent_installs_are_isolated(self) -> None:
+ """What one agent installs, no other agent can see."""
+ ws = await self._workspace()
+ await ws.add_skill(self._make_skill("only-a", "a-skill"), agent_id="A")
+
+ self.assertEqual(
+ [s.name for s in await ws.list_skills(agent_id="A")],
+ ["a-skill"],
+ )
+ self.assertEqual(await ws.list_skills(agent_id="B"), [])
+ self.assertEqual(await ws.list_skills(), [])
+ self.assertTrue(
+ os.path.isdir(os.path.join(self.skills_dir, "A", "a-skill")),
+ )
+
+ async def test_seeds_equip_each_agent_with_its_own_copy(self) -> None:
+ """``skill_paths`` reach every agent, but as separate copies."""
+ ws = await self._workspace(
+ skill_paths=[self._make_skill("seeded", "seed-skill")],
+ )
+
+ for agent_id in ("A", "B"):
+ self.assertEqual(
+ [s.name for s in await ws.list_skills(agent_id=agent_id)],
+ ["seed-skill"],
+ )
+
+ # A drops its copy: B keeps its own, and A does not get it back.
+ await ws.remove_skill("seed-skill", agent_id="A")
+ self.assertEqual(await ws.list_skills(agent_id="A"), [])
+ self.assertEqual(
+ [s.name for s in await ws.list_skills(agent_id="B")],
+ ["seed-skill"],
+ )
+ self.assertTrue(
+ os.path.isdir(
+ os.path.join(self.skills_dir, ".seed", "seed-skill"),
+ ),
+ )
+
+ async def test_unnamed_caller_gets_the_default_partition(self) -> None:
+ """The SDK path, which never names an agent, is just a partition."""
+ ws = await self._workspace(
+ skill_paths=[self._make_skill("seeded", "seed-skill")],
+ )
+ await ws.add_skill(self._make_skill("plain", "plain-skill"))
+
+ self.assertEqual(
+ sorted(s.name for s in await ws.list_skills()),
+ ["plain-skill", "seed-skill"],
+ )
+ self.assertTrue(
+ os.path.isdir(
+ os.path.join(self.skills_dir, "default", "plain-skill"),
+ ),
+ )
+ # An agent is equipped from the template, not from that partition.
+ self.assertEqual(
+ [s.name for s in await ws.list_skills(agent_id="A")],
+ ["seed-skill"],
+ )
+
+ async def test_pre_partition_layout_becomes_the_template(self) -> None:
+ """Skills sitting directly under ``skills/`` equip every agent."""
+ legacy = os.path.join(self.skills_dir, "legacy")
+ os.makedirs(legacy)
+ with open(
+ os.path.join(legacy, "SKILL.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write("---\nname: old\ndescription: d\n---\n\nbody\n")
+ with open(
+ os.path.join(self.skills_dir, ".skills"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ json.dump(
+ {
+ "skills_dir_mtime": 0.0,
+ "skills": {"legacy": {"hash": "h", "skill_name": "old"}},
+ },
+ f,
+ )
+
+ ws = await self._workspace()
+
+ self.assertEqual(os.listdir(self.skills_dir), [".seed"])
+ self.assertEqual(
+ [s.name for s in await ws.list_skills(agent_id="A")],
+ ["old"],
+ )
+ self.assertTrue(
+ os.path.isfile(os.path.join(self.skills_dir, ".seed", ".index")),
+ )
+
+ async def test_traversing_agent_id_is_refused(self) -> None:
+ """An agent id is a directory name, so it may not escape."""
+ ws = await self._workspace()
+ for agent_id in ("../escape", "..", ".seed"):
+ with self.assertRaises(ValueError):
+ await ws.list_skills(agent_id=agent_id)
+
+ async def test_purge_agent_drops_its_partition(self) -> None:
+ """Deleting an agent takes its skills with it."""
+ ws = await self._workspace()
+ await ws.add_skill(self._make_skill("only-a", "a-skill"), agent_id="A")
+
+ await ws.purge_agent(agent_id="A")
+
+ self.assertFalse(os.path.exists(os.path.join(self.skills_dir, "A")))
+ self.assertEqual(await ws.list_skills(agent_id="A"), [])
diff --git a/tests/workspace_skill_archive_test.py b/tests/workspace_skill_archive_test.py
index ac5dd0419..f13fd160e 100644
--- a/tests/workspace_skill_archive_test.py
+++ b/tests/workspace_skill_archive_test.py
@@ -141,7 +141,7 @@ class AddSkillArchiveSandboxedTest(IsolatedAsyncioTestCase):
self.tmp = self.enterContext(tempfile.TemporaryDirectory())
self.workspace = LocalWorkspace(workdir=self.tmp)
await self.workspace.initialize()
- self.skills_dir = os.path.join(self.tmp, "skills")
+ self.skills_dir = os.path.join(self.tmp, "skills", "default")
async def test_directory_name_is_suffixed_when_taken(self) -> None:
"""A repeated name gets a numeric suffix rather than an error."""