AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): upload and download a skill as a zip package (#14555)
Reinier van der Leerbbc7bd6d3715
diff --git a/autogpt_platform/backend/backend/api/features/skill_zip.py b/autogpt_platform/backend/backend/api/features/skill_zip.pynew file mode 100644index 0000000000..d4653c5d78--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/skill_zip.py@@ -0,0 +1,165 @@+"""The ``.zip`` transport for a skill package.++A skill is a directory, so upload and download carry it as an archive. The caps+and the path rules live in :mod:`backend.copilot.tools.skills`; what is here is+only what an archive can carry that a path check cannot see — a symlink, an+encrypted member, a declared size that would unpack to gigabytes.++Both entry points are CPU-bound and synchronous; callers run them off the event+loop.+"""++import io+import zipfile++from backend.copilot.tools.skills import (+ MAX_PACKAGE_BYTES,+ MAX_PACKAGE_FILE_BYTES,+ MAX_PACKAGE_FILES,+ SkillFile,+ SkillPackage,+ SkillPackageError,+ validate_package,+)++ROOT_SKILL_MD = "SKILL.md"+# A compressed archive already past the uncompressed cap cannot hold a package+# that fits, so one number bounds both the request body and the tree.+MAX_ZIP_BYTES = MAX_PACKAGE_BYTES+++def package_from_zip(data: bytes) -> SkillPackage:+ """Unpack an uploaded archive into a validated :class:`SkillPackage`.++ Every refusal is a :class:`SkillPackageError`, ``over_limit`` set where the+ REST edge owes a 413. Sizes are checked from the central directory, so a+ zip bomb is refused without a member being decompressed.+ """+ try:+ archive = zipfile.ZipFile(io.BytesIO(data))+ except (zipfile.BadZipFile, OSError) as exc:+ raise SkillPackageError(f"upload is not a readable zip archive: {exc}")+ with archive:+ members = _unwrapped(_checked_members(archive.infolist()))+ root = members.pop(ROOT_SKILL_MD)+ # A member's CRC is verified as it decompresses, so a corrupt archive+ # opens cleanly and fails here.+ try:+ skill_md = _decoded(archive.read(root))+ files = [+ SkillFile(+ relative_path=path,+ content=archive.read(info),+ is_executable=bool(_mode(info) & 0o111),+ )+ for path, info in members.items()+ ]+ except (zipfile.BadZipFile, OSError) as exc:+ raise SkillPackageError(f"archive member could not be read: {exc}")+ package = SkillPackage(skill_md=skill_md, files=files)+ validate_package(package)+ return package+++def zip_from_package(package: SkillPackage) -> bytes:+ """Write a stored package back out: ``SKILL.md`` at the root, siblings at+ their relative paths, executable bits in the mode field so a script that+ was runnable still is after a round trip."""+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:+ _add(archive, ROOT_SKILL_MD, package.skill_md.encode("utf-8"), False)+ for entry in package.files:+ _add(archive, entry.relative_path, entry.content, entry.is_executable)+ return buffer.getvalue()+++_ENCRYPTED_FLAG = 0x1+_FILE_TYPE_MASK = 0o170000+_SYMLINK_TYPE = 0o120000+++def _checked_members(infos: list[zipfile.ZipInfo]) -> dict[str, zipfile.ZipInfo]:+ """Every regular member by its archive path, refusing what an archive can+ carry that a path check never sees, and the sizes the central directory+ declares — all before the first member is read."""+ members: dict[str, zipfile.ZipInfo] = {}+ total = 0+ for info in infos:+ if info.is_dir():+ continue+ named = f"member '{info.filename[:120]}'"+ if info.flag_bits & _ENCRYPTED_FLAG:+ raise SkillPackageError(f"{named} is encrypted")+ if _mode(info) & _FILE_TYPE_MASK == _SYMLINK_TYPE:+ raise SkillPackageError(f"{named} is a symlink")+ if info.filename in members:+ raise SkillPackageError(f"{named} appears twice in the archive")+ if info.file_size > MAX_PACKAGE_FILE_BYTES:+ raise SkillPackageError(+ f"{named} unpacks to {info.file_size} bytes; the limit is "+ f"{MAX_PACKAGE_FILE_BYTES}",+ over_limit=True,+ )+ total += info.file_size+ if total > MAX_PACKAGE_BYTES:+ raise SkillPackageError(+ f"archive unpacks to more than {MAX_PACKAGE_BYTES} bytes",+ over_limit=True,+ )+ members[info.filename] = info+ # The files cap counts siblings, so the root SKILL.md is the one over it.+ if len(members) > MAX_PACKAGE_FILES + 1:+ raise SkillPackageError(+ f"package has {len(members) - 1} files; the limit is "+ f"{MAX_PACKAGE_FILES}",+ over_limit=True,+ )+ if not members:+ raise SkillPackageError("archive holds no files")+ return members+++def _unwrapped(members: dict[str, zipfile.ZipInfo]) -> dict[str, zipfile.ZipInfo]:+ """Strip the wrapping directory a "download zip" button adds, so+ ``webapp-testing-main/SKILL.md`` is the package root.++ Only when one directory holds every member and the ``SKILL.md`` is the one+ inside it, so a package whose own root is present is never rewritten.+ """+ tops = {name.split("/", 1)[0] for name in members}+ if len(tops) == 1 and (top := tops.pop()) and f"{top}/{ROOT_SKILL_MD}" in members:+ members = {name[len(top) + 1 :]: info for name, info in members.items()}+ if ROOT_SKILL_MD not in members:+ raise SkillPackageError(+ "archive has no SKILL.md at its root — a skill package is a "+ "SKILL.md and the files beside it"+ )+ return members+++def _decoded(raw: bytes) -> str:+ try:+ return raw.decode("utf-8")+ except UnicodeDecodeError:+ raise SkillPackageError("SKILL.md is not UTF-8 text")+++def _mode(info: zipfile.ZipInfo) -> int:+ """The unix mode a member was archived with, or 0 when the archive carries+ none — one written on Windows, or by a library that omits it."""+ return info.external_attr >> 16+++# A live stamp would make two downloads of an unchanged skill differ, and the+# workspace keeps no per-file mtime to use instead.+_ZIP_EPOCH = (1980, 1, 1, 0, 0, 0)+++def _add(+ archive: zipfile.ZipFile, path: str, content: bytes, is_executable: bool+) -> None:+ info = zipfile.ZipInfo(path, date_time=_ZIP_EPOCH)+ info.compress_type = zipfile.ZIP_DEFLATED+ # The workspace has no mode bits — this is where the stored flag becomes one.+ info.external_attr = (0o100755 if is_executable else 0o100644) << 16+ archive.writestr(info, content)diff --git a/autogpt_platform/backend/backend/api/features/skill_zip_test.py b/autogpt_platform/backend/backend/api/features/skill_zip_test.pynew file mode 100644index 0000000000..c6bb6a06c8--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/skill_zip_test.py@@ -0,0 +1,311 @@+"""Tests for the ``.zip`` transport: what an archive may carry into a skill+folder, and what a stored package looks like on the way back out."""++import io+import struct+import zipfile+from unittest.mock import MagicMock++import pytest++from backend.api.features.skill_zip import (+ MAX_ZIP_BYTES,+ package_from_zip,+ zip_from_package,+)+from backend.copilot.tools.skills import (+ MAX_PACKAGE_BYTES,+ MAX_PACKAGE_FILE_BYTES,+ MAX_PACKAGE_FILES,+ SkillFile,+ SkillPackage,+ SkillPackageError,+)++SKILL_MD = "---\nname: demo\ndescription: A demo package.\n---\n\n# Demo\n"+++def _zip(+ members: dict[str, bytes | str],+ *,+ executable: set[str] = set(),+ directories: tuple[str, ...] = (),+) -> bytes:+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:+ for name in directories:+ archive.writestr(zipfile.ZipInfo(name), b"")+ for name, content in members.items():+ info = zipfile.ZipInfo(name)+ info.compress_type = zipfile.ZIP_DEFLATED+ info.external_attr = (0o100755 if name in executable else 0o100644) << 16+ archive.writestr(info, content)+ return buffer.getvalue()+++# ---------------------------------------------------------------------------+# Round trip+# ---------------------------------------------------------------------------+++def test_download_then_upload_is_the_same_tree():+ """A stored package written out and read back is byte-identical, bits+ included — otherwise a download is not a backup."""+ package = SkillPackage(+ skill_md=SKILL_MD,+ files=[+ SkillFile(relative_path="references/API.md", content=b"# API\n"),+ SkillFile(+ relative_path="scripts/run.py",+ content=b"#!/usr/bin/env python3\nprint(1)\n",+ is_executable=True,+ ),+ ],+ )++ restored = package_from_zip(zip_from_package(package))++ assert restored.skill_md == package.skill_md+ assert [(f.relative_path, f.content, f.is_executable) for f in restored.files] == [+ (f.relative_path, f.content, f.is_executable) for f in package.files+ ]+++def test_an_uploaded_scripts_executable_bit_is_read():+ """Real packages ship 100755 scripts; ``./run.py`` stops working without+ the bit, and the workspace has nowhere else to keep it."""+ package = package_from_zip(+ _zip(+ {"SKILL.md": SKILL_MD, "scripts/run.py": b"x"},+ executable={"scripts/run.py"},+ )+ )+ assert [(f.relative_path, f.is_executable) for f in package.files] == [+ ("scripts/run.py", True)+ ]+++def test_an_archive_with_no_unix_modes_is_read_as_non_executable():+ """A zip written on Windows carries no mode field at all."""+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as archive:+ archive.writestr("SKILL.md", SKILL_MD)+ archive.writestr("scripts/run.py", b"x")++ package = package_from_zip(buffer.getvalue())+ assert [f.is_executable for f in package.files] == [False]+++def test_a_download_carries_a_fixed_timestamp():+ """A per-download stamp would make two downloads of an unchanged skill+ differ; the workspace keeps no per-file mtime to use instead."""+ data = zip_from_package(+ SkillPackage(+ skill_md=SKILL_MD,+ files=[SkillFile(relative_path="a.txt", content=b"a")],+ )+ )+ with zipfile.ZipFile(io.BytesIO(data)) as archive:+ assert {i.date_time for i in archive.infolist()} == {(1980, 1, 1, 0, 0, 0)}+++# ---------------------------------------------------------------------------+# What an archive may not carry+# ---------------------------------------------------------------------------+++ "path",+ ["../escape.md", "/etc/passwd", "a\\b.md", "nested/../../escape.md"],+)+def test_a_member_that_escapes_the_skill_folder_is_refused(path: str):+ with pytest.raises(SkillPackageError) as exc:+ package_from_zip(_zip({"SKILL.md": SKILL_MD, path: b"x"}))+ assert not exc.value.over_limit+++def test_a_symlink_member_is_refused():+ """A symlink passes every path check and then points wherever it likes, so+ it is refused on its mode rather than its name."""+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as archive:+ archive.writestr("SKILL.md", SKILL_MD)+ link = zipfile.ZipInfo("scripts/secrets")+ link.external_attr = (0o120777) << 16+ archive.writestr(link, "/etc/passwd")++ with pytest.raises(SkillPackageError, match="symlink"):+ package_from_zip(buffer.getvalue())+++def test_an_encrypted_member_is_refused():+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_STORED) as archive:+ archive.writestr("SKILL.md", SKILL_MD)+ archive.writestr("secret.bin", b"x")++ with pytest.raises(SkillPackageError, match="encrypted"):+ package_from_zip(_with_encryption_flag(buffer.getvalue()))+++def _with_encryption_flag(data: bytes) -> bytes:+ """Set the general-purpose encryption bit in every header. ``writestr``+ rewrites ``flag_bits``, so the standard library cannot build an encrypted+ member any other way."""+ out = bytearray(data)+ for signature, flag_offset in ((b"PK\x03\x04", 6), (b"PK\x01\x02", 8)):+ start = 0+ while (found := out.find(signature, start)) != -1:+ out[found + flag_offset] |= 0x1+ start = found + 4+ return bytes(out)+++def test_a_bomb_is_refused_without_a_member_being_read(monkeypatch):+ """The declared sizes are the whole check: 22 MiB of zeros compresses to a+ few KB, so reading first is how a bomb lands in memory."""+ member = b"\0" * MAX_PACKAGE_FILE_BYTES+ data = _zip({"SKILL.md": SKILL_MD, **{f"f{i}.bin": member for i in range(11)}})+ assert len(data) < MAX_PACKAGE_BYTES++ opened = MagicMock(side_effect=AssertionError("a member was read"))+ monkeypatch.setattr(zipfile.ZipFile, "open", opened)++ with pytest.raises(SkillPackageError) as exc:+ package_from_zip(data)+ assert exc.value.over_limit+ opened.assert_not_called()+++def test_a_file_over_the_per_file_cap_is_refused_unread(monkeypatch):+ """The package validator would also catch the size — but only after the+ member has been decompressed, which is the cost this check avoids."""+ data = _zip({"SKILL.md": SKILL_MD, "big.bin": b"\0" * (MAX_PACKAGE_FILE_BYTES + 1)})+ opened = MagicMock(side_effect=AssertionError("a member was read"))+ monkeypatch.setattr(zipfile.ZipFile, "open", opened)++ with pytest.raises(SkillPackageError) as exc:+ package_from_zip(data)+ assert exc.value.over_limit+ assert str(MAX_PACKAGE_FILE_BYTES) in str(exc.value)+ opened.assert_not_called()+++def test_too_many_files_names_the_field_and_the_limit():+ members = {f"f{i}.txt": b"x" for i in range(MAX_PACKAGE_FILES + 1)}+ with pytest.raises(SkillPackageError) as exc:+ package_from_zip(_zip({"SKILL.md": SKILL_MD, **members}))+ assert exc.value.over_limit+ assert f"{MAX_PACKAGE_FILES + 1} files" in str(exc.value)+ assert str(MAX_PACKAGE_FILES) in str(exc.value)+++def test_a_package_at_the_files_cap_is_accepted():+ """The cap counts siblings, so the root SKILL.md is not one of the 100."""+ members = {f"f{i}.txt": b"x" for i in range(MAX_PACKAGE_FILES)}+ package = package_from_zip(_zip({"SKILL.md": SKILL_MD, **members}))+ assert len(package.files) == MAX_PACKAGE_FILES+++def test_the_body_cap_is_the_compressed_cap_too():+ """One number bounds the request body and the unpacked tree."""+ assert MAX_ZIP_BYTES == MAX_PACKAGE_BYTES+++# ---------------------------------------------------------------------------+# Finding the package root+# ---------------------------------------------------------------------------+++def test_a_wrapping_directory_is_unwrapped():+ """What a "download zip" button produces: one directory holding the+ package."""+ package = package_from_zip(+ _zip(+ {+ "webapp-testing-main/SKILL.md": SKILL_MD,+ "webapp-testing-main/scripts/run.py": b"print(1)",+ },+ directories=("webapp-testing-main/", "webapp-testing-main/scripts/"),+ )+ )+ assert package.skill_md == SKILL_MD+ assert [f.relative_path for f in package.files] == ["scripts/run.py"]+++def test_a_package_with_its_own_root_is_never_unwrapped():+ package = package_from_zip(+ _zip({"SKILL.md": SKILL_MD, "scripts/run.py": b"print(1)"})+ )+ assert [f.relative_path for f in package.files] == ["scripts/run.py"]+++def test_two_packages_in_one_archive_are_refused():+ with pytest.raises(SkillPackageError, match="no SKILL.md"):+ package_from_zip(_zip({"one/SKILL.md": SKILL_MD, "two/SKILL.md": SKILL_MD}))+++def test_two_root_skill_mds_are_refused():+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as archive:+ archive.writestr("SKILL.md", SKILL_MD)+ with pytest.warns(UserWarning, match="Duplicate name"):+ archive.writestr("SKILL.md", SKILL_MD.replace("demo", "other"))++ with pytest.raises(SkillPackageError, match="twice"):+ package_from_zip(buffer.getvalue())+++def test_a_nested_skill_md_is_an_ordinary_file():+ """Packages ship example SKILL.mds; only the root one names the skill."""+ package = package_from_zip(+ _zip({"SKILL.md": SKILL_MD, "references/SKILL.md": b"# example\n"})+ )+ assert [f.relative_path for f in package.files] == ["references/SKILL.md"]+++def test_an_archive_without_a_skill_md_is_refused():+ with pytest.raises(SkillPackageError, match="no SKILL.md"):+ package_from_zip(_zip({"notes.md": b"x"}))+++def test_an_empty_archive_is_refused():+ with pytest.raises(SkillPackageError, match="no files"):+ package_from_zip(_zip({}))+++def test_a_member_with_a_corrupt_crc_is_refused_as_a_bad_upload():+ """A member's CRC is verified only as it decompresses, so a corrupt archive+ survives the open and fails on the read — where it must still read as a bad+ upload rather than an unhandled error the route answers 500 to."""+ with pytest.raises(SkillPackageError, match="could not be read"):+ package_from_zip(+ _with_a_corrupt_member(_zip({"SKILL.md": SKILL_MD, "a.txt": b"x" * 400}))+ )+++def _with_a_corrupt_member(data: bytes) -> bytes:+ """Flip a byte inside the last member's deflate stream, leaving every header+ intact so the central directory still parses."""+ out = bytearray(data)+ header = out.rfind(b"PK\x03\x04")+ name_len, extra_len = struct.unpack_from("<HH", out, header + 26)+ out[header + 30 + name_len + extra_len + 2] ^= 0xFF+ return bytes(out)+++def test_something_that_is_not_a_zip_is_refused():+ with pytest.raises(SkillPackageError, match="not a readable zip"):+ package_from_zip(b"---\nname: demo\n---\n")+++def test_a_skill_md_that_is_not_utf8_is_refused():+ with pytest.raises(SkillPackageError, match="UTF-8"):+ package_from_zip(_zip({"SKILL.md": b"\xff\xfe binary"}))+++def test_directory_entries_are_skipped():+ package = package_from_zip(+ _zip({"SKILL.md": SKILL_MD}, directories=("scripts/", "references/"))+ )+ assert package.files == []diff --git a/autogpt_platform/backend/backend/api/features/store/skill_seed.py b/autogpt_platform/backend/backend/api/features/store/skill_seed.pyindex 11c0c5992e..ad3c96f62f 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_seed.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_seed.py@@ -5,22 +5,30 @@ roster seed. Idempotent: re-running updates the live version in place ratherthan stacking a new one, so the catalogue can be edited by editing themarkdown.-Each listing's content is its ``SKILL.md`` under ``starter_skills/``, parsed-with the same :func:`parse_skill_markdown` the copilot and the upload endpoint-use, so a starter skill cannot drift from the format an installed skill has.-The seed adds only what a listing needs beyond the file: its categories and-the integrations its instructions assume.+Each listing's content is its ``SKILL.md`` under ``starter_skills/`` — either a+flat ``<slug>.md`` or a ``<slug>/`` package directory — parsed with the same+:func:`parse_skill_markdown` the copilot and the upload endpoint use, so a+starter skill cannot drift from the format an installed skill has. The seed+adds only what a listing needs beyond the file: its categories and the+integrations its instructions assume."""import asyncioimport logging+import osfrom pathlib import Pathfrom typing import TypedDictimport prisma.enumsimport prisma.models-from backend.copilot.tools.skills import ParsedSkill, parse_skill_markdown+from backend.copilot.tools.skills import (+ ParsedSkill,+ SkillFile,+ SkillPackage,+ parse_skill_markdown,+ validate_package,+)from backend.data import db as databaselogger = logging.getLogger(__name__)@@ -52,10 +60,15 @@ async def seed_starter_skills() -> list[str]:"""Upsert every starter listing. Returns the listing ids."""listing_ids = []for entry in STARTER_SKILLS:- parsed = _load(entry["slug"])+ # A starter's package files are read and validated here but not stored:+ # a listing version carries only its SKILL.md today.+ parsed, files = _load(entry["slug"])listing = await _upsert_listing(entry, parsed)listing_ids.append(listing.id)- logger.info(f"Seeded starter skill '{entry['slug']}' (#{listing.id})")+ logger.info(+ f"Seeded starter skill '{entry['slug']}' (#{listing.id})"+ + (f" with {len(files)} package files" if files else "")+ )return listing_ids@@ -118,18 +131,41 @@ async def _upsert_version()-def _load(slug: str) -> ParsedSkill:- path = _CONTENT_DIR / f"{slug}.md"- parsed = parse_skill_markdown(path.read_text(encoding="utf-8"))+def _load(slug: str) -> tuple[ParsedSkill, list[SkillFile]]:+ """A starter skill's root and its package files, from either layout: a+ flat ``<slug>.md``, or a ``<slug>/`` directory whose ``SKILL.md`` sits+ beside the resources it references."""+ directory = _CONTENT_DIR / slug+ is_package = directory.is_dir()+ root = directory / "SKILL.md" if is_package else _CONTENT_DIR / f"{slug}.md"+ named = f"starter_skills/{root.relative_to(_CONTENT_DIR)}"+ text = root.read_text(encoding="utf-8")+ parsed = parse_skill_markdown(text)if parsed is None:- raise ValueError(f"starter_skills/{slug}.md is not a valid SKILL.md")+ raise ValueError(f"{named} is not a valid SKILL.md")if parsed.name != slug:raise ValueError(- f"starter_skills/{slug}.md declares name '{parsed.name}'; the "- "frontmatter name is the installed skill's name and must match "- "the listing slug"+ f"{named} declares name '{parsed.name}'; the frontmatter name is "+ "the installed skill's name and must match the listing slug"+ )+ files = _package_files(directory) if is_package else []+ validate_package(SkillPackage(skill_md=text, files=files))+ return parsed, files+++def _package_files(directory: Path) -> list[SkillFile]:+ """Every file beside the directory's ``SKILL.md``, by its relative path.+ The executable bit rides along so a seeded script stays runnable."""+ root = directory / "SKILL.md"+ return [+ SkillFile(+ relative_path=path.relative_to(directory).as_posix(),+ content=path.read_bytes(),+ is_executable=os.access(path, os.X_OK),)- return parsed+ for path in sorted(directory.rglob("*"))+ if path.is_file() and path != root+ ]async def main() -> None:diff --git a/autogpt_platform/backend/backend/api/features/store/skill_seed_test.py b/autogpt_platform/backend/backend/api/features/store/skill_seed_test.pynew file mode 100644index 0000000000..4fc2ac02d9--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/store/skill_seed_test.py@@ -0,0 +1,74 @@+"""Tests for the starter-skill loader: a starter is either a flat SKILL.md or+a package directory, and a broken one fails the seed rather than the install."""++import pathlib++import pytest++from backend.api.features.store.skill_seed import STARTER_SKILLS, _load+from backend.copilot.tools.skills import SkillPackageError++SKILL_MD = "---\nname: demo\ndescription: A demo starter.\n---\n\n# Demo\n"+++def _write(root: pathlib.Path, relative: str, content: str) -> pathlib.Path:+ path = root / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+ return path+++def test_a_flat_starter_loads_with_no_package_files(monkeypatch, tmp_path):+ monkeypatch.setattr("backend.api.features.store.skill_seed._CONTENT_DIR", tmp_path)+ _write(tmp_path, "demo.md", SKILL_MD)++ parsed, files = _load("demo")++ assert (parsed.name, parsed.body.strip()) == ("demo", "# Demo")+ assert files == []+++def test_a_directory_starter_loads_its_siblings(monkeypatch, tmp_path):+ """A package directory's resources travel with it, executable bit and all,+ at the paths its SKILL.md references them by."""+ monkeypatch.setattr("backend.api.features.store.skill_seed._CONTENT_DIR", tmp_path)+ _write(tmp_path, "demo/SKILL.md", SKILL_MD)+ _write(tmp_path, "demo/references/API.md", "# API\n")+ script = _write(tmp_path, "demo/scripts/run.py", "print(1)\n")+ script.chmod(0o755)++ parsed, files = _load("demo")++ assert parsed.name == "demo"+ assert [(f.relative_path, f.content, f.is_executable) for f in files] == [+ ("references/API.md", b"# API\n", False),+ ("scripts/run.py", b"print(1)\n", True),+ ]+++def test_a_directory_starter_breaking_a_package_rule_fails_the_seed(+ monkeypatch, tmp_path+):+ """A hidden file would install into the skill folder unseen, so the seed+ refuses it here rather than at every user's install."""+ monkeypatch.setattr("backend.api.features.store.skill_seed._CONTENT_DIR", tmp_path)+ _write(tmp_path, "demo/SKILL.md", SKILL_MD)+ _write(tmp_path, "demo/.env", "SECRET=1\n")++ with pytest.raises(SkillPackageError):+ _load("demo")+++def test_a_starter_whose_frontmatter_name_differs_is_refused(monkeypatch, tmp_path):+ monkeypatch.setattr("backend.api.features.store.skill_seed._CONTENT_DIR", tmp_path)+ _write(tmp_path, "demo/SKILL.md", SKILL_MD.replace("demo", "something-else"))++ with pytest.raises(ValueError, match="must match the listing slug"):+ _load("demo")++[email protected]("entry", STARTER_SKILLS, ids=lambda e: e["slug"])+def test_every_shipped_starter_still_loads(entry):+ parsed, files = _load(entry["slug"])+ assert parsed.name == entry["slug"]+ assert files == []diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex c87393fdc9..22b82fc5d8 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -44,6 +44,11 @@ from backend.api.features.executions.activity_gate import (hide_activity_summary_if_disabled,)from backend.api.features.experts import experts_db+from backend.api.features.skill_zip import (+ MAX_ZIP_BYTES,+ package_from_zip,+ zip_from_package,+)from backend.api.features.store.exceptions import VirusDetectedError, VirusScanErrorfrom backend.api.features.workspace.routes import create_file_download_responsefrom backend.api.model import (@@ -59,14 +64,19 @@ from backend.blocks import get_block, get_blocksfrom backend.copilot.rate_limit import enforce_payment_paywall, get_tier_multipliersfrom backend.copilot.tools.skills import (BuiltInSkillError,+ ParsedSkill,+ SkillFile,SkillLimitError,SkillNotFoundError,+ SkillPackageError,delete_user_skill,get_default_skill_with_body,- list_user_skill_sibling_paths,+ list_user_skill_files,list_user_skills,parse_skill_markdown,+ read_user_skill_package,read_user_skill_with_body,+ skill_folder,store_user_skill,)from backend.data import execution as execution_db@@ -2749,6 +2759,15 @@ class CopilotSkillInfo(BaseModel):triggers: list[str] = []+class CopilotSkillFile(BaseModel):+ """One file of a skill package, by its path relative to the skill folder+ (``scripts/run.py``) — the path the SKILL.md body references it by."""++ path: str+ size_bytes: int+ is_executable: bool = False++class CopilotSkillDetail(BaseModel):"""Full SKILL.md content surfaced to the library expand-to-view UI."""@@ -2758,11 +2777,9 @@ class CopilotSkillDetail(BaseModel):body: strversion: str | None = Noneis_default: bool = False- # Sibling files in the same skill folder (references/, scripts/,- # assets/, etc.) — the workspace paths the model can reach via- # ``read_workspace_file``. Empty for built-in defaults since they- # ship as on-disk markdown and have no sibling artefacts.- sibling_files: list[str] = []+ # The package's other files (references/, scripts/, assets/). Empty for+ # built-in defaults, which ship as one on-disk markdown file.+ files: list[CopilotSkillFile] = []class UploadCopilotSkillRequest(BaseModel):@@ -2857,8 +2874,78 @@ async def upload_copilot_skill("'name' and 'description' followed by a markdown body."),)+ stored = await _store_uploaded_skill(user_id, parsed, expert_id=expert_id)+ return CopilotSkillInfo(+ name=stored.name,+ description=stored.description,+ triggers=list(stored.triggers),+ )+++@v1_router.post(+ path="/skills/package",+ summary="Upload a copilot skill as a zipped package",+ operation_id="uploadCopilotSkillPackage",+ tags=["skills"],+ status_code=201,+ responses={+ 400: {"description": "Unreadable archive, or a malformed SKILL.md or path"},+ 409: {"description": "Per-user skill limit reached"},+ 413: {"description": "Archive, file or file count over the package limit"},+ },+ dependencies=[Security(requires_user)],+)+async def upload_copilot_skill_package(+ user_id: Annotated[str, Security(get_user_id)],+ file: UploadFile,+ expert_id: str | None = Query(+ default=None, description="Store the skill as this expert's own."+ ),+) -> CopilotSkillInfo:+ """Create a skill from a zipped package — a root ``SKILL.md`` plus the+ files beside it.++ The zip is transport only: it is unpacked here and stored as the skill's+ folder, so the model reaches ``scripts/`` and ``references/`` by path+ exactly as it does for a package copied from another skill.+ """+ await _require_skill_owner(user_id, expert_id)+ data = await _read_upload(file, MAX_ZIP_BYTES)try:- stored = await store_user_skill(+ package = await run_in_threadpool(package_from_zip, data)+ except SkillPackageError as exc:+ raise HTTPException(status_code=413 if exc.over_limit else 400, detail=str(exc))+ parsed = parse_skill_markdown(package.skill_md)+ if parsed is None:+ raise HTTPException(+ status_code=400,+ detail=(+ "The archive's SKILL.md is not valid — expected YAML "+ "frontmatter with 'name' and 'description' followed by a "+ "markdown body."+ ),+ )+ stored = await _store_uploaded_skill(+ user_id, parsed, expert_id=expert_id, files=package.files+ )+ return CopilotSkillInfo(+ name=stored.name,+ description=stored.description,+ triggers=list(stored.triggers),+ )+++async def _store_uploaded_skill(+ user_id: str,+ parsed: ParsedSkill,+ *,+ expert_id: str | None,+ files: list[SkillFile] | None = None,+) -> ParsedSkill:+ """Persist a parsed upload, mapping each refusal to its status: 409 at the+ per-user cap, 413 over a package limit, 400 for anything malformed."""+ try:+ return await store_user_skill(user_id,expert_id=expert_id,name=parsed.name,@@ -2867,21 +2954,35 @@ async def upload_copilot_skill(triggers=list(parsed.triggers),version=parsed.version,extra=parsed.extra,+ files=files,)except SkillLimitError as exc:raise HTTPException(status_code=409, detail=str(exc))except (VirusDetectedError, VirusScanError) as exc:- logger.warning("[skills] virus scan rejected uploaded skill: %s", exc)+ logger.warning(f"[skills] virus scan rejected an uploaded skill: {exc}")raise HTTPException(status_code=400, detail="Skill content rejected by virus scan")+ except SkillPackageError as exc:+ raise HTTPException(status_code=413 if exc.over_limit else 400, detail=str(exc))except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc))- return CopilotSkillInfo(- name=stored.name,- description=stored.description,- triggers=list(stored.triggers),- )+++async def _read_upload(file: UploadFile, max_bytes: int) -> bytes:+ """Read an upload with an early abort, so a body over the cap is refused+ without ever being held whole."""+ chunks: list[bytes] = []+ total = 0+ while chunk := await file.read(64 * 1024):+ total += len(chunk)+ if total > max_bytes:+ raise HTTPException(+ status_code=413,+ detail=f"Archive is larger than the {max_bytes}-byte limit",+ )+ chunks.append(chunk)+ return b"".join(chunks)@v1_router.get(@@ -2930,9 +3031,7 @@ async def read_copilot_skill(raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Skill '{slug}' not found")- sibling_files = await list_user_skill_sibling_paths(- user_id, slug, expert_id=expert_id- )+ prefix = f"{skill_folder(expert_id)}/{slug}/"return CopilotSkillDetail(name=parsed.name,description=parsed.description,@@ -2940,7 +3039,62 @@ async def read_copilot_skill(body=parsed.body,version=parsed.version,is_default=False,- sibling_files=sibling_files,+ files=[+ CopilotSkillFile(+ path=f.path.removeprefix(prefix),+ size_bytes=f.size_bytes,+ is_executable=f.is_executable,+ )+ for f in await list_user_skill_files(user_id, slug, expert_id=expert_id)+ ],+ )+++@v1_router.get(+ path="/skills/{name}/package",+ summary="Download a copilot skill as a zipped package",+ operation_id="downloadCopilotSkillPackage",+ tags=["skills"],+ response_class=Response,+ responses={+ 200: {+ "content": {+ "application/zip": {"schema": {"type": "string", "format": "binary"}}+ },+ "description": "The skill folder as a zip archive",+ },+ 404: {"description": "Skill not found"},+ },+ dependencies=[Security(requires_user)],+)+async def download_copilot_skill_package(+ user_id: Annotated[str, Security(get_user_id)],+ name: str = Path(..., description="Slug of the skill to download"),+ expert_id: str | None = Query(+ default=None, description="Download this expert's own copy of the skill."+ ),+) -> Response:+ """Return the skill's whole folder as a zip — ``SKILL.md`` at the root,+ siblings at their relative paths, executable bits preserved — so a+ download re-uploads to the same tree.++ Built-in defaults are single on-disk files and are not downloadable here;+ GET ``/skills/{name}`` serves their body.+ """+ await _require_skill_owner(user_id, expert_id)+ slug = name.strip().lower()+ try:+ package = await read_user_skill_package(user_id, slug, expert_id=expert_id)+ except SkillPackageError as exc:+ raise HTTPException(status_code=413 if exc.over_limit else 400, detail=str(exc))+ if package is None:+ raise HTTPException(+ status_code=HTTP_404_NOT_FOUND, detail=f"Skill '{slug}' not found"+ )+ return Response(+ content=await run_in_threadpool(zip_from_package, package),+ media_type="application/zip",+ headers={"Content-Disposition": f'attachment; filename="{slug}.zip"'},)diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex 49260b2e1e..a66cb2e065 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -12,13 +12,26 @@ from autogpt_libs.auth.models import RequestContextfrom fastapi import HTTPException, UploadFilefrom pytest_snapshot.plugin import Snapshot+from backend.api.features.skill_zip import package_from_zip, zip_from_packagefrom backend.api.features.store.exceptions import VirusDetectedErrorfrom backend.api.rest_api import handle_internal_http_errorfrom backend.copilot.tools.skills import (+ MAX_PACKAGE_FILES,BuiltInSkillError,ParsedSkill,+ SkillFile,SkillLimitError,SkillNotFoundError,+ SkillPackage,+ parse_skill_markdown,+ render_skill_markdown,+)++# The skills layer's own test owns the in-memory workspace these round-trip+# tests need; a second copy here would drift from the real manager's surface.+from backend.copilot.tools.skills_test import ( # noqa: E402+ _FakeWorkspaceManager,+ _patch_skills_path,)from backend.data.credit import AutoTopUpConfigfrom backend.data.graph import GraphModel@@ -1641,6 +1654,216 @@ def test_upload_copilot_skill_returns_400_on_virus_detection(assert "virus scan" in response.json()["detail"]+# Storing a skill re-renders its frontmatter, so the canonical form is what a+# download hands back and what an upload→download round trip can compare.+_PARSED_VALID_SKILL = parse_skill_markdown(_VALID_SKILL_MD)+assert _PARSED_VALID_SKILL is not None+_CANONICAL_SKILL_MD = render_skill_markdown(_PARSED_VALID_SKILL)+++def _package_zip(files: list[SkillFile] | None = None) -> bytes:+ """A valid package archive: the canonical SKILL.md plus *files*."""+ return zip_from_package(+ SkillPackage(skill_md=_CANONICAL_SKILL_MD, files=files or [])+ )+++_PACKAGE_FILES = [+ SkillFile(relative_path="references/providers.md", content=b"# Providers\n"),+ SkillFile(relative_path="references/errors.md", content=b"# Errors\n"),+ SkillFile(relative_path="assets/logo.svg", content=b"<svg/>"),+ SkillFile(relative_path="assets/nested/icon.svg", content=b"<svg id=1/>"),+ SkillFile(+ relative_path="scripts/exchange_code.py",+ content=b"#!/usr/bin/env python3\nprint(1)\n",+ is_executable=True,+ ),+ SkillFile(relative_path="scripts/helpers.py", content=b"X = 1\n"),+]+++def test_skill_package_round_trips_through_upload_and_download() -> None:+ """The tree a user uploads is the tree they get back — same paths, same+ bytes, and a script that arrived executable is still executable."""+ with _patch_skills_path(_FakeWorkspaceManager()):+ created = client.post(+ "/skills/package",+ files={+ "file": ("pkg.zip", _package_zip(_PACKAGE_FILES), "application/zip")+ },+ )+ assert created.status_code == 201, created.text+ assert created.json()["name"] == "oauth_flow"++ assert [s["name"] for s in client.get("/skills").json()] == ["oauth_flow"]++ detail = client.get("/skills/oauth_flow")+ assert detail.status_code == 200+ assert {f["path"]: f["is_executable"] for f in detail.json()["files"]} == {+ f.relative_path: f.is_executable for f in _PACKAGE_FILES+ }++ downloaded = client.get("/skills/oauth_flow/package")++ assert downloaded.status_code == 200+ assert downloaded.headers["content-type"] == "application/zip"+ assert "oauth_flow.zip" in downloaded.headers["content-disposition"]+ restored = package_from_zip(downloaded.content)+ assert restored.skill_md == _CANONICAL_SKILL_MD+ assert sorted(+ (f.relative_path, f.content, f.is_executable) for f in restored.files+ ) == sorted((f.relative_path, f.content, f.is_executable) for f in _PACKAGE_FILES)+++def test_upload_package_over_the_files_cap_is_413_and_writes_nothing() -> None:+ manager = _FakeWorkspaceManager()+ oversized = [+ SkillFile(relative_path=f"f{i}.txt", content=b"x")+ for i in range(MAX_PACKAGE_FILES + 1)+ ]++ with _patch_skills_path(manager):+ response = client.post(+ "/skills/package",+ files={"file": ("pkg.zip", _package_zip(oversized), "application/zip")},+ )++ assert response.status_code == 413+ detail = response.json()["detail"]+ assert "files" in detail and str(MAX_PACKAGE_FILES) in detail+ assert manager.files == {}+++def test_upload_package_with_an_escaping_member_is_400_and_writes_nothing() -> None:+ """Zip slip is refused before the first write, so a rejected archive+ leaves the workspace exactly as it was."""+ manager = _FakeWorkspaceManager()+ escaping = [SkillFile(relative_path="../../etc/passwd", content=b"x")]++ with _patch_skills_path(manager):+ response = client.post(+ "/skills/package",+ files={"file": ("pkg.zip", _package_zip(escaping), "application/zip")},+ )++ assert response.status_code == 400+ assert manager.files == {}+++def test_upload_package_refuses_an_oversized_body_before_parsing(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The body cap aborts mid-read, so a 20 MiB archive never lands in+ memory whole."""+ mocker.patch("backend.api.features.v1.MAX_ZIP_BYTES", 64)+ parse = mocker.patch("backend.api.features.v1.package_from_zip")++ response = client.post(+ "/skills/package",+ files={"file": ("pkg.zip", b"x" * 4096, "application/zip")},+ )++ assert response.status_code == 413+ parse.assert_not_called()+++def test_upload_package_rejects_an_archive_whose_skill_md_is_malformed() -> None:+ response = client.post(+ "/skills/package",+ files={+ "file": (+ "pkg.zip",+ zip_from_package(SkillPackage(skill_md="no frontmatter here")),+ "application/zip",+ )+ },+ )+ assert response.status_code == 400+++def test_upload_package_rejects_something_that_is_not_a_zip() -> None:+ response = client.post(+ "/skills/package",+ files={"file": ("pkg.zip", _VALID_SKILL_MD.encode(), "application/zip")},+ )+ assert response.status_code == 400+++def test_download_refuses_rather_than_serving_a_package_it_cannot_read_whole() -> None:+ """A download is a backup: a sibling that will not read must fail the+ request, not quietly produce an archive with the file missing."""++ class _OneUnreadableSibling(_FakeWorkspaceManager):+ async def read_file(self, path: str) -> bytes:+ if path.endswith("references/providers.md"):+ raise RuntimeError("storage unavailable")+ return await super().read_file(path)++ with _patch_skills_path(_OneUnreadableSibling()):+ created = client.post(+ "/skills/package",+ files={+ "file": ("pkg.zip", _package_zip(_PACKAGE_FILES), "application/zip")+ },+ )+ assert created.status_code == 201, created.text++ with pytest.raises(RuntimeError, match="storage unavailable"):+ client.get("/skills/oauth_flow/package")+++def test_download_does_not_report_a_storage_failure_as_a_missing_skill() -> None:+ """404 means the user has no such skill. A storage failure reading the+ SKILL.md is ours, and saying "not found" would send them looking for a+ skill they still have."""++ class _UnreadableRoot(_FakeWorkspaceManager):+ async def read_file(self, path: str) -> bytes:+ if path.endswith("/SKILL.md"):+ raise RuntimeError("storage unavailable")+ return await super().read_file(path)++ with _patch_skills_path(_UnreadableRoot()):+ created = client.post(+ "/skills/package",+ files={"file": ("pkg.zip", _package_zip(), "application/zip")},+ )+ assert created.status_code == 201, created.text++ with pytest.raises(RuntimeError, match="storage unavailable"):+ client.get("/skills/oauth_flow/package")+++def test_download_refuses_a_stored_package_over_the_files_cap() -> None:+ """Only a legacy or hand-made folder can be over the cap, and truncating it+ to the cap would hand back an archive that silently is not the skill."""+ manager = _FakeWorkspaceManager()+ with _patch_skills_path(manager):+ created = client.post(+ "/skills/package",+ files={"file": ("pkg.zip", _package_zip(), "application/zip")},+ )+ assert created.status_code == 201, created.text+ # Seed the folder past the cap the way only a pre-cap write could have.+ for i in range(MAX_PACKAGE_FILES + 1):+ manager.files[f"/skills/oauth_flow/f{i}.txt"] = b"x"++ response = client.get("/skills/oauth_flow/package")++ assert response.status_code == 413+ assert str(MAX_PACKAGE_FILES) in response.json()["detail"]+++def test_download_package_returns_404_for_a_missing_skill(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.v1.read_user_skill_package",+ AsyncMock(return_value=None),+ )+ assert client.get("/skills/missing/package").status_code == 404++_EXPERT_SKILL_ROUTES = {"list": lambda expert_id: client.get("/skills", params=_owner(expert_id)),"upload": lambda expert_id: client.post(@@ -1649,6 +1872,14 @@ _EXPERT_SKILL_ROUTES = {"read": lambda expert_id: client.get("/skills/oauth_flow", params=_owner(expert_id)),+ "upload_package": lambda expert_id: client.post(+ "/skills/package",+ params=_owner(expert_id),+ files={"file": ("pkg.zip", _package_zip(), "application/zip")},+ ),+ "download_package": lambda expert_id: client.get(+ "/skills/oauth_flow/package", params=_owner(expert_id)+ ),"delete": lambda expert_id: client.delete("/skills/oauth_flow", params=_owner(expert_id)),@@ -1661,6 +1892,7 @@ _SKILL_LAYER = {name="oauth_flow", description="d", body="b"),"delete_user_skill": "oauth_flow",+ "read_user_skill_package": SkillPackage(skill_md=_CANONICAL_SKILL_MD),}@@ -1697,6 +1929,8 @@ def test_expert_skill_routes_refuse_an_expert_the_caller_does_not_own(("upload", "store_user_skill"),("read", "read_user_skill_with_body"),("delete", "delete_user_skill"),+ ("upload_package", "store_user_skill"),+ ("download_package", "read_user_skill_package"),],)def test_expert_skill_routes_forward_an_owned_expert(@@ -1711,7 +1945,7 @@ def test_expert_skill_routes_forward_an_owned_expert(AsyncMock(return_value=True),)mocker.patch(- "backend.api.features.v1.list_user_skill_sibling_paths",+ "backend.api.features.v1.list_user_skill_files",AsyncMock(return_value=[]),)target = mocker.patch(@@ -1737,7 +1971,7 @@ def test_personal_autopilot_skill_routes_skip_the_expert_gate(AsyncMock(return_value=False),)mocker.patch(- "backend.api.features.v1.list_user_skill_sibling_paths",+ "backend.api.features.v1.list_user_skill_files",AsyncMock(return_value=[]),)for name, value in _SKILL_LAYER.items():diff --git a/autogpt_platform/backend/backend/copilot/tools/skills.py b/autogpt_platform/backend/backend/copilot/tools/skills.pyindex e047913e67..c0bee7a56b 100644--- a/autogpt_platform/backend/backend/copilot/tools/skills.py+++ b/autogpt_platform/backend/backend/copilot/tools/skills.py@@ -796,9 +796,9 @@ async def store_user_skill(),)except Exception:- # Undo only what this call created: a file that was already- # there has lost its old bytes either way, and deleting it would- # turn a failed write into a lost file.+ # Not a rollback: a file already here keeps the new bytes, so an+ # upsert can fail mixed. Undo only what this call created — deleting+ # the rest would turn a failed write into a lost file.await _delete_paths(manager, written - existing_paths)raiseawait manager.write_file(@@ -1178,32 +1178,62 @@ async def read_user_skill_with_body(return await _parse_skill_from_workspace(manager, _skill_md_path(slug, expert_id))-async def list_user_skill_sibling_paths(+async def read_user_skill_package(user_id: str,name: str,*,expert_id: str | None = None,scope: WorkspaceScope | None = None,-) -> list[str]:- """Return the workspace paths of files siblings to ``SKILL.md`` in a- user-stored skill's folder (``references/``, ``scripts/``, ``assets/``,- or anything the model stashed there at distillation time).-- Used by the REST GET ``/skills/{name}`` endpoint so the library UI's- expand-to-view dialog can show the model what extra artefacts the- skill bundle carries. Returns ``[]`` on any error — sibling listing- is best-effort and must not fail the parent request.+) -> SkillPackage | None:+ """The whole stored skill — the ``SKILL.md`` exactly as stored plus every+ sibling — or ``None`` when the slug has no ``SKILL.md``.++ What the zip download hands out, so a downloaded package re-uploads to a+ byte-identical tree. :func:`read_user_skill_with_body` is the root alone.++ Only a missing skill answers ``None``: a storage failure or an undecodable+ file raises, because a download that quietly omits part of the tree is worse+ than one that fails.+ """+ slug = name.strip().lower()+ if not slug:+ return None+ manager = await _get_user_skill_manager(user_id, scope)+ try:+ raw = await manager.read_file(_skill_md_path(slug, expert_id))+ except FileNotFoundError:+ return None+ return SkillPackage(+ skill_md=raw.decode("utf-8"),+ files=await _read_package_files(+ manager, skill_folder(expert_id), slug, complete=True+ ),+ )+++async def list_user_skill_files(+ user_id: str,+ name: str,+ *,+ expert_id: str | None = None,+ scope: WorkspaceScope | None = None,+) -> list[SkillFileInfo]:+ """Every file beside a stored skill's ``SKILL.md`` — ``references/``,+ ``scripts/``, ``assets/``, or anything the model stashed there — with the+ size and executable bit the library UI's file tree shows.++ Returns ``[]`` on any error: listing decorates the read it accompanies and+ must not fail it."""slug = name.strip().lower()if not slug:return []try:manager = await _get_user_skill_manager(user_id, scope)- files = await _list_package_files(manager, skill_folder(expert_id), slug)- return [f.path for f in files]+ return await _list_package_files(manager, skill_folder(expert_id), slug)except Exception:logger.warning(- "[skills] failed to list sibling files for %s", slug, exc_info=True+ "[skills] failed to list package files for %s", slug, exc_info=True)return []@@ -1285,7 +1315,7 @@ async def copy_skill_to_expert(user_id: str, expert_id: str, name: str) -> str |async def _read_package_files(- manager: WorkspaceManager, folder: str, slug: str+ manager: WorkspaceManager, folder: str, slug: str, *, complete: bool = False) -> list[SkillFile]:"""Load a stored package's siblings into memory, ready to be writtensomewhere else. Reads run concurrently — each is a blob fetch, and a@@ -1293,12 +1323,24 @@ async def _read_package_files(A file that cannot be read raises, because the caller's copy is idempotenton the root alone: a package written without it would never be repaired.+ ``complete`` additionally refuses a tree that is over the files cap, which+ a download owes its caller; the copy path truncates instead, so a legacy+ oversized folder can still be hired rather than blocking the hire outright."""prefix = f"{folder}/{slug}/"infos = await _list_package_files(manager, folder, slug)if len(infos) > MAX_PACKAGE_FILES:- # Written before the cap existed, or by hand. Validating it whole- # would fail and take the hire down, so truncate as read_skill does.+ # Written before the cap existed, or by hand.+ # Keep both branches: raising repairs a failed read, but not a documented+ # cap — so the download refuses and the copy truncates.+ if complete:+ raise SkillPackageError(+ f"stored package has more than {MAX_PACKAGE_FILES} files and "+ "cannot be served whole",+ over_limit=True,+ )+ # Validating it whole would fail and take the hire down, so truncate+ # as read_skill does.logger.warning("[skills] package %s has more than %s files; copying the first %s",slug,@@ -2192,10 +2234,8 @@ async def _sync_skill_package(for c in copied}- # The manifest is what a later activation trusts instead of re-doing work,- # so it records only what actually happened. A mode that would not apply or- # a file that would not go is left out of it, and the next activation tries- # again; committing them would make a transient failure permanent.+ # A later activation trusts this instead of re-doing the work, so it records+ # only what happened — committing a failure would make it permanent.settled = dict(written)# Only files this pass wrote carry a ``target``; a manifest hit needs nodiff --git a/autogpt_platform/backend/backend/copilot/tools/skills_test.py b/autogpt_platform/backend/backend/copilot/tools/skills_test.pyindex f5d1619df2..afb46a2609 100644--- a/autogpt_platform/backend/backend/copilot/tools/skills_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/skills_test.py@@ -47,7 +47,7 @@ from backend.copilot.tools.skills import (find_user_skill_slugs,get_default_skills,list_all_skills,- list_user_skill_sibling_paths,+ list_user_skill_files,parse_skill_markdown,render_skill_markdown,render_skills_index,@@ -1379,7 +1379,7 @@ async def test_a_nested_skill_md_is_neither_indexed_nor_a_second_skill():with _patch_skills_path(fake):skills = await _list_user_skills_from_workspace("user-1")slugs = await find_user_skill_slugs("user-1", ["big", "examples"])- siblings = await list_user_skill_sibling_paths("user-1", "big")+ siblings = [f.path for f in await list_user_skill_files("user-1", "big")]assert [s.name for s in skills] == ["big"]assert slugs == {"big": "big"}assert siblings == ["/skills/big/references/examples/SKILL.md"]@@ -1389,7 +1389,7 @@ async def test_a_nested_skill_md_is_neither_indexed_nor_a_second_skill():async def test_package_enumeration_pages_past_the_old_fifty_row_limit():fake = _package_manager(siblings=80)with _patch_skills_path(fake):- siblings = await list_user_skill_sibling_paths("user-1", "big")+ siblings = [f.path for f in await list_user_skill_files("user-1", "big")]assert len(siblings) == 80@@ -1399,7 +1399,7 @@ async def test_package_enumeration_stops_one_past_the_cap():instead of quietly presenting a truncated package as whole."""fake = _package_manager(siblings=MAX_PACKAGE_FILES + 50)with _patch_skills_path(fake):- siblings = await list_user_skill_sibling_paths("user-1", "big")+ siblings = [f.path for f in await list_user_skill_files("user-1", "big")]assert len(siblings) == MAX_PACKAGE_FILES + 1@@ -1760,6 +1760,48 @@ async def test_a_failed_file_write_leaves_no_skill_and_no_tree():assert fake.files == {}+async def test_a_failed_re_store_undoes_only_what_it_wrote():+ """The rollback deletes what this call created, never what was already+ there: a file that existed has lost its old bytes to the overwrite either+ way, so deleting it would turn a failed write into a lost file."""+ fake = _FailingWorkspaceManager(fail_on=6)+ with _patch_skills_path(fake):+ # Writes 1-2 the siblings, 3 the SKILL.md.+ fake.fail_on = 0+ await store_user_skill(+ "user-1",+ name="pkg",+ description="d",+ body="b",+ files=[+ SkillFile(relative_path="kept.md", content=b"old"),+ SkillFile(relative_path="untouched.md", content=b"old too"),+ ],+ )+ # Writes 4 kept.md (already there), 5 added.md (new), 6 fails.+ fake.fail_on = 6+ with pytest.raises(RuntimeError, match="storage unavailable"):+ await store_user_skill(+ "user-1",+ name="pkg",+ description="d",+ body="b",+ files=[+ SkillFile(relative_path="kept.md", content=b"new"),+ SkillFile(relative_path="added.md", content=b"new"),+ SkillFile(relative_path="doomed.md", content=b"never"),+ ],+ )++ assert "/skills/pkg/kept.md" in fake.files, "an existing file was deleted"+ assert "/skills/pkg/untouched.md" in fake.files+ assert "/skills/pkg/added.md" not in fake.files+ assert "/skills/pkg/doomed.md" not in fake.files+ # The skill itself survives: the root was never rewritten.+ assert "/skills/pkg/SKILL.md" in fake.files++@pytest.mark.asyncioasync def test_re_storing_with_fewer_files_removes_the_orphans():fake = _FakeWorkspaceManager()diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsxindex c578beb278..436b137546 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsx@@ -6,7 +6,9 @@ import {getReadCopilotSkillMockHandler404,getUploadCopilotSkillMockHandler201,getUploadCopilotSkillMockHandler409,+ getUploadCopilotSkillPackageMockHandler201,} from "@/app/api/__generated__/endpoints/skills/skills.msw";+import { http, HttpResponse } from "msw";import type { CopilotSkillInfo } from "@/app/api/__generated__/models/copilotSkillInfo";import type { CopilotSkillDetail } from "@/app/api/__generated__/models/copilotSkillDetail";import { server } from "@/mocks/mock-server";@@ -55,6 +57,30 @@ function makeSkill(overrides: Partial<CopilotSkillInfo>): CopilotSkillInfo {};}+function makePackageDetail(): CopilotSkillDetail {+ return {+ name: "oauth_flow",+ description: "OAuth handshake recipe.",+ triggers: [],+ body: "# Body",+ version: null,+ is_default: false,+ files: [+ {+ path: "references/providers.md",+ size_bytes: 2048,+ is_executable: false,+ },+ { path: "references/errors.md", size_bytes: 300, is_executable: false },+ {+ path: "scripts/exchange_code.py",+ size_bytes: 512,+ is_executable: true,+ },+ ],+ };+}+describe("SkillsPage", () => {beforeEach(() => {toastMock.mockClear();@@ -143,7 +169,7 @@ describe("SkillsPage", () => {body: "## Why\n\nProviders share an OAuth dance.\n\n## Steps\n1. Hit /authorize\n2. Trade code for token",version: null,is_default: false,- sibling_files: [],+ files: [],};server.use(getListCopilotSkillsMockHandler([makeSkill({ name: "oauth_flow" })]),@@ -158,42 +184,34 @@ describe("SkillsPage", () => {// Body is rendered (not the loading spinner / error card).const body = await screen.findByTestId("skill-view-body");expect(body.textContent).toContain("Hit /authorize");- // No sibling-files section when sibling_files is empty.- expect(screen.queryByTestId("skill-view-sibling-files")).toBeNull();+ // No file tree when the skill is a lone SKILL.md.+ expect(screen.queryByTestId("skill-view-files")).toBeNull();// No error state when fetch succeeds.expect(screen.queryByTestId("skill-view-error")).toBeNull();});- test("View dialog lists sibling files when the skill bundle has them", async () => {- const detail: CopilotSkillDetail = {- name: "oauth_flow",- description: "OAuth handshake recipe.",- triggers: [],- body: "# Body",- version: null,- is_default: false,- sibling_files: [- "/skills/oauth_flow/references/providers.md",- "/skills/oauth_flow/scripts/exchange_code.py",- ],- };+ test("View dialog renders the package as a tree of directories and sized files", async () => {server.use(getListCopilotSkillsMockHandler([makeSkill({ name: "oauth_flow" })]),- getReadCopilotSkillMockHandler(detail),+ getReadCopilotSkillMockHandler(makePackageDetail()),);render(<SkillsPage />);- const viewButton = await screen.findByTestId("skill-view-button");- fireEvent.click(viewButton);+ fireEvent.click(await screen.findByTestId("skill-view-button"));- const siblings = await screen.findByTestId("skill-view-sibling-files");+ const tree = await screen.findByTestId("skill-view-files");+ // Each directory appears once, above its own files, and only files carry+ // a size.expect(- within(siblings).getByText("/skills/oauth_flow/references/providers.md"),- ).toBeDefined();- expect(- within(siblings).getByText("/skills/oauth_flow/scripts/exchange_code.py"),- ).toBeDefined();+ Array.from(tree.querySelectorAll("li")).map((li) => li.textContent),+ ).toEqual([+ "references/",+ "errors.md300 B",+ "providers.md2.0 KB",+ "scripts/",+ "exchange_code.py512 B",+ ]);});test("View dialog shows an error card when the detail fetch fails", async () => {@@ -233,7 +251,7 @@ describe("SkillsPage", () => {body: "## Steps\n1. Hit /authorize",version: null,is_default: false,- sibling_files: [],+ files: [],};server.use(getListCopilotSkillsMockHandler([makeSkill({ name: "oauth_flow" })]),@@ -256,6 +274,114 @@ describe("SkillsPage", () => {}});+ test("Download gives a .zip when the skill carries package files", async () => {+ const createObjectURL = vi.fn((_: Blob | MediaSource) => "blob:mock-url");+ const originalCreate = URL.createObjectURL;+ const originalRevoke = URL.revokeObjectURL;+ URL.createObjectURL = createObjectURL;+ URL.revokeObjectURL = vi.fn();+ const saved: string[] = [];+ const clickSpy = vi+ .spyOn(HTMLAnchorElement.prototype, "click")+ .mockImplementation(function (this: HTMLAnchorElement) {+ saved.push(this.download);+ });++ try {+ server.use(+ getListCopilotSkillsMockHandler([makeSkill({ name: "oauth_flow" })]),+ getReadCopilotSkillMockHandler(makePackageDetail()),+ // The generated handler hardcodes application/json, which would send+ // the archive through the mutator's text path — mock the zip itself.+ http.get(+ "/api/proxy/api/skills/:name/package",+ () =>+ new HttpResponse(+ new Blob([new Uint8Array([0x50, 0x4b, 0x03, 0x04])]),+ {+ headers: { "Content-Type": "application/zip" },+ },+ ),+ ),+ );++ render(<SkillsPage />);++ fireEvent.click(await screen.findByTestId("skill-download-button"));++ await vi.waitFor(() => expect(saved).toEqual(["oauth_flow.zip"]));+ // The archive must survive the fetch layer as bytes; read as text it+ // would download corrupted and open in nothing.+ expect(createObjectURL.mock.calls[0][0]).toBeInstanceOf(Blob);+ } finally {+ URL.createObjectURL = originalCreate;+ URL.revokeObjectURL = originalRevoke;+ clickSpy.mockRestore();+ }+ });++ test("a picked .zip goes to the package endpoint and a .md to the single-file one", async () => {+ const posted: string[] = [];+ const record = ({ request }: { request: Request }) => {+ if (request.method === "POST") posted.push(new URL(request.url).pathname);+ };+ server.events.on("request:start", record);++ try {+ server.use(+ getListCopilotSkillsMockHandler([]),+ getUploadCopilotSkillMockHandler201({+ name: "from_md",+ description: "d",+ triggers: [],+ }),+ getUploadCopilotSkillPackageMockHandler201({+ name: "from_zip",+ description: "d",+ triggers: [],+ }),+ );++ render(<SkillsPage />);+ await screen.findByTestId("skills-empty");+ const input = screen.getByTestId("skill-upload-input");+ expect(input.getAttribute("accept")).toContain(".zip");++ fireEvent.change(input, {+ target: {+ files: [+ new File([new Uint8Array([0x50, 0x4b, 0x03, 0x04])], "pkg.zip", {+ type: "application/zip",+ }),+ ],+ },+ });+ await vi.waitFor(() =>+ expect(posted).toEqual(["/api/proxy/api/skills/package"]),+ );++ fireEvent.change(input, {+ target: {+ files: [+ new File(+ ["---\nname: from_md\ndescription: d\n---\n\nbody"],+ "from_md.md",+ { type: "text/markdown" },+ ),+ ],+ },+ });+ await vi.waitFor(() =>+ expect(posted).toEqual([+ "/api/proxy/api/skills/package",+ "/api/proxy/api/skills",+ ]),+ );+ } finally {+ server.events.removeListener("request:start", record);+ }+ });+test("Upload button sends the picked file and refreshes the list", async () => {server.use(getListCopilotSkillsMockHandler([]),diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.tsindex f3e60f6457..ca3de60ce5 100644--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts@@ -39,6 +39,7 @@ const getBody = async <T>(c: Response | Request): Promise<T> => {if (contentType &&(contentType.includes("application/pdf") ||+ contentType.includes("application/zip") ||contentType.startsWith("image/") ||contentType.startsWith("video/"))) {diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex b8d0224bb6..38bdf94af2 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -13793,6 +13793,66 @@}}},+ "/api/skills/package": {+ "post": {+ "tags": ["v1", "skills"],+ "summary": "Upload a copilot skill as a zipped package",+ "description": "Create a skill from a zipped package — a root ``SKILL.md`` plus the\nfiles beside it.\n\nThe zip is transport only: it is unpacked here and stored as the skill's\nfolder, so the model reaches ``scripts/`` and ``references/`` by path\nexactly as it does for a package copied from another skill.",+ "operationId": "uploadCopilotSkillPackage",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "expert_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "description": "Store the skill as this expert's own.",+ "title": "Expert Id"+ },+ "description": "Store the skill as this expert's own."+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "multipart/form-data": {+ "schema": {+ "$ref": "#/components/schemas/Body_uploadCopilotSkillPackage"+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/CopilotSkillInfo" }+ }+ }+ },+ "400": {+ "description": "Unreadable archive, or a malformed SKILL.md or path"+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "409": { "description": "Per-user skill limit reached" },+ "413": {+ "description": "Archive, file or file count over the package limit"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/skills/{name}": {"delete": {"tags": ["v1", "skills"],@@ -13904,6 +13964,61 @@}}},+ "/api/skills/{name}/package": {+ "get": {+ "tags": ["v1", "skills"],+ "summary": "Download a copilot skill as a zipped package",+ "description": "Return the skill's whole folder as a zip — ``SKILL.md`` at the root,\nsiblings at their relative paths, executable bits preserved — so a\ndownload re-uploads to the same tree.\n\nBuilt-in defaults are single on-disk files and are not downloadable here;\nGET ``/skills/{name}`` serves their body.",+ "operationId": "downloadCopilotSkillPackage",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "name",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "description": "Slug of the skill to download",+ "title": "Name"+ },+ "description": "Slug of the skill to download"+ },+ {+ "name": "expert_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "description": "Download this expert's own copy of the skill.",+ "title": "Expert Id"+ },+ "description": "Download this expert's own copy of the skill."+ }+ ],+ "responses": {+ "200": {+ "description": "The skill folder as a zip archive",+ "content": {+ "application/zip": {+ "schema": { "type": "string", "format": "binary" }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Skill not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/store/admin/listings": {"get": {"tags": ["v2", "admin", "store", "admin"],@@ -17833,6 +17948,14 @@"required": ["file"],"title": "Body_postV2Upload submission media"},+ "Body_uploadCopilotSkillPackage": {+ "properties": {+ "file": { "type": "string", "format": "binary", "title": "File" }+ },+ "type": "object",+ "required": ["file"],+ "title": "Body_uploadCopilotSkillPackage"+ },"Body_uploadWorkspaceFile": {"properties": {"file": { "type": "string", "format": "binary", "title": "File" }@@ -18847,10 +18970,10 @@"title": "Is Default","default": false},- "sibling_files": {- "items": { "type": "string" },+ "files": {+ "items": { "$ref": "#/components/schemas/CopilotSkillFile" },"type": "array",- "title": "Sibling Files",+ "title": "Files","default": []}},@@ -18859,6 +18982,21 @@"title": "CopilotSkillDetail","description": "Full SKILL.md content surfaced to the library expand-to-view UI."},+ "CopilotSkillFile": {+ "properties": {+ "path": { "type": "string", "title": "Path" },+ "size_bytes": { "type": "integer", "title": "Size Bytes" },+ "is_executable": {+ "type": "boolean",+ "title": "Is Executable",+ "default": false+ }+ },+ "type": "object",+ "required": ["path", "size_bytes"],+ "title": "CopilotSkillFile",+ "description": "One file of a skill package, by its path relative to the skill folder\n(``scripts/run.py``) — the path the SKILL.md body references it by."+ },"CopilotSkillInfo": {"properties": {"name": { "type": "string", "title": "Name" },diff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/SkillListItem.tsx b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/SkillListItem.tsxindex b9564dd0f0..6e8de60213 100644--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/SkillListItem.tsx+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/SkillListItem.tsx@@ -27,6 +27,7 @@ export function SkillListItem({ skill, isNew = false }: Props) {const {descriptionPreview,triggers,+ fileRows,isDeleteOpen,openDelete,closeDelete,@@ -163,19 +164,26 @@ export function SkillListItem({ skill, isNew = false }: Props) {>{detail?.body || "(no body)"}</pre>- {detail?.sibling_files && detail.sibling_files.length > 0 ? (+ {fileRows.length > 0 ? (<divclassName="flex flex-col gap-1"- data-testid="skill-view-sibling-files"+ data-testid="skill-view-files"><Text variant="small" className="!text-zinc-500">- Bundled files ({detail.sibling_files.length}- ):+ Package files ({detail?.files?.length ?? 0}):</Text>- <ul className="flex flex-col gap-0.5 pl-3 text-xs text-zinc-600">- {detail.sibling_files.map((path) => (- <li key={path} className="break-all">- {path}+ <ul className="flex flex-col gap-0.5 text-xs text-zinc-600">+ {fileRows.map((row) => (+ <li+ key={row.path}+ className={`flex items-baseline justify-between gap-3 ${indentClass(row.depth)}`}+ >+ <span className="break-all">{row.label}</span>+ {row.sizeLabel ? (+ <span className="flex-shrink-0 tabular-nums text-zinc-400">+ {row.sizeLabel}+ </span>+ ) : null}</li>))}</ul>@@ -221,3 +229,12 @@ export function SkillListItem({ skill, isNew = false }: Props) {</div>);}++// Tailwind only sees class names it can read literally, so the indent is a+// lookup rather than a computed padding; a path deeper than the list shares+// its last step.+const INDENT_CLASSES = ["pl-0", "pl-3", "pl-6", "pl-9", "pl-12"];++function indentClass(depth: number): string {+ return INDENT_CLASSES[Math.min(depth, INDENT_CLASSES.length - 1)];+}diff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/helpers.ts b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/helpers.tsindex e6960d757a..047991f96e 100644--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/helpers.ts+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/helpers.ts@@ -1,4 +1,5 @@import type { CopilotSkillDetail } from "@/app/api/__generated__/models/copilotSkillDetail";+import type { CopilotSkillFile } from "@/app/api/__generated__/models/copilotSkillFile";import type { CopilotSkillInfo } from "@/app/api/__generated__/models/copilotSkillInfo";const DESCRIPTION_PREVIEW_MAX_LEN = 220;@@ -38,8 +39,49 @@ export function renderSkillMarkdown(detail: CopilotSkillDetail): string {return `${frontmatter.join("\n")}\n\n${(detail.body ?? "").trim()}\n`;}-export function downloadTextFile(filename: string, text: string): void {- const blob = new Blob([text], { type: "text/markdown;charset=utf-8" });+export interface SkillFileRow {+ path: string;+ depth: number;+ label: string;+ sizeLabel: string | null;+}++// Flatten a package's relative paths into indented rows, each directory once+// above its files, so the dialog renders a tree without recursing.+export function buildSkillFileRows(+ files: CopilotSkillFile[] | undefined,+): SkillFileRow[] {+ const rows: SkillFileRow[] = [];+ const seen = new Set<string>();+ const sorted = [...(files ?? [])].sort((a, b) =>+ a.path.localeCompare(b.path),+ );++ for (const file of sorted) {+ const segments = file.path.split("/");+ segments.forEach((segment, index) => {+ const path = segments.slice(0, index + 1).join("/");+ if (seen.has(path)) return;+ seen.add(path);+ const isLeaf = index === segments.length - 1;+ rows.push({+ path,+ depth: index,+ label: isLeaf ? segment : `${segment}/`,+ sizeLabel: isLeaf ? formatFileSize(file.size_bytes) : null,+ });+ });+ }+ return rows;+}++function formatFileSize(bytes: number): string {+ if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${bytes} B`;+}++export function downloadFile(filename: string, blob: Blob): void {const url = URL.createObjectURL(blob);const anchor = document.createElement("a");anchor.href = url;diff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.ts b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.tsindex 4528c4365a..31ea26750c 100644--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.ts+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.ts@@ -1,4 +1,5 @@import {+ downloadCopilotSkillPackage,getListCopilotSkillsQueryKey,readCopilotSkill,useDeleteCopilotSkill,@@ -10,8 +11,9 @@ import { useToast } from "@/components/molecules/Toast/use-toast";import { useQueryClient } from "@tanstack/react-query";import { useState } from "react";import {+ buildSkillFileRows,describeSkill,- downloadTextFile,+ downloadFile,renderSkillMarkdown,} from "./helpers";@@ -72,6 +74,8 @@ export function useSkillListItem({ skill }: Args) {setIsViewOpen(open);}+ // A package downloads as the zip the upload endpoint takes back; a skill+ // that is only a SKILL.md stays a .md, which is what most users exported.async function handleDownload() {setIsDownloading(true);try {@@ -80,7 +84,20 @@ export function useSkillListItem({ skill }: Args) {throw new Error(`Failed to download skill (HTTP ${res.status})`);}const skillDetail = res.data as CopilotSkillDetail;- downloadTextFile(`${skill.name}.md`, renderSkillMarkdown(skillDetail));+ if (skillDetail.files?.length) {+ const archive = await downloadCopilotSkillPackage(skill.name);+ if (archive.status !== 200) {+ throw new Error(`Failed to download skill (HTTP ${archive.status})`);+ }+ downloadFile(`${skill.name}.zip`, archive.data);+ return;+ }+ downloadFile(+ `${skill.name}.md`,+ new Blob([renderSkillMarkdown(skillDetail)], {+ type: "text/markdown;charset=utf-8",+ }),+ );} catch (error) {toast({title: "Failed to download skill",@@ -118,6 +135,7 @@ export function useSkillListItem({ skill }: Args) {return {descriptionPreview,triggers,+ fileRows: buildSkillFileRows(detail?.files),isDeleteOpen,openDelete,closeDelete,diff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/UploadSkillButton.tsx b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/UploadSkillButton.tsxindex 03bde6a052..ca7ab56123 100644--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/UploadSkillButton.tsx+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/UploadSkillButton.tsx@@ -23,7 +23,7 @@ export function UploadSkillButton({ onUploaded }: Props) {<inputref={fileInputRef}type="file"- accept=".md,.markdown,text/markdown"+ accept=".md,.markdown,text/markdown,.zip,application/zip"className="hidden"onChange={handleFileChange}data-testid="skill-upload-input"@@ -42,7 +42,7 @@ export function UploadSkillButton({ onUploaded }: Props) {</Button></TooltipTrigger><TooltipContent side="bottom">- Import a skill file you've exported+ Import a SKILL.md, or a zipped skill package</TooltipContent></Tooltip></>diff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/helpers.ts b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/helpers.tsindex ce112c3d89..b2893d8322 100644--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/helpers.ts+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/helpers.ts@@ -5,6 +5,13 @@ export const MAX_SKILL_DESCRIPTION_CHARS = 1024;const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---/;+// A zip goes to the package endpoint, anything else to the single-file one.+// Matched on the extension, not the MIME type: browsers report a zip as+// application/zip, application/x-zip-compressed or "" depending on the OS.+export function isSkillPackageFile(file: File): boolean {+ return file.name.toLowerCase().endsWith(".zip");+}+// Best-effort, dependency-free pre-flight for an uploaded SKILL.md. The// backend remains the source of truth — this only catches the common,// confidently-detectable cases (missing frontmatter, over-long single-linediff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/useUploadSkillButton.ts b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/useUploadSkillButton.tsindex 1033e148d1..4e95a5dc30 100644--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/useUploadSkillButton.ts+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/UploadSkillButton/useUploadSkillButton.ts@@ -1,11 +1,12 @@import {getListCopilotSkillsQueryKey,useUploadCopilotSkill,+ useUploadCopilotSkillPackage,} from "@/app/api/__generated__/endpoints/skills/skills";import { useToast } from "@/components/molecules/Toast/use-toast";import { useQueryClient } from "@tanstack/react-query";import { useRef } from "react";-import { getSkillUploadError } from "./helpers";+import { getSkillUploadError, isSkillPackageFile } from "./helpers";interface Args {onUploaded?: (name: string) => void;@@ -16,8 +17,11 @@ export function useUploadSkillButton({ onUploaded }: Args = {}) {const queryClient = useQueryClient();const fileInputRef = useRef<HTMLInputElement>(null);- const { mutateAsync: uploadSkill, isPending: isUploading } =+ const { mutateAsync: uploadSkill, isPending: isUploadingFile } =useUploadCopilotSkill();+ const { mutateAsync: uploadPackage, isPending: isUploadingPackage } =+ useUploadCopilotSkillPackage();+ const isUploading = isUploadingFile || isUploadingPackage;function openFilePicker() {fileInputRef.current?.click();@@ -30,21 +34,11 @@ export function useUploadSkillButton({ onUploaded }: Args = {}) {if (!file) return;try {- const content = await file.text();+ const result = isSkillPackageFile(file)+ ? await uploadPackage({ data: { file } })+ : await uploadMarkdownSkill(file);+ if (!result) return;- // Pre-flight the common rejections client-side so the user gets an- // instant, specific message instead of waiting on a server round-trip.- const validationError = getSkillUploadError(content);- if (validationError) {- toast({- title: "Can't upload this skill",- description: validationError,- variant: "destructive",- });- return;- }-- const result = await uploadSkill({ data: { content } });const name =result.status === 201 ? result.data.name : (file.name ?? "skill");toast({ title: `Skill "${name}" uploaded` });@@ -66,6 +60,25 @@ export function useUploadSkillButton({ onUploaded }: Args = {}) {}}+ // `null` when the client-side pre-flight rejected the file and has already+ // said so, so the caller reports nothing further.+ async function uploadMarkdownSkill(file: File) {+ const content = await file.text();++ // Pre-flight the common rejections client-side so the user gets an+ // instant, specific message instead of waiting on a server round-trip.+ const validationError = getSkillUploadError(content);+ if (validationError) {+ toast({+ title: "Can't upload this skill",+ description: validationError,+ variant: "destructive",+ });+ return null;+ }+ return uploadSkill({ data: { content } });+ }+return {fileInputRef,isUploading,