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): seed the skills marketplace from a private skills catalog (#14600)
Ubbe6920c1d7cc9e
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex b313deeb5e..81e5741851 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -394,3 +394,10 @@ RMFG_API_KEY=# "Connect your tools" panel. Recommendations are best-effort — a failure# here never blocks onboarding.# BRAIN_DUMP_RECOMMEND_MODEL=anthropic/claude-sonnet-5++# Skills marketplace seed (python -m backend.api.features.store.skill_seed).+# Reads the private skills catalog repo; a local checkout skips the download.+# SKILLS_CATALOG_REPO=Significant-Gravitas/skills-catalog+# SKILLS_CATALOG_REF=main+# SKILLS_CATALOG_TOKEN=+# SKILLS_CATALOG_PATH=diff --git a/autogpt_platform/backend/backend/api/features/experts/seed.py b/autogpt_platform/backend/backend/api/features/experts/seed.pyindex 55e59305ce..9ef6f1188f 100644--- a/autogpt_platform/backend/backend/api/features/experts/seed.py+++ b/autogpt_platform/backend/backend/api/features/experts/seed.py@@ -1371,7 +1371,7 @@ async def _resolve_roster_skills() -> dict[str, str]:if missing:raise RuntimeError(f"Skills Hub is missing roster listings for: {', '.join(missing)}. "- "Seed the starter skills before seeding the expert roster."+ "Seed the skills catalog before seeding the expert roster.")return resolveddiff --git a/autogpt_platform/backend/backend/api/features/store/skill_db.py b/autogpt_platform/backend/backend/api/features/store/skill_db.pyindex 8b838a1701..c9cee13c95 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_db.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_db.py@@ -172,7 +172,8 @@ async def install_marketplace_skill(caller's own library when ``None``.The listing's slug becomes the installed skill's name, so an install is- idempotent and a re-install picks up a newer approved version.+ idempotent and a re-install picks up a newer approved version. The whole+ package is passed, so a file the new version dropped is removed too."""listing = await _find_live_listing(slug)active = skill_model.active_version(listing)@@ -187,6 +188,15 @@ async def install_marketplace_skill(body=active.body,triggers=list(active.triggers),version=str(active.version),+ extra={+ key: value+ for key, value in (+ ("license", active.license),+ ("source", active.sourceRepo),+ ("source_url", active.sourceUrl),+ )+ if value is not None+ },# `[]`, never `None` — which means "leave the folder alone" and would# keep a sibling only the previously installed version had.files=await _read_version_files(active.id),diff --git a/autogpt_platform/backend/backend/api/features/store/skill_db_test.py b/autogpt_platform/backend/backend/api/features/store/skill_db_test.pyindex 6dc8884201..6841f3cf4c 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_db_test.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_db_test.py@@ -7,6 +7,7 @@ import prisma.enumsimport prisma.modelsimport pytest+from backend.copilot.tools.skills import SkillPackageErrorfrom backend.copilot.tools.skills_test import _FakeWorkspaceManager, _patch_skills_pathfrom backend.util.exceptions import NotFoundErrorfrom backend.util.test import SpinTestServer@@ -356,36 +357,202 @@ async def test_install_of_an_off_shelf_listing_never_reaches_the_library(stored.assert_not_awaited()-async def test_seed_is_idempotent_and_keeps_one_version_per_listing():- first = await skill_seed.seed_starter_skills()- second = await skill_seed.seed_starter_skills()+CATALOG_YML = (+ "skills:\n"+ " - slug: brand-voice-guide\n"+ " categories: [content]\n"+ " required_providers: []\n"+ " source: platform\n"+ " - slug: cold-email\n"+ " categories: [sales]\n"+ " required_providers: [google]\n"+ " source: acme/marketing-skills/skills/cold-email\n"+ " license: MIT\n"+)+COLD_EMAIL_MD = (+ "---\n"+ "name: cold-email\n"+ "description: Write cold emails.\n"+ "license: MIT\n"+ "metadata:\n"+ " source: acme/marketing-skills\n"+ " source_url: https://github.com/acme/marketing-skills/tree/abc/skills/cold-email\n"+ "---\n\n# Cold email\n\nSee references/frameworks.md.\n"+)+++def _write_catalog(+ root, frameworks: str = "# Frameworks\n", brand_body: str = "# Voice\n"+):+ (root / "catalog.yml").write_text(CATALOG_YML, encoding="utf-8")+ brand = root / "skills" / "brand-voice-guide"+ brand.mkdir(parents=True, exist_ok=True)+ (brand / "SKILL.md").write_text(+ "---\nname: brand-voice-guide\ndescription: Keep one voice.\n---\n\n"+ + brand_body,+ encoding="utf-8",+ )+ cold = root / "skills" / "cold-email" / "references"+ cold.mkdir(parents=True, exist_ok=True)+ (cold.parent / "SKILL.md").write_text(COLD_EMAIL_MD, encoding="utf-8")+ (cold / "frameworks.md").write_text(frameworks, encoding="utf-8")+ return root+++async def test_seed_is_idempotent_and_rewrites_the_live_package_in_place(tmp_path):+ catalog = _write_catalog(tmp_path)+ first = await skill_seed.seed_catalog_skills(catalog)+ _write_catalog(tmp_path, frameworks="# Frameworks v2\n")+ second = await skill_seed.seed_catalog_skills(catalog)assert first == second- versions = await prisma.models.SkillListingVersion.prisma().count()- assert versions == len(skill_seed.STARTER_SKILLS)+ assert await prisma.models.SkillListingVersion.prisma().count() == 2+ files = await prisma.models.SkillListingFile.prisma().find_many()+ assert [(f.relativePath, f.content.decode()) for f in files] == [+ ("references/frameworks.md", b"# Frameworks v2\n")+ ]-async def test_seeded_skills_are_installable_under_their_own_slug(mocker):- await skill_seed.seed_starter_skills()- stored = mocker.patch.object(skill_db, "store_user_skill")- mocker.patch.object(skill_db, "list_user_skills", return_value=[])+async def test_seed_keeps_the_old_package_when_file_replacement_fails(mocker, tmp_path):+ catalog = _write_catalog(tmp_path)+ await skill_seed.seed_catalog_skills(catalog)+ listing = await prisma.models.SkillListing.prisma().find_unique(+ where={"slug": "cold-email"}, include={"ActiveVersion": True}+ )+ assert listing is not None and listing.ActiveVersion is not None+ version_id = listing.ActiveVersion.id+ original_snapshot = skill_seed.snapshot_version_files++ async def fail_after_delete(skill_listing_version_id, files, tx):+ if skill_listing_version_id == version_id:+ await prisma.models.SkillListingFile.prisma(tx).delete_many(+ where={"skillListingVersionId": skill_listing_version_id}+ )+ raise RuntimeError("file write failed")+ await original_snapshot(skill_listing_version_id, files, tx)- result = await skill_db.install_marketplace_skill("user-1", "brand-voice-guide")+ mocker.patch.object(+ skill_seed, "snapshot_version_files", side_effect=fail_after_delete+ )+ _write_catalog(tmp_path, frameworks="# Frameworks v2\n")- assert result.name == "brand-voice-guide"- assert stored.await_args.kwargs["name"] == "brand-voice-guide"+ with pytest.raises(RuntimeError, match="file write failed"):+ await skill_seed.seed_catalog_skills(catalog)+ files = await prisma.models.SkillListingFile.prisma().find_many(+ where={"skillListingVersionId": version_id}+ )+ assert [(file.relativePath, file.content.decode()) for file in files] == [+ ("references/frameworks.md", b"# Frameworks\n")+ ]-def test_seed_rejects_a_file_whose_frontmatter_name_is_not_the_slug(- monkeypatch, tmp_path++async def test_seed_rolls_back_every_listing_when_one_file_write_fails(+ mocker, tmp_path):- """The frontmatter name becomes the installed skill's name, so a mismatch- would install a starter skill under a name the marketplace never shows."""- (tmp_path / "mismatched.md").write_text(- '---\nname: "something-else"\ndescription: "d"\n---\n\nbody\n',- encoding="utf-8",+ catalog = _write_catalog(tmp_path)+ await skill_seed.seed_catalog_skills(catalog)+ cold_email = await prisma.models.SkillListing.prisma().find_unique(+ where={"slug": "cold-email"}, include={"ActiveVersion": True}+ )+ assert cold_email is not None and cold_email.ActiveVersion is not None+ failing_version_id = cold_email.ActiveVersion.id+ original_snapshot = skill_seed.snapshot_version_files++ async def fail_on_cold_email(skill_listing_version_id, files, tx):+ if skill_listing_version_id == failing_version_id:+ raise RuntimeError("file write failed")+ await original_snapshot(skill_listing_version_id, files, tx)++ mocker.patch.object(+ skill_seed, "snapshot_version_files", side_effect=fail_on_cold_email+ )+ _write_catalog(tmp_path, frameworks="# Frameworks v2\n", brand_body="# Voice v2\n")++ with pytest.raises(RuntimeError, match="file write failed"):+ await skill_seed.seed_catalog_skills(catalog)++ brand_voice = await prisma.models.SkillListing.prisma().find_unique(+ where={"slug": "brand-voice-guide"}, include={"ActiveVersion": True})- monkeypatch.setattr(skill_seed, "_CONTENT_DIR", tmp_path)+ assert brand_voice is not None and brand_voice.ActiveVersion is not None+ assert brand_voice.ActiveVersion.body == "# Voice\n"+++async def test_seed_rejects_a_slug_owned_by_a_creator(tmp_path, setup_test_user):+ await prisma.models.Profile.prisma().upsert(+ where={"userId": setup_test_user},+ data={+ "create": {+ "userId": setup_test_user,+ "username": "catalog-collision-owner",+ "name": "Catalog Collision Owner",+ "description": "",+ "links": [],+ },+ "update": {},+ },+ )+ owned = await prisma.models.SkillListing.prisma().create(+ data={"slug": "cold-email", "owningUserId": setup_test_user}+ )++ with pytest.raises(ValueError, match="conflicts with an owned listing"):+ await skill_seed.seed_catalog_skills(_write_catalog(tmp_path))++ unchanged = await prisma.models.SkillListing.prisma().find_unique(+ where={"id": owned.id}+ )+ assert unchanged is not None+ assert unchanged.owningUserId == setup_test_user+ assert unchanged.hasApprovedVersion is False+ assert (+ await prisma.models.SkillListingVersion.prisma().count(+ where={"skillListingId": owned.id}+ )+ == 0+ )+++async def test_seeded_skills_carry_their_attribution(tmp_path):+ await skill_seed.seed_catalog_skills(_write_catalog(tmp_path))++ vendored = await skill_db.get_marketplace_skill("cold-email")+ own = await skill_db.get_marketplace_skill("brand-voice-guide")++ assert (vendored.source_repo, vendored.license) == ("acme/marketing-skills", "MIT")+ assert vendored.source_url is not None and vendored.source_url.endswith(+ "/skills/cold-email"+ )+ assert (own.source_repo, own.source_url, own.license) == (None, None, None)+++async def test_seeded_skills_install_with_their_package_files(mocker, tmp_path):+ await skill_seed.seed_catalog_skills(_write_catalog(tmp_path))+ stored = mocker.patch.object(skill_db, "store_user_skill")+ mocker.patch.object(skill_db, "list_user_skills", return_value=[])++ result = await skill_db.install_marketplace_skill("user-1", "cold-email")++ assert result.name == "cold-email"+ assert stored.await_args.kwargs["name"] == "cold-email"+ assert stored.await_args.kwargs["extra"] == {+ "license": "MIT",+ "source": "acme/marketing-skills",+ "source_url": (+ "https://github.com/acme/marketing-skills/tree/abc/skills/cold-email"+ ),+ }+ assert [+ (f.relative_path, f.content) for f in stored.await_args.kwargs["files"]+ ] == [("references/frameworks.md", b"# Frameworks\n")]+++async def test_a_bad_catalog_entry_writes_nothing(tmp_path):+ catalog = _write_catalog(tmp_path)+ (catalog / "skills" / "cold-email" / ".env").write_text("x=1", encoding="utf-8")++ with pytest.raises(SkillPackageError):+ await skill_seed.seed_catalog_skills(catalog)- with pytest.raises(ValueError, match="must match"):- skill_seed._load("mismatched")+ assert await prisma.models.SkillListing.prisma().count() == 0diff --git a/autogpt_platform/backend/backend/api/features/store/skill_model.py b/autogpt_platform/backend/backend/api/features/store/skill_model.pyindex 7901b8b512..d79a4302b3 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_model.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_model.py@@ -29,6 +29,12 @@ class MarketplaceSkill(pydantic.BaseModel):install_count: intcreator: str | None = Nonecreator_avatar: str | None = None+ source_repo: str | None = pydantic.Field(+ default=None,+ description="GitHub repo a vendored skill was taken from, as owner/name.",+ )+ source_url: str | None = None+ license: str | None = None@classmethoddef from_db(cls, listing: prisma.models.SkillListing) -> "MarketplaceSkill":@@ -44,6 +50,9 @@ class MarketplaceSkill(pydantic.BaseModel):install_count=listing.installCount,creator=profile.username if profile else None,creator_avatar=profile.avatarUrl if profile else None,+ source_repo=version.sourceRepo,+ source_url=version.sourceUrl,+ license=version.license,)diff --git a/autogpt_platform/backend/backend/api/features/store/skill_package_test.py b/autogpt_platform/backend/backend/api/features/store/skill_package_test.pyindex ab96580d3e..00daacd434 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_package_test.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_package_test.py@@ -37,7 +37,7 @@ FIXTURE_DIR = (Path(__file__).parents[4] / "test" / "fixtures" / "skills" / "webapp-testing")SLUG = "webapp-testing"-STARTER_SLUG = "starter-with-a-package"+CATALOG_SLUG = "catalog-skill-with-a-package"def _fixture_files() -> list[SkillFile]:@@ -120,10 +120,10 @@ async def _drop_our_listings() -> None:"""By slug, not wholesale: this table is shared with every other checkouthere, where the starter listings are real rows."""await prisma.models.SkillListingVersion.prisma().delete_many(- where={"SkillListing": {"is": {"slug": {"in": [SLUG, STARTER_SLUG]}}}}+ where={"SkillListing": {"is": {"slug": {"in": [SLUG, CATALOG_SLUG]}}}})await prisma.models.SkillListing.prisma().delete_many(- where={"slug": {"in": [SLUG, STARTER_SLUG]}}+ where={"slug": {"in": [SLUG, CATALOG_SLUG]}})@@ -260,94 +260,61 @@ async def test_installing_a_single_file_listing_clears_a_package_left_behind(assert await list_user_skill_files(creator, SLUG, expert_id=expert) == []-async def test_a_seeded_starter_package_installs_its_siblings(- creator: str, expert: str, monkeypatch, tmp_path+async def test_a_seeded_catalog_package_installs_its_siblings(+ creator: str, expert: str, tmp_path):- """The seed is the other writer of a listing version, and a starter whose+ """The seed is the other writer of a listing version, and a skill whosepackage never reached the shelf would install as a bare SKILL.md."""- directory = tmp_path / STARTER_SLUG+ directory = _write_catalog(tmp_path)(directory / "scripts").mkdir(parents=True)- (directory / "SKILL.md").write_text(- f"---\nname: {STARTER_SLUG}\ndescription: Ships a script.\n---\n\n# Body\n",- encoding="utf-8",- )script = directory / "scripts" / "run.sh"script.write_text("#!/bin/sh\necho hi\n", encoding="utf-8")script.chmod(0o755)- monkeypatch.setattr(skill_seed, "_CONTENT_DIR", tmp_path)- # Never the shipped list: seeding that upserts the real starter listings.- monkeypatch.setattr(- skill_seed,- "STARTER_SKILLS",- [{"slug": STARTER_SLUG, "categories": ["content"], "required_providers": []}],- )- await skill_seed.seed_starter_skills()- await skill_db.install_marketplace_skill(creator, STARTER_SLUG, expert_id=expert)+ await skill_seed.seed_catalog_skills(tmp_path)+ await skill_db.install_marketplace_skill(creator, CATALOG_SLUG, expert_id=expert)- rows = await _starter_file_rows()+ rows = await _catalog_file_rows()assert [(r.relativePath, r.isExecutable) for r in rows] == [("scripts/run.sh", True)]installed = {f.path- for f in await list_user_skill_files(creator, STARTER_SLUG, expert_id=expert)+ for f in await list_user_skill_files(creator, CATALOG_SLUG, expert_id=expert)}- assert f"/experts/{expert}/skills/{STARTER_SLUG}/scripts/run.sh" in installed+ assert f"/experts/{expert}/skills/{CATALOG_SLUG}/scripts/run.sh" in installed-async def test_re_seeding_a_starter_that_lost_a_file_drops_its_row(- creator: str, monkeypatch, tmp_path+async def test_re_seeding_a_catalog_skill_that_lost_a_file_drops_its_row(+ creator: str, tmp_path):"""The seed rewrites its version in place, so the package has to bereplaced rather than added to."""- directory = tmp_path / STARTER_SLUG- directory.mkdir()- (directory / "SKILL.md").write_text(- f"---\nname: {STARTER_SLUG}\ndescription: Ships a script.\n---\n\n# Body\n",- encoding="utf-8",- )+ directory = _write_catalog(tmp_path)(directory / "notes.md").write_text("# Notes\n", encoding="utf-8")- monkeypatch.setattr(skill_seed, "_CONTENT_DIR", tmp_path)- monkeypatch.setattr(- skill_seed,- "STARTER_SKILLS",- [{"slug": STARTER_SLUG, "categories": ["content"], "required_providers": []}],- )- await skill_seed.seed_starter_skills()+ await skill_seed.seed_catalog_skills(tmp_path)# Asserted before the removal: a seed that stores nothing at all would# satisfy the empty assertion below without ever replacing anything.- assert [r.relativePath for r in await _starter_file_rows()] == ["notes.md"]+ assert [r.relativePath for r in await _catalog_file_rows()] == ["notes.md"](directory / "notes.md").unlink()- await skill_seed.seed_starter_skills()+ await skill_seed.seed_catalog_skills(tmp_path)- assert await _starter_file_rows() == []+ assert await _catalog_file_rows() == []-async def test_a_seed_that_cannot_write_the_package_leaves_the_version_alone(+async def test_a_catalog_seed_that_cannot_write_the_package_leaves_the_version_alone(creator: str, monkeypatch, tmp_path):"""The live version and its files are replaced together, so a failed packagewrite cannot leave new instructions on the shelf beside the old package."""- directory = tmp_path / STARTER_SLUG- directory.mkdir()+ directory = _write_catalog(tmp_path, body="# First\n")root = directory / "SKILL.md"- root.write_text(- f"---\nname: {STARTER_SLUG}\ndescription: Ships a note.\n---\n\n# First\n",- encoding="utf-8",- )(directory / "notes.md").write_text("# Notes\n", encoding="utf-8")- monkeypatch.setattr(skill_seed, "_CONTENT_DIR", tmp_path)- monkeypatch.setattr(- skill_seed,- "STARTER_SKILLS",- [{"slug": STARTER_SLUG, "categories": ["content"], "required_providers": []}],- )- await skill_seed.seed_starter_skills()+ await skill_seed.seed_catalog_skills(tmp_path)root.write_text(- f"---\nname: {STARTER_SLUG}\ndescription: Ships a note.\n---\n\n# Second\n",+ f"---\nname: {CATALOG_SLUG}\ndescription: Ships a note.\n---\n\n# Second\n",encoding="utf-8",)@@ -356,21 +323,34 @@ async def test_a_seed_that_cannot_write_the_package_leaves_the_version_alone(monkeypatch.setattr(skill_seed, "snapshot_version_files", fails)with pytest.raises(RuntimeError):- await skill_seed.seed_starter_skills()+ await skill_seed.seed_catalog_skills(tmp_path)listing = await prisma.models.SkillListing.prisma().find_unique(- where={"slug": STARTER_SLUG}, include={"ActiveVersion": True}+ where={"slug": CATALOG_SLUG}, include={"ActiveVersion": True})assert listing is not None and listing.ActiveVersion is not Noneassert listing.ActiveVersion.body.strip() == "# First"- assert [r.relativePath for r in await _starter_file_rows()] == ["notes.md"]+ assert [r.relativePath for r in await _catalog_file_rows()] == ["notes.md"]+++def _write_catalog(root: Path, body: str = "# Body\n") -> Path:+ (root / "catalog.yml").write_text(+ f"skills:\n - slug: {CATALOG_SLUG}\n categories: [content]\n",+ encoding="utf-8",+ )+ directory = root / "skills" / CATALOG_SLUG+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "SKILL.md").write_text(+ f"---\nname: {CATALOG_SLUG}\ndescription: Ships a note.\n---\n\n{body}",+ encoding="utf-8",+ )+ return directory-async def _starter_file_rows() -> list[prisma.models.SkillListingFile]:- """The seeded starter's own file rows — never the whole table, which this- suite shares with every other one that publishes a package."""+async def _catalog_file_rows() -> list[prisma.models.SkillListingFile]:+ """The seeded catalog skill's own rows, never the shared whole table."""listing = await prisma.models.SkillListing.prisma().find_unique(- where={"slug": STARTER_SLUG}+ where={"slug": CATALOG_SLUG})assert listing is not None and listing.activeVersionId is not Nonereturn await prisma.models.SkillListingFile.prisma().find_many(diff --git a/autogpt_platform/backend/backend/api/features/store/skill_seed.py b/autogpt_platform/backend/backend/api/features/store/skill_seed.pyindex 3f02b4ef8b..be001e2f58 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_seed.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_seed.py@@ -1,44 +1,70 @@-"""Seed the platform-authored starter skill listings.+"""Seed the platform-authored skill listings from the skills catalog.Run as ``python -m backend.api.features.store.skill_seed``, like the expert-roster seed. Idempotent: re-running updates the live version in place rather-than stacking a new one, so the catalogue can be edited by editing the-markdown.+roster seed. Idempotent: re-running rewrites each listing's live version in+place rather than stacking a new one, so the marketplace is edited by editing+the catalog and seeding again.-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+The catalog is the private ``Significant-Gravitas/skills-catalog`` repo. Its+``catalog.yml`` names every listing with its categories and the integrations+its instructions assume; ``skills/<slug>/`` holds the SKILL.md beside the+references it points at. Each SKILL.md is 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.+seeded skill cannot drift from the format an installed skill has, and the+package files go through the same :func:`validate_package` an upload does.++Environment:++``SKILLS_CATALOG_PATH``+ A local checkout to seed from instead of GitHub.+``SKILLS_CATALOG_REPO`` / ``SKILLS_CATALOG_REF``+ The repo (``owner/name``) and branch, tag or commit to download.+``SKILLS_CATALOG_TOKEN``+ A GitHub token that can read the repo; ``GITHUB_TOKEN`` is the fallback."""import asyncio+import ioimport loggingimport os+import tarfile+import tempfilefrom pathlib import Path+import httpx+import prismaimport prisma.enumsimport prisma.models+import yamlfrom backend.copilot.tools.skills import (ParsedSkill,SkillFile,SkillPackage,+ SkillPackageError,+ _validate_name,parse_skill_markdown,validate_package,+ validate_skill_content,)from backend.data import db as database+from .categories import validate_canonical_categoriesfrom .skill_submission_db import snapshot_version_filesfrom .starter_skill_catalog_wave_three import WAVE_THREE_STARTER_SKILLS, StarterSkilllogger = logging.getLogger(__name__)+DEFAULT_CATALOG_REPO = "Significant-Gravitas/skills-catalog"+DEFAULT_CATALOG_REF = "main"+CATALOG_FILE = "catalog.yml"+SKILLS_DIR = "skills"_CONTENT_DIR = Path(__file__).parent / "starter_skills"-STARTER_SKILLS: list[StarterSkill] = [+CatalogEntry = StarterSkill++STARTER_SKILLS: list[CatalogEntry] = [{"slug": "brand-voice-guide","categories": ["content"],@@ -367,35 +393,142 @@ STARTER_SKILLS: list[StarterSkill] = []+async def seed_catalog_skills(catalog_dir: Path | None = None) -> list[str]:+ """Upsert every catalog listing. Returns the listing ids.++ An explicit *catalog_dir* seeds only that tree. A normal run downloads the+ catalog, or reads ``SKILLS_CATALOG_PATH``, and also keeps checked-in skills+ that the expert roster needs until the catalog holds the same slug.+ """+ if catalog_dir is not None:+ return await _seed_catalog(catalog_dir, include_starters=False)++ local = os.environ.get("SKILLS_CATALOG_PATH")+ if local:+ return await _seed_catalog(Path(local), include_starters=True)+ with tempfile.TemporaryDirectory() as tmp:+ return await _seed_catalog(_download_catalog(Path(tmp)), include_starters=True)+++async def _seed_catalog(root: Path, *, include_starters: bool) -> list[str]:+ entries = load_catalog(root)+ loaded = [(entry, *_load(root, entry)) for entry in entries]+ if not include_starters:+ return await _seed_loaded(loaded)++ catalog_slugs = {entry["slug"] for entry in entries}+ loaded += [+ (entry, *_load_starter(entry))+ for entry in STARTER_SKILLS+ if entry["slug"] not in catalog_slugs+ ]+ return await _seed_loaded(loaded)++async def seed_starter_skills() -> list[str]:- """Upsert every starter listing. Returns the listing ids."""+ """Upsert the checked-in skills needed by the expert roster."""+ loaded = [(entry, *_load_starter(entry)) for entry in STARTER_SKILLS]+ return await _seed_loaded(loaded)+++async def _seed_loaded(+ loaded: list[tuple[CatalogEntry, ParsedSkill, list[SkillFile]]],+) -> list[str]:+ """Write a set whose packages have all been loaded and checked."""listing_ids = []- for entry in STARTER_SKILLS:- parsed, files = _load(entry["slug"])- listing = await _upsert_listing(entry, parsed, files)- listing_ids.append(listing.id)- logger.info(- f"Seeded starter skill '{entry['slug']}' (#{listing.id})"- + (f" with {len(files)} package files" if files else "")- )+ async with database.transaction() as tx:+ for entry, parsed, files in loaded:+ listing = await _upsert_listing(tx, entry, parsed, files)+ listing_ids.append(listing.id)+ logger.info(+ f"Seeded skill '{entry['slug']}' (#{listing.id})"+ + (f" with {len(files)} package files" if files else "")+ )return listing_ids+def load_catalog(root: Path) -> list[CatalogEntry]:+ """The catalog's entries, each with a canonical category set."""+ raw = yaml.safe_load((root / CATALOG_FILE).read_text(encoding="utf-8")) or {}+ if not isinstance(raw, dict):+ raise ValueError(f"{CATALOG_FILE} must contain a mapping")+ skills = raw.get("skills") or []+ if not isinstance(skills, list):+ raise ValueError(f"{CATALOG_FILE}: skills must be a list")+ entries: list[CatalogEntry] = []+ seen: set[str] = set()+ for item in skills:+ if not isinstance(item, dict):+ raise ValueError(f"{CATALOG_FILE}: every skill must be a mapping")+ slug = str(item.get("slug") or "").strip()+ if not slug:+ raise ValueError(f"{CATALOG_FILE}: an entry has no slug")+ if error := _validate_name(slug):+ raise ValueError(f"{CATALOG_FILE}: '{slug}' {error}")+ if slug in seen:+ raise ValueError(f"{CATALOG_FILE}: '{slug}' is listed twice")+ seen.add(slug)+ raw_categories = item.get("categories")+ categories = [] if raw_categories is None else raw_categories+ if not isinstance(categories, list) or not all(+ isinstance(category, str) for category in categories+ ):+ raise ValueError(+ f"{CATALOG_FILE}: '{slug}' categories must be a list of strings"+ )+ raw_required_providers = item.get("required_providers")+ required_providers = (+ [] if raw_required_providers is None else raw_required_providers+ )+ if not isinstance(required_providers, list) or not all(+ isinstance(provider, str) for provider in required_providers+ ):+ raise ValueError(+ f"{CATALOG_FILE}: '{slug}' required_providers must be a list of strings"+ )+ entries.append(+ CatalogEntry(+ slug=slug,+ categories=validate_canonical_categories(categories),+ required_providers=required_providers,+ )+ )+ if not entries:+ raise ValueError(f"{CATALOG_FILE} lists no skills")+ return entries++async def _upsert_listing(- entry: StarterSkill, parsed: ParsedSkill, files: list[SkillFile]+ tx: prisma.Prisma,+ entry: CatalogEntry,+ parsed: ParsedSkill,+ files: list[SkillFile],) -> prisma.models.SkillListing:- listing = await prisma.models.SkillListing.prisma().upsert(- where={"slug": entry["slug"]},- data={- "create": {"slug": entry["slug"], "hasApprovedVersion": True},- "update": {"hasApprovedVersion": True, "isDeleted": False},- },- include={"ActiveVersion": True},+ listing = await prisma.models.SkillListing.prisma(tx).find_unique(+ where={"slug": entry["slug"]}, include={"ActiveVersion": True})- version = await _upsert_version(listing, entry, parsed, files)+ if listing is None:+ listing = await prisma.models.SkillListing.prisma(tx).create(+ data={"slug": entry["slug"], "hasApprovedVersion": True},+ include={"ActiveVersion": True},+ )+ else:+ if listing.owningUserId is not None or listing.owningOrgId is not None:+ raise ValueError(+ f"catalog skill '{entry['slug']}' conflicts with an owned listing"+ )+ listing = (+ await prisma.models.SkillListing.prisma(tx).update(+ where={"id": listing.id},+ data={"hasApprovedVersion": True, "isDeleted": False},+ include={"ActiveVersion": True},+ )+ or listing+ )+ version = await _upsert_version(tx, listing, entry, parsed, files)if listing.activeVersionId != version.id:listing = (- await prisma.models.SkillListing.prisma().update(+ await prisma.models.SkillListing.prisma(tx).update(where={"id": listing.id},data={"activeVersionId": version.id},include={"ActiveVersion": True},@@ -406,17 +539,22 @@ async def _upsert_listing(async def _upsert_version(+ tx: prisma.Prisma,listing: prisma.models.SkillListing,- entry: StarterSkill,+ entry: CatalogEntry,parsed: ParsedSkill,files: list[SkillFile],) -> prisma.models.SkillListingVersion:"""Rewrite the listing's live version in place, package and all.- A starter skill is platform-authored, so there is no review to preserve and- no creator waiting on a version history — editing the markdown should change- what installers get, not add a row.+ A catalog skill is platform-authored, so there is no review to preserve+ and no creator waiting on a version history — editing the catalog should+ change what installers get, not add a row."""+ metadata = parsed.extra.get("metadata") or {}+ if not isinstance(metadata, dict):+ metadata = {}+ license_value = parsed.extra.get("license")content: dict = {"name": parsed.name,"description": parsed.description,@@ -425,32 +563,65 @@ async def _upsert_version("categories": entry["categories"],"requiredProviders": entry["required_providers"],"sourceSkillSlug": entry["slug"],+ "sourceRepo": _attribution_value(parsed, metadata, "source"),+ "sourceUrl": _attribution_value(parsed, metadata, "source_url"),+ "license": _optional_str(license_value),"isAvailable": True,"isDeleted": False,"submissionStatus": prisma.enums.SubmissionStatus.APPROVED,}existing = listing.ActiveVersion- # One transaction: an install reads a version's instructions and its package- # together, so neither may become visible without the other.- async with database.transaction() as tx:- if existing is not None:- updated = await prisma.models.SkillListingVersion.prisma(tx).update(- where={"id": existing.id}, data=content- )- if updated is not None:- await snapshot_version_files(updated.id, files, tx)- return updated- created = await prisma.models.SkillListingVersion.prisma(tx).create(- data={**content, "skillListingId": listing.id}+ if existing is not None:+ updated = await prisma.models.SkillListingVersion.prisma(tx).update(+ where={"id": existing.id}, data=content)- await snapshot_version_files(created.id, files, tx)- return created+ if updated is not None:+ await snapshot_version_files(updated.id, files, tx)+ return updated+ created = await prisma.models.SkillListingVersion.prisma(tx).create(+ data={**content, "skillListingId": listing.id}+ )+ await snapshot_version_files(created.id, files, tx)+ return created++def _optional_str(value: object) -> str | None:+ text = str(value).strip() if value is not None else ""+ return text or None-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."""++def _attribution_value(+ parsed: ParsedSkill, metadata: dict[object, object], key: str+) -> str | None:+ return _optional_str(metadata.get(key)) or _optional_str(parsed.extra.get(key))+++def _load(root: Path, entry: CatalogEntry) -> tuple[ParsedSkill, list[SkillFile]]:+ """A catalog skill's SKILL.md and the files beside it, validated as the+ package an installer will receive."""+ slug = entry["slug"]+ directory = root / SKILLS_DIR / slug+ skill_md = directory / "SKILL.md"+ named = f"{SKILLS_DIR}/{slug}/SKILL.md"+ if not skill_md.is_file():+ raise ValueError(f"{named} is missing")+ text = skill_md.read_text(encoding="utf-8")+ parsed = parse_skill_markdown(text)+ if parsed is None:+ raise ValueError(f"{named} is not a valid SKILL.md")+ if parsed.name != slug:+ raise ValueError(+ f"{named} declares name '{parsed.name}'; the frontmatter name is "+ "the installed skill's name and must match the catalog slug"+ )+ validate_skill_content(parsed.description, parsed.body, parsed.triggers)+ files = _package_files(directory)+ validate_package(SkillPackage(skill_md=text, files=files))+ return parsed, files+++def _load_starter(entry: CatalogEntry) -> tuple[ParsedSkill, list[SkillFile]]:+ slug = entry["slug"]directory = _CONTENT_DIR / slugis_package = directory.is_dir()root = directory / "SKILL.md" if is_package else _CONTENT_DIR / f"{slug}.md"@@ -464,6 +635,7 @@ def _load(slug: str) -> tuple[ParsedSkill, list[SkillFile]]:f"{named} declares name '{parsed.name}'; the frontmatter name is ""the installed skill's name and must match the listing slug")+ validate_skill_content(parsed.description, parsed.body, parsed.triggers)files = _package_files(directory) if is_package else []validate_package(SkillPackage(skill_md=text, files=files))return parsed, files@@ -473,21 +645,75 @@ 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),+ files = []+ for path in sorted(directory.rglob("*")):+ relative_path = path.relative_to(directory).as_posix()+ if path.is_symlink():+ raise SkillPackageError(f"file '{relative_path}' may not be a symlink")+ if path.is_file() and path != root:+ files.append(+ SkillFile(+ relative_path=relative_path,+ content=path.read_bytes(),+ is_executable=os.access(path, os.X_OK),+ )+ )+ return files+++def _download_catalog(into: Path) -> Path:+ """Fetch the catalog repo's tarball from GitHub and unpack it under *into*,+ returning the checkout root."""+ repo = os.environ.get("SKILLS_CATALOG_REPO") or DEFAULT_CATALOG_REPO+ ref = os.environ.get("SKILLS_CATALOG_REF") or DEFAULT_CATALOG_REF+ token = os.environ.get("SKILLS_CATALOG_TOKEN") or os.environ.get("GITHUB_TOKEN")+ if not token:+ raise RuntimeError(+ "SKILLS_CATALOG_TOKEN (or GITHUB_TOKEN) is required to download "+ f"{repo}; set SKILLS_CATALOG_PATH to seed from a local checkout")- for path in sorted(directory.rglob("*"))- if path.is_file() and path != root- ]+ logger.info(f"Downloading {repo}@{ref}")+ response = httpx.get(+ f"https://api.github.com/repos/{repo}/tarball/{ref}",+ headers={+ "Authorization": f"Bearer {token}",+ "Accept": "application/vnd.github+json",+ "User-Agent": "autogpt-platform-skill-seed",+ },+ follow_redirects=True,+ timeout=60,+ )+ response.raise_for_status()+ with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:gz") as tar:+ _extract_catalog_archive(tar, into)+ # GitHub wraps the tree in one "<owner>-<repo>-<sha>" directory.+ roots = [p for p in into.iterdir() if p.is_dir()]+ if len(roots) != 1:+ raise RuntimeError(f"unexpected tarball layout for {repo}: {roots}")+ return roots[0]+++def _extract_catalog_archive(archive: tarfile.TarFile, into: Path) -> None:+ """Extract with the data filter, including on Python versions before its backport."""+ if hasattr(tarfile, "data_filter"):+ archive.extractall(into, filter="data")+ return++ root = into.resolve()+ members = archive.getmembers()+ for member in members:+ target = (into / member.name).resolve()+ if not (member.isfile() or member.isdir()) or (+ target != root and root not in target.parents+ ):+ raise RuntimeError(f"unsafe catalog archive member: {member.name}")+ archive.extractall(into, members=members)async def main() -> None:await database.connect()try:- await seed_starter_skills()+ await seed_catalog_skills()finally:await database.disconnect()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.pyindex 117f85dade..e2f16bd6c4 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_seed_test.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_seed_test.py@@ -1,15 +1,32 @@-"""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."""+"""Tests for the catalog loader: a skill is a directory with a SKILL.md and+the files beside it, and a broken one fails the seed rather than the install."""import pathlib+import tarfileimport pytestfrom backend.api.features.store.skill_model import skill_title-from backend.api.features.store.skill_seed import STARTER_SKILLS, _load-from backend.copilot.tools.skills import SkillPackageError+from backend.api.features.store.skill_seed import (+ STARTER_SKILLS,+ CatalogEntry,+ _attribution_value,+ _extract_catalog_archive,+ _load,+ _load_starter,+ load_catalog,+)+from backend.copilot.tools.skills import (+ MAX_BODY_CHARS,+ MAX_DESCRIPTION_CHARS,+ MAX_TRIGGER_CHARS,+ MAX_TRIGGERS,+ ParsedSkill,+ SkillPackageError,+)-SKILL_MD = "---\nname: demo\ndescription: A demo starter.\n---\n\n# Demo\n"+SKILL_MD = "---\nname: demo\ndescription: A demo skill.\n---\n\n# Demo\n"+ENTRY = CatalogEntry(slug="demo", categories=["content"], required_providers=[])def _write(root: pathlib.Path, relative: str, content: str) -> pathlib.Path:@@ -19,62 +36,224 @@ def _write(root: pathlib.Path, relative: str, content: str) -> pathlib.Path: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")+def test_a_skill_loads_its_siblings(tmp_path):+ """A package's resources travel with it, executable bit and all, at the+ paths its SKILL.md references them by."""+ _write(tmp_path, "skills/demo/SKILL.md", SKILL_MD)+ _write(tmp_path, "skills/demo/references/API.md", "# API\n")+ script = _write(tmp_path, "skills/demo/scripts/run.py", "print(1)\n")script.chmod(0o755)- parsed, files = _load("demo")+ parsed, files = _load(tmp_path, ENTRY)- assert parsed.name == "demo"+ assert (parsed.name, parsed.body.strip()) == ("demo", "# 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-):+def test_a_skill_breaking_a_package_rule_fails_the_seed(tmp_path):"""A hidden file would install into the skill folder unseen, so the seedrefuses 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")+ _write(tmp_path, "skills/demo/SKILL.md", SKILL_MD)+ _write(tmp_path, "skills/demo/.env", "SECRET=1\n")with pytest.raises(SkillPackageError):- _load("demo")+ _load(tmp_path, ENTRY)-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"))+def test_a_skill_package_cannot_read_through_a_symlink(tmp_path):+ _write(tmp_path, "skills/demo/SKILL.md", SKILL_MD)+ outside = _write(tmp_path, "outside.txt", "secret\n")+ linked = tmp_path / "skills" / "demo" / "references" / "outside.txt"+ linked.parent.mkdir(parents=True)+ linked.symlink_to(outside)++ with pytest.raises(SkillPackageError, match="may not be a symlink"):+ _load(tmp_path, ENTRY)+++def test_a_skill_whose_frontmatter_name_differs_is_refused(tmp_path):+ """The frontmatter name becomes the installed skill's name, so a mismatch+ would install a skill under a name the marketplace never shows."""+ _write(tmp_path, "skills/demo/SKILL.md", SKILL_MD.replace("demo", "other"))++ with pytest.raises(ValueError, match="must match the catalog slug"):+ _load(tmp_path, ENTRY)+++def test_a_listed_skill_without_a_skill_md_is_refused(tmp_path):+ _write(tmp_path, "skills/demo/references/API.md", "# API\n")++ with pytest.raises(ValueError, match="is missing"):+ _load(tmp_path, ENTRY)+++ ("frontmatter", "body", "message"),+ [+ (+ f"description: {'x' * (MAX_DESCRIPTION_CHARS + 1)}\n",+ "# Demo\n",+ "description is",+ ),+ ("description: A demo skill.\n", "x" * (MAX_BODY_CHARS + 1), "body must"),+ (+ "description: A demo skill.\n"+ f"triggers: {[f't{i}' for i in range(MAX_TRIGGERS + 1)]}\n",+ "# Demo\n",+ "triggers must",+ ),+ (+ "description: A demo skill.\n"+ f"triggers: [{'x' * (MAX_TRIGGER_CHARS + 1)}]\n",+ "# Demo\n",+ "exceeds",+ ),+ ],+)+def test_a_skill_that_cannot_be_installed_is_refused(+ tmp_path, frontmatter: str, body: str, message: str+):+ skill_md = f"---\nname: demo\n{frontmatter}---\n\n{body}"+ _write(tmp_path, "skills/demo/SKILL.md", skill_md)++ with pytest.raises(ValueError, match=message):+ _load(tmp_path, ENTRY)- with pytest.raises(ValueError, match="must match the listing slug"):- _load("demo")+def test_attribution_accepts_top_level_fields_but_prefers_metadata():+ parsed = ParsedSkill(+ name="demo",+ description="Demo",+ body="# Demo\n",+ extra={"source": "top/repo", "source_url": "https://example.com/top"},+ )++ assert _attribution_value(parsed, {"source": "nested/repo"}, "source") == (+ "nested/repo"+ )+ assert _attribution_value(parsed, {}, "source_url") == "https://example.com/top"++[email protected]("entry", STARTER_SKILLS, ids=lambda entry: entry["slug"])+def test_every_checked_in_starter_skill_loads(entry):+ parsed, files = _load_starter(entry)[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 == []+def test_a_starter_that_cannot_be_installed_is_refused(monkeypatch, tmp_path):+ monkeypatch.setattr("backend.api.features.store.skill_seed._CONTENT_DIR", tmp_path)+ _write(+ tmp_path,+ "demo.md",+ SKILL_MD.replace("A demo skill.", "x" * (MAX_DESCRIPTION_CHARS + 1)),+ )++ with pytest.raises(ValueError, match="description is"):+ _load_starter(ENTRY)+++def test_the_catalog_folds_categories_onto_the_canonical_set(tmp_path):+ _write(+ tmp_path,+ "catalog.yml",+ "skills:\n"+ " - slug: demo\n"+ " categories: [writing]\n"+ " required_providers: [google]\n"+ " source: platform\n",+ )++ assert load_catalog(tmp_path) == [+ CatalogEntry(slug="demo", categories=["content"], required_providers=["google"])+ ]+++ "catalog, message",+ [+ ("skills:\n - slug: demo\n categories: [nonsense]\n", "category"),+ (+ "skills:\n - slug: demo\n categories: [sales]\n"+ " - slug: demo\n categories: [sales]\n",+ "listed twice",+ ),+ ("skills: []\n", "lists no skills"),+ ("skills:\n - categories: [sales]\n", "has no slug"),+ (+ "skills:\n - slug: ../demo\n categories: [sales]\n",+ "name must be a slug",+ ),+ (+ "skills:\n - slug: demo\n categories: [sales]\n"+ " required_providers: google\n",+ "required_providers must be a list of strings",+ ),+ (+ "skills:\n - slug: demo\n categories: [sales]\n"+ " required_providers: [google, 1]\n",+ "required_providers must be a list of strings",+ ),+ (+ 'skills:\n - slug: demo\n categories: ""\n',+ "categories must be a list of strings",+ ),+ (+ "skills:\n - slug: demo\n categories: [sales]\n"+ ' required_providers: ""\n',+ "required_providers must be a list of strings",+ ),+ ],+ ids=[+ "unknown-category",+ "duplicate-slug",+ "empty",+ "no-slug",+ "invalid-slug",+ "scalar-provider",+ "mixed-providers",+ "falsey-scalar-categories",+ "falsey-scalar-providers",+ ],+)+def test_a_malformed_catalog_fails_before_anything_is_written(+ tmp_path, catalog: str, message: str+):+ _write(tmp_path, "catalog.yml", catalog)++ with pytest.raises(ValueError, match=message):+ load_catalog(tmp_path)+++def test_archive_fallback_extracts_checked_files(mocker, monkeypatch, tmp_path):+ monkeypatch.delattr(tarfile, "data_filter")+ archive = mocker.Mock()+ member = tarfile.TarInfo("repo/catalog.yml")+ archive.getmembers.return_value = [member]++ _extract_catalog_archive(archive, tmp_path)++ archive.extractall.assert_called_once_with(tmp_path, members=[member])+++def test_archive_fallback_rejects_paths_outside_the_target(+ mocker, monkeypatch, tmp_path+):+ monkeypatch.delattr(tarfile, "data_filter")+ archive = mocker.Mock()+ member = tarfile.TarInfo("../outside")+ archive.getmembers.return_value = [member]++ with pytest.raises(RuntimeError, match="unsafe catalog archive member"):+ _extract_catalog_archive(archive, tmp_path)++ archive.extractall.assert_not_called()++@pytest.mark.parametrize(("slug", "title"),[@@ -87,5 +266,6 @@ def test_every_shipped_starter_still_loads(entry):def test_a_shipped_starter_keeps_the_casing_its_author_wrote(slug, title):"""A starter's frontmatter name is its slug, so a title derived from itreads back as "Seo content brief"."""- parsed, _ = _load(slug)+ entry = next(entry for entry in STARTER_SKILLS if entry["slug"] == slug)+ parsed, _ = _load_starter(entry)assert skill_title(parsed.name, parsed.body) == titlediff --git a/autogpt_platform/backend/backend/api/features/store/skill_submission_db.py b/autogpt_platform/backend/backend/api/features/store/skill_submission_db.pyindex 432dac7bb3..b7969cb37c 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_submission_db.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_submission_db.py@@ -26,6 +26,8 @@ from backend.util.exceptions import NotFoundError, PreconditionFailedfrom . import skill_db, skill_model+_MAX_LICENSE_CHARS = 256+async def submit_skill(user_id: str, request: skill_model.SkillSubmissionRequest@@ -65,6 +67,7 @@ async def submit_skill("categories": request.categories,"requiredProviders": request.required_providers,"sourceSkillSlug": slug,+ "license": _license_of(skill),"changesSummary": request.changes_summary or "Initial submission","submissionStatus": prisma.enums.SubmissionStatus.PENDING,"submittedAt": datetime.datetime.now(datetime.timezone.utc),@@ -125,6 +128,7 @@ async def edit_skill_submission("triggers": list(skill.triggers),"categories": request.categories,"requiredProviders": request.required_providers,+ "license": _license_of(skill),"changesSummary": request.changes_summary or version.changesSummary,},)@@ -134,6 +138,18 @@ async def edit_skill_submission(return skill_model.SkillSubmission.from_db(updated, listing)+def _license_of(skill: ParsedSkill) -> str | None:+ value = skill.extra.get("license")+ if value is None:+ return None+ if not isinstance(value, str):+ raise ValueError("license must be a string")+ license_name = value.strip()+ if len(license_name) > _MAX_LICENSE_CHARS:+ raise ValueError(f"license must be ≤{_MAX_LICENSE_CHARS} chars")+ return license_name or None++async def review_skill_submission(skill_listing_version_id: str,*,diff --git a/autogpt_platform/backend/backend/api/features/store/skill_submission_db_test.py b/autogpt_platform/backend/backend/api/features/store/skill_submission_db_test.pyindex 7a192232b2..6b451f5668 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_submission_db_test.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_submission_db_test.py@@ -23,6 +23,15 @@ LIBRARY_SKILL = ParsedSkill()+def _package(+ skill: ParsedSkill | None, files: list[SkillFile] | None = None+) -> SkillPackage | None:+ """What the library hands a submission: the rendered SKILL.md plus siblings."""+ if skill is None:+ return None+ return SkillPackage(skill_md=render_skill_markdown(skill), files=files or [])++def _library_package(files: list[SkillFile] | None = None) -> SkillPackage:return SkillPackage(skill_md=render_skill_markdown(LIBRARY_SKILL), files=files or []@@ -102,6 +111,45 @@ async def test_publishing_without_a_marketplace_profile_is_refused(setup_test_usassert await prisma.models.SkillListing.prisma().count() == 0+async def test_publishing_and_editing_snapshot_the_skill_license(creator, mocker):+ package = mocker.patch.object(+ skill_submission_db,+ "read_user_skill_package",+ return_value=_package(+ ParsedSkill(+ name=LIBRARY_SKILL.name,+ description=LIBRARY_SKILL.description,+ body=LIBRARY_SKILL.body,+ triggers=LIBRARY_SKILL.triggers,+ extra={"license": "MIT"},+ )+ ),+ )+ submission = await skill_submission_db.submit_skill(creator, _request())+ created = await prisma.models.SkillListingVersion.prisma().find_unique(+ where={"id": submission.skill_listing_version_id}+ )+ assert created is not None and created.license == "MIT"++ package.return_value = _package(+ ParsedSkill(+ name=LIBRARY_SKILL.name,+ description=LIBRARY_SKILL.description,+ body=LIBRARY_SKILL.body,+ triggers=LIBRARY_SKILL.triggers,+ extra={"license": "Apache-2.0"},+ )+ )+ await skill_submission_db.edit_skill_submission(+ creator, submission.skill_listing_version_id, _request()+ )++ updated = await prisma.models.SkillListingVersion.prisma().find_unique(+ where={"id": submission.skill_listing_version_id}+ )+ assert updated is not None and updated.license == "Apache-2.0"++async def test_publishing_a_skill_that_is_not_in_the_library_is_refused(creator, mocker):diff --git a/autogpt_platform/backend/backend/api/features/store/skill_submission_db_unit_test.py b/autogpt_platform/backend/backend/api/features/store/skill_submission_db_unit_test.pynew file mode 100644index 0000000000..93ce6c0b3b--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/store/skill_submission_db_unit_test.py@@ -0,0 +1,29 @@+import pytest++from backend.copilot.tools.skills import ParsedSkill++from .skill_submission_db import _MAX_LICENSE_CHARS, _license_of+++def _skill_with_license(value: object) -> ParsedSkill:+ return ParsedSkill(+ name="demo",+ description="Demo",+ body="# Demo\n",+ extra={"license": value},+ )+++def test_license_is_trimmed():+ assert _license_of(_skill_with_license(" Apache-2.0 ")) == "Apache-2.0"++[email protected]("value", [{"name": "MIT"}, ["MIT"], 1])+def test_license_must_be_text(value: object):+ with pytest.raises(ValueError, match="license must be a string"):+ _license_of(_skill_with_license(value))+++def test_license_length_is_bounded():+ with pytest.raises(ValueError, match=f"license must be ≤{_MAX_LICENSE_CHARS}"):+ _license_of(_skill_with_license("x" * (_MAX_LICENSE_CHARS + 1)))diff --git a/autogpt_platform/backend/backend/copilot/tools/skills.py b/autogpt_platform/backend/backend/copilot/tools/skills.pyindex 47d926b371..4ced28f5df 100644--- a/autogpt_platform/backend/backend/copilot/tools/skills.py+++ b/autogpt_platform/backend/backend/copilot/tools/skills.py@@ -196,9 +196,16 @@ _DEFAULT_SKILLS_BY_NAME: dict[str, _DefaultSkill] = {s.name: s for s in DEFAULT__FRONTMATTER_RE = re.compile(r"^---\n(.*?)\n---\n?(.*)$", re.DOTALL)-# Spec frontmatter the platform has no use for. Dropping it rewrites the-# author's SKILL.md on every store, so it rides through parse and render.-_CARRIED_FRONTMATTER_KEYS = ("license", "compatibility", "allowed-tools", "metadata")+# Frontmatter outside the core skill fields. Dropping it rewrites the author's+# SKILL.md on every store, so it rides through parse and render.+_CARRIED_FRONTMATTER_KEYS = (+ "license",+ "compatibility",+ "allowed-tools",+ "metadata",+ "source",+ "source_url",+)@dataclass(frozen=True)@@ -281,6 +288,37 @@ def _validate_name(name: str) -> str | None:return None+def validate_skill_content(+ description: str, body: str, triggers: Iterable[str]+) -> None:+ trigger_list = list(triggers)+ if not description:+ raise ValueError("description is required")+ if len(description) > MAX_DESCRIPTION_CHARS:+ raise ValueError(+ f"description is {len(description)}/{MAX_DESCRIPTION_CHARS} chars "+ f"— trim {len(description) - MAX_DESCRIPTION_CHARS} "+ "(it appears in every turn's skills index)"+ )+ if not body:+ raise ValueError("body is required")+ if len(body) > MAX_BODY_CHARS:+ raise ValueError(f"body must be ≤{MAX_BODY_CHARS} chars")+ if len(trigger_list) > MAX_TRIGGERS:+ raise ValueError(+ f"triggers must be ≤{MAX_TRIGGERS} entries "+ "(they are inlined in <available_skills> every turn)"+ )+ oversized_trigger = next(+ (trigger for trigger in trigger_list if len(trigger) > MAX_TRIGGER_CHARS),+ None,+ )+ if oversized_trigger is not None:+ raise ValueError(+ f"trigger '{oversized_trigger[:32]}…' exceeds {MAX_TRIGGER_CHARS} chars"+ )++# ---------------------------------------------------------------------------# Workspace registry — read/write/delete user skills as folders under# ``/skills/{slug}/SKILL.md``. We construct a *session-less*@@ -662,28 +700,7 @@ async def store_user_skill(name_err = _validate_name(name)if name_err:raise ValueError(name_err)- if not description:- raise ValueError("description is required")- if len(description) > MAX_DESCRIPTION_CHARS:- raise ValueError(- f"description is {len(description)}/{MAX_DESCRIPTION_CHARS} chars "- f"— trim {len(description) - MAX_DESCRIPTION_CHARS} "- "(it appears in every turn's skills index)"- )- if not body:- raise ValueError("body is required")- if len(body) > MAX_BODY_CHARS:- raise ValueError(f"body must be ≤{MAX_BODY_CHARS} chars")- if len(triggers) > MAX_TRIGGERS:- raise ValueError(- f"triggers must be ≤{MAX_TRIGGERS} entries "- "(they are inlined in <available_skills> every turn)"- )- oversized_trigger = next((t for t in triggers if len(t) > MAX_TRIGGER_CHARS), None)- if oversized_trigger is not None:- raise ValueError(- f"trigger '{oversized_trigger[:32]}…' exceeds {MAX_TRIGGER_CHARS} chars"- )+ validate_skill_content(description, body, triggers)parsed = ParsedSkill(name=name,diff --git a/autogpt_platform/backend/backend/copilot/tools/skills_test.py b/autogpt_platform/backend/backend/copilot/tools/skills_test.pyindex 14f0e35712..a071b44023 100644--- a/autogpt_platform/backend/backend/copilot/tools/skills_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/skills_test.py@@ -1818,7 +1818,7 @@ def test_upstream_frontmatter_survives_a_round_trip(slug):assert render_skill_markdown(reparsed) == rendered-def test_every_spec_frontmatter_field_is_carried():+def test_carried_frontmatter_fields_survive_a_round_trip():raw = ("---\n""name: kitchen-sink\n"@@ -1830,6 +1830,8 @@ def test_every_spec_frontmatter_field_is_carried():" - Read\n""metadata:\n"" author: someone\n"+ "source: owner/repo\n"+ "source_url: https://github.com/owner/repo/tree/abc/skills/kitchen-sink\n""---\n""body\n")@@ -1840,6 +1842,8 @@ def test_every_spec_frontmatter_field_is_carried():"compatibility": "claude-code >=2.0","allowed-tools": ["Bash", "Read"],"metadata": {"author": "someone"},+ "source": "owner/repo",+ "source_url": "https://github.com/owner/repo/tree/abc/skills/kitchen-sink",}assert parse_skill_markdown(render_skill_markdown(parsed)).extra == parsed.extradiff --git a/autogpt_platform/backend/migrations/20260915190000_add_skill_listing_files/migration.sql b/autogpt_platform/backend/migrations/20260915190000_add_skill_listing_files/migration.sqlnew file mode 100644index 0000000000..61d80ad760--- /dev/null+++ b/autogpt_platform/backend/migrations/20260915190000_add_skill_listing_files/migration.sql@@ -0,0 +1,4 @@+-- AlterTable+ALTER TABLE "SkillListingVersion" ADD COLUMN "license" TEXT,+ADD COLUMN "sourceRepo" TEXT,+ADD COLUMN "sourceUrl" TEXT;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex 2e193b5526..cffc04a818 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -2288,6 +2288,12 @@ model SkillListingVersion {// re-publish can find its listing again. Null once that skill is deleted.sourceSkillSlug String?+ // Where a vendored skill came from, shown as attribution on the card. Null+ // for a creator's own skill and for one the platform wrote itself.+ sourceRepo String?+ sourceUrl String?+ license String?+isDeleted Boolean @default(false)isAvailable Boolean @default(true)diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsxindex 6127203581..fc1124c98b 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsx@@ -191,6 +191,32 @@ describe("Marketplace SkillsSection", () => {expect(brand.textContent).not.toContain("Works with");});+ test("credits the repo a vendored skill came from, and nothing for our own", async () => {+ const coldEmail: MarketplaceSkill = {+ ...outreach,+ slug: "cold-email",+ name: "cold-email",+ title: "Cold email",+ source_repo: "coreyhaines31/marketingskills",+ source_url:+ "https://github.com/coreyhaines31/marketingskills/tree/abc/skills/cold-email",+ license: "MIT",+ };+ server.use(listing([brandVoice, coldEmail]));++ render(<MainMarkeplacePage />);++ await screen.findAllByTestId("skill-card", undefined, { timeout: 10000 });+ const vendored = await screen.findByRole("link", { name: /Cold email/ });+ expect(vendored.textContent).toContain(+ "From coreyhaines31/marketingskills",+ );+ const own = await screen.findByRole("link", {+ name: /Brand voice guide/,+ });+ expect(own.textContent).not.toContain("From ");+ });+test("marks a skill the user already has as Added", async () => {server.use(listing([brandVoice, outreach]),diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/components/SkillCard.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/components/SkillCard.tsxindex 21c204c5db..afcecb89c7 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/components/SkillCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/components/SkillCard.tsx@@ -83,6 +83,12 @@ export function SkillCard({ skill, isInstalled }: Props) {</Avatar>by {skill.creator ?? "AutoGPT"}</span>+ {skill.source_repo ? (+ <span className="inline-flex items-center gap-1.5">+ <span aria-hidden>·</span>+ From {skill.source_repo}+ </span>+ ) : null}{providers.length > 0 ? (<span className="inline-flex items-center gap-1.5"><span aria-hidden>·</span>diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/main.test.tsxindex 30db260d33..0c80d74886 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/main.test.tsx@@ -141,6 +141,45 @@ describe("Marketplace skill page", () => {).toHaveLength(1);});+ test("links a vendored skill to its source and shows its license", async () => {+ server.use(+ getGetV2GetMarketplaceSkillMockHandler200({+ ...outreach,+ source_repo: "coreyhaines31/marketingskills",+ source_url:+ "https://github.com/coreyhaines31/marketingskills/tree/abc/skills/cold-email",+ license: "MIT",+ }),+ getGetV1ListCredentialsMockHandler200([]),+ userSkillsHandler(),+ );+ render(<SkillPage slug="outreach-playbook" />);++ const source = await screen.findByRole("link", {+ name: "coreyhaines31/marketingskills",+ });+ expect(source.getAttribute("href")).toBe(+ "https://github.com/coreyhaines31/marketingskills/tree/abc/skills/cold-email",+ );+ expect(await screen.findByText("License: MIT")).toBeDefined();+ });++ test("shows a creator skill license without a source repo", async () => {+ server.use(+ getGetV2GetMarketplaceSkillMockHandler200({+ ...outreach,+ source_repo: null,+ source_url: null,+ license: "Proprietary",+ }),+ getGetV1ListCredentialsMockHandler200([]),+ userSkillsHandler(),+ );+ render(<SkillPage slug="outreach-playbook" />);++ expect(await screen.findByText("License: Proprietary")).toBeDefined();+ });+test("installs in one click and offers the connect step afterwards", async () => {renderPage([]);diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsxindex 2317718b77..5934fdc9ec 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsx@@ -159,6 +159,32 @@ export function SkillPage({ slug }: Props) {<span>Updated {formatTimeAgo(String(skill.updated_at))}</span></>) : null}+ {skill.source_repo ? (+ <>+ <span aria-hidden>·</span>+ <span>+ From{" "}+ {skill.source_url ? (+ <a+ href={skill.source_url}+ target="_blank"+ rel="noreferrer"+ className="underline decoration-zinc-300 underline-offset-2 hover:text-zinc-900"+ >+ {skill.source_repo}+ </a>+ ) : (+ skill.source_repo+ )}+ </span>+ </>+ ) : null}+ {skill.license ? (+ <>+ <span aria-hidden>·</span>+ <span>License: {skill.license}</span>+ </>+ ) : null}{providers.length > 0 ? (<><span aria-hidden>·</span>diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 6a358376e1..c36699ed23 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -25321,6 +25321,19 @@"creator_avatar": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Creator Avatar"+ },+ "source_repo": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Source Repo",+ "description": "GitHub repo a vendored skill was taken from, as owner/name."+ },+ "source_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Source Url"+ },+ "license": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "License"}},"type": "object",@@ -25360,6 +25373,19 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Creator Avatar"},+ "source_repo": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Source Repo",+ "description": "GitHub repo a vendored skill was taken from, as owner/name."+ },+ "source_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Source Url"+ },+ "license": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "License"+ },"skill_listing_version_id": {"type": "string","title": "Skill Listing Version Id"