| 1 |
"""Skill download + archive extraction for the agent toolset. |
| 2 |
|
| 3 |
Split out from `agent_toolset` because fetching a session agent's skills and |
| 4 |
safely unpacking a (possibly third-party) archive is a distinct concern from the |
| 5 |
tool implementations themselves. |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import os |
| 11 |
import stat |
| 12 |
import shutil |
| 13 |
import logging |
| 14 |
import tarfile |
| 15 |
import zipfile |
| 16 |
import tempfile |
| 17 |
from typing import TYPE_CHECKING |
| 18 |
from pathlib import Path, PurePosixPath |
| 19 |
from functools import partial |
| 20 |
from collections.abc import Iterable |
| 21 |
|
| 22 |
import anyio |
| 23 |
from anyio.to_thread import run_sync |
| 24 |
|
| 25 |
if TYPE_CHECKING: |
| 26 |
from ..._client import AsyncAnthropic |
| 27 |
from ...types.beta import BetaManagedAgentsSession |
| 28 |
|
| 29 |
__all__ = ["download_session_skills"] |
| 30 |
|
| 31 |
# Skill dirs hold downloaded, possibly third-party content — keep them |
| 32 |
# owner-only rather than inheriting whatever the process umask happens to be. |
| 33 |
_SKILL_DIR_MODE = 0o700 |
| 34 |
|
| 35 |
log = logging.getLogger("anthropic.lib.tools.agent_toolset") |
| 36 |
|
| 37 |
|
| 38 |
def _within(child: Path, root: Path) -> bool: |
| 39 |
"""True if `child` is `root` or a path inside it (both already resolved).""" |
| 40 |
try: |
| 41 |
child.relative_to(root) |
| 42 |
except ValueError: |
| 43 |
return False |
| 44 |
return True |
| 45 |
|
| 46 |
|
| 47 |
def _safe_member_name(name: str) -> str: |
| 48 |
"""Return `name` as a confined relative path, or raise on path-traversal. |
| 49 |
|
| 50 |
Strips `.` components; rejects absolute paths and any `..` component |
| 51 |
outright (those only appear in malicious archives). Returns `""` for |
| 52 |
entries that resolve to nothing (e.g. `"./"`) — the caller should skip |
| 53 |
those. |
| 54 |
""" |
| 55 |
norm = name.replace("\\", "/") |
| 56 |
if norm.startswith("/") or PurePosixPath(norm).is_absolute(): |
| 57 |
raise ValueError(f"refusing archive member with absolute path {name!r}") |
| 58 |
parts = [p for p in PurePosixPath(norm).parts if p != "."] |
| 59 |
if any(p == ".." for p in parts): |
| 60 |
raise ValueError(f"refusing archive member with '..' component: {name!r}") |
| 61 |
return str(PurePosixPath(*parts)) if parts else "" |
| 62 |
|
| 63 |
|
| 64 |
def _archive_top_dir(names: list[str]) -> str: |
| 65 |
"""Return the single top-level directory shared by every archive entry, or |
| 66 |
`""` if the entries don't all live under one common directory. |
| 67 |
|
| 68 |
Skill bundles are packaged wrapped in one directory named after the skill |
| 69 |
(e.g. `pdf/SKILL.md`, `pdf/scripts/...`). The extractor strips that |
| 70 |
wrapper so the contents land directly in the skill's destination directory |
| 71 |
instead of a redundant nested `<skill>/<skill>/` level. |
| 72 |
""" |
| 73 |
tops: set[str] = set() |
| 74 |
has_nested = False |
| 75 |
for n in names: |
| 76 |
parts = PurePosixPath(n).parts |
| 77 |
if not parts: |
| 78 |
continue |
| 79 |
tops.add(parts[0]) |
| 80 |
if len(parts) > 1: |
| 81 |
has_nested = True |
| 82 |
return next(iter(tops)) if len(tops) == 1 and has_nested else "" |
| 83 |
|
| 84 |
|
| 85 |
def _wrapper_dir(all_names: Iterable[str], plain_names: Iterable[str]) -> str: |
| 86 |
"""Screen every member name (raising on path traversal, extracted or not), |
| 87 |
then return the wrapper directory shared by the members that will be |
| 88 |
extracted.""" |
| 89 |
for name in all_names: |
| 90 |
_safe_member_name(name) |
| 91 |
return _archive_top_dir([s for n in plain_names if (s := _safe_member_name(n))]) |
| 92 |
|
| 93 |
|
| 94 |
# Zip creator hosts whose `external_attr` high bits are a Unix `st_mode`. |
| 95 |
_ZIP_UNIX_HOSTS = (3, 19) |
| 96 |
_SPECIAL_FILE_TYPES = (stat.S_IFLNK, stat.S_IFCHR, stat.S_IFBLK, stat.S_IFIFO, stat.S_IFSOCK) |
| 97 |
|
| 98 |
|
| 99 |
def _zip_unix_mode(info: zipfile.ZipInfo) -> int | None: |
| 100 |
return info.external_attr >> 16 if info.create_system in _ZIP_UNIX_HOSTS else None |
| 101 |
|
| 102 |
|
| 103 |
def _zip_info_is_special(info: zipfile.ZipInfo) -> bool: |
| 104 |
"""True for a Unix-host entry recorded as a symlink, device, FIFO or socket. |
| 105 |
Type bits from other hosts are not a mode, so those entries stay plain files.""" |
| 106 |
mode = _zip_unix_mode(info) |
| 107 |
return mode is not None and stat.S_IFMT(mode) in _SPECIAL_FILE_TYPES |
| 108 |
|
| 109 |
|
| 110 |
def _zip_info_is_dir(info: zipfile.ZipInfo) -> bool: |
| 111 |
mode = _zip_unix_mode(info) |
| 112 |
return info.is_dir() or (mode is not None and stat.S_ISDIR(mode)) |
| 113 |
|
| 114 |
|
| 115 |
def _strip_top(safe: str, top: str) -> str: |
| 116 |
"""Drop the leading `top` component from `safe` (an already-confined |
| 117 |
relative path). Returns `""` for the bare top-dir entry itself.""" |
| 118 |
if not top: |
| 119 |
return safe |
| 120 |
parts = PurePosixPath(safe).parts |
| 121 |
if parts and parts[0] == top: |
| 122 |
rest = parts[1:] |
| 123 |
return str(PurePosixPath(*rest)) if rest else "" |
| 124 |
return safe |
| 125 |
|
| 126 |
|
| 127 |
def _archive_file_mode(src_mode: int) -> int: |
| 128 |
"""Reduce an archive entry's Unix mode to `0o755` if it is executable, |
| 129 |
`0o644` otherwise. |
| 130 |
|
| 131 |
Skill bundles can ship executable scripts (e.g. `scripts/foo.sh`), so the |
| 132 |
execute bit recorded in the archive must survive extraction or invoking the |
| 133 |
script directly fails with permission denied. The mode is deliberately |
| 134 |
collapsed to one of two values: this preserves "is it executable" while |
| 135 |
never propagating setuid/setgid/sticky or group/other-write bits from a |
| 136 |
(possibly third-party) archive. |
| 137 |
""" |
| 138 |
return 0o755 if src_mode & 0o111 else 0o644 |
| 139 |
|
| 140 |
|
| 141 |
def _extract_skill_archive(archive_path: Path, dest: Path) -> None: |
| 142 |
"""Extract a skill download (a zip or tar.* archive) from disk into `dest`. |
| 143 |
|
| 144 |
Skill bundles are wrapped in a single directory named after the skill; that |
| 145 |
wrapper is stripped so files land directly under `dest` rather than a |
| 146 |
redundant `dest/<skill>/` level. Skills can be third-party, so this |
| 147 |
refuses any member that would escape `dest` (zip-slip / tar-slip) and |
| 148 |
skips any member that is not a regular file or directory (symlink, |
| 149 |
hardlink, device, FIFO), in zip and tar archives alike. |
| 150 |
""" |
| 151 |
dest.mkdir(parents=True, exist_ok=True, mode=_SKILL_DIR_MODE) |
| 152 |
root = dest.resolve() |
| 153 |
|
| 154 |
if zipfile.is_zipfile(archive_path): |
| 155 |
with zipfile.ZipFile(archive_path) as zf: |
| 156 |
infos = zf.infolist() |
| 157 |
plain = [info for info in infos if not _zip_info_is_special(info)] |
| 158 |
top = _wrapper_dir((info.filename for info in infos), (info.filename for info in plain)) |
| 159 |
for info in plain: |
| 160 |
safe = _strip_top(_safe_member_name(info.filename), top) |
| 161 |
if not safe: |
| 162 |
continue |
| 163 |
target = (root / safe).resolve() |
| 164 |
if not _within(target, root): |
| 165 |
raise ValueError(f"refusing to extract unsafe zip member {info.filename!r}") |
| 166 |
if _zip_info_is_dir(info): |
| 167 |
target.mkdir(parents=True, exist_ok=True) |
| 168 |
continue |
| 169 |
target.parent.mkdir(parents=True, exist_ok=True) |
| 170 |
with zf.open(info) as src, open(target, "wb") as out: |
| 171 |
shutil.copyfileobj(src, out) |
| 172 |
# `external_attr`'s high 16 bits hold the Unix mode; it is 0 |
| 173 |
# for archives created without Unix attrs -> non-executable. |
| 174 |
os.chmod(target, _archive_file_mode(info.external_attr >> 16)) |
| 175 |
return |
| 176 |
|
| 177 |
# tarfile.open with "r:*" transparently handles tar / tar.gz / tar.bz2 / tar.xz. |
| 178 |
with tarfile.open(archive_path, mode="r:*") as tf: |
| 179 |
all_members = tf.getmembers() |
| 180 |
members = [m for m in all_members if m.isreg() or m.isdir()] |
| 181 |
top = _wrapper_dir((m.name for m in all_members), (m.name for m in members)) |
| 182 |
for member in members: |
| 183 |
safe = _strip_top(_safe_member_name(member.name), top) |
| 184 |
if not safe: |
| 185 |
continue |
| 186 |
target = (root / safe).resolve() |
| 187 |
if not _within(target, root): |
| 188 |
raise ValueError(f"refusing to extract unsafe tar member {member.name!r}") |
| 189 |
if member.isdir(): |
| 190 |
target.mkdir(parents=True, exist_ok=True) |
| 191 |
continue |
| 192 |
target.parent.mkdir(parents=True, exist_ok=True) |
| 193 |
extracted = tf.extractfile(member) |
| 194 |
if extracted is None: |
| 195 |
continue |
| 196 |
with extracted as src, open(target, "wb") as out: |
| 197 |
shutil.copyfileobj(src, out) |
| 198 |
os.chmod(target, _archive_file_mode(member.mode)) |
| 199 |
|
| 200 |
|
| 201 |
async def download_session_skills( |
| 202 |
client: AsyncAnthropic, |
| 203 |
*, |
| 204 |
workdir: str | os.PathLike[str], |
| 205 |
session: BetaManagedAgentsSession | None = None, |
| 206 |
session_id: str | None = None, |
| 207 |
) -> list[Path]: |
| 208 |
"""Download the session agent's skills into `{workdir}/skills/<name>/`. |
| 209 |
|
| 210 |
Reads the resolved agent off `session`, and for each skill fetches its |
| 211 |
files via `client.beta.skills.versions.download` and extracts the archive |
| 212 |
under a directory named after the skill. The archive is streamed to a temp |
| 213 |
file rather than buffered whole in memory. A failure on one skill is logged |
| 214 |
and does not block the others. |
| 215 |
|
| 216 |
Pass `session`. A session's resources cannot change while it runs, so the |
| 217 |
caller fetches it once and shares that snapshot with the memory-store |
| 218 |
download — the two can then never disagree about the attached resources. |
| 219 |
|
| 220 |
`session_id` is deprecated: it costs an extra `sessions.retrieve` round |
| 221 |
trip on every call, and a caller that uses it for both this and the |
| 222 |
memory-store download fetches the session twice. It remains supported for |
| 223 |
callers written before `session` existed. |
| 224 |
|
| 225 |
Returns the list of skill directories that were created, so the caller can |
| 226 |
remove them when the workdir is torn down. |
| 227 |
""" |
| 228 |
if session is None: |
| 229 |
if session_id is None: |
| 230 |
raise ValueError("download_session_skills: pass session (preferred) or session_id") |
| 231 |
log.warning( |
| 232 |
"download_session_skills(session_id=...) is deprecated and costs an extra session fetch; " |
| 233 |
"fetch the session once and pass session= instead" |
| 234 |
) |
| 235 |
# The sessions/skills resources inject their anthropic-beta headers |
| 236 |
# (managed-agents / skills) themselves — no need to pass `betas=` here. |
| 237 |
session = await client.beta.sessions.retrieve(session_id) |
| 238 |
skills_root = Path(await (anyio.Path(workdir) / "skills").resolve()) |
| 239 |
# `skills_root` is created lazily by the extraction below — don't create it |
| 240 |
# up front so an agent with no skills leaves no stray directory behind. |
| 241 |
downloaded: list[Path] = [] |
| 242 |
for skill in session.agent.skills: |
| 243 |
try: |
| 244 |
version = await client.beta.skills.versions.retrieve(skill.version, skill_id=skill.skill_id) |
| 245 |
# The directory is the skill's name, but reduce it to a single safe |
| 246 |
# path component so a hostile name can't escape skills_root. |
| 247 |
dirname = os.path.basename(version.name.strip()) or skill.skill_id |
| 248 |
if dirname in ("", ".", ".."): |
| 249 |
dirname = skill.skill_id |
| 250 |
dest = Path(await (anyio.Path(skills_root) / dirname).resolve()) |
| 251 |
if not _within(dest, skills_root): |
| 252 |
log.warning("skill name %r escapes the skills dir; skipping", version.name) |
| 253 |
continue |
| 254 |
adest = anyio.Path(dest) |
| 255 |
if await adest.is_symlink(): |
| 256 |
await adest.unlink() |
| 257 |
# `shutil.rmtree` is blocking; keep it off the event loop. |
| 258 |
await run_sync(partial(shutil.rmtree, dest, ignore_errors=True)) |
| 259 |
# `skill.version` may be the alias `"latest"`, which only the |
| 260 |
# retrieve endpoint resolves; download by the concrete id it returned. |
| 261 |
await _download_and_extract(client, skill.skill_id, version.id, dest) |
| 262 |
downloaded.append(dest) |
| 263 |
log.info("downloaded skill skill_id=%s version=%s -> %s", skill.skill_id, version.id, dest) |
| 264 |
except Exception as e: |
| 265 |
log.warning("failed to download skill skill_id=%s: %s", skill.skill_id, e) |
| 266 |
return downloaded |
| 267 |
|
| 268 |
|
| 269 |
async def _download_and_extract(client: AsyncAnthropic, skill_id: str, version_id: str, dest: Path) -> None: |
| 270 |
"""Stream the skill archive to a temp file, then extract it into `dest`.""" |
| 271 |
await anyio.Path(dest.parent).mkdir(parents=True, exist_ok=True, mode=_SKILL_DIR_MODE) |
| 272 |
fd, tmp_name = await run_sync(partial(tempfile.mkstemp, prefix=".skill-", suffix=".archive", dir=dest.parent)) |
| 273 |
os.close(fd) |
| 274 |
tmp = anyio.Path(tmp_name) |
| 275 |
try: |
| 276 |
async with client.beta.skills.versions.with_streaming_response.download( |
| 277 |
version_id, skill_id=skill_id |
| 278 |
) as archive: |
| 279 |
await archive.stream_to_file(tmp_name) |
| 280 |
# zipfile / tarfile are blocking; keep them off the event loop. |
| 281 |
await run_sync(_extract_skill_archive, Path(tmp_name), dest) |
| 282 |
finally: |
| 283 |
await tmp.unlink(missing_ok=True) |