Files
Atrium/backend/app/services/skill_pack.py
T
tobayahandClaude Opus 5.5 1adb783d4a fix(skills): import przyjmuje naglowki SKILL.md w stylu Claude Code
52 z 57 realnych skilli ma opis z drugim dwukropkiem (description: Use when ... SKIP: x),
ktory scisly YAML odrzuca, a Claude Code czyta jako jeden tekst. Gdy YAML zawodzi,
naglowek z samych linii klucz: tekst (plus wciete kontynuacje) jest czytany jako
teksty; wartosc zaczynajaca sie od znaku YAML ([, ", !, *, ...) jest parsowana osobno
i zepsuta nadal odrzuca calosc. Na skillach autora: 50/57 przechodzi, 6 odpada za
skrypty (zgodnie z decyzja: skill bez kodu), 1 za opis > 1024 znaki (limit standardu).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJbh3fPYdfdLG3MU6f
2026-11-06 14:16:48 +01:00

555 lines
27 KiB
Python

"""A skill pack (ZIP) — pure functions, no database.
`read_pack` is the ONE gate an uploaded archive passes before anything of it is kept. It refuses
the whole pack, never a part of it: a pack that silently loses a file is a pack whose author and
importer disagree about what it says. Every refusal is a `PackRejected` carrying a machine-readable
`code` (and the offending paths), the same shape as `module_admission_refused`, so the console can
word it in the reader's language.
The archive rules are checked on the central directory BEFORE a single byte is decompressed, and
on the raw names (`ZipInfo.orig_filename`): on Windows `zipfile` rewrites `\\` to `/` in
`filename`, which would let a backslash path through on a developer machine and not in CI.
"""
from __future__ import annotations
import hashlib
import io
import json
import re
import stat
import struct
import unicodedata
import zipfile
import zlib
from collections.abc import Sequence
from dataclasses import dataclass
import yaml
from app.errors import ValidationError
MAX_PACK_BYTES = 10 * 1024 * 1024
MAX_FILES = 200
MAX_UNPACKED_BYTES = 50 * 1024 * 1024
MAX_RATIO = 100
#: code -> (PL, EN). The console words a refusal by `code`; keep `frontend/app.js` in step.
MESSAGES = {
"pack_too_large": ("Paczka jest większa niż 10 MB.", "The pack is larger than 10 MB."),
"pack_not_zip": ("Plik nie jest poprawnym archiwum ZIP.", "The file is not a valid ZIP archive."),
"pack_zip64": ("Archiwa ZIP64 nie są przyjmowane.", "ZIP64 archives are not accepted."),
"pack_too_many_files": ("Paczka ma więcej niż 200 plików.", "The pack has more than 200 files."),
"pack_unpacked_too_large": ("Po rozpakowaniu paczka przekracza 50 MB.",
"The pack exceeds 50 MB once unpacked."),
"pack_compression_ratio": ("Plik jest skompresowany ponad 100:1.",
"A file is compressed more than 100:1."),
"pack_bad_path": ("Niedozwolona ścieżka pliku (.., ścieżka absolutna albo \\).",
"Forbidden file path (.., absolute path or \\)."),
"pack_link": ("Paczka zawiera dowiązanie.", "The pack contains a link."),
"pack_duplicate_name": ("Paczka zawiera dwa pliki o tej samej nazwie.",
"The pack contains two files with the same name."),
"pack_case_collision": ("Paczka zawiera nazwy różniące się tylko wielkością liter.",
"The pack contains names that differ only in letter case."),
"pack_file_type": ("Niedozwolony typ pliku (dozwolone: .md .txt .docx .pdf .xlsx .csv .json "
".yaml .yml).",
"Forbidden file type (allowed: .md .txt .docx .pdf .xlsx .csv .json "
".yaml .yml)."),
"pack_signature_mismatch": ("Treść pliku nie zgadza się z jego rozszerzeniem.",
"A file's content does not match its extension."),
"pack_macros": ("Dokument zawiera makra (vbaProject.bin).",
"A document contains macros (vbaProject.bin)."),
"pack_nested_zip": ("Paczka zawiera archiwum ZIP, które nie jest dokumentem Word ani Excel.",
"The pack contains a ZIP archive that is not a Word or Excel document."),
"pack_plugin_code": ("Wtyczka zawiera skrypty, hooki albo serwery MCP.",
"The plugin contains scripts, hooks or MCP servers."),
"pack_manifest_invalid": ("Plik atrium-pack.json jest uszkodzony.",
"The atrium-pack.json file is malformed."),
"pack_manifest_mismatch": ("Pliki paczki nie zgadzają się z sumami w atrium-pack.json.",
"The pack's files do not match the sums in atrium-pack.json."),
"pack_no_skill": ("Paczka nie zawiera pliku SKILL.md.", "The pack contains no SKILL.md."),
"pack_not_agent": ("Paczka nie zawiera pliku agent.md — zaimportuj ją jako skill.",
"The pack contains no agent.md — import it as a skill."),
"pack_agent_kind": ("Ten rodzaj agenta nie jest obsługiwany (tylko assistant).",
"This kind of agent is not supported (assistant only)."),
"pack_is_agent": ("To paczka agenta — zaimportuj ją jako agenta.",
"This is an agent pack — import it as an agent."),
"skill_not_utf8": ("SKILL.md albo agent.md nie jest zapisany w UTF-8.",
"SKILL.md or agent.md is not UTF-8."),
"skill_frontmatter_too_large": ("Nagłówek SKILL.md albo agent.md jest większy niż 8 KB.",
"The SKILL.md or agent.md frontmatter is larger than 8 KB."),
"skill_frontmatter_alias": ("Nagłówek SKILL.md albo agent.md używa aliasów albo kotwic YAML.",
"The SKILL.md or agent.md frontmatter uses YAML aliases or anchors."),
"skill_frontmatter_invalid": ("Nagłówek SKILL.md albo agent.md nie jest poprawnym YAML.",
"The SKILL.md or agent.md frontmatter is not valid YAML."),
"skill_frontmatter_not_mapping": ("Nagłówek SKILL.md albo agent.md nie jest mapą klucz: wartość.",
"The SKILL.md or agent.md frontmatter is not a key: value mapping."),
"skill_missing_field": ("SKILL.md albo agent.md nie ma pola name albo description.",
"SKILL.md or agent.md lacks a name or a description."),
"skill_bad_name": ("Pole name musi być w formacie kebab-case, najwyżej 64 znaki.",
"The name must be kebab-case, at most 64 characters."),
"skill_description_too_long": ("Opis (description) jest dłuższy niż 1024 znaki.",
"The description is longer than 1024 characters."),
"skill_body_too_long": ("Treść SKILL.md jest dłuższa niż 30 000 znaków.",
"The SKILL.md body is longer than 30,000 characters."),
}
TEXT_TYPES = {".md", ".txt", ".csv", ".json", ".yaml", ".yml"}
OFFICE_TYPES = {".docx", ".xlsx"}
ALLOWED_TYPES = TEXT_TYPES | OFFICE_TYPES | {".pdf"}
MAX_MANIFEST_BYTES = 1024 * 1024
#: Content types that make an OOXML document carry code (VBA, macro sheets, ActiveX), lower-cased.
_MACRO_TYPES = ("vbaproject", "macroenabled", "macrosheet", "activex")
_ZIP_MAGIC = (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")
class PackRejected(ValidationError):
"""The whole pack is refused. `code` is a key of `MESSAGES`; `files` names what caused it."""
def __init__(self, code: str, files=()):
self.code = code
self.files = sorted(set(files))
self.message_pl, self.message_en = MESSAGES[code]
# Polish `detail` + English `en`, the shape of dredd-core's refusals: the console's
# `coreRefusal` words it in either language without a second copy of MESSAGES.
super().__init__(self.message_pl, extra={"code": code, "files": self.files,
"en": self.message_en})
MAX_FRONTMATTER_BYTES = 8 * 1024
MAX_NAME = 64
MAX_DESCRIPTION = 1024
MAX_BODY = 30_000 # the chat tool's result limit
_KEBAB = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
#: D3: kept as information, never granted. The platform decides what a skill may do.
INFO_ONLY_KEYS = ("allowed-tools", "model", "hooks", "mcpServers", "permissionMode")
#: Plugin manifest keys that declare code inline (D1).
_PLUGIN_CODE_KEYS = ("hooks", "mcpServers")
_PLUGIN_CODE_DIRS = ("hooks/", "scripts/", "bin/")
@dataclass(frozen=True)
class SkillDoc:
path: str # of its SKILL.md inside the pack
name: str
description: str
body: str
frontmatter: dict # every key, the info-only ones included
info_only: dict # D3: what the file asked for and was not given
@dataclass(frozen=True)
class AgentDoc:
name: str
description: str
body: str # the instructions
frontmatter: dict # `kind`, `tools`, `model` (a hint) — the service decides what to keep
@dataclass(frozen=True)
class Pack:
files: dict[str, bytes] # path -> content, directories and the manifest left out
skills: tuple[SkillDoc, ...] = () # one per SKILL.md, in path order
agent: AgentDoc | None = None # from a root `agent.md`
kind: str | None = None # the manifest's `type`; None for a pack without one
@dataclass(frozen=True)
class SkillContent:
"""One skill as it is hashed and packed: its folder name, frontmatter, body and the files beside
its SKILL.md (paths relative to the folder). The service builds it from a stored version."""
folder: str
frontmatter: dict
body: str
files: dict[str, bytes]
MANIFEST = "atrium-pack.json"
FORMAT_VERSION = 1
AGENT_DOC = "agent.md"
_ZIP64_EXTRA = 0x0001
_LOCAL_HEADER = struct.Struct("<4s2B4HL2L2H") # zipfile's own `structFileHeader`
def _extra_ids(extra: bytes) -> set[int]:
ids, i = set(), 0
while i + 4 <= len(extra):
tag, size = struct.unpack_from("<HH", extra, i)
ids.add(tag)
i += 4 + size
return ids
def _is_zip64(data: bytes, infos: list[zipfile.ZipInfo]) -> bool:
# ponytail: a ZIP64 locator signature anywhere in the tail refuses, a comment quoting it included
# — fail closed. The local headers are read too: `force_zip64` writes the extra only there.
if b"PK\x06\x07" in data[-(65535 + 22 + 20):]:
return True
for info in infos:
if _ZIP64_EXTRA in _extra_ids(info.extra):
return True
head = data[info.header_offset:info.header_offset + _LOCAL_HEADER.size]
if len(head) < _LOCAL_HEADER.size:
continue # a truncated header fails the read below
fields = _LOCAL_HEADER.unpack(head)
start = info.header_offset + _LOCAL_HEADER.size + fields[10]
if _ZIP64_EXTRA in _extra_ids(data[start:start + fields[11]]):
return True
return False
def bad_path(name: str) -> bool:
return (not name or "\\" in name or "\0" in name or name.startswith("/")
or (len(name) > 1 and name[1] == ":")
or any(part == ".." for part in name.split("/")))
def _open_archive(data: bytes) -> tuple[zipfile.ZipFile, list[zipfile.ZipInfo]]:
"""Every archive rule, on the central directory alone — nothing is decompressed here. Shared by
the pack and by each DOCX/XLSX inside it ("the same limits")."""
if len(data) > MAX_PACK_BYTES:
raise PackRejected("pack_too_large")
try:
zf = zipfile.ZipFile(io.BytesIO(data))
except (zipfile.BadZipFile, ValueError, EOFError):
raise PackRejected("pack_not_zip") from None
infos = zf.infolist()
if _is_zip64(data, infos):
raise PackRejected("pack_zip64")
members = [i for i in infos if not i.is_dir()]
if len(members) > MAX_FILES:
raise PackRejected("pack_too_many_files")
names = [i.orig_filename for i in infos]
bad = [n for n in names if bad_path(n)]
if bad:
raise PackRejected("pack_bad_path", bad)
links = [i.orig_filename for i in infos if stat.S_ISLNK(i.external_attr >> 16)]
if links:
raise PackRejected("pack_link", links)
seen, dupes = set(), set()
for n in names:
(dupes if n in seen else seen).add(n)
if dupes:
raise PackRejected("pack_duplicate_name", dupes)
folded: dict[str, str] = {}
clashes = set()
for n in names:
other = folded.setdefault(n.rstrip("/").casefold(), n)
if other != n:
clashes |= {n, other}
if clashes:
raise PackRejected("pack_case_collision", clashes)
if sum(i.file_size for i in members) > MAX_UNPACKED_BYTES:
raise PackRejected("pack_unpacked_too_large")
steep = [i.orig_filename for i in members if i.file_size > MAX_RATIO * max(i.compress_size, 1)]
if steep:
raise PackRejected("pack_compression_ratio", steep)
return zf, members
def _suffix(path: str) -> str:
name = path.rsplit("/", 1)[-1]
return name[name.rfind("."):].lower() if "." in name else ""
def _bounded_read(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> bytes:
"""A member's bytes, never inflating more than its declared size + 1. `zf.read(info)` is NOT
bounded: `ZipExtFile.read()` with no size decompresses the whole stream (up to ~2 GB) and only
then trims to the declared size, so a 300 KB member declaring 5 MB took 600 MB of memory. A
sized read passes the size down to `decompress(max_length=...)`. A stream longer or shorter
than declared is a lie about the size, refused like any other broken archive."""
with zf.open(info) as member:
data = member.read(info.file_size + 1)
if len(data) != info.file_size:
raise PackRejected("pack_not_zip")
return data
def _check_office(path: str, data: bytes) -> None:
# Only `[Content_Types].xml` is ever inflated (capped first); no other part is read. The name
# `vbaProject.bin` is a convention, not a rule — a renamed part still has to declare its content
# type, so the manifest is searched too (as bytes: nothing here parses XML).
# ponytail: an embedded document (word/embeddings/*.docm) is not recursed into; Word itself asks
# before running its macros. Recurse here if that stops being enough.
try:
zf, parts = _open_archive(data)
by_name = {p.orig_filename: p for p in parts}
manifest = by_name.get("[Content_Types].xml")
if manifest is None or manifest.file_size > MAX_MANIFEST_BYTES:
raise PackRejected("pack_signature_mismatch")
types = _bounded_read(zf, manifest)
# Fail closed on anything a substring search could be fooled by: UTF-16/32 (NULs), XML
# character references (`&#x76;baProject`), bytes that are not UTF-8. Office writes none.
if b"\0" in types or b"&#" in types:
raise PackRejected("pack_signature_mismatch")
types = types.decode("utf-8").lower()
except PackRejected as inner:
raise PackRejected(inner.code, [path]) from None
except UnicodeDecodeError:
raise PackRejected("pack_signature_mismatch", [path]) from None
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, EOFError, zlib.error):
raise PackRejected("pack_not_zip", [path]) from None
if (any(n.rsplit("/", 1)[-1].lower() == "vbaproject.bin" for n in by_name)
or any(marker in types for marker in _MACRO_TYPES)):
raise PackRejected("pack_macros", [path])
def _check_files(files: dict[str, bytes]) -> None:
"""The file rules: an allowed extension, and content that is what the extension says. Nothing
here reads text (variant b): a signature is checked, never parsed."""
wrong_type = [p for p in files if _suffix(p) not in ALLOWED_TYPES]
if wrong_type:
raise PackRejected("pack_file_type", wrong_type)
for path, data in files.items():
kind = _suffix(path)
if kind in OFFICE_TYPES:
if not data.startswith(b"PK\x03\x04"):
raise PackRejected("pack_signature_mismatch", [path])
_check_office(path, data)
elif kind == ".pdf":
if not data.startswith(b"%PDF-"):
raise PackRejected("pack_signature_mismatch", [path])
elif data.startswith(_ZIP_MAGIC):
raise PackRejected("pack_nested_zip", [path])
elif b"\0" in data:
# ponytail: "text" = no NUL byte, so any binary (and UTF-16) is refused while a
# Windows-1250 CSV still passes; the encoding itself is SKILL.md's rule, not a resource's.
raise PackRejected("pack_signature_mismatch", [path])
def _check_plugin(files: dict[str, bytes]) -> None:
"""A Claude Code plugin (a `.claude-plugin/` folder) is read for its `skills/*/SKILL.md`; code
in it refuses the whole pack WITH the list of files (D1), never by quietly leaving it out — a
skill may lean on its plugin's hook, and the importer must know it did not come along. Runs
before the extension rule, so a plugin's `.sh` is named as plugin code, not as a wrong type."""
# By path segment, every one of them: a plugin nested in another is judged against both roots.
roots = set()
for path in files:
parts = path.split("/")
roots |= {"/".join(parts[:i]) + "/" if i else "" for i, part in enumerate(parts[:-1])
if part == ".claude-plugin"}
code = []
for path, data in files.items():
for rel in (path[len(r):] for r in roots if path.startswith(r)):
if (_suffix(rel) not in ALLOWED_TYPES or rel.startswith(_PLUGIN_CODE_DIRS)
or rel.rsplit("/", 1)[-1] == ".mcp.json"):
code.append(path)
elif rel.startswith(".claude-plugin/") and rel.endswith(".json"):
try:
manifest = json.loads(data)
except ValueError:
raise PackRejected("pack_signature_mismatch", [path]) from None
if isinstance(manifest, dict) and any(k in manifest for k in _PLUGIN_CODE_KEYS):
code.append(path)
if code:
raise PackRejected("pack_plugin_code", code)
class _JsonLoader(yaml.SafeLoader):
"""SafeLoader that keeps `2025-01-01` a string. Frontmatter lands in a JSONB column, and the
stock resolver turns dates into `datetime.date`, which JSON cannot carry (a 500 on save).
Explicit tags that build non-JSON values (`!!binary`, `!!set`) are caught after loading."""
_JsonLoader.yaml_implicit_resolvers = {
first: [(tag, regexp) for tag, regexp in resolvers if tag != "tag:yaml.org,2002:timestamp"]
for first, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items()
}
def _has_alias(text: str) -> bool:
return any(isinstance(t, yaml.AliasToken | yaml.AnchorToken)
for t in yaml.scan(text, Loader=yaml.SafeLoader))
def _split_frontmatter(text: str) -> tuple[str, str]:
"""`---` line, YAML, `---` line, body. No opening fence = no frontmatter (and so no name)."""
if not text.startswith("---\n"):
return "", text
end = text.find("\n---\n", 3)
if end == -1:
return (text[4:], "") if text.endswith("\n---") else ("", text)
return text[4:end + 1], text[end + 5:]
_FLAT_KEY = re.compile(r"([A-Za-z][\w-]*):(?:[ \t]+(.*))?")
_YAML_INDICATORS = set("[]{}!&*|>'\"%@`#,?-")
def _flat_frontmatter(head: str) -> dict | None:
"""Claude Code reads `description: Use when ... SKIP: x` as one string; strict YAML refuses the
second `: `. Most real SKILL.md files are written that way, so when YAML fails we accept the
shape only if every line is a top-level `key: text` or an indented continuation of one —
every value a plain string. Anything nested still has to be valid YAML."""
meta: dict = {}
last = None
for line in head.split("\n"):
if not line.strip():
continue
m = None if line[0] in " \t" else _FLAT_KEY.fullmatch(line.rstrip())
if m and (m.group(2) or "")[:1] in _YAML_INDICATORS:
# `paths: ["*.gs"]`, `hint: "[review]"`: that one value is YAML, read alone. A broken
# one (`[x`, `!!python/...`, a dangling `*alias`) refuses the whole frontmatter.
try:
meta[m.group(1)] = yaml.load(m.group(2), Loader=_JsonLoader) # noqa: S506 - SafeLoader subclass
except yaml.YAMLError:
return None
last = None # a structured value takes no continuation lines
continue
if m:
last = m.group(1)
meta[last] = (m.group(2) or "").strip()
elif last is not None and line[0] in " \t":
meta[last] = f"{meta[last]} {line.strip()}".strip()
else:
return None
return meta
def _read_doc(path: str, data: bytes) -> tuple[dict, str, str, str]:
"""The frontmatter rules SKILL.md and agent.md share: -> (frontmatter, name, description, body)."""
try:
text = data.decode("utf-8-sig")
except UnicodeDecodeError:
raise PackRejected("skill_not_utf8", [path]) from None
head, body = _split_frontmatter(text.replace("\r\n", "\n").replace("\r", "\n"))
# The size gate comes first: it is what bounds the YAML parser's work.
if len(head.encode("utf-8")) > MAX_FRONTMATTER_BYTES:
raise PackRejected("skill_frontmatter_too_large", [path])
try:
# A billion-laughs bomb fits in 8 KB, and a skill's frontmatter has no use for aliases.
try:
if _has_alias(head):
raise PackRejected("skill_frontmatter_alias", [path])
meta = yaml.load(head, Loader=_JsonLoader) if head.strip() else {} # noqa: S506 - SafeLoader subclass
except yaml.YAMLError:
# Not YAML at all: flat text, never interpreted, so no alias can expand in it.
meta = _flat_frontmatter(head)
if meta is None:
raise
# What reaches JSONB must be JSON: `!!binary`, `!!set`, a timestamp tag, `.nan` (JSONB refuses NaN).
json.dumps(meta, allow_nan=False)
except (yaml.YAMLError, RecursionError, TypeError, ValueError): # 8 KB of `[` nests deeper than the composer recurses
raise PackRejected("skill_frontmatter_invalid", [path]) from None
if not isinstance(meta, dict):
raise PackRejected("skill_frontmatter_not_mapping", [path])
name, description = meta.get("name"), meta.get("description")
if not (isinstance(name, str) and name and isinstance(description, str) and description.strip()):
raise PackRejected("skill_missing_field", [path])
return meta, name, description, body
def _read_skill(path: str, data: bytes) -> SkillDoc:
meta, name, description, body = _read_doc(path, data)
if len(name) > MAX_NAME or not _KEBAB.fullmatch(name):
raise PackRejected("skill_bad_name", [path])
if len(description) > MAX_DESCRIPTION:
raise PackRejected("skill_description_too_long", [path])
if len(body) > MAX_BODY:
raise PackRejected("skill_body_too_long", [path])
return SkillDoc(path=path, name=name, description=description, body=body, frontmatter=meta,
info_only={k: meta[k] for k in INFO_ONLY_KEYS if k in meta})
def read_pack(data: bytes) -> Pack:
"""Check an uploaded archive against every archive rule and every file rule, and return its
files, or raise `PackRejected`. Sizes are trusted from the central directory only because
`_bounded_read` never inflates past a member's declared size + 1 and refuses a member whose
stream disagrees with it, so the declared total bounds what is actually inflated."""
zf, members = _open_archive(data)
try:
files = {i.filename: _bounded_read(zf, i) for i in members}
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, EOFError, zlib.error):
# A CRC mismatch, an encrypted member, an unknown compression method, a truncated stream.
raise PackRejected("pack_not_zip") from None
_check_plugin(files)
_check_files(files)
kind = _check_manifest(files)
# ponytail: a pack with no SKILL.md is not refused here — an agent pack may pin none; whether a
# skill import needs one is the import's rule (services/skills.py).
skills = tuple(_read_skill(p, d) for p, d in sorted(files.items())
if p.rsplit("/", 1)[-1] == "SKILL.md")
agent = None
if AGENT_DOC in files:
meta, name, description, body = _read_doc(AGENT_DOC, files[AGENT_DOC])
agent = AgentDoc(name=name, description=description, body=body, frontmatter=meta)
return Pack(files=files, skills=skills, agent=agent, kind=kind)
def _sha(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _check_manifest(files: dict[str, bytes]) -> str | None:
"""Verify `atrium-pack.json` and take it out of `files`. A pack without one (a skill ZIP from
elsewhere) is accepted: the sums guard a pack against change on the way, they say nothing of
its author, so their absence takes nothing away."""
raw = files.pop(MANIFEST, None)
if raw is None:
return None
try:
manifest = json.loads(raw)
listed = {f["path"]: f["sha256"] for f in manifest["files"]}
kind = manifest["type"]
if manifest["format"] != FORMAT_VERSION or kind not in ("skill", "agent"):
raise ValueError
except (ValueError, KeyError, TypeError):
raise PackRejected("pack_manifest_invalid", [MANIFEST]) from None
# Both directions: a file added on the way is as much a change as one altered.
wrong = {p for p in listed.keys() | files.keys()
if p not in files or listed.get(p) != _sha(files[p])}
if wrong:
raise PackRejected("pack_manifest_mismatch", wrong)
return kind
def skill_content(pack: Pack, skill: SkillDoc) -> SkillContent:
"""The skill as `content_sha256` and `build_pack` see it: everything under its SKILL.md's folder."""
# ponytail: a SKILL.md nested inside another skill's folder is counted in both; packs this module
# builds never nest, and an import keeps one skill per folder.
prefix = skill.path[: -len("SKILL.md")]
files = {p[len(prefix):]: d for p, d in pack.files.items()
if p.startswith(prefix) and p != skill.path and not (prefix == "" and p == AGENT_DOC)}
return SkillContent(folder=prefix.rstrip("/").rsplit("/", 1)[-1] or skill.name,
frontmatter=skill.frontmatter, body=skill.body, files=files)
def _document(frontmatter: dict, body: str) -> str:
"""The canonical text: NFC, LF, the frontmatter re-dumped with its keys in alphabetical order —
so a pack that went out and came back in hashes the same however its YAML was spelt."""
head = yaml.safe_dump(frontmatter, sort_keys=True, allow_unicode=True, default_flow_style=False)
text = f"---\n{head}---\n{body}".replace("\r\n", "\n").replace("\r", "\n")
return unicodedata.normalize("NFC", text)
def content_sha256(skill: SkillContent) -> str:
"""SHA-256 of the canonical SKILL.md and the sorted `path\\0sha256` lines of its files."""
listing = "\n".join(f"{p}\0{_sha(d)}" for p, d in sorted(skill.files.items()))
return _sha(_document(skill.frontmatter, skill.body).encode("utf-8") + b"\0\0"
+ listing.encode("utf-8"))
def build_pack(skills: Sequence[SkillContent], agent: AgentDoc | None = None) -> bytes:
"""A ZIP of one skill (`agent=None`) or of an agent with the skills it pins, each in its own
folder, plus `atrium-pack.json` listing every file's sha256. What it writes, `read_pack` reads."""
folders = [s.folder for s in skills]
if len(set(folders)) != len(folders) or (agent is None and len(skills) != 1):
raise ValueError("a pack holds one skill, or an agent with skills in distinct folders")
files: dict[str, bytes] = {}
for s in skills:
files[f"{s.folder}/SKILL.md"] = _document(s.frontmatter, s.body).encode("utf-8")
files.update({f"{s.folder}/{p}": d for p, d in s.files.items()})
if agent is not None:
files[AGENT_DOC] = _document(agent.frontmatter, agent.body).encode("utf-8")
manifest = {"format": FORMAT_VERSION, "type": "skill" if agent is None else "agent",
"files": [{"path": p, "sha256": _sha(d)} for p, d in sorted(files.items())]}
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
for path, data in sorted(files.items()):
zf.writestr(path, data)
zf.writestr(MANIFEST, json.dumps(manifest, ensure_ascii=False, indent=2))
return buf.getvalue()