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): show a skill's package on the Hub and in admin review (#14561)
Reinier van der Leerd858b189887c
diff --git a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.pyindex fedf722c13..f8b15c7ea0 100644--- a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py+++ b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py@@ -187,6 +187,31 @@ async def list_pending_skill_submissions() -> list[skill_model.SkillSubmission]:return await skill_submission_db.list_pending_skill_submissions()+ "/skills/submissions/{skill_listing_version_id}/files/{path:path}",+ summary="Admin Read Skill Submission File",+ tags=["store", "admin"],+ response_class=fastapi.responses.PlainTextResponse,+ responses={+ 404: {"description": "File not found"},+ 413: {"description": "File is too large to view"},+ 415: {"description": "File is not text"},+ },+ dependencies=[fastapi.Depends(skill_routes.require_skills_hub_flag)],+)+async def read_skill_submission_file(+ skill_listing_version_id: str,+ path: str,+) -> str:+ """One submitted file's text, so a reviewer reads a script before approving.++ The version is addressed directly rather than through its listing: a first+ submission has no approved version for a slug to resolve to, and this+ router's admin check is what grants the pending read.+ """+ return await skill_routes.read_package_file(skill_listing_version_id, path)++@router.post("/skills/submissions/{skill_listing_version_id}/review",summary="Review Skill Submission",diff --git a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.pyindex 8bdabc828b..df1512614c 100644--- a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py@@ -145,6 +145,19 @@ def test_add_to_library_requires_admin(mock_jwt_user) -> None:assert response.status_code == 403+def test_skill_submission_file_requires_admin(+ monkeypatch: pytest.MonkeyPatch, mock_jwt_user+) -> None:+ """This route reads a package nobody has approved, addressed by version id+ with no ownership check of its own — the admin gate is the whole check."""+ monkeypatch.setenv("FORCE_FLAG_SKILLS_HUB", "true")+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]++ response = client.get(f"/admin/skills/submissions/{SLV_ID}/files/scripts/run.sh")++ assert response.status_code == 403++def test_preview_nonexistent_submission(mocker: pytest_mock.MockerFixture,) -> None:@@ -357,8 +370,9 @@ async def test_library_member_can_view_pending_agent_in_builder() -> None:[lambda: client.get("/admin/skills/submissions"),lambda: client.post(f"/admin/skills/submissions/{SLV_ID}/review"),+ lambda: client.get(f"/admin/skills/submissions/{SLV_ID}/files/SKILL.md"),],- ids=["list-pending", "review"],+ ids=["list-pending", "review", "read-file"],)def test_skill_review_is_404_when_the_skills_hub_flag_is_off(monkeypatch: pytest.MonkeyPatch, calldiff --git a/autogpt_platform/backend/backend/api/features/store/skill_db.py b/autogpt_platform/backend/backend/api/features/store/skill_db.pyindex d7c065701a..8b838a1701 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_db.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_db.py@@ -65,6 +65,90 @@ async def get_marketplace_skill(slug: str) -> skill_model.MarketplaceSkillDetail)+async def find_readable_version(+ slug: str, *, version_id: str | None, user_id: str | None+) -> prisma.models.SkillListingVersion:+ """The version of *slug* whose package *user_id* may read.++ Without a version id the live one, which is public like the listing it+ serves. With one, the live version stays public and any other — a pending+ submission — is the submitter's alone, so a stranger cannot read a package+ the marketplace has not approved. Admins come through the admin router,+ which carries its own check.+ """+ if version_id is None:+ return skill_model.active_version(await _find_live_listing(slug))++ version = await prisma.models.SkillListingVersion.prisma().find_unique(+ where={"id": version_id}, include={"SkillListing": True}+ )+ listing = version.SkillListing if version is not None else None+ if version is None or listing is None or listing.slug != slug:+ raise NotFoundError(f"Skill '{slug}' has no version {version_id}")+ if listing.activeVersionId == version.id:+ # Through the same query the anonymous path uses, so a listing taken+ # down keeps its pointer without keeping its visibility.+ await _find_live_listing(slug)+ return version+ if user_id is None or listing.owningUserId != user_id:+ raise NotFoundError(f"Skill '{slug}' has no version {version_id}")+ return version+++async def get_package_file_meta(+ skill_listing_version_id: str, relative_path: str+) -> skill_model.SkillPackageFile | None:+ """One published file's metadata, bytes excluded.++ The size cap is decided on this, so refusing an oversized file never+ reads it.+ """+ rows = await query_raw_with_schema(+ _FILE_META_SELECT + 'WHERE "skillListingVersionId" = $1 '+ 'AND "relativePath" = $2',+ skill_listing_version_id,+ relative_path,+ )+ return _to_file_meta(rows[0]) if rows else None+++async def read_package_file_bytes(+ skill_listing_version_id: str, relative_path: str+) -> bytes | None:+ """The file's stored bytes, once the caps have let it through."""+ row = await prisma.models.SkillListingFile.prisma().find_unique(+ where={+ "skillListingVersionId_relativePath": {+ "skillListingVersionId": skill_listing_version_id,+ "relativePath": relative_path,+ }+ }+ )+ return row.content.decode() if row is not None else None+++async def file_meta_by_version(+ version_ids: list[str],+) -> dict[str, list[skill_model.SkillPackageFile]]:+ """Every version's file list in one query, keyed by version id."""+ if not version_ids:+ return {}+ placeholders = ", ".join(f"${i + 1}" for i in range(len(version_ids)))+ rows = await query_raw_with_schema(+ _FILE_META_SELECT+ + 'WHERE "skillListingVersionId" IN ('+ + placeholders+ + ') ORDER BY "relativePath"',+ *version_ids,+ )+ by_version: dict[str, list[skill_model.SkillPackageFile]] = {}+ for row in rows:+ by_version.setdefault(row["skillListingVersionId"], []).append(+ _to_file_meta(row)+ )+ return by_version++async def get_live_skills(listing_ids: list[str],) -> dict[str, skill_model.MarketplaceSkill]:@@ -136,17 +220,25 @@ async def _read_version_files(skill_listing_version_id: str) -> list[SkillFile]:async def _list_version_file_meta(skill_listing_version_id: str,) -> list[skill_model.SkillPackageFile]:- """Path and size per file, without the bytes.+ return (await file_meta_by_version([skill_listing_version_id])).get(+ skill_listing_version_id, []+ )- 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,++# Raw because prisma-client-py always selects every column, and a page that+# pulled `content` would carry the whole package per request.+_FILE_META_SELECT = (+ 'SELECT "skillListingVersionId", "relativePath", "sizeBytes", "mimeType", '+ '"isExecutable" FROM {schema_prefix}"SkillListingFile" '+)+++def _to_file_meta(row: dict) -> skill_model.SkillPackageFile:+ return skill_model.SkillPackageFile(+ path=row["relativePath"],+ size_bytes=row["sizeBytes"],+ mime_type=row["mimeType"],+ is_executable=row["isExecutable"],)diff --git a/autogpt_platform/backend/backend/api/features/store/skill_file_routes_test.py b/autogpt_platform/backend/backend/api/features/store/skill_file_routes_test.pynew file mode 100644index 0000000000..c66cde13ee--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/store/skill_file_routes_test.py@@ -0,0 +1,294 @@+"""Reading one file of a published skill package.++The viewer exists so someone deciding to install a package — or an admin+deciding to approve one — can read its scripts before committing to them. It+serves text and refuses everything else, and a submission nobody has approved+is the submitter's and the reviewer's alone.+"""++from unittest.mock import AsyncMock, patch++import fastapi+import prisma.models+import pytest+import pytest_mock++from backend.api.features.admin import store_admin_routes+from backend.copilot.tools.skills import (+ SkillFile,+ parse_skill_markdown,+ store_user_skill,+)+from backend.util.exceptions import NotFoundError+from backend.util.test import SpinTestServer++from . import skill_db, skill_model, skill_routes, skill_submission_db++SLUG = "package-viewer"+SKILL_MD = (+ "---\nname: package-viewer\ndescription: A package worth reading\n---\n\nRead me.\n"+)+SCRIPT = SkillFile(+ relative_path="scripts/run.sh",+ content=b"#!/bin/sh\necho hi\n",+ is_executable=True,+)+# Enough of a header to be unmistakably not text, and short enough to publish.+PNG = SkillFile(+ relative_path="assets/logo.png", content=b"\x89PNG\r\n\x1a\n" + bytes(16)+)+++async def test_the_live_version_serves_a_text_file_to_anyone(+ creator: str, setup_admin_user: str+):+ """Anonymous, because the listing this belongs to is public. Without it+ every refusal below would pass on a door that never opens."""+ await _publish(creator, [SCRIPT], approved_by=setup_admin_user)++ text = await skill_routes.read_marketplace_skill_file(+ slug=SLUG, path=SCRIPT.relative_path, version_id=None, user_id=None+ )++ assert text == "#!/bin/sh\necho hi\n"+++async def test_a_file_whose_type_has_no_name_is_decided_on_its_bytes(+ creator: str, setup_admin_user: str+):+ """`mimetypes` cannot name a `Makefile`, and a reviewer still has to read+ one, so the decode decides rather than the missing name."""+ await _publish(+ creator,+ [SkillFile(relative_path="Makefile", content=b"all:\n\techo hi\n")],+ approved_by=setup_admin_user,+ )+ row = await prisma.models.SkillListingFile.prisma().find_first(+ where={"relativePath": "Makefile"}+ )+ assert row is not None and row.mimeType is None, "the null branch moved"++ text = await skill_routes.read_marketplace_skill_file(+ slug=SLUG, path="Makefile", version_id=None, user_id=None+ )++ assert text == "all:\n\techo hi\n"+++async def test_a_file_over_the_cap_is_refused_without_reading_its_bytes(+ creator: str, setup_admin_user: str, mocker: pytest_mock.MockerFixture+):+ oversized = SkillFile(+ relative_path="references/big.md",+ content=b"x" * (skill_routes.MAX_VIEWABLE_FILE_BYTES + 1),+ )+ await _publish(creator, [oversized], approved_by=setup_admin_user)+ read_bytes = mocker.spy(skill_db, "read_package_file_bytes")++ with pytest.raises(fastapi.HTTPException) as refused:+ await skill_routes.read_marketplace_skill_file(+ slug=SLUG, path=oversized.relative_path, version_id=None, user_id=None+ )++ assert refused.value.status_code == 413+ # The cap is decided on the metadata row, so the bytes it refuses are+ # never loaded to refuse them.+ assert read_bytes.call_count == 0+++async def test_a_binary_file_is_refused_by_its_type(+ creator: str, setup_admin_user: str, mocker: pytest_mock.MockerFixture+):+ await _publish(creator, [PNG], approved_by=setup_admin_user)+ read_bytes = mocker.spy(skill_db, "read_package_file_bytes")++ with pytest.raises(fastapi.HTTPException) as refused:+ await skill_routes.read_marketplace_skill_file(+ slug=SLUG, path=PNG.relative_path, version_id=None, user_id=None+ )++ assert refused.value.status_code == 415+ assert "image/png" in refused.value.detail+ assert read_bytes.call_count == 0+++async def test_a_path_outside_the_package_is_not_found_and_reads_nothing(+ creator: str, setup_admin_user: str, mocker: pytest_mock.MockerFixture+):+ """The path is matched against the published rows, so it addresses no+ storage and a traversal attempt is simply a path the package lacks."""+ await _publish(creator, [SCRIPT], approved_by=setup_admin_user)+ read_bytes = mocker.spy(skill_db, "read_package_file_bytes")++ with pytest.raises(fastapi.HTTPException) as refused:+ await skill_routes.read_marketplace_skill_file(+ slug=SLUG, path="../../etc/passwd", version_id=None, user_id=None+ )++ assert refused.value.status_code == 404+ assert read_bytes.call_count == 0+++async def test_a_pending_submission_is_readable_by_its_submitter_alone(+ creator: str, stranger: str+):+ """A first submission has no approved version, so the slug resolves to no+ live listing at all — which is why the version id exists."""+ version_id = await _publish(creator, [SCRIPT], approved_by=None)++ assert (+ await skill_routes.read_marketplace_skill_file(+ slug=SLUG,+ path=SCRIPT.relative_path,+ version_id=version_id,+ user_id=creator,+ )+ == "#!/bin/sh\necho hi\n"+ )++ # `rest_api.py` maps NotFoundError to 404, so a stranger cannot tell an+ # unapproved package from one that does not exist.+ for caller in (stranger, None):+ with pytest.raises(NotFoundError):+ await skill_routes.read_marketplace_skill_file(+ slug=SLUG,+ path=SCRIPT.relative_path,+ version_id=version_id,+ user_id=caller,+ )+ with pytest.raises(NotFoundError):+ await skill_routes.read_marketplace_skill_file(+ slug=SLUG, path=SCRIPT.relative_path, version_id=None, user_id=creator+ )+++async def test_a_reviewer_reads_a_pending_submission_through_the_admin_route(+ creator: str,+):+ """The admin router's own security is what grants this; the handler is+ reached by version id because a first submission has no live slug."""+ version_id = await _publish(creator, [SCRIPT], approved_by=None)++ text = await store_admin_routes.read_skill_submission_file(+ version_id, SCRIPT.relative_path+ )++ assert text == "#!/bin/sh\necho hi\n"+++async def test_a_pending_submission_lists_its_files_for_the_reviewer(creator: str):+ await _publish(creator, [SCRIPT, PNG], approved_by=None)++ pending = await skill_submission_db.list_pending_skill_submissions()+ [submission] = [s for s in pending if s.slug == SLUG]++ assert [(f.path, f.is_executable) for f in submission.files] == [+ (PNG.relative_path, False),+ (SCRIPT.relative_path, True),+ ]+ assert submission.files[0].mime_type == "image/png"+ assert submission.files[1].size_bytes == len(SCRIPT.content)+ # Not a literal: `.sh` is `application/x-sh` here and `text/x-sh` on CI.+ assert submission.files[1].mime_type is not None+++async def test_the_detail_response_names_each_file_type_and_mode(+ creator: str, setup_admin_user: str+):+ """Against the stored rows, never a literal type: publish derives the type+ with ``mimetypes``, which reads the host's /etc/mime.types, so `.sh` is+ ``application/x-sh`` on this machine and ``text/x-sh`` on CI."""+ await _publish(creator, [SCRIPT, PNG], approved_by=setup_admin_user)++ details = await skill_db.get_marketplace_skill(SLUG)++ stored = {+ row.relativePath: row+ for row in await prisma.models.SkillListingFile.prisma().find_many(+ where={+ "SkillListingVersion": {"is": {"SkillListing": {"is": {"slug": SLUG}}}}+ }+ )+ }+ assert [(f.path, f.mime_type, f.is_executable) for f in details.files] == [+ (PNG.relative_path, stored[PNG.relative_path].mimeType, False),+ (SCRIPT.relative_path, stored[SCRIPT.relative_path].mimeType, True),+ ]+ assert stored[PNG.relative_path].mimeType == "image/png"+++async def _publish(+ user_id: str, files: list[SkillFile], *, approved_by: str | None+) -> str:+ """Store *files* as the caller's library skill and submit it, returning the+ submitted version's id; approved when *approved_by* names a reviewer."""+ parsed = parse_skill_markdown(SKILL_MD, 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,+ )+ submission = await skill_submission_db.submit_skill(+ user_id,+ skill_model.SkillSubmissionRequest(skill_name=SLUG, categories=["content"]),+ )+ if approved_by is not None:+ await skill_submission_db.review_skill_submission(+ submission.skill_listing_version_id,+ is_approved=True,+ reviewer_id=approved_by,+ comments="ok",+ )+ return submission.skill_listing_version_id+++async def creator(setup_test_user, server: SpinTestServer):+ await _drop_our_listing()+ await prisma.models.Profile.prisma().upsert(+ where={"userId": setup_test_user},+ data={+ "create": {+ "userId": setup_test_user,+ "username": "viewer-creator",+ "name": "Viewer Creator",+ "description": "",+ "links": [],+ },+ "update": {},+ },+ )+ yield setup_test_user+ # Left behind, these rows fail the emptiness guard in the store suites that+ # sort after this one.+ await _drop_our_listing()+++async def _drop_our_listing() -> 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": SLUG}}}+ )+ await prisma.models.SkillListing.prisma().delete_many(where={"slug": SLUG})+++def stranger() -> str:+ """Never a row: the check compares the listing's owner to a caller id, so+ a string that owns nothing is exactly the case under test."""+ return "a-user-who-owns-nothing"++[email protected](autouse=True)+def skills_enabled():+ with patch(+ "backend.copilot.tools.skills.is_skills_feature_enabled",+ new=AsyncMock(return_value=True),+ ):+ yielddiff --git a/autogpt_platform/backend/backend/api/features/store/skill_model.py b/autogpt_platform/backend/backend/api/features/store/skill_model.pyindex 5ad92455ee..033b47c601 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_model.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_model.py@@ -55,6 +55,10 @@ class SkillPackageFile(pydantic.BaseModel):path: strsize_bytes: int+ # Null for an extension `mimetypes` cannot name — a `Makefile`, a `.toml`+ # — which the viewer still serves, deciding on the bytes instead.+ mime_type: str | None = None+ is_executable: bool = Falseclass MarketplaceSkillDetails(MarketplaceSkill):@@ -142,12 +146,20 @@ class SkillSubmission(pydantic.BaseModel):is_live: bool = pydantic.Field(description="Whether this version is the one the marketplace serves.")+ files: list[SkillPackageFile] = pydantic.Field(+ default_factory=list,+ description=(+ "Files beside the submitted SKILL.md, so a reviewer sees what a "+ "package ships before approving it."+ ),+ )@classmethoddef from_db(cls,version: prisma.models.SkillListingVersion,listing: prisma.models.SkillListing,+ files: list[SkillPackageFile] | None = None,) -> "SkillSubmission":return cls(skill_listing_version_id=version.id,@@ -160,4 +172,5 @@ class SkillSubmission(pydantic.BaseModel):status=version.submissionStatus,review_comments=version.reviewComments,is_live=listing.activeVersionId == version.id,+ files=files or [],)diff --git a/autogpt_platform/backend/backend/api/features/store/skill_routes.py b/autogpt_platform/backend/backend/api/features/store/skill_routes.pyindex 29fb5bafa5..5d59311f8f 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_routes.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_routes.py@@ -14,6 +14,10 @@ from . import skill_db, skill_model, skill_submission_db# evaluated as an anonymous context, which with the flag off answers False._ANONYMOUS_FLAG_KEY = "anonymous"+# This endpoint is a source viewer for someone deciding to install or approve a+# package, not a file server: a file past this is refused rather than streamed.+MAX_VIEWABLE_FILE_BYTES = 256 * 1024+async def require_skills_hub_flag(user_id: str | None = Security(autogpt_libs.auth.get_optional_user_id),@@ -117,6 +121,108 @@ async def get_marketplace_skill(return await skill_db.get_marketplace_skill(slug)+ "/{slug}/files/{path:path}",+ summary="Read marketplace skill file",+ tags=["store", "public"],+ response_class=fastapi.responses.PlainTextResponse,+ responses={+ 404: {"description": "Skill, version or file not found"},+ 413: {"description": "File is too large to view"},+ 415: {"description": "File is not text"},+ },+)+async def read_marketplace_skill_file(+ slug: str = Path(..., description="Slug of the skill listing"),+ path: str = Path(..., description="File's path relative to the skill folder"),+ version_id: str | None = Query(+ default=None,+ description=(+ "Read this version instead of the live one. A pending submission "+ "is readable only by the creator who submitted it."+ ),+ ),+ user_id: str | None = Security(autogpt_libs.auth.get_optional_user_id),+) -> str:+ """One file's text, for reading a package before installing it."""+ version = await skill_db.find_readable_version(+ slug, version_id=version_id, user_id=user_id+ )+ return await read_package_file(version.id, path)+++async def read_package_file(skill_listing_version_id: str, relative_path: str) -> str:+ """The published file's text, or the refusal that applies to it.++ Shared with the admin reviewer's own route, which reaches a pending+ version through its router's admin check rather than through this one.+ """+ meta = await skill_db.get_package_file_meta(skill_listing_version_id, relative_path)+ # The path is matched against the published rows, so nothing here can+ # address storage — an unknown path is simply not part of the package.+ if meta is None:+ raise fastapi.HTTPException(+ status_code=404, detail=f"'{relative_path}' is not part of this package"+ )+ if meta.size_bytes > MAX_VIEWABLE_FILE_BYTES:+ raise fastapi.HTTPException(+ status_code=413,+ detail=(+ f"'{relative_path}' is {meta.size_bytes} bytes; this endpoint "+ f"serves up to {MAX_VIEWABLE_FILE_BYTES}"+ ),+ )+ if not _is_text_type(meta.mime_type):+ raise fastapi.HTTPException(+ status_code=415,+ detail=f"'{relative_path}' is {meta.mime_type}, which is not text",+ )+ content = await skill_db.read_package_file_bytes(+ skill_listing_version_id, relative_path+ )+ if content is None:+ raise fastapi.HTTPException(+ status_code=404, detail=f"'{relative_path}' is not part of this package"+ )+ try:+ return content.decode("utf-8")+ except UnicodeDecodeError:+ raise fastapi.HTTPException(+ status_code=415, detail=f"'{relative_path}' is not valid UTF-8 text"+ )+++def _is_text_type(mime_type: str | None) -> bool:+ """Whether the viewer will serve a file of this type.++ ``None`` is an extension ``mimetypes`` cannot name — a ``Makefile``, a+ ``.toml`` — which a reviewer still has to read, so the decode below is+ what refuses those rather than the name.+ """+ if mime_type is None:+ return True+ return mime_type.startswith("text/") or mime_type in _TEXT_APPLICATION_TYPES+++# `application/…` types a package ships as source a reviewer reads; every other+# non-`text/` type is a binary this will not serve. Listed rather than derived+# from `mimetypes`, which reads the publishing host's /etc/mime.types, so a row+# can carry a spelling this machine never produces.+_TEXT_APPLICATION_TYPES = frozenset(+ {+ "application/javascript",+ "application/json",+ "application/sql",+ "application/toml",+ "application/x-httpd-php",+ "application/x-sh",+ "application/x-yaml",+ "application/xml",+ "application/yaml",+ }+)++@router.post("/{slug}/install",summary="Install marketplace skill",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.pyindex 544586bdc3..432dac7bb3 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@@ -24,7 +24,7 @@ from backend.copilot.tools.skills import (from backend.data.db import transactionfrom backend.util.exceptions import NotFoundError, PreconditionFailed-from . import skill_model+from . import skill_db, skill_modelasync def submit_skill(@@ -196,8 +196,11 @@ async def list_pending_skill_submissions() -> list[skill_model.SkillSubmission]:include={"SkillListing": True},order={"createdAt": "asc"},)+ # In one query rather than per row: a reviewer sees what a package ships+ # without opening it, and the bytes stay behind the file route.+ files = await skill_db.file_meta_by_version([v.id for v in versions])return [- skill_model.SkillSubmission.from_db(v, v.SkillListing)+ skill_model.SkillSubmission.from_db(v, v.SkillListing, files.get(v.id, []))for v in versionsif v.SkillListing is not None]diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/__tests__/skill-submissions.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/__tests__/skill-submissions.test.tsxindex 0961084d66..9cd3e55fab 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/__tests__/skill-submissions.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/__tests__/skill-submissions.test.tsx@@ -25,8 +25,24 @@ const pending: SkillSubmission = {status: "PENDING",review_comments: null,is_live: false,+ files: [],};+const PACKAGE = [+ {+ path: "references/tone.md",+ size_bytes: 2048,+ mime_type: "text/markdown",+ is_executable: false,+ },+ {+ path: "scripts/check.sh",+ size_bytes: 3693,+ mime_type: "application/x-sh",+ is_executable: true,+ },+];+describe("admin skill submissions", () => {test("shows what a reviewer needs to judge the submission", async () => {server.use(@@ -100,6 +116,39 @@ describe("admin skill submissions", () => {expect(screen.queryByText(/No skill submissions are waiting/)).toBeNull();});+ test("counts a package's files and opens one before approving", async () => {+ server.use(+ getGetV2AdminListPendingSkillSubmissionsMockHandler200([+ { ...pending, files: PACKAGE },+ ]),+ http.get("*/api/store/admin/skills/submissions/:id/files/*", () =>+ HttpResponse.text("#!/bin/sh\necho checking\n"),+ ),+ );++ render(<AdminSkillSubmissions />);++ await userEvent.click(await screen.findByTestId("files-version-1"));+ expect(await screen.findByText("2 files")).toBeDefined();+ expect(await screen.findByText("scripts/check.sh")).toBeDefined();+ expect(screen.getByText("executable")).toBeDefined();++ await userEvent.click(screen.getByRole("button", { name: /check\.sh/ }));++ expect(await screen.findByText(/echo checking/)).toBeDefined();+ });++ test("shows no file control for a single-file submission", async () => {+ server.use(+ getGetV2AdminListPendingSkillSubmissionsMockHandler200([pending]),+ );++ render(<AdminSkillSubmissions />);++ await screen.findByTestId("admin-skill-submissions");+ expect(screen.queryByTestId("files-version-1")).toBeNull();+ });+test("says the queue is empty rather than rendering an empty list", async () => {server.use(getGetV2AdminListPendingSkillSubmissionsMockHandler200([]));diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminSkillSubmissionFiles.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminSkillSubmissionFiles.tsxnew file mode 100644index 0000000000..e1af3cacb7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminSkillSubmissionFiles.tsx@@ -0,0 +1,54 @@+"use client";++import type { SkillPackageFile } from "@/app/api/__generated__/models/skillPackageFile";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { SkillFileViewer } from "@/components/contextual/SkillPackage/SkillFileViewer";+import { SkillPackageFileList } from "@/components/contextual/SkillPackage/SkillPackageFileList";+import { ArrowDown01Icon, ArrowRight01Icon } from "@hugeicons/core-free-icons";+import { useState } from "react";++interface Props {+ versionId: string;+ files: SkillPackageFile[];+}++export function AdminSkillSubmissionFiles({ versionId, files }: Props) {+ const [isExpanded, setIsExpanded] = useState(false);+ const [openFilePath, setOpenFilePath] = useState<string | null>(null);++ if (files.length === 0) return null;++ return (+ <div className="w-full">+ <button+ type="button"+ onClick={() => setIsExpanded(!isExpanded)}+ aria-expanded={isExpanded}+ className="inline-flex items-center gap-1 rounded-md text-zinc-500 transition-colors hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-300 focus-visible:ring-offset-2"+ data-testid={`files-${versionId}`}+ >+ <Icon+ icon={isExpanded ? ArrowDown01Icon : ArrowRight01Icon}+ size={14}+ aria-hidden+ />+ <Text variant="small" className="!text-inherit">+ {files.length === 1 ? "1 file" : `${files.length} files`}+ </Text>+ </button>++ {isExpanded ? (+ <div className="mt-2">+ <SkillPackageFileList files={files} onOpenFile={setOpenFilePath} />+ </div>+ ) : null}++ <SkillFileViewer+ source={{ kind: "submission", versionId }}+ path={openFilePath}+ onClose={() => setOpenFilePath(null)}+ />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminSkillSubmissions.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminSkillSubmissions.tsxindex 5de9200bb6..72ccd5de43 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminSkillSubmissions.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminSkillSubmissions.tsx@@ -2,6 +2,7 @@import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";+import { AdminSkillSubmissionFiles } from "./AdminSkillSubmissionFiles";import { useAdminSkillSubmissions } from "./useAdminSkillSubmissions";export function AdminSkillSubmissions() {@@ -76,6 +77,10 @@ export function AdminSkillSubmissions() {Approve</Button></div>+ <AdminSkillSubmissionFiles+ versionId={submission.skill_listing_version_id}+ files={submission.files ?? []}+ /></li>))}</ul>diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/package-contents.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/package-contents.test.tsxnew file mode 100644index 0000000000..7cf821cb42--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/package-contents.test.tsx@@ -0,0 +1,233 @@+import { getListCopilotSkillsMockHandler200 } from "@/app/api/__generated__/endpoints/skills/skills.msw";+import {+ getGetV2GetMarketplaceSkillMockHandler200,+ getGetV2ListMarketplaceSkillsMockHandler200,+} from "@/app/api/__generated__/endpoints/store/store.msw";+import type { MarketplaceSkillDetails } from "@/app/api/__generated__/models/marketplaceSkillDetails";+import type { SkillPackageFile } from "@/app/api/__generated__/models/skillPackageFile";+import { server } from "@/mocks/mock-server";+import {+ configure,+ render,+ screen,+ within,+} from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { HttpResponse, http } from "msw";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { SkillPage } from "../components/SkillPage";++// The page waits on several queries before anything renders, and CI is slower+// than a dev machine; the testing-library default is one second.+configure({ asyncUtilTimeout: 10000 });++const mockUseAuth = vi.hoisted(() => vi.fn());+const mockNotFound = vi.hoisted(() => vi.fn());+const flag = vi.hoisted(() => ({ enabled: true, ready: true }));++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+ replace: vi.fn(),+ }),+ usePathname: () => "/marketplace/skills/webapp-testing",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({ slug: SLUG }),+ notFound: mockNotFound,+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({ useAuth: mockUseAuth }));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return { ...actual, useFlagStatus: () => flag };+});++const SLUG = "webapp-testing";+const SCRIPT_PATH = "scripts/with_server.py";+const SCRIPT_SOURCE = "#!/usr/bin/env python3\nprint('serving')\n";++// The vendored fixture's published package, byte sizes included, so the+// rendered sizes are a real package's rather than round numbers.+const PACKAGE: SkillPackageFile[] = [+ {+ path: "LICENSE.txt",+ size_bytes: 11345,+ mime_type: "text/plain",+ is_executable: false,+ },+ {+ path: "examples/console_logging.py",+ size_bytes: 1027,+ mime_type: "text/x-python",+ is_executable: false,+ },+ {+ path: "examples/element_discovery.py",+ size_bytes: 1463,+ mime_type: "text/x-python",+ is_executable: false,+ },+ {+ path: "examples/static_html_automation.py",+ size_bytes: 953,+ mime_type: "text/x-python",+ is_executable: false,+ },+ {+ path: SCRIPT_PATH,+ size_bytes: 3693,+ mime_type: "text/x-python",+ is_executable: true,+ },+];++describe("Marketplace skill package contents", () => {+ beforeEach(() => {+ flag.enabled = true;+ flag.ready = true;+ mockNotFound.mockClear();+ mockUseAuth.mockReturnValue({+ user: { id: "user-1" },+ isLoggedIn: true,+ isUserLoading: false,+ });+ server.use(+ getListCopilotSkillsMockHandler200([]),+ getGetV2ListMarketplaceSkillsMockHandler200({+ skills: [],+ pagination: {+ total_items: 0,+ total_pages: 1,+ current_page: 1,+ page_size: 3,+ },+ }),+ );+ });++ test("lists every file in the package with its size", async () => {+ server.use(detail({ files: PACKAGE }));++ render(<SkillPage slug={SLUG} />);++ const list = await screen.findByTestId("skill-package-files");+ expect(await screen.findByText("Package contents")).toBeDefined();+ for (const file of PACKAGE) {+ expect(await screen.findByText(file.path)).toBeDefined();+ }+ expect(screen.getByText("11.1 KB")).toBeDefined();+ expect(screen.getByText("3.6 KB")).toBeDefined();+ // One file in this package is executable, and the badge says which.+ const badges = within(list).getAllByText("executable");+ expect(badges.length).toBe(1);+ });++ test("shows no section at all for a single-file skill", async () => {+ server.use(detail({ files: [] }));++ render(<SkillPage slug={SLUG} />);++ await screen.findByText("Instructions");+ expect(screen.queryByTestId("skill-package-files")).toBeNull();+ expect(screen.queryByText("Package contents")).toBeNull();+ });++ test("opens a file from the list", async () => {+ server.use(detail({ files: PACKAGE }), fileText(SCRIPT_SOURCE));++ render(<SkillPage slug={SLUG} />);++ await screen.findByTestId("skill-package-files");+ await userEvent.click(screen.getByRole("button", { name: /with_server/ }));++ expect(await screen.findByText(/print\('serving'\)/)).toBeDefined();+ });++ test("opens a relative link in the body instead of following it", async () => {+ server.use(+ detail({+ files: PACKAGE,+ body: `Run the server with [the runner](./${SCRIPT_PATH}).`,+ }),+ fileText(SCRIPT_SOURCE),+ );++ render(<SkillPage slug={SLUG} />);++ const link = await screen.findByRole("button", { name: "the runner" });+ // A link the marketplace never served: it has to open the viewer, so it+ // must not be an anchor pointing at a path that 404s.+ expect(screen.queryByRole("link", { name: "the runner" })).toBeNull();+ await userEvent.click(link);++ expect(await screen.findByText(/print\('serving'\)/)).toBeDefined();+ });++ test("leaves an absolute link in the body alone", async () => {+ server.use(+ detail({+ files: PACKAGE,+ body: "See [the docs](https://example.com/scripts/with_server.py).",+ }),+ );++ render(<SkillPage slug={SLUG} />);++ const link = await screen.findByRole("link", { name: "the docs" });+ expect(link.getAttribute("href")).toBe(+ "https://example.com/scripts/with_server.py",+ );+ });++ test("says so when a file is not one the viewer can show", async () => {+ // The generated handler answers 200 whatever it is given, so the refusal+ // is mocked at the transport.+ server.use(+ detail({ files: PACKAGE }),+ http.get(`/api/proxy/api/store/skills/${SLUG}/files/*`, () =>+ HttpResponse.json({ detail: "not text" }, { status: 415 }),+ ),+ );++ render(<SkillPage slug={SLUG} />);++ await screen.findByTestId("skill-package-files");+ await userEvent.click(screen.getByRole("button", { name: /LICENSE/ }));++ expect(await screen.findByText(/can't be previewed/)).toBeDefined();+ });+});++function detail(overrides: Partial<MarketplaceSkillDetails>) {+ return getGetV2GetMarketplaceSkillMockHandler200({+ slug: SLUG,+ name: SLUG,+ description: "Test a web app end to end.",+ categories: ["development"],+ required_providers: [],+ install_count: 3,+ creator: "anthropics",+ creator_avatar: null,+ skill_listing_version_id: "version-1",+ body: "Use the scripts in this package.",+ triggers: [],+ updated_at: new Date("2026-09-01T00:00:00Z"),+ files: [],+ ...overrides,+ });+}++function fileText(text: string) {+ return http.get(`/api/proxy/api/store/skills/${SLUG}/files/*`, () =>+ HttpResponse.text(text),+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillBody.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillBody.tsxindex 3c804d6948..26f97a652b 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillBody.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillBody.tsx@@ -1,3 +1,4 @@+import { resolvePackagePath } from "@/components/contextual/SkillPackage/helpers";import ReactMarkdown, { type Components } from "react-markdown";import remarkGfm from "remark-gfm";import { prepareSkillBody } from "./helpers";@@ -5,18 +6,68 @@ import { prepareSkillBody } from "./helpers";interface Props {body: string;title: string;+ packagePaths: string[];+ onOpenFile: (path: string) => void;}-export function SkillBody({ body, title }: Props) {+export function SkillBody({ body, title, packagePaths, onOpenFile }: Props) {+ const withFileLinks: Components = {+ ...components,+ a: ({ children, href }) => (+ <BodyLink href={href} packagePaths={packagePaths} onOpenFile={onOpenFile}>+ {children}+ </BodyLink>+ ),+ };+return (<div className="text-[15px] leading-6 text-zinc-700 [overflow-wrap:anywhere]">- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={withFileLinks}>{prepareSkillBody(body, title)}</ReactMarkdown></div>);}+interface BodyLinkProps {+ href: string | undefined;+ packagePaths: string[];+ onOpenFile: (path: string) => void;+ children: React.ReactNode;+}++/** A link to a file the package ships opens the viewer; the marketplace never+ * served those paths, so following one used to 404. */+function BodyLink({ href, packagePaths, onOpenFile, children }: BodyLinkProps) {+ const path = resolvePackagePath(href, packagePaths);+ if (path !== null) {+ return (+ <button+ type="button"+ onClick={() => onOpenFile(path)}+ className={`${LINK_CLASS} font-mono text-[13px]`}+ >+ {children}+ </button>+ );+ }++ const isExternal = /^https?:\/\//i.test(href ?? "");+ return (+ <a+ href={href}+ rel="noreferrer"+ {...(isExternal ? { target: "_blank" } : {})}+ className={LINK_CLASS}+ >+ {children}+ </a>+ );+}++const LINK_CLASS =+ "rounded-sm text-zinc-900 underline underline-offset-2 transition-colors hover:text-violet-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-300 focus-visible:ring-offset-2";+const components: Components = {h1: ({ children }) => <Heading level={3}>{children}</Heading>,h2: ({ children }) => <Heading level={3}>{children}</Heading>,@@ -34,19 +85,6 @@ const components: Components = {strong: ({ children }) => (<strong className="font-semibold text-zinc-900">{children}</strong>),- a: ({ children, href }) => {- const isExternal = /^https?:\/\//i.test(href ?? "");- return (- <a- href={href}- rel="noreferrer"- {...(isExternal ? { target: "_blank" } : {})}- className="text-zinc-900 underline underline-offset-2 transition-colors hover:text-violet-600"- >- {children}- </a>- );- },// Creator markdown carries no dimensions, so the shift is contained by the// radius and max-width rather than eliminated.img: ({ src, alt }) => (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 16ebc03b95..64495c3190 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@@ -20,6 +20,8 @@ import { getCategoryAccent } from "../../../components/ExpertsSection/helpers";import { SkillCard } from "../../../components/SkillsSection/components/SkillCard";import { formatSkillTitle } from "../../../components/SkillsSection/helpers";import { ExpertSection } from "../../../experts/[expertId]/components/ExpertSection";+import { SkillFileViewer } from "@/components/contextual/SkillPackage/SkillFileViewer";+import { SkillPackageFileList } from "@/components/contextual/SkillPackage/SkillPackageFileList";import { ConnectStep } from "./ConnectStep";import { SkillActions } from "./SkillActions";import { SkillBody } from "./SkillBody";@@ -50,6 +52,10 @@ export function SkillPage({ slug }: Props) {addToExpert,pendingConnections,moreSkills,+ files,+ openFilePath,+ openFile,+ closeFile,isConnectOpen,openConnect,setIsConnectOpen,@@ -180,10 +186,25 @@ export function SkillPage({ slug }: Props) {}>{skill.body.trim() ? (- <SkillBody body={skill.body} title={title} />+ <SkillBody+ body={skill.body}+ title={title}+ packagePaths={files.map((file) => file.path)}+ onOpenFile={openFile}+ />) : null}</ExpertSection>+ {files.length > 0 ? (+ <ExpertSection+ title="Package contents"+ count={files.length}+ description="Files installed alongside these instructions."+ >+ <SkillPackageFileList files={files} onOpenFile={openFile} />+ </ExpertSection>+ ) : null}+{skill.triggers.length > 0 ? (<ExpertSectiontitle="Triggers"@@ -214,6 +235,12 @@ export function SkillPage({ slug }: Props) {) : null}</div>+ <SkillFileViewer+ source={{ kind: "listing", slug }}+ path={openFilePath}+ onClose={closeFile}+ />+<ConnectServiceDialogopen={isConnectOpen}onOpenChange={setIsConnectOpen}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.tsindex e08e5cea22..c6c86c90d3 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.ts@@ -33,6 +33,9 @@ export function useSkillPage(slug: string) {const { toast } = useToast();const flag = useFlagStatus(Flag.SKILLS_HUB);const [isConnectOpen, setIsConnectOpen] = useState(false);+ // Page state rather than the list's: a relative link in the body opens the+ // same viewer the package list does.+ const [openFilePath, setOpenFilePath] = useState<string | null>(null);const query = useGetV2GetMarketplaceSkill(slug, {query: { select: (response) => okData(response) ?? null },@@ -140,6 +143,10 @@ export function useSkillPage(slug: string) {.filter((provider) => !connected.has(provider)).map(formatProviderName),moreSkills: (more.data ?? []).filter((skill) => skill.slug !== slug),+ files: query.data?.files ?? [],+ openFilePath,+ openFile: (path: string) => setOpenFilePath(path),+ closeFile: () => setOpenFilePath(null),isConnectOpen,openConnect: () => setIsConnectOpen(true),setIsConnectOpen,diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex ed351dcd92..dfc80d2d05 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -14112,6 +14112,49 @@"security": [{ "HTTPBearerJWT": [] }, { "HTTPBearer": [] }]}},+ "/api/store/admin/skills/submissions/{skill_listing_version_id}/files/{path}": {+ "get": {+ "tags": ["v2", "admin", "store", "admin", "store", "admin"],+ "summary": "Admin Read Skill Submission File",+ "description": "One submitted file's text, so a reviewer reads a script before approving.\n\nThe version is addressed directly rather than through its listing: a first\nsubmission has no approved version for a slug to resolve to, and this\nrouter's admin check is what grants the pending read.",+ "operationId": "getV2Admin read skill submission file",+ "security": [{ "HTTPBearerJWT": [] }, { "HTTPBearer": [] }],+ "parameters": [+ {+ "name": "skill_listing_version_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Skill Listing Version Id" }+ },+ {+ "name": "path",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Path" }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": { "text/plain": { "schema": { "type": "string" } } }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "File not found" },+ "413": { "description": "File is too large to view" },+ "415": { "description": "File is not text" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/store/admin/skills/submissions/{skill_listing_version_id}/review": {"post": {"tags": ["v2", "admin", "store", "admin", "store", "admin"],@@ -15297,6 +15340,67 @@}}},+ "/api/store/skills/{slug}/files/{path}": {+ "get": {+ "tags": ["v2", "store", "public"],+ "summary": "Read marketplace skill file",+ "description": "One file's text, for reading a package before installing it.",+ "operationId": "getV2Read marketplace skill file",+ "security": [{ "HTTPBearer": [] }],+ "parameters": [+ {+ "name": "slug",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "description": "Slug of the skill listing",+ "title": "Slug"+ },+ "description": "Slug of the skill listing"+ },+ {+ "name": "path",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "description": "File's path relative to the skill folder",+ "title": "Path"+ },+ "description": "File's path relative to the skill folder"+ },+ {+ "name": "version_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "description": "Read this version instead of the live one. A pending submission is readable only by the creator who submitted it.",+ "title": "Version Id"+ },+ "description": "Read this version instead of the live one. A pending submission is readable only by the creator who submitted it."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": { "text/plain": { "schema": { "type": "string" } } }+ },+ "404": { "description": "Skill, version or file not found" },+ "413": { "description": "File is too large to view" },+ "415": { "description": "File is not text" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/store/skills/{slug}/install": {"post": {"tags": ["v2", "store", "private"],@@ -28341,7 +28445,16 @@"SkillPackageFile": {"properties": {"path": { "type": "string", "title": "Path" },- "size_bytes": { "type": "integer", "title": "Size Bytes" }+ "size_bytes": { "type": "integer", "title": "Size Bytes" },+ "mime_type": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Mime Type"+ },+ "is_executable": {+ "type": "boolean",+ "title": "Is Executable",+ "default": false+ }},"type": "object","required": ["path", "size_bytes"],@@ -28391,6 +28504,12 @@"type": "boolean","title": "Is Live","description": "Whether this version is the one the marketplace serves."+ },+ "files": {+ "items": { "$ref": "#/components/schemas/SkillPackageFile" },+ "type": "array",+ "title": "Files",+ "description": "Files beside the submitted SKILL.md, so a reviewer sees what a package ships before approving it."}},"type": "object",diff --git a/autogpt_platform/frontend/src/components/contextual/SkillPackage/SkillFileViewer.tsx b/autogpt_platform/frontend/src/components/contextual/SkillPackage/SkillFileViewer.tsxnew file mode 100644index 0000000000..de50329685--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/SkillPackage/SkillFileViewer.tsx@@ -0,0 +1,50 @@+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import {+ type SkillPackageSource,+ useSkillFileViewer,+} from "./useSkillFileViewer";++interface Props {+ source: SkillPackageSource;+ path: string | null;+ onClose: () => void;+}++export function SkillFileViewer({ source, path, onClose }: Props) {+ const { content, isLoading, unavailable } = useSkillFileViewer({+ source,+ path,+ });++ return (+ <Dialog+ title={<span className="break-all font-mono text-sm">{path}</span>}+ styling={{ width: "760px" }}+ controlled={{+ isOpen: path !== null,+ set: (open) => {+ if (!open) onClose();+ },+ }}+ >+ <Dialog.Content>+ <div data-testid="skill-file-viewer">+ {isLoading ? (+ <div className="space-y-2">+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-5/6" />+ <Skeleton className="h-4 w-2/3" />+ </div>+ ) : unavailable ? (+ <p className="text-sm text-zinc-500">{unavailable}</p>+ ) : (+ <pre className="max-h-[60vh] overflow-auto rounded-md bg-zinc-50 p-3 font-mono text-[13px] leading-5 text-zinc-700">+ {content}+ </pre>+ )}+ </div>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/components/contextual/SkillPackage/SkillPackageFileList.tsx b/autogpt_platform/frontend/src/components/contextual/SkillPackage/SkillPackageFileList.tsxnew file mode 100644index 0000000000..681e9705e8--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/SkillPackage/SkillPackageFileList.tsx@@ -0,0 +1,46 @@+import type { SkillPackageFile } from "@/app/api/__generated__/models/skillPackageFile";+import { Icon } from "@/components/atoms/Icon/Icon";+import { File01Icon } from "@hugeicons/core-free-icons";+import { formatFileSize } from "./helpers";++interface Props {+ files: SkillPackageFile[];+ onOpenFile: (path: string) => void;+}++export function SkillPackageFileList({ files, onOpenFile }: Props) {+ return (+ <ul+ className="divide-y divide-zinc-100 overflow-hidden rounded-xl border border-zinc-200"+ data-testid="skill-package-files"+ >+ {files.map((file) => (+ <li key={file.path}>+ <button+ type="button"+ onClick={() => onOpenFile(file.path)}+ className="flex w-full items-center gap-3 px-3 py-2 text-left transition-colors hover:bg-zinc-50 focus-visible:outline-none focus-visible:-outline-offset-2 focus-visible:ring-2 focus-visible:ring-zinc-300"+ >+ <Icon+ icon={File01Icon}+ size={14}+ className="shrink-0 text-zinc-400"+ aria-hidden+ />+ <span className="min-w-0 flex-1 truncate font-mono text-[13px] text-zinc-700">+ {file.path}+ </span>+ {file.is_executable ? (+ <span className="shrink-0 rounded-md bg-zinc-100 px-1.5 py-0.5 text-[11px] font-medium text-zinc-500">+ executable+ </span>+ ) : null}+ <span className="shrink-0 text-xs tabular-nums text-zinc-400">+ {formatFileSize(file.size_bytes)}+ </span>+ </button>+ </li>+ ))}+ </ul>+ );+}diff --git a/autogpt_platform/frontend/src/components/contextual/SkillPackage/helpers.ts b/autogpt_platform/frontend/src/components/contextual/SkillPackage/helpers.tsnew file mode 100644index 0000000000..d604b77b38--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/SkillPackage/helpers.ts@@ -0,0 +1,41 @@+const UNITS = ["B", "KB", "MB"];++/** Deliberately not `toLocaleString`: this machine's Dutch locale renders+ * 1,024 as 1.024, and a package's sizes are compared as rendered text. */+export function formatFileSize(bytes: number): string {+ let size = bytes;+ let unit = 0;+ while (size >= 1024 && unit < UNITS.length - 1) {+ size /= 1024;+ unit += 1;+ }+ // Non-breaking: a size must never wrap between its number and unit.+ return `${unit === 0 ? size : size.toFixed(1)}\u00a0${UNITS[unit]}`;+}++/** The package file a body link points at, or `null` when the link is not one+ * — an absolute URL, an anchor, or a path this package does not ship. */+export function resolvePackagePath(+ href: string | undefined,+ paths: string[],+): string | null {+ if (!href) return null;+ const isAbsolute =+ /^[a-z][a-z0-9+.-]*:/i.test(href) ||+ href.startsWith("//") ||+ href.startsWith("/");+ if (isAbsolute || href.startsWith("#")) return null;++ const bare = href.split(/[?#]/)[0].replace(/^\.\//, "");+ if (!bare) return null;+ const decoded = decodePath(bare);+ return paths.includes(decoded) ? decoded : null;+}++function decodePath(value: string): string {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}diff --git a/autogpt_platform/frontend/src/components/contextual/SkillPackage/useSkillFileViewer.ts b/autogpt_platform/frontend/src/components/contextual/SkillPackage/useSkillFileViewer.tsnew file mode 100644index 0000000000..8bf5aa583c--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/SkillPackage/useSkillFileViewer.ts@@ -0,0 +1,47 @@+import { useGetV2AdminReadSkillSubmissionFile } from "@/app/api/__generated__/endpoints/admin/admin";+import { useGetV2ReadMarketplaceSkillFile } from "@/app/api/__generated__/endpoints/store/store";+import { okData } from "@/app/api/helpers";++export type SkillPackageSource =+ | { kind: "listing"; slug: string }+ | { kind: "submission"; versionId: string };++interface Args {+ source: SkillPackageSource;+ path: string | null;+}++export function useSkillFileViewer({ source, path }: Args) {+ const isListing = source.kind === "listing";+ // Both are declared and one is enabled: a listing reads the approved+ // version, a submission goes through the admin route that can see a+ // version nobody has approved.+ const listing = useGetV2ReadMarketplaceSkillFile(+ isListing ? source.slug : "",+ path ?? "",+ undefined,+ { query: { enabled: isListing && path !== null, retry: false } },+ );+ const submission = useGetV2AdminReadSkillSubmissionFile(+ isListing ? "" : source.versionId,+ path ?? "",+ { query: { enabled: !isListing && path !== null, retry: false } },+ );++ const query = isListing ? listing : submission;+ return {+ content: okData(query.data) ?? null,+ isLoading: query.isPending && path !== null,+ // A refusal is a state to render, not a failure to hide: only the+ // endpoint knows whether a file is one this viewer can serve.+ unavailable: query.isError+ ? describeRefusal((query.error as { status?: number } | null)?.status)+ : null,+ };+}++function describeRefusal(status: number | undefined): string {+ if (status === 413) return "This file is too large to preview here.";+ if (status === 415) return "This file isn't text, so it can't be previewed.";+ return "Couldn't load this file.";+}