Skip to content

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(backend): publish and install a skill as its whole package (#14557)

Reinier van der Leer86ccc051c643
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9d656e5a15..d8ae4c8b31 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -192,6 +192,11 @@ repos:
alias: isort-platform-backend
entry: poetry -P autogpt_platform/backend run isort -p backend
files: ^autogpt_platform/backend/
+ # Vendored upstream packages are test data compared byte for byte
+ # against what the code stored; sorting their imports rewrites the
+ # fixture. isort's own skip settings do not reach a file named on the
+ # command line, which is how this hook invokes it.
+ exclude: ^autogpt_platform/backend/test/fixtures/
types: [file, python]
language: system
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_db.py b/autogpt_platform/backend/backend/api/features/store/skill_db.py
index fc038bf3a2..d7c065701a 100644
--- a/autogpt_platform/backend/backend/api/features/store/skill_db.py
+++ b/autogpt_platform/backend/backend/api/features/store/skill_db.py
@@ -13,7 +13,8 @@ import prisma.enums
import prisma.models
import prisma.types
-from backend.copilot.tools.skills import list_user_skills, store_user_skill
+from backend.copilot.tools.skills import SkillFile, list_user_skills, store_user_skill
+from backend.data.db import query_raw_with_schema
from backend.util.exceptions import NotFoundError
from backend.util.models import Pagination
@@ -58,7 +59,10 @@ async def get_marketplace_skills(
async def get_marketplace_skill(slug: str) -> skill_model.MarketplaceSkillDetails:
listing = await _find_live_listing(slug)
- return skill_model.MarketplaceSkillDetails.from_db(listing)
+ version = skill_model.active_version(listing)
+ return skill_model.MarketplaceSkillDetails.from_db(
+ listing, files=await _list_version_file_meta(version.id)
+ )
async def get_live_skills(
@@ -80,7 +84,7 @@ async def get_live_skills(
async def install_marketplace_skill(
user_id: str, slug: str, *, expert_id: str | None = None
) -> skill_model.InstalledSkill:
- """Copy a listing's SKILL.md into *expert_id*'s skill folder, or the
+ """Copy a listing's whole package into *expert_id*'s skill folder, or the
caller's own library when ``None``.
The listing's slug becomes the installed skill's name, so an install is
@@ -99,6 +103,9 @@ async def install_marketplace_skill(
body=active.body,
triggers=list(active.triggers),
version=str(active.version),
+ # `[]`, 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),
expert_id=expert_id,
)
if is_new:
@@ -110,6 +117,39 @@ async def install_marketplace_skill(
)
+async def _read_version_files(skill_listing_version_id: str) -> list[SkillFile]:
+ """The published package's files, contents included, ready to install."""
+ rows = await prisma.models.SkillListingFile.prisma().find_many(
+ where={"skillListingVersionId": skill_listing_version_id},
+ order={"relativePath": "asc"},
+ )
+ return [
+ SkillFile(
+ relative_path=row.relativePath,
+ content=row.content.decode(),
+ is_executable=row.isExecutable,
+ )
+ for row in rows
+ ]
+
+
+async def _list_version_file_meta(
+ skill_listing_version_id: str,
+) -> list[skill_model.SkillPackageFile]:
+ """Path and size per file, without the bytes.
+
+ Raw because prisma-client-py always selects every column, and a detail
+ page that pulled `content` would carry the whole package per request.
+ """
+ return await query_raw_with_schema(
+ 'SELECT "relativePath" AS path, "sizeBytes" AS size_bytes '
+ 'FROM {schema_prefix}"SkillListingFile" '
+ 'WHERE "skillListingVersionId" = $1 ORDER BY "relativePath"',
+ skill_listing_version_id,
+ model=skill_model.SkillPackageFile,
+ )
+
+
async def _find_live_listing(slug: str) -> prisma.models.SkillListing:
listing = await prisma.models.SkillListing.prisma().find_first(
where=_live_listing_where({"slug": slug}), include=_LISTING_INCLUDE
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.py
index 23bd428d05..6dc8884201 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
@@ -2,6 +2,7 @@ import datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
+import prisma
import prisma.enums
import prisma.models
import pytest
@@ -63,8 +64,13 @@ async def _make_listing(
@pytest.fixture(autouse=True)
async def clean_skill_listings(server: SpinTestServer):
- await prisma.models.SkillListingVersion.prisma().delete_many()
- await prisma.models.SkillListing.prisma().delete_many()
+ # These tests assert on the WHOLE marketplace, so they need the listing
+ # table to themselves — take it only when empty, never by emptying it.
+ if await prisma.models.SkillListing.prisma().count():
+ pytest.fail(
+ "this database already holds skill listings; run this file against a "
+ "throwaway Postgres, not the one every worktree here shares"
+ )
yield
await prisma.models.SkillListingVersion.prisma().delete_many()
await prisma.models.SkillListing.prisma().delete_many()
@@ -252,6 +258,70 @@ async def test_install_writes_into_the_target_owners_folder_and_no_other(
)
+async def test_install_of_a_listing_with_no_files_passes_an_empty_package(mocker):
+ """`files=None` means "leave the folder alone", so a single-file listing
+ installed over a package would leave the old package's files in place."""
+ listing = await _make_listing("no-files-one")
+ stored = mocker.patch.object(skill_db, "store_user_skill")
+ mocker.patch.object(skill_db, "list_user_skills", return_value=[])
+
+ await skill_db.install_marketplace_skill("user-1", listing.slug)
+
+ assert stored.await_args.kwargs["files"] == []
+
+
+async def test_install_carries_the_versions_files_and_their_executable_bits(mocker):
+ listing = await _make_listing("with-files-one")
+ assert listing.activeVersionId is not None
+ await prisma.models.SkillListingFile.prisma().create_many(
+ data=[
+ {
+ "skillListingVersionId": listing.activeVersionId,
+ "relativePath": "scripts/run.py",
+ "sizeBytes": 5,
+ "sha256": "x",
+ "isExecutable": True,
+ "content": prisma.Base64.encode(b"print"),
+ },
+ {
+ "skillListingVersionId": listing.activeVersionId,
+ "relativePath": "references/a.md",
+ "sizeBytes": 3,
+ "sha256": "y",
+ "content": prisma.Base64.encode(b"ref"),
+ },
+ ]
+ )
+ stored = mocker.patch.object(skill_db, "store_user_skill")
+ mocker.patch.object(skill_db, "list_user_skills", return_value=[])
+
+ await skill_db.install_marketplace_skill("user-1", listing.slug)
+
+ files = stored.await_args.kwargs["files"]
+ assert [(f.relative_path, f.content, f.is_executable) for f in files] == [
+ ("references/a.md", b"ref", False),
+ ("scripts/run.py", b"print", True),
+ ]
+
+
+async def test_detail_lists_the_package_files_without_their_bytes(mocker):
+ listing = await _make_listing("detail-files-one")
+ assert listing.activeVersionId is not None
+ await prisma.models.SkillListingFile.prisma().create(
+ data={
+ "skillListingVersionId": listing.activeVersionId,
+ "relativePath": "scripts/run.py",
+ "sizeBytes": 5,
+ "sha256": "x",
+ "content": prisma.Base64.encode(b"print"),
+ }
+ )
+
+ detail = await skill_db.get_marketplace_skill("detail-files-one")
+
+ assert [(f.path, f.size_bytes) for f in detail.files] == [("scripts/run.py", 5)]
+
+
async def test_reinstalling_stores_again_but_does_not_count_again(mocker):
listing = await _make_listing("install-twice", body="# do this\n")
stored = mocker.patch.object(skill_db, "store_user_skill")
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_model.py b/autogpt_platform/backend/backend/api/features/store/skill_model.py
index c929aa9ef7..5ad92455ee 100644
--- a/autogpt_platform/backend/backend/api/features/store/skill_model.py
+++ b/autogpt_platform/backend/backend/api/features/store/skill_model.py
@@ -1,9 +1,10 @@
"""API models for marketplace skill listings.
A skill listing publishes a ``SKILL.md`` — instructions and examples the
-copilot reads — rather than a runnable graph. The listing's ``slug`` is both
-its marketplace URL segment and the name the skill takes once installed, so
-the two can never drift; ``name`` is the human title shown on the card.
+copilot reads — and the files beside it, rather than a runnable graph. The
+listing's ``slug`` is both its marketplace URL segment and the name the skill
+takes once installed, so the two can never drift; ``name`` is the human title
+shown on the card.
"""
import datetime
@@ -48,14 +49,27 @@ class MarketplaceSkillsResponse(pydantic.BaseModel):
pagination: Pagination
+class SkillPackageFile(pydantic.BaseModel):
+ """One file beside the published ``SKILL.md``, by its path relative to the
+ skill folder. The contents are not inlined — a package runs to 20 MiB."""
+
+ path: str
+ size_bytes: int
+
+
class MarketplaceSkillDetails(MarketplaceSkill):
skill_listing_version_id: str
body: str
triggers: list[str]
updated_at: datetime.datetime
+ files: list[SkillPackageFile] = []
@classmethod
- def from_db(cls, listing: prisma.models.SkillListing) -> "MarketplaceSkillDetails":
+ def from_db(
+ cls,
+ listing: prisma.models.SkillListing,
+ files: list[SkillPackageFile] | None = None,
+ ) -> "MarketplaceSkillDetails":
version = active_version(listing)
summary = MarketplaceSkill.from_db(listing)
return cls(
@@ -64,6 +78,7 @@ class MarketplaceSkillDetails(MarketplaceSkill):
body=version.body,
triggers=list(version.triggers),
updated_at=version.updatedAt,
+ files=files or [],
)
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.py
new file mode 100644
index 0000000000..ab96580d3e
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/skill_package_test.py
@@ -0,0 +1,379 @@
+"""The marketplace round trip for a whole skill package.
+
+Publishing snapshots the creator's tree into the version, installing writes it
+back, and the copilot then finds the files where its own read tool looks. The
+fixture is a real published package rather than a hand-made one, because the
+shapes that break this are the ones nobody would invent: a nested directory, a
+licence file at the root, and a script that has to stay executable.
+"""
+
+import hashlib
+import os
+from pathlib import Path
+from unittest.mock import AsyncMock, patch
+
+import prisma.models
+import pytest
+
+from backend.copilot.context import set_execution_context
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.skills import (
+ ReadSkillResponse,
+ ReadSkillTool,
+ SkillFile,
+ list_user_skill_files,
+ parse_skill_markdown,
+ store_user_skill,
+)
+from backend.copilot.tools.workspace_files import (
+ ReadWorkspaceFileTool,
+ WorkspaceFileContentResponse,
+)
+from backend.util.test import SpinTestServer
+
+from . import skill_db, skill_model, skill_seed, skill_submission_db
+
+FIXTURE_DIR = (
+ Path(__file__).parents[4] / "test" / "fixtures" / "skills" / "webapp-testing"
+)
+SLUG = "webapp-testing"
+STARTER_SLUG = "starter-with-a-package"
+
+
+def _fixture_files() -> list[SkillFile]:
+ """The vendored package's siblings, with the executable bit git preserved.
+
+ ``README.md`` is ours, naming the upstream commit; it is not part of the
+ package.
+ """
+ return [
+ SkillFile(
+ relative_path=str(path.relative_to(FIXTURE_DIR)),
+ content=path.read_bytes(),
+ is_executable=bool(path.stat().st_mode & 0o111),
+ )
+ for path in sorted(FIXTURE_DIR.rglob("*"))
+ if path.is_file() and path.name not in {"SKILL.md", "README.md"}
+ ]
+
+
+def test_the_fixture_still_carries_one_executable_script():
+ """A checkout that lost the mode bit would leave every assertion below
+ passing while proving nothing about executables."""
+ executable = [f.relative_path for f in _fixture_files() if f.is_executable]
+
+ assert executable == ["scripts/with_server.py"]
+
+
+async def _store_library_package(user_id: str, files: list[SkillFile]) -> None:
+ parsed = parse_skill_markdown(
+ (FIXTURE_DIR / "SKILL.md").read_text(encoding="utf-8"), fallback_name=SLUG
+ )
+ assert parsed is not None
+ await store_user_skill(
+ user_id,
+ name=SLUG,
+ description=parsed.description,
+ body=parsed.body,
+ triggers=list(parsed.triggers),
+ extra=parsed.extra,
+ files=files,
+ )
+
+
+async def _publish(user_id: str, reviewer_id: str) -> skill_model.SkillSubmission:
+ submission = await skill_submission_db.submit_skill(
+ user_id,
+ skill_model.SkillSubmissionRequest(skill_name=SLUG, categories=["content"]),
+ )
+ return await skill_submission_db.review_skill_submission(
+ submission.skill_listing_version_id,
+ is_approved=True,
+ reviewer_id=reviewer_id,
+ comments="ok",
+ )
+
+
+async def creator(setup_test_user, server: SpinTestServer):
+ await _drop_our_listings()
+ await prisma.models.Profile.prisma().upsert(
+ where={"userId": setup_test_user},
+ data={
+ "create": {
+ "userId": setup_test_user,
+ "username": "package-creator",
+ "name": "Package Creator",
+ "description": "",
+ "links": [],
+ },
+ "update": {},
+ },
+ )
+ yield setup_test_user
+ # Left behind, these rows fail the emptiness guard in the suites that sort
+ # after this one.
+ await _drop_our_listings()
+
+
+async def _drop_our_listings() -> None:
+ """By slug, not wholesale: this table is shared with every other checkout
+ here, where the starter listings are real rows."""
+ await prisma.models.SkillListingVersion.prisma().delete_many(
+ where={"SkillListing": {"is": {"slug": {"in": [SLUG, STARTER_SLUG]}}}}
+ )
+ await prisma.models.SkillListing.prisma().delete_many(
+ where={"slug": {"in": [SLUG, STARTER_SLUG]}}
+ )
+
+
+async def expert(creator: str) -> str:
+ """A real row, because the workspace scope an expert session runs under is
+ resolved from it and fails closed when it is missing."""
+ row = await prisma.models.Expert.prisma().create(
+ data={
+ "ownerUserId": creator,
+ "name": "Nova",
+ "role": "",
+ "identity": "I'm Nova, raised by you.",
+ }
+ )
+ return row.id
+
+
[email protected](autouse=True)
+def skills_enabled():
+ with patch(
+ "backend.copilot.tools.skills.is_skills_feature_enabled",
+ new=AsyncMock(return_value=True),
+ ):
+ yield
+ # The context var outlives the test and would scope the next one's reads.
+ set_execution_context(None, None)
+
+
+async def test_a_published_package_survives_install_into_an_expert(
+ creator: str, expert: str, setup_admin_user: str
+):
+ files = _fixture_files()
+ await _store_library_package(creator, files)
+
+ await _publish(creator, setup_admin_user)
+ await skill_db.install_marketplace_skill(creator, SLUG, expert_id=expert)
+
+ session = ChatSession.new(creator, dry_run=False, expert_id=expert)
+ # The workspace scope comes from the executing turn, never from a tool
+ # argument, so the read tools see nothing without one.
+ set_execution_context(creator, session)
+ read = await ReadSkillTool()._execute(user_id=creator, session=session, name=SLUG)
+ assert isinstance(read, ReadSkillResponse), read.message
+ assert len(read.files) == len(files) == 5
+ assert read.package_dir is not None
+
+ # The path read_skill advertises is the one read_workspace_file must find.
+ script = f"/experts/{expert}/skills/{SLUG}/scripts/with_server.py"
+ assert script in {f.path for f in read.files}
+ content = await ReadWorkspaceFileTool()._execute(
+ user_id=creator, session=session, path=script
+ )
+ assert isinstance(content, WorkspaceFileContentResponse), content.message
+
+ source = FIXTURE_DIR / "scripts" / "with_server.py"
+ materialised = os.path.join(read.package_dir, "scripts", "with_server.py")
+ with open(materialised, "rb") as handle:
+ assert handle.read() == source.read_bytes()
+ assert os.stat(materialised).st_mode & 0o111
+
+
+async def test_the_version_keeps_its_own_bytes_when_the_library_copy_changes(
+ creator: str, setup_admin_user: str
+):
+ await _store_library_package(creator, _fixture_files())
+ published = await _publish(creator, setup_admin_user)
+
+ await _store_library_package(
+ creator,
+ [SkillFile(relative_path="references/notes.md", content=b"rewritten")],
+ )
+
+ rows = await prisma.models.SkillListingFile.prisma().find_many(
+ where={"skillListingVersionId": published.skill_listing_version_id}
+ )
+ # Sorted here rather than in the query: Postgres orders by its own
+ # collation, which puts `examples/` before `LICENSE.txt`.
+ assert sorted(row.relativePath for row in rows) == [
+ "LICENSE.txt",
+ "examples/console_logging.py",
+ "examples/element_discovery.py",
+ "examples/static_html_automation.py",
+ "scripts/with_server.py",
+ ]
+ script = next(r for r in rows if r.relativePath == "scripts/with_server.py")
+ source = (FIXTURE_DIR / "scripts" / "with_server.py").read_bytes()
+ assert script.content.decode() == source
+ assert script.sha256 == hashlib.sha256(source).hexdigest()
+ assert script.sizeBytes == len(source)
+ assert script.mimeType == "text/x-python"
+ assert script.isExecutable is True
+ assert [r.isExecutable for r in rows].count(True) == 1
+
+
+# Both re-install tests install into an EXPERT, never the library: the library
+# folder is where the creator's own skill lives, so re-storing it there would
+# remove the sibling by itself and the assertion would hold with the install
+# doing nothing.
+async def test_installing_a_newer_version_drops_a_sibling_the_old_one_had(
+ creator: str, expert: str, setup_admin_user: str
+):
+ await _store_library_package(creator, _fixture_files())
+ await _publish(creator, setup_admin_user)
+ await skill_db.install_marketplace_skill(creator, SLUG, expert_id=expert)
+
+ await _store_library_package(
+ creator, [f for f in _fixture_files() if f.relative_path != "LICENSE.txt"]
+ )
+ await _publish(creator, setup_admin_user)
+ await skill_db.install_marketplace_skill(creator, SLUG, expert_id=expert)
+
+ installed = {
+ f.path for f in await list_user_skill_files(creator, SLUG, expert_id=expert)
+ }
+ folder = f"/experts/{expert}/skills/{SLUG}"
+ assert f"{folder}/LICENSE.txt" not in installed
+ assert f"{folder}/scripts/with_server.py" in installed
+
+
+async def test_installing_a_single_file_listing_clears_a_package_left_behind(
+ creator: str, expert: str, setup_admin_user: str
+):
+ """A version with no file rows is a single-file skill, so its install must
+ pass an empty package rather than "leave the folder alone"."""
+ await _store_library_package(creator, _fixture_files())
+ await _publish(creator, setup_admin_user)
+ await skill_db.install_marketplace_skill(creator, SLUG, expert_id=expert)
+
+ await _store_library_package(creator, [])
+ await _publish(creator, setup_admin_user)
+ await skill_db.install_marketplace_skill(creator, SLUG, expert_id=expert)
+
+ 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
+):
+ """The seed is the other writer of a listing version, and a starter whose
+ package never reached the shelf would install as a bare SKILL.md."""
+ directory = tmp_path / STARTER_SLUG
+ (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)
+
+ rows = await _starter_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)
+ }
+ assert f"/experts/{expert}/skills/{STARTER_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
+):
+ """The seed rewrites its version in place, so the package has to be
+ replaced 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 / "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()
+ # 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"]
+
+ (directory / "notes.md").unlink()
+ await skill_seed.seed_starter_skills()
+
+ assert await _starter_file_rows() == []
+
+
+async def test_a_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 package
+ write cannot leave new instructions on the shelf beside the old package."""
+ directory = tmp_path / STARTER_SLUG
+ directory.mkdir()
+ 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()
+
+ root.write_text(
+ f"---\nname: {STARTER_SLUG}\ndescription: Ships a note.\n---\n\n# Second\n",
+ encoding="utf-8",
+ )
+
+ async def fails(*_args, **_kwargs):
+ raise RuntimeError("the package write failed")
+
+ monkeypatch.setattr(skill_seed, "snapshot_version_files", fails)
+ with pytest.raises(RuntimeError):
+ await skill_seed.seed_starter_skills()
+
+ listing = await prisma.models.SkillListing.prisma().find_unique(
+ where={"slug": STARTER_SLUG}, include={"ActiveVersion": True}
+ )
+ assert listing is not None and listing.ActiveVersion is not None
+ assert listing.ActiveVersion.body.strip() == "# First"
+ assert [r.relativePath for r in await _starter_file_rows()] == ["notes.md"]
+
+
+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."""
+ listing = await prisma.models.SkillListing.prisma().find_unique(
+ where={"slug": STARTER_SLUG}
+ )
+ assert listing is not None and listing.activeVersionId is not None
+ return await prisma.models.SkillListingFile.prisma().find_many(
+ where={"skillListingVersionId": listing.activeVersionId},
+ order={"relativePath": "asc"},
+ )
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_seed.py b/autogpt_platform/backend/backend/api/features/store/skill_seed.py
index ad3c96f62f..05880064f7 100644
--- a/autogpt_platform/backend/backend/api/features/store/skill_seed.py
+++ b/autogpt_platform/backend/backend/api/features/store/skill_seed.py
@@ -31,6 +31,8 @@ from backend.copilot.tools.skills import (
)
from backend.data import db as database
+from .skill_submission_db import snapshot_version_files
+
logger = logging.getLogger(__name__)
_CONTENT_DIR = Path(__file__).parent / "starter_skills"
@@ -60,10 +62,8 @@ async def seed_starter_skills() -> list[str]:
"""Upsert every starter listing. Returns the listing ids."""
listing_ids = []
for entry in STARTER_SKILLS:
- # 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 = await _upsert_listing(entry, parsed, files)
listing_ids.append(listing.id)
logger.info(
f"Seeded starter skill '{entry['slug']}' (#{listing.id})"
@@ -73,7 +73,7 @@ async def seed_starter_skills() -> list[str]:
async def _upsert_listing(
- entry: StarterSkill, parsed: ParsedSkill
+ entry: StarterSkill, parsed: ParsedSkill, files: list[SkillFile]
) -> prisma.models.SkillListing:
listing = await prisma.models.SkillListing.prisma().upsert(
where={"slug": entry["slug"]},
@@ -83,7 +83,7 @@ async def _upsert_listing(
},
include={"ActiveVersion": True},
)
- version = await _upsert_version(listing, entry, parsed)
+ version = await _upsert_version(listing, entry, parsed, files)
if listing.activeVersionId != version.id:
listing = (
await prisma.models.SkillListing.prisma().update(
@@ -100,8 +100,9 @@ async def _upsert_version(
listing: prisma.models.SkillListing,
entry: StarterSkill,
parsed: ParsedSkill,
+ files: list[SkillFile],
) -> prisma.models.SkillListingVersion:
- """Rewrite the listing's live version in place.
+ """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
@@ -120,15 +121,21 @@ async def _upsert_version(
"submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
}
existing = listing.ActiveVersion
- if existing is not None:
- updated = await prisma.models.SkillListingVersion.prisma().update(
- where={"id": existing.id}, data=content
+ # 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 updated is not None:
- return updated
- return await prisma.models.SkillListingVersion.prisma().create(
- data={**content, "skillListingId": listing.id}
- )
+ await snapshot_version_files(created.id, files, tx)
+ return created
def _load(slug: str) -> tuple[ParsedSkill, list[SkillFile]]:
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_submission_db.py b/autogpt_platform/backend/backend/api/features/store/skill_submission_db.py
index ba7e1d52e7..544586bdc3 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
@@ -1,17 +1,26 @@
"""Publishing a library skill as a marketplace listing, and reviewing it.
-A submission snapshots the creator's own ``SKILL.md`` at submit time, so
-editing the library copy afterwards never changes what installers get — only
-a new submission does. The live version stays served throughout: approval is
-what promotes a pending version, and a rejection leaves the shelf untouched.
+A submission snapshots the creator's own package — the ``SKILL.md`` and every
+file beside it — at submit time, so editing the library copy afterwards never
+changes what installers get; only a new submission does. The live version stays
+served throughout: approval is what promotes a pending version, and a rejection
+leaves the shelf untouched.
"""
import datetime
+import hashlib
+import mimetypes
+import prisma
import prisma.enums
import prisma.models
-from backend.copilot.tools.skills import read_user_skill_with_body
+from backend.copilot.tools.skills import (
+ ParsedSkill,
+ SkillFile,
+ parse_skill_markdown,
+ read_user_skill_package,
+)
from backend.data.db import transaction
from backend.util.exceptions import NotFoundError, PreconditionFailed
@@ -27,10 +36,10 @@ async def submit_skill(
the live one, so what the marketplace serves only changes on approval.
"""
slug = request.skill_name.strip().lower()
- skill = await read_user_skill_with_body(user_id, slug)
- if skill is None:
- raise NotFoundError(f"Skill '{slug}' is not in your library")
await _require_profile(user_id)
+ # One bracketed read, after the refusals: the body and the files must be the
+ # same version of the skill, and these are blob reads of up to 20 MiB.
+ skill, files = await _read_library_package(user_id, slug)
async with transaction() as tx:
listing = await prisma.models.SkillListing.prisma(tx).find_unique(
@@ -61,6 +70,7 @@ async def submit_skill(
"submittedAt": datetime.datetime.now(datetime.timezone.utc),
}
)
+ await snapshot_version_files(version.id, files, tx)
return skill_model.SkillSubmission.from_db(version, listing)
@@ -103,24 +113,24 @@ async def edit_skill_submission(
f"This submission publishes '{listing.slug}'. Publish '{slug}' as "
"its own listing instead."
)
- skill = await read_user_skill_with_body(user_id, slug)
- if skill is None:
- raise NotFoundError(f"Skill '{slug}' is not in your library")
+ skill, files = await _read_library_package(user_id, slug)
- updated = await prisma.models.SkillListingVersion.prisma().update(
- where={"id": version.id},
- data={
- "name": skill.name,
- "description": skill.description,
- "body": skill.body,
- "triggers": list(skill.triggers),
- "categories": request.categories,
- "requiredProviders": request.required_providers,
- "changesSummary": request.changes_summary or version.changesSummary,
- },
- )
- if updated is None:
- raise NotFoundError(f"Submission #{skill_listing_version_id} not found")
+ async with transaction() as tx:
+ updated = await prisma.models.SkillListingVersion.prisma(tx).update(
+ where={"id": version.id},
+ data={
+ "name": skill.name,
+ "description": skill.description,
+ "body": skill.body,
+ "triggers": list(skill.triggers),
+ "categories": request.categories,
+ "requiredProviders": request.required_providers,
+ "changesSummary": request.changes_summary or version.changesSummary,
+ },
+ )
+ if updated is None:
+ raise NotFoundError(f"Submission #{skill_listing_version_id} not found")
+ await snapshot_version_files(updated.id, files, tx)
return skill_model.SkillSubmission.from_db(updated, listing)
@@ -193,6 +203,56 @@ async def list_pending_skill_submissions() -> list[skill_model.SkillSubmission]:
]
+async def snapshot_version_files(
+ skill_listing_version_id: str,
+ files: list[SkillFile],
+ tx: prisma.Prisma | None = None,
+) -> None:
+ """Make *files* the version's package, replacing whatever it held.
+
+ The bytes are copied rather than referenced, which is what lets the
+ creator keep editing their library skill without moving the shelf.
+ """
+ await prisma.models.SkillListingFile.prisma(tx).delete_many(
+ where={"skillListingVersionId": skill_listing_version_id}
+ )
+ if not files:
+ return
+ await prisma.models.SkillListingFile.prisma(tx).create_many(
+ data=[
+ {
+ "skillListingVersionId": skill_listing_version_id,
+ "relativePath": f.relative_path,
+ "sizeBytes": f.size_bytes,
+ "sha256": hashlib.sha256(f.content).hexdigest(),
+ # What the workspace stored for it: `write_file` guesses from
+ # the filename whenever the caller passes no type, as ours do.
+ "mimeType": mimetypes.guess_type(f.relative_path)[0],
+ "isExecutable": f.is_executable,
+ "content": prisma.Base64.encode(f.content),
+ }
+ for f in files
+ ]
+ )
+
+
+async def _read_library_package(
+ user_id: str, slug: str
+) -> tuple[ParsedSkill, list[SkillFile]]:
+ """The creator's skill as one consistent version — its parsed ``SKILL.md``
+ and the files beside it, read together so a store landing between them
+ cannot publish one version's body with another's files."""
+ package = await read_user_skill_package(user_id, slug)
+ skill = (
+ parse_skill_markdown(package.skill_md, fallback_name=slug)
+ if package is not None
+ else None
+ )
+ if package is None or skill is None:
+ raise NotFoundError(f"Skill '{slug}' is not in your library")
+ return skill, package.files
+
+
async def _owned_version(
user_id: str, skill_listing_version_id: str
) -> tuple[prisma.models.SkillListingVersion, prisma.models.SkillListing]:
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.py
index 6d03d9a02c..7a192232b2 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
@@ -1,8 +1,15 @@
+import hashlib
+
import prisma.enums
import prisma.models
import pytest
-from backend.copilot.tools.skills import ParsedSkill
+from backend.copilot.tools.skills import (
+ ParsedSkill,
+ SkillFile,
+ SkillPackage,
+ render_skill_markdown,
+)
from backend.util.exceptions import NotFoundError, PreconditionFailed
from backend.util.test import SpinTestServer
@@ -16,6 +23,12 @@ LIBRARY_SKILL = ParsedSkill(
)
+def _library_package(files: list[SkillFile] | None = None) -> SkillPackage:
+ return SkillPackage(
+ skill_md=render_skill_markdown(LIBRARY_SKILL), files=files or []
+ )
+
+
def _request(**overrides) -> skill_model.SkillSubmissionRequest:
data = {
"skill_name": "brand-voice-guide",
@@ -28,11 +41,20 @@ def _request(**overrides) -> skill_model.SkillSubmissionRequest:
@pytest.fixture(autouse=True)
async def library_skill(mocker, server: SpinTestServer):
+ # A single-file skill unless a test says otherwise; the package round trip
+ # runs against a real workspace in skill_package_test.py.
mocker.patch.object(
- skill_submission_db, "read_user_skill_with_body", return_value=LIBRARY_SKILL
+ skill_submission_db,
+ "read_user_skill_package",
+ return_value=_library_package(),
)
- await prisma.models.SkillListingVersion.prisma().delete_many()
- await prisma.models.SkillListing.prisma().delete_many()
+ # These tests assert on the WHOLE marketplace, so they need the listing
+ # table to themselves — take it only when empty, never by emptying it.
+ if await prisma.models.SkillListing.prisma().count():
+ pytest.fail(
+ "this database already holds skill listings; run this file against a "
+ "throwaway Postgres, not the one every worktree here shares"
+ )
yield
await prisma.models.SkillListingVersion.prisma().delete_many()
await prisma.models.SkillListing.prisma().delete_many()
@@ -84,7 +106,7 @@ async def test_publishing_a_skill_that_is_not_in_the_library_is_refused(
creator, mocker
):
mocker.patch.object(
- skill_submission_db, "read_user_skill_with_body", return_value=None
+ skill_submission_db, "read_user_skill_package", return_value=None
)
with pytest.raises(NotFoundError):
@@ -146,12 +168,16 @@ async def test_republishing_leaves_the_live_version_serving_until_approved(
)
mocker.patch.object(
skill_submission_db,
- "read_user_skill_with_body",
- return_value=ParsedSkill(
- name="brand-voice-guide",
- description="Rewritten.",
- body="# Rewritten\n",
- triggers=(),
+ "read_user_skill_package",
+ return_value=SkillPackage(
+ skill_md=render_skill_markdown(
+ ParsedSkill(
+ name="brand-voice-guide",
+ description="Rewritten.",
+ body="# Rewritten\n",
+ triggers=(),
+ )
+ )
),
)
@@ -167,12 +193,16 @@ async def test_editing_re_snapshots_the_library_skill(creator, mocker):
submission = await skill_submission_db.submit_skill(creator, _request())
mocker.patch.object(
skill_submission_db,
- "read_user_skill_with_body",
- return_value=ParsedSkill(
- name="brand-voice-guide",
- description="Tightened.",
- body="# Tightened\n",
- triggers=(),
+ "read_user_skill_package",
+ return_value=SkillPackage(
+ skill_md=render_skill_markdown(
+ ParsedSkill(
+ name="brand-voice-guide",
+ description="Tightened.",
+ body="# Tightened\n",
+ triggers=(),
+ )
+ )
),
)
@@ -227,16 +257,79 @@ async def test_the_review_queue_holds_only_pending_submissions(creator, reviewer
assert await skill_submission_db.list_pending_skill_submissions() == []
+async def test_publishing_snapshots_every_file_beside_the_skill_md(creator, mocker):
+ mocker.patch.object(
+ skill_submission_db,
+ "read_user_skill_package",
+ return_value=_library_package(
+ [
+ SkillFile(relative_path="references/tone.md", content=b"warm"),
+ SkillFile(
+ relative_path="scripts/lint.py", content=b"x", is_executable=True
+ ),
+ ]
+ ),
+ )
+
+ submission = await skill_submission_db.submit_skill(creator, _request())
+
+ rows = await prisma.models.SkillListingFile.prisma().find_many(
+ where={"skillListingVersionId": submission.skill_listing_version_id},
+ order={"relativePath": "asc"},
+ )
+ assert [(r.relativePath, r.sizeBytes, r.isExecutable) for r in rows] == [
+ ("references/tone.md", 4, False),
+ ("scripts/lint.py", 1, True),
+ ]
+ assert rows[0].sha256 == hashlib.sha256(b"warm").hexdigest()
+ assert rows[0].mimeType == "text/markdown"
+
+
+async def test_editing_a_pending_submission_drops_a_file_it_no_longer_has(
+ creator, mocker
+):
+ """The rows are the version's package, so an edit replaces them whole —
+ a file left behind would ship in a version its creator never published."""
+ package = mocker.patch.object(
+ skill_submission_db,
+ "read_user_skill_package",
+ return_value=_library_package(
+ [
+ SkillFile(relative_path="references/tone.md", content=b"warm"),
+ SkillFile(relative_path="references/gone.md", content=b"bye"),
+ ]
+ ),
+ )
+ submission = await skill_submission_db.submit_skill(creator, _request())
+ package.return_value = _library_package(
+ [SkillFile(relative_path="references/tone.md", content=b"warmer")]
+ )
+
+ await skill_submission_db.edit_skill_submission(
+ creator, submission.skill_listing_version_id, _request()
+ )
+
+ rows = await prisma.models.SkillListingFile.prisma().find_many(
+ where={"skillListingVersionId": submission.skill_listing_version_id}
+ )
+ assert [r.relativePath for r in rows] == ["references/tone.md"]
+ assert rows[0].content.decode() == b"warmer"
+
+
async def test_editing_cannot_repoint_the_submission_at_another_skill(creator, mocker):
submission = await skill_submission_db.submit_skill(creator, _request())
mocker.patch.object(
skill_submission_db,
- "read_user_skill_with_body",
- return_value=ParsedSkill(
- name="other-skill",
- description="Someone else's content.",
- body="# Other\n",
- triggers=(),
+ "read_user_skill_package",
+ return_value=SkillPackage(
+ skill_md=render_skill_markdown(
+ ParsedSkill(
+ name="other-skill",
+ description="Someone else's content.",
+ body="# Other\n",
+ triggers=(),
+ )
+ )
),
)
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index a66cb2e065..6a96875f3c 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -29,14 +29,11 @@ from backend.copilot.tools.skills import (
# 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.copilot.tools.skills_test import _FakeWorkspaceManager, _patch_skills_path
from backend.data.credit import AutoTopUpConfig
from backend.data.graph import GraphModel
from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationError
-from backend.util.exceptions import InsufficientBalanceError
+from backend.util.exceptions import ConflictError, InsufficientBalanceError
from .v1 import upload_file, v1_router
@@ -60,6 +57,10 @@ app.include_router(v1_router)
# Mirror rest_api.py's GraphActivationError → 400 mapping so the atomicity
# tests below verify the same behaviour the real app exposes.
app.add_exception_handler(GraphActivationError, handle_internal_http_error(400))
+# Same reason: ConflictError is mapped app-wide, never on the route, so without
+# this a conflict reads here as an unhandled error rather than the 409 a client
+# actually gets.
+app.add_exception_handler(ConflictError, handle_internal_http_error(409))
client = fastapi.testclient.TestClient(app)
@@ -1854,6 +1855,22 @@ def test_download_refuses_a_stored_package_over_the_files_cap() -> None:
assert str(MAX_PACKAGE_FILES) in response.json()["detail"]
+def test_download_of_a_package_being_rewritten_is_409_not_a_bad_request(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """A tree that will not hold still is a conflict the caller can retry, not
+ a malformed package: 400 or 413 would blame the user for their own
+ concurrent edit."""
+ mocker.patch(
+ "backend.api.features.v1.read_user_skill_package",
+ AsyncMock(side_effect=ConflictError("changed while it was read")),
+ )
+
+ response = client.get("/skills/oauth_flow/package")
+
+ assert response.status_code == 409, response.text
+
+
def test_download_package_returns_404_for_a_missing_skill(
mocker: pytest_mock.MockFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills.py b/autogpt_platform/backend/backend/copilot/tools/skills.py
index c0bee7a56b..d1155b80f9 100644
--- a/autogpt_platform/backend/backend/copilot/tools/skills.py
+++ b/autogpt_platform/backend/backend/copilot/tools/skills.py
@@ -102,6 +102,8 @@ MAX_PACKAGE_PATH_DEPTH = 8
# An E2B write is a 200 ms round trip and a workspace read a blob fetch, so
# 60 of either in series is seconds of a turn. Bounded, not unlimited.
_COPY_CONCURRENCY = 16
+# Attempts at reading a package whose tree keeps moving under the read.
+_PACKAGE_READ_ATTEMPTS = 3
# Passes delete_user_skill will make over a folder, each one page deep.
# Bounded so a file that cannot be deleted can never spin the loop.
_DELETE_PASSES = 20
@@ -1194,23 +1196,54 @@ async def read_user_skill_package(
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.
+
+ The read is bracketed by a fingerprint of the tree and retried when it
+ moves, because ``store_user_skill`` writes the siblings before the root: a
+ concurrent store caught mid-write would otherwise hand back one version's
+ ``SKILL.md`` with another's files. Exhausting the attempts raises rather
+ than serving a package that may be mixed.
"""
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
- ),
+ folder = skill_folder(expert_id)
+ root_path = _skill_md_path(slug, expert_id)
+ for _ in range(_PACKAGE_READ_ATTEMPTS):
+ before = await _package_fingerprint(manager, folder, slug, root_path)
+ if before is None:
+ return None
+ try:
+ raw = await manager.read_file(root_path)
+ except FileNotFoundError:
+ return None
+ # Only a moved fingerprint retries; any other failure in here is this
+ # caller's answer, not a concurrent write.
+ files = await _read_package_files(manager, folder, slug, complete=True)
+ if await _package_fingerprint(manager, folder, slug, root_path) == before:
+ return SkillPackage(skill_md=raw.decode("utf-8"), files=files)
+ raise ConflictError(
+ f"Skill '{slug}' was being changed while it was read. Try again."
)
+async def _package_fingerprint(
+ manager: WorkspaceManager, folder: str, slug: str, root_path: str
+) -> tuple[str, tuple[tuple[str, str], ...]] | None:
+ """Row ids of a package's ``SKILL.md`` and every sibling, ``None`` when the
+ skill is not there.
+
+ Sound only because ``write_file`` mints a fresh id per write and overwrites
+ by deleting and recreating rather than updating in place, so no write to
+ this tree can leave the ids untouched.
+ """
+ root = await manager.get_file_info_by_path(root_path)
+ if root is None:
+ return None
+ files = await _list_package_files(manager, folder, slug, cap=None)
+ return root.id, tuple(sorted((f.path, f.file_id) for f in files))
+
+
async def list_user_skill_files(
user_id: str,
name: str,
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills_test.py b/autogpt_platform/backend/backend/copilot/tools/skills_test.py
index afb46a2609..1b2d3121be 100644
--- a/autogpt_platform/backend/backend/copilot/tools/skills_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/skills_test.py
@@ -49,11 +49,13 @@ from backend.copilot.tools.skills import (
list_all_skills,
list_user_skill_files,
parse_skill_markdown,
+ read_user_skill_package,
render_skill_markdown,
render_skills_index,
store_user_skill,
validate_package,
)
+from backend.util.exceptions import ConflictError
# ---------------------------------------------------------------------------
# Round-trip
@@ -1359,6 +1361,80 @@ def _package_manager(slug: str = "big", siblings: int = 0) -> _FakeWorkspaceMana
return fake
+class _MovingTree(_FakeWorkspaceManager):
+ """A store that keeps landing under the read.
+
+ Each listing reports a fresh row id for one sibling, which is what a real
+ overwrite does — ``write_file`` mints a new uuid and recreates the row, so
+ the id is what a concurrent write moves. Deriving the id from the path, as
+ the plain fake does, cannot express that.
+ """
+
+ def __init__(self, settles_at: int | None = None):
+ super().__init__()
+ self.files["/skills/big/SKILL.md"] = render_skill_markdown(
+ ParsedSkill(name="big", description="big description", body="steps")
+ ).encode()
+ self.files["/skills/big/references/moving.md"] = b"contents"
+ self.listings = 0
+ self.settles_at = settles_at
+
+ async def list_files(self, **kwargs):
+ self.listings += 1
+ rows = await super().list_files(**kwargs)
+ if self.settles_at is None or self.listings < self.settles_at:
+ for row in rows:
+ if row.path.endswith("moving.md"):
+ row.id = f"id-moving-{self.listings}"
+ return rows
+
+
+async def test_a_package_read_retries_until_the_tree_stops_moving():
+ # Settles from the third listing: attempt one sees the tree move, attempt
+ # two finds it still.
+ fake = _MovingTree(settles_at=3)
+ with _patch_skills_path(fake):
+ package = await read_user_skill_package("user-1", "big")
+ assert package is not None
+ assert [f.relative_path for f in package.files] == ["references/moving.md"]
+
+
+async def test_a_package_read_that_never_settles_raises_instead_of_mixing():
+ """The body and the files would otherwise come from different versions, and
+ a publish would put that mix on the shelf permanently."""
+ fake = _MovingTree()
+ with _patch_skills_path(fake):
+ with pytest.raises(ConflictError):
+ await read_user_skill_package("user-1", "big")
+
+
+async def test_a_read_failure_is_answered_once_and_never_retried():
+ """Only a moved fingerprint costs an attempt. Retrying a storage failure
+ would turn one error into three reads and report a concurrency conflict for
+ something that is not one."""
+ fake = _package_manager()
+ fake.files["/skills/big/references/guide.md"] = b"read me"
+ reads = 0
+ original = fake.read_file
+
+ async def counted(path: str) -> bytes:
+ nonlocal reads
+ reads += 1
+ if path.endswith("references/guide.md"):
+ raise RuntimeError("blob store down")
+ return await original(path)
+
+ fake.read_file = counted
+ with _patch_skills_path(fake):
+ with pytest.raises(RuntimeError, match="blob store down"):
+ await read_user_skill_package("user-1", "big")
+ # The root plus the one sibling that raised: a retry would read them again.
+ assert reads == 2
+
+
@pytest.mark.asyncio
async def test_a_package_bigger_than_the_listing_cap_stays_indexed():
"""201 sibling files created after the SKILL.md used to push it off the
diff --git a/autogpt_platform/backend/backend/data/workspace.py b/autogpt_platform/backend/backend/data/workspace.py
index e474704c76..b3ecf5dd94 100644
--- a/autogpt_platform/backend/backend/data/workspace.py
+++ b/autogpt_platform/backend/backend/data/workspace.py
@@ -442,9 +442,9 @@ async def soft_delete_workspace_file(
return None
deleted_at = datetime.now(timezone.utc)
- # Modify path to free up the unique constraint for new files at original path
- # Format: {original_path}__deleted__{timestamp}
- deleted_path = f"{file.path}__deleted__{int(deleted_at.timestamp())}"
+ # Frees the path for the next write, to microseconds: `write_file` soft-deletes
+ # the row it overwrites, so two writes in one second would collide here.
+ deleted_path = f"{file.path}__deleted__{deleted_at.timestamp():.6f}"
updated = await UserWorkspaceFile.prisma().update(
where={"id": file_id},
diff --git a/autogpt_platform/backend/backend/data/workspace_test.py b/autogpt_platform/backend/backend/data/workspace_test.py
new file mode 100644
index 0000000000..5ca82b049f
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/workspace_test.py
@@ -0,0 +1,56 @@
+"""Soft-deleting a workspace file frees its path for the next write.
+
+``write_file(overwrite=True)`` soft-deletes the row it replaces, so the renamed
+path is what two writes to one path race on.
+"""
+
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from backend.data import workspace
+
+WITHIN_ONE_SECOND = [
+ datetime(2026, 9, 14, 12, 0, 0, tzinfo=timezone.utc) + timedelta(milliseconds=ms)
+ for ms in (0, 120)
+]
+
+
+class _Row:
+ def __init__(self, path: str):
+ self.id = "file-1"
+ self.path = path
+
+
+def renames(mocker):
+ """Every path ``soft_delete_workspace_file`` renames a row to, with a clock
+ that advances inside one second so only the suffix separates two calls."""
+ mocker.patch.object(
+ workspace, "get_workspace_file", mocker.AsyncMock(return_value=_Row("/a/b.txt"))
+ )
+ mocker.patch.object(
+ workspace,
+ "datetime",
+ mocker.MagicMock(now=mocker.MagicMock(side_effect=WITHIN_ONE_SECOND)),
+ )
+ captured: list[str] = []
+ prisma = mocker.MagicMock()
+ prisma.update = mocker.AsyncMock(
+ side_effect=lambda where, data: captured.append(data["path"])
+ )
+ mocker.patch.object(
+ workspace.UserWorkspaceFile, "prisma", mocker.MagicMock(return_value=prisma)
+ )
+ return captured
+
+
+async def test_two_deletes_in_one_second_free_the_path_twice(renames: list[str]):
+ """A second-resolution suffix gave both the same name, so the second rename
+ failed the unique index it exists to get out of the way of — leaving a file
+ the user could no longer overwrite."""
+ await workspace.soft_delete_workspace_file("file-1", "ws-1")
+ await workspace.soft_delete_workspace_file("file-1", "ws-1")
+
+ assert renames[0] != renames[1]
+ assert all(name.startswith("/a/b.txt__deleted__") for name in renames)
diff --git a/autogpt_platform/backend/migrations/20260914151516_add_skill_listing_file/migration.sql b/autogpt_platform/backend/migrations/20260914151516_add_skill_listing_file/migration.sql
new file mode 100644
index 0000000000..39a14f5c44
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260914151516_add_skill_listing_file/migration.sql
@@ -0,0 +1,20 @@
+-- CreateTable
+CREATE TABLE "SkillListingFile" (
+ "id" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "skillListingVersionId" TEXT NOT NULL,
+ "relativePath" TEXT NOT NULL,
+ "sizeBytes" INTEGER NOT NULL,
+ "sha256" TEXT NOT NULL,
+ "mimeType" TEXT,
+ "isExecutable" BOOLEAN NOT NULL DEFAULT false,
+ "content" BYTEA NOT NULL,
+
+ CONSTRAINT "SkillListingFile_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "SkillListingFile_skillListingVersionId_relativePath_key" ON "SkillListingFile"("skillListingVersionId", "relativePath");
+
+-- AddForeignKey
+ALTER TABLE "SkillListingFile" ADD CONSTRAINT "SkillListingFile_skillListingVersionId_fkey" FOREIGN KEY ("skillListingVersionId") REFERENCES "SkillListingVersion"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.toml
index 11ff0891d4..029218fb2c 100644
--- a/autogpt_platform/backend/pyproject.toml
+++ b/autogpt_platform/backend/pyproject.toml
@@ -156,6 +156,12 @@ oauth-tool = "backend.cli.oauth_tool:cli"
[tool.isort]
profile = "black"
+extend_skip_glob = ["test/fixtures/*", "*/test/fixtures/*"]
+
+[tool.black]
+# A vendored upstream package is test data: the suite compares it byte for byte
+# against what publishing stored, so reformatting it would test our own output.
+force-exclude = "test/fixtures/"
[tool.coverage.run]
# Offline eval harnesses: run manually with LLM credentials / ffmpeg
@@ -200,3 +206,7 @@ filterwarnings = [
[tool.ruff]
target-version = "py310"
+extend-exclude = ["test/fixtures"]
+# `poetry run format` runs `ruff check --fix .`, which would otherwise rewrite
+# the vendored fixture it walks into.
+force-exclude = true
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index dcd77a9242..0b988fedc3 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -2166,6 +2166,8 @@ model SkillListingVersion {
// Tenancy
organizationId String?
+ Files SkillListingFile[]
+
@@unique([skillListingId, version])
@@index([skillListingId, submissionStatus, isAvailable])
@@index([submissionStatus])
@@ -2173,6 +2175,30 @@ model SkillListingVersion {
@@index([organizationId])
}
+/// One file beside a published version's SKILL.md, snapshotted at submit time
+/// like the body is. Bytes live in the row: a version is immutable once
+/// approved, capped at 20 MiB in the application layer, and cascade-deleted
+/// with its version, so a blob store would only add orphan cleanup.
+model SkillListingFile {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+
+ skillListingVersionId String
+ SkillListingVersion SkillListingVersion @relation(fields: [skillListingVersionId], references: [id], onDelete: Cascade)
+
+ /// Posix path relative to the skill folder, e.g. `scripts/with_server.py`.
+ relativePath String
+ sizeBytes Int
+ sha256 String
+ mimeType String?
+ /// Restored on install: `python scripts/x.py` works without it, `./x.py` does not.
+ isExecutable Boolean @default(false)
+
+ content Bytes
+
+ @@unique([skillListingVersionId, relativePath])
+}
+
// Content type enum for unified search across store agents, blocks, docs
// Note: BLOCK/INTEGRATION are file-based (Python classes), not DB records
// DOCUMENTATION are file-based (.md files), not DB records
diff --git a/autogpt_platform/backend/test/fixtures/skills/webapp-testing/LICENSE.txt b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/LICENSE.txt
new file mode 100644
index 0000000000..4f881c52d1
--- /dev/null
+++ b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 Anthropic, PBC.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/autogpt_platform/backend/test/fixtures/skills/webapp-testing/README.md b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/README.md
new file mode 100644
index 0000000000..89366cc023
--- /dev/null
+++ b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/README.md
@@ -0,0 +1,14 @@
+# `webapp-testing` — vendored test fixture
+
+Verbatim copy of `skills/webapp-testing` from
+[anthropics/skills](https://github.com/anthropics/skills) at commit
+`34040c9c56`, used as the real-world package the marketplace publish/install
+tests round-trip. Six files, 22,394 bytes, one `100755` script — the shape a
+hand-written fixture would not have.
+
+Licensed Apache-2.0 (`LICENSE.txt`, Copyright 2026 Anthropic, PBC). The other
+packages in that repository (`pdf`, `docx`, `pptx`, `xlsx`) are proprietary and
+are deliberately not vendored.
+
+Do not edit: the tests assert byte-equality against what publish stored, and
+`scripts/with_server.py` must keep its executable bit.
diff --git a/autogpt_platform/backend/test/fixtures/skills/webapp-testing/SKILL.md b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/SKILL.md
new file mode 100644
index 0000000000..4726215301
--- /dev/null
+++ b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/SKILL.md
@@ -0,0 +1,96 @@
+---
+name: webapp-testing
+description: Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
+license: Complete terms in LICENSE.txt
+---
+
+# Web Application Testing
+
+To test local web applications, write native Python Playwright scripts.
+
+**Helper Scripts Available**:
+- `scripts/with_server.py` - Manages server lifecycle (supports multiple servers)
+
+**Always run scripts with `--help` first** to see usage. DO NOT read the source until you try running the script first and find that a customized solution is abslutely necessary. These scripts can be very large and thus pollute your context window. They exist to be called directly as black-box scripts rather than ingested into your context window.
+
+## Decision Tree: Choosing Your Approach
+
+```
+User task → Is it static HTML?
+ ├─ Yes → Read HTML file directly to identify selectors
+ │ ├─ Success → Write Playwright script using selectors
+ │ └─ Fails/Incomplete → Treat as dynamic (below)
+ │
+ └─ No (dynamic webapp) → Is the server already running?
+ ├─ No → Run: python scripts/with_server.py --help
+ │ Then use the helper + write simplified Playwright script
+ │
+ └─ Yes → Reconnaissance-then-action:
+ 1. Navigate and wait for networkidle
+ 2. Take screenshot or inspect DOM
+ 3. Identify selectors from rendered state
+ 4. Execute actions with discovered selectors
+```
+
+## Example: Using with_server.py
+
+To start a server, run `--help` first, then use the helper:
+
+**Single server:**
+```bash
+python scripts/with_server.py --server "npm run dev" --port 5173 -- python your_automation.py
+```
+
+**Multiple servers (e.g., backend + frontend):**
+```bash
+python scripts/with_server.py \
+ --server "cd backend && python server.py" --port 3000 \
+ --server "cd frontend && npm run dev" --port 5173 \
+ -- python your_automation.py
+```
+
+To create an automation script, include only Playwright logic (servers are managed automatically):
+```python
+from playwright.sync_api import sync_playwright
+
+with sync_playwright() as p:
+ browser = p.chromium.launch(headless=True) # Always launch chromium in headless mode
+ page = browser.new_page()
+ page.goto('http://localhost:5173') # Server already running and ready
+ page.wait_for_load_state('networkidle') # CRITICAL: Wait for JS to execute
+ # ... your automation logic
+ browser.close()
+```
+
+## Reconnaissance-Then-Action Pattern
+
+1. **Inspect rendered DOM**:
+ ```python
+ page.screenshot(path='/tmp/inspect.png', full_page=True)
+ content = page.content()
+ page.locator('button').all()
+ ```
+
+2. **Identify selectors** from inspection results
+
+3. **Execute actions** using discovered selectors
+
+## Common Pitfall
+
+❌ **Don't** inspect the DOM before waiting for `networkidle` on dynamic apps
+✅ **Do** wait for `page.wait_for_load_state('networkidle')` before inspection
+
+## Best Practices
+
+- **Use bundled scripts as black boxes** - To accomplish a task, consider whether one of the scripts available in `scripts/` can help. These scripts handle common, complex workflows reliably without cluttering the context window. Use `--help` to see usage, then invoke directly.
+- Use `sync_playwright()` for synchronous scripts
+- Always close the browser when done
+- Use descriptive selectors: `text=`, `role=`, CSS selectors, or IDs
+- Add appropriate waits: `page.wait_for_selector()` or `page.wait_for_timeout()`
+
+## Reference Files
+
+- **examples/** - Examples showing common patterns:
+ - `element_discovery.py` - Discovering buttons, links, and inputs on a page
+ - `static_html_automation.py` - Using file:// URLs for local HTML
+ - `console_logging.py` - Capturing console logs during automation
\ No newline at end of file
diff --git a/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/console_logging.py b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/console_logging.py
new file mode 100644
index 0000000000..9329b5e232
--- /dev/null
+++ b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/console_logging.py
@@ -0,0 +1,35 @@
+from playwright.sync_api import sync_playwright
+
+# Example: Capturing console logs during browser automation
+
+url = 'http://localhost:5173' # Replace with your URL
+
+console_logs = []
+
+with sync_playwright() as p:
+ browser = p.chromium.launch(headless=True)
+ page = browser.new_page(viewport={'width': 1920, 'height': 1080})
+
+ # Set up console log capture
+ def handle_console_message(msg):
+ console_logs.append(f"[{msg.type}] {msg.text}")
+ print(f"Console: [{msg.type}] {msg.text}")
+
+ page.on("console", handle_console_message)
+
+ # Navigate to page
+ page.goto(url)
+ page.wait_for_load_state('networkidle')
+
+ # Interact with the page (triggers console logs)
+ page.click('text=Dashboard')
+ page.wait_for_timeout(1000)
+
+ browser.close()
+
+# Save console logs to file
+with open('/mnt/user-data/outputs/console.log', 'w') as f:
+ f.write('\n'.join(console_logs))
+
+print(f"\nCaptured {len(console_logs)} console messages")
+print(f"Logs saved to: /mnt/user-data/outputs/console.log")
\ No newline at end of file
diff --git a/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/element_discovery.py b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/element_discovery.py
new file mode 100644
index 0000000000..917ba72f52
--- /dev/null
+++ b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/element_discovery.py
@@ -0,0 +1,40 @@
+from playwright.sync_api import sync_playwright
+
+# Example: Discovering buttons and other elements on a page
+
+with sync_playwright() as p:
+ browser = p.chromium.launch(headless=True)
+ page = browser.new_page()
+
+ # Navigate to page and wait for it to fully load
+ page.goto('http://localhost:5173')
+ page.wait_for_load_state('networkidle')
+
+ # Discover all buttons on the page
+ buttons = page.locator('button').all()
+ print(f"Found {len(buttons)} buttons:")
+ for i, button in enumerate(buttons):
+ text = button.inner_text() if button.is_visible() else "[hidden]"
+ print(f" [{i}] {text}")
+
+ # Discover links
+ links = page.locator('a[href]').all()
+ print(f"\nFound {len(links)} links:")
+ for link in links[:5]: # Show first 5
+ text = link.inner_text().strip()
+ href = link.get_attribute('href')
+ print(f" - {text} -> {href}")
+
+ # Discover input fields
+ inputs = page.locator('input, textarea, select').all()
+ print(f"\nFound {len(inputs)} input fields:")
+ for input_elem in inputs:
+ name = input_elem.get_attribute('name') or input_elem.get_attribute('id') or "[unnamed]"
+ input_type = input_elem.get_attribute('type') or 'text'
+ print(f" - {name} ({input_type})")
+
+ # Take screenshot for visual reference
+ page.screenshot(path='/tmp/page_discovery.png', full_page=True)
+ print("\nScreenshot saved to /tmp/page_discovery.png")
+
+ browser.close()
\ No newline at end of file
diff --git a/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/static_html_automation.py b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/static_html_automation.py
new file mode 100644
index 0000000000..90bbedcc08
--- /dev/null
+++ b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/examples/static_html_automation.py
@@ -0,0 +1,33 @@
+from playwright.sync_api import sync_playwright
+import os
+
+# Example: Automating interaction with static HTML files using file:// URLs
+
+html_file_path = os.path.abspath('path/to/your/file.html')
+file_url = f'file://{html_file_path}'
+
+with sync_playwright() as p:
+ browser = p.chromium.launch(headless=True)
+ page = browser.new_page(viewport={'width': 1920, 'height': 1080})
+
+ # Navigate to local HTML file
+ page.goto(file_url)
+
+ # Take screenshot
+ page.screenshot(path='/mnt/user-data/outputs/static_page.png', full_page=True)
+
+ # Interact with elements
+ page.click('text=Click Me')
+ page.fill('#name', 'John Doe')
+ page.fill('#email', '[email protected]')
+
+ # Submit form
+ page.click('button[type="submit"]')
+ page.wait_for_timeout(500)
+
+ # Take final screenshot
+ page.screenshot(path='/mnt/user-data/outputs/after_submit.png', full_page=True)
+
+ browser.close()
+
+print("Static HTML automation completed!")
\ No newline at end of file
diff --git a/autogpt_platform/backend/test/fixtures/skills/webapp-testing/scripts/with_server.py b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/scripts/with_server.py
new file mode 100755
index 0000000000..431f2eba16
--- /dev/null
+++ b/autogpt_platform/backend/test/fixtures/skills/webapp-testing/scripts/with_server.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""
+Start one or more servers, wait for them to be ready, run a command, then clean up.
+
+Usage:
+ # Single server
+ python scripts/with_server.py --server "npm run dev" --port 5173 -- python automation.py
+ python scripts/with_server.py --server "npm start" --port 3000 -- python test.py
+
+ # Multiple servers
+ python scripts/with_server.py \
+ --server "cd backend && python server.py" --port 3000 \
+ --server "cd frontend && npm run dev" --port 5173 \
+ -- python test.py
+"""
+
+import subprocess
+import socket
+import time
+import sys
+import argparse
+
+def is_server_ready(port, timeout=30):
+ """Wait for server to be ready by polling the port."""
+ start_time = time.time()
+ while time.time() - start_time < timeout:
+ try:
+ with socket.create_connection(('localhost', port), timeout=1):
+ return True
+ except (socket.error, ConnectionRefusedError):
+ time.sleep(0.5)
+ return False
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Run command with one or more servers')
+ parser.add_argument('--server', action='append', dest='servers', required=True, help='Server command (can be repeated)')
+ parser.add_argument('--port', action='append', dest='ports', type=int, required=True, help='Port for each server (must match --server count)')
+ parser.add_argument('--timeout', type=int, default=30, help='Timeout in seconds per server (default: 30)')
+ parser.add_argument('command', nargs=argparse.REMAINDER, help='Command to run after server(s) ready')
+
+ args = parser.parse_args()
+
+ # Remove the '--' separator if present
+ if args.command and args.command[0] == '--':
+ args.command = args.command[1:]
+
+ if not args.command:
+ print("Error: No command specified to run")
+ sys.exit(1)
+
+ # Parse server configurations
+ if len(args.servers) != len(args.ports):
+ print("Error: Number of --server and --port arguments must match")
+ sys.exit(1)
+
+ servers = []
+ for cmd, port in zip(args.servers, args.ports):
+ servers.append({'cmd': cmd, 'port': port})
+
+ server_processes = []
+
+ try:
+ # Start all servers
+ for i, server in enumerate(servers):
+ print(f"Starting server {i+1}/{len(servers)}: {server['cmd']}")
+
+ # Use shell=True to support commands with cd and &&
+ process = subprocess.Popen(
+ server['cmd'],
+ shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE
+ )
+ server_processes.append(process)
+
+ # Wait for this server to be ready
+ print(f"Waiting for server on port {server['port']}...")
+ if not is_server_ready(server['port'], timeout=args.timeout):
+ raise RuntimeError(f"Server failed to start on port {server['port']} within {args.timeout}s")
+
+ print(f"Server ready on port {server['port']}")
+
+ print(f"\nAll {len(servers)} server(s) ready")
+
+ # Run the command
+ print(f"Running: {' '.join(args.command)}\n")
+ result = subprocess.run(args.command)
+ sys.exit(result.returncode)
+
+ finally:
+ # Clean up all servers
+ print(f"\nStopping {len(server_processes)} server(s)...")
+ for i, process in enumerate(server_processes):
+ try:
+ process.terminate()
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ print(f"Server {i+1} stopped")
+ print("All servers stopped")
+
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 96c79d757d..ed351dcd92 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -24728,6 +24728,12 @@
"type": "string",
"format": "date-time",
"title": "Updated At"
+ },
+ "files": {
+ "items": { "$ref": "#/components/schemas/SkillPackageFile" },
+ "type": "array",
+ "title": "Files",
+ "default": []
}
},
"type": "object",
@@ -28332,6 +28338,16 @@
"title": "SharedExecutionResponse",
"description": "Public-safe response for shared executions"
},
+ "SkillPackageFile": {
+ "properties": {
+ "path": { "type": "string", "title": "Path" },
+ "size_bytes": { "type": "integer", "title": "Size Bytes" }
+ },
+ "type": "object",
+ "required": ["path", "size_bytes"],
+ "title": "SkillPackageFile",
+ "description": "One file beside the published ``SKILL.md``, by its path relative to the\nskill folder. The contents are not inlined — a package runs to 20 MiB."
+ },
"SkillReviewRequest": {
"properties": {
"is_approved": { "type": "boolean", "title": "Is Approved" },