AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): upload and download AutoPilot skills from the library (#13421)
Abhimanyu Yadave2711b1748bd
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex 9ae5472613..204deb5910 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -35,6 +35,7 @@ from starlette.status import ()from typing_extensions import Optional, TypedDict+from backend.api.features.store.exceptions import VirusDetectedError, VirusScanErrorfrom backend.api.features.workspace.routes import create_file_download_responsefrom backend.api.model import (CreateAPIKeyRequest,@@ -52,12 +53,15 @@ from backend.blocks import get_block, get_blocksfrom backend.copilot.rate_limit import enforce_payment_paywall, get_tier_multipliersfrom backend.copilot.tools.skills import (BuiltInSkillError,+ SkillLimitError,SkillNotFoundError,delete_user_skill,get_default_skill_with_body,list_user_skill_sibling_paths,list_user_skills,+ parse_skill_markdown,read_user_skill_with_body,+ store_user_skill,)from backend.data import execution as execution_dbfrom backend.data import graph as graph_db@@ -2484,6 +2488,17 @@ class CopilotSkillDetail(BaseModel):sibling_files: list[str] = []+class UploadCopilotSkillRequest(BaseModel):+ """Body for the library UI's "upload skill" action.++ Carries the raw ``SKILL.md`` text (YAML frontmatter + markdown body) the+ user picked from disk; the server parses + validates it so the upload and+ the copilot's ``store_skill`` tool share one source of truth.+ """++ content: str++@v1_router.get(path="/skills",summary="List user-distilled copilot skills",@@ -2512,6 +2527,64 @@ async def list_copilot_skills(]+@v1_router.post(+ path="/skills",+ summary="Upload a copilot skill from a SKILL.md file",+ operation_id="uploadCopilotSkill",+ tags=["skills"],+ status_code=201,+ responses={+ 400: {"description": "Malformed SKILL.md or validation error"},+ 409: {"description": "Per-user skill limit reached"},+ },+ dependencies=[Security(requires_user)],+)+async def upload_copilot_skill(+ user_id: Annotated[str, Security(get_user_id)],+ body: UploadCopilotSkillRequest,+) -> CopilotSkillInfo:+ """Create a user-distilled skill from an uploaded ``SKILL.md`` file.++ Parses the canonical frontmatter + body, then reuses+ :func:`backend.copilot.tools.skills.store_user_skill` so an uploaded skill+ is validated, capped, and persisted exactly like one the copilot distils+ via ``store_skill``. Malformed files return 400, the per-user cap returns+ 409, and an existing slug is overwritten (upsert).+ """+ parsed = parse_skill_markdown(body.content)+ if parsed is None:+ raise HTTPException(+ status_code=400,+ detail=(+ "File is not a valid SKILL.md — expected YAML frontmatter with "+ "'name' and 'description' followed by a markdown body."+ ),+ )+ try:+ stored = await store_user_skill(+ user_id,+ name=parsed.name,+ description=parsed.description,+ body=parsed.body,+ triggers=list(parsed.triggers),+ version=parsed.version,+ )+ except SkillLimitError as exc:+ raise HTTPException(status_code=409, detail=str(exc))+ except (VirusDetectedError, VirusScanError) as exc:+ logger.warning("[skills] virus scan rejected uploaded skill: %s", exc)+ raise HTTPException(+ status_code=400, detail="Skill content rejected by virus scan"+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc))+ return CopilotSkillInfo(+ name=stored.name,+ description=stored.description,+ triggers=list(stored.triggers),+ )++@v1_router.get(path="/skills/{name}",summary="Read a single copilot skill with its full SKILL.md body",diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex da6428ec69..df241552a9 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -11,10 +11,12 @@ import starlette.datastructuresfrom fastapi import HTTPException, UploadFilefrom pytest_snapshot.plugin import Snapshot+from backend.api.features.store.exceptions import VirusDetectedErrorfrom backend.api.rest_api import handle_internal_http_errorfrom backend.copilot.tools.skills import (BuiltInSkillError,ParsedSkill,+ SkillLimitError,SkillNotFoundError,)from backend.data.credit import AutoTopUpConfig@@ -1420,3 +1422,85 @@ def test_read_copilot_skill_returns_404_when_missing(response = client.get("/skills/missing")assert response.status_code == 404+++_VALID_SKILL_MD = (+ "---\n"+ "name: oauth_flow\n"+ "description: OAuth handshake recipe\n"+ "triggers:\n"+ " - auth\n"+ "---\n\n"+ "# OAuth flow\n\nStep 1: redirect to /authorize\n"+)+++def test_upload_copilot_skill_creates_skill(+ mocker: pytest_mock.MockFixture,+) -> None:+ """POST /skills parses the SKILL.md and persists it via store_user_skill."""+ store_mock = AsyncMock(+ return_value=ParsedSkill(+ name="oauth_flow",+ description="OAuth handshake recipe",+ body="# OAuth flow",+ triggers=("auth",),+ )+ )+ mocker.patch("backend.api.features.v1.store_user_skill", store_mock)++ response = client.post("/skills", json={"content": _VALID_SKILL_MD})+ assert response.status_code == 201+ body = response.json()+ assert body["name"] == "oauth_flow"+ assert body["triggers"] == ["auth"]+ store_mock.assert_awaited_once()+ assert store_mock.await_args.kwargs["name"] == "oauth_flow"+++def test_upload_copilot_skill_rejects_malformed_markdown() -> None:+ """A file without valid frontmatter returns 400 before touching storage."""+ response = client.post(+ "/skills", json={"content": "just some text, no frontmatter"}+ )+ assert response.status_code == 400+++def test_upload_copilot_skill_returns_409_when_at_cap(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The per-user cap surfaces as 409 so the UI can prompt a delete."""+ mocker.patch(+ "backend.api.features.v1.store_user_skill",+ AsyncMock(side_effect=SkillLimitError("Skill limit reached (50).")),+ )++ response = client.post("/skills", json={"content": _VALID_SKILL_MD})+ assert response.status_code == 409+++def test_upload_copilot_skill_returns_400_on_validation_error(+ mocker: pytest_mock.MockFixture,+) -> None:+ """A validation failure from store_user_skill maps to 400."""+ mocker.patch(+ "backend.api.features.v1.store_user_skill",+ AsyncMock(side_effect=ValueError("name must be a slug")),+ )++ response = client.post("/skills", json={"content": _VALID_SKILL_MD})+ assert response.status_code == 400+++def test_upload_copilot_skill_returns_400_on_virus_detection(+ mocker: pytest_mock.MockFixture,+) -> None:+ """A virus-scan rejection surfaces as a 400 client error, not a 500."""+ mocker.patch(+ "backend.api.features.v1.store_user_skill",+ AsyncMock(side_effect=VirusDetectedError("nasty")),+ )++ response = client.post("/skills", json={"content": _VALID_SKILL_MD})+ assert response.status_code == 400+ assert "virus scan" in response.json()["detail"]diff --git a/autogpt_platform/backend/backend/copilot/tools/skills.py b/autogpt_platform/backend/backend/copilot/tools/skills.pyindex a08d26354d..aad6499973 100644--- a/autogpt_platform/backend/backend/copilot/tools/skills.py+++ b/autogpt_platform/backend/backend/copilot/tools/skills.py@@ -287,6 +287,10 @@ class BuiltInSkillError(Exception):"""Raised by :func:`delete_user_skill` for default seeded skills."""+class SkillLimitError(Exception):+ """Raised by :func:`store_user_skill` when the per-user cap is reached."""++async def delete_user_skill(user_id: str, name: str) -> str:"""Delete a user-distilled skill folder by slug.@@ -360,6 +364,155 @@ async def delete_user_skill(user_id: str, name: str) -> str:return slug+async def store_user_skill(+ user_id: str,+ *,+ name: str,+ description: str,+ body: str,+ triggers: list[str] | None = None,+ version: str | None = None,+) -> ParsedSkill:+ """Validate + persist a user-distilled skill, returning the stored skill.++ Shared by the ``store_skill`` copilot tool and the REST ``POST /skills``+ upload endpoint so both honour the same validation, per-user cap, and+ write-lock semantics. Raises :class:`ValueError` for any validation+ failure, :class:`SkillLimitError` when the per-user cap is reached, and+ propagates ``VirusDetectedError`` / ``VirusScanError`` (and any other+ workspace write error) to the caller.+ """+ name = name.strip().lower()+ # Strip any server-injected XML tags (``<available_skills>``,+ # ``<env_context>``, etc.) from the persisted fields *before* storage —+ # when the skill is later loaded that text lands in conversation history+ # and could otherwise appear alongside the real server-injected versions.+ description = strip_server_injected_tags(description.strip())+ body = strip_server_injected_tags(body.strip())+ triggers = [+ strip_server_injected_tags(t.strip())+ for t in (triggers or [])+ if str(t).strip()+ ]+ triggers = [t for t in triggers if t]++ name_err = _validate_name(name)+ if name_err:+ raise ValueError(name_err)+ if not description:+ raise ValueError("description is required")+ if len(description) > MAX_DESCRIPTION_CHARS:+ raise ValueError(+ f"description is {len(description)}/{MAX_DESCRIPTION_CHARS} chars "+ f"— trim {len(description) - MAX_DESCRIPTION_CHARS} "+ "(it appears in every turn's skills index)"+ )+ if not body:+ raise ValueError("body is required")+ if len(body) > MAX_BODY_CHARS:+ raise ValueError(f"body must be ≤{MAX_BODY_CHARS} chars")+ if len(triggers) > MAX_TRIGGERS:+ raise ValueError(+ f"triggers must be ≤{MAX_TRIGGERS} entries "+ "(they are inlined in <available_skills> every turn)"+ )+ oversized_trigger = next((t for t in triggers if len(t) > MAX_TRIGGER_CHARS), None)+ if oversized_trigger is not None:+ raise ValueError(+ f"trigger '{oversized_trigger[:32]}…' exceeds {MAX_TRIGGER_CHARS} chars"+ )++ # Serialise the count-then-write critical section per-user so two+ # concurrent writers cannot both pass the MAX_USER_SKILLS check.+ # ``AsyncClusterLock.try_acquire`` is non-blocking, so poll for up to+ # ~1s before falling back to the strict-cap unlocked path below — without+ # the wait, two near-simultaneous calls at MAX-1 both proceed unlocked,+ # both see N<MAX, and both write (cap overruns by 1). Lock failure+ # (Redis unavailable) still falls back to the unlocked write but the+ # cap-enforcement branch below refuses any at-cap write in that case.+ lock: AsyncClusterLock | None = None+ lock_held = False+ try:+ lock = AsyncClusterLock(+ redis=await get_redis_async(),+ key=f"{_SKILL_WRITE_LOCK_KEY_PREFIX}{user_id}",+ owner_id=uuid.uuid4().hex,+ timeout=_SKILL_WRITE_LOCK_TTL_SECONDS,+ )+ for _ in range(10):+ if (await lock.try_acquire()) == lock.owner_id:+ lock_held = True+ break+ await asyncio.sleep(0.1)+ except Exception:+ logger.warning(+ "[skills] failed to acquire write lock for user %s — "+ "falling back to unlocked best-effort write",+ user_id,+ exc_info=True,+ )+ try:+ manager = await _get_user_skill_manager(user_id)+ # Enforce the per-user cap *before* we write. When the lock IS held+ # this is a true atomic check-then-write — an upsert at-cap is safe+ # because no new slot is consumed. When the lock FAILED to acquire,+ # the check is no longer atomic, so refuse any write at-or-above the+ # cap defensively (the caller can retry; a Redis blip is rare).+ existing = await list_user_skills(user_id)+ existing_slugs = {s.name for s in existing}+ at_cap = len(existing_slugs) >= MAX_USER_SKILLS+ is_new = name not in existing_slugs+ if at_cap and (is_new or not lock_held):+ if not lock_held:+ logger.warning(+ "[skills] refusing at-cap unlocked write for user %s "+ "(is_new=%s) — concurrent write could otherwise overrun "+ "the cap",+ user_id,+ is_new,+ )+ raise SkillLimitError(+ f"Skill limit reached ({MAX_USER_SKILLS}). "+ "Delete an unused skill first."+ )++ parsed = ParsedSkill(+ name=name,+ description=description,+ body=body,+ triggers=tuple(triggers),+ version=version,+ )+ rendered = render_skill_markdown(parsed)+ metadata: dict[str, Any] = {+ _META_KIND: _META_KIND_VALUE,+ _META_DESCRIPTION: description,+ _META_TRIGGERS: list(triggers),+ }+ if version:+ metadata[_META_VERSION] = version+ await manager.write_file(+ content=rendered.encode("utf-8"),+ filename="SKILL.md",+ path=_skill_md_path(name),+ mime_type="text/markdown",+ overwrite=True,+ metadata=metadata,+ )+ await invalidate_skills_index_cache(user_id)+ return parsed+ finally:+ if lock is not None and lock_held:+ try:+ await lock.release()+ except Exception:+ logger.warning(+ "[skills] failed to release write lock for user %s",+ user_id,+ exc_info=True,+ )++async def _parse_skill_from_workspace(manager: WorkspaceManager, file_path: str) -> ParsedSkill | None:@@ -822,150 +975,14 @@ class StoreSkillTool(BaseTool):session_id=session_id,)- name = name.strip().lower()- # Strip any server-injected XML tags (``<available_skills>``,- # ``<env_context>``, etc.) from the description/body/triggers- # *before* persistence — when the model later loads the skill via- # read_skill, that text lands in the conversation history and- # could otherwise appear alongside the real server-injected- # versions in the next turn's first user message.- description = strip_server_injected_tags(description.strip())- body = strip_server_injected_tags(body.strip())- triggers = [- strip_server_injected_tags(t.strip())- for t in (triggers or [])- if str(t).strip()- ]- triggers = [t for t in triggers if t]-- name_err = _validate_name(name)- if name_err:- return ErrorResponse(message=name_err, session_id=session_id)- if not description:- return ErrorResponse(- message="description is required", session_id=session_id- )- if len(description) > MAX_DESCRIPTION_CHARS:- return ErrorResponse(- message=(- f"description must be ≤{MAX_DESCRIPTION_CHARS} chars "- "(it appears in every turn's skills index)"- ),- session_id=session_id,- )- if not body:- return ErrorResponse(message="body is required", session_id=session_id)- if len(body) > MAX_BODY_CHARS:- return ErrorResponse(- message=f"body must be ≤{MAX_BODY_CHARS} chars",- session_id=session_id,- )- if len(triggers) > MAX_TRIGGERS:- return ErrorResponse(- message=(- f"triggers must be ≤{MAX_TRIGGERS} entries "- "(they are inlined in <available_skills> every turn)"- ),- session_id=session_id,- )- oversized_trigger = next(- (t for t in triggers if len(t) > MAX_TRIGGER_CHARS), None- )- if oversized_trigger is not None:- return ErrorResponse(- message=(- f"trigger '{oversized_trigger[:32]}…' exceeds "- f"{MAX_TRIGGER_CHARS} chars"- ),- session_id=session_id,- )-- # Serialise the count-then-write critical section per-user so two- # concurrent ``store_skill`` calls cannot both pass the MAX- # check. ``AsyncClusterLock.try_acquire`` is non-blocking, so- # poll for up to ~1s before falling back to the strict-cap- # unlocked path below — without the wait, two near-simultaneous- # calls at MAX-1 both proceed unlocked, both see N<MAX, and- # both write (cap overruns by 1). Lock failure (Redis- # unavailable) still falls back to the unlocked write but the- # cap-enforcement branch below refuses any at-cap write in- # that case.- lock: AsyncClusterLock | None = None- lock_held = Falsetry:- lock = AsyncClusterLock(- redis=await get_redis_async(),- key=f"{_SKILL_WRITE_LOCK_KEY_PREFIX}{user_id}",- owner_id=uuid.uuid4().hex,- timeout=_SKILL_WRITE_LOCK_TTL_SECONDS,- )- for _ in range(10):- if (await lock.try_acquire()) == lock.owner_id:- lock_held = True- break- await asyncio.sleep(0.1)- except Exception:- logger.warning(- "[skills] failed to acquire write lock for user %s — "- "falling back to unlocked best-effort write",+ parsed = await store_user_skill(user_id,- exc_info=True,- )- try:- manager = await _get_user_skill_manager(user_id)- # Enforce the per-user cap *before* we write.- #- # When the lock IS held this is a true atomic check-then-write- # — an upsert at-cap is safe because no new slot is consumed.- #- # When the lock FAILED to acquire (Redis hiccup or genuine- # contention) the check is no longer atomic, so two unlocked- # writers could both see ``N == MAX_USER_SKILLS`` and both- # commit, landing at ``MAX_USER_SKILLS+1``. Treat the cap- # strictly in that branch: refuse any write at-or-above the- # cap, including upserts (the model can retry; a transient- # Redis blip is rare and recovery is cheap).- existing = await list_user_skills(user_id)- existing_slugs = {s.name for s in existing}- at_cap = len(existing_slugs) >= MAX_USER_SKILLS- is_new = name not in existing_slugs- if at_cap and (is_new or not lock_held):- if not lock_held:- logger.warning(- "[skills] refusing at-cap unlocked write for user %s "- "(is_new=%s) — concurrent store_skill could "- "otherwise overrun the cap",- user_id,- is_new,- )- return ErrorResponse(- message=(- f"Skill limit reached ({MAX_USER_SKILLS}). "- "Delete an unused skill with delete_skill first."- ),- session_id=session_id,- )-- parsed = ParsedSkill(name=name,description=description,body=body,- triggers=tuple(triggers),- )- rendered = render_skill_markdown(parsed)- await manager.write_file(- content=rendered.encode("utf-8"),- filename="SKILL.md",- path=_skill_md_path(name),- mime_type="text/markdown",- overwrite=True,- metadata={- _META_KIND: _META_KIND_VALUE,- _META_DESCRIPTION: description,- _META_TRIGGERS: list(triggers),- },+ triggers=triggers,)- await invalidate_skills_index_cache(user_id)except (VirusDetectedError, VirusScanError) as exc:logger.warning("[skills] virus scan failed for %s: %s", name, exc)return ErrorResponse(@@ -973,7 +990,7 @@ class StoreSkillTool(BaseTool):error=str(exc),session_id=session_id,)- except ValueError as exc:+ except (ValueError, SkillLimitError) as exc:return ErrorResponse(message=str(exc), session_id=session_id)except Exception as exc:logger.exception("[skills] failed to store skill %s", name)@@ -982,23 +999,13 @@ class StoreSkillTool(BaseTool):error=str(exc),session_id=session_id,)- finally:- if lock is not None and lock_held:- try:- await lock.release()- except Exception:- logger.warning(- "[skills] failed to release write lock for user %s",- user_id,- exc_info=True,- )return StoreSkillResponse(- name=name,- description=description,- triggers=list(triggers),+ name=parsed.name,+ description=parsed.description,+ triggers=list(parsed.triggers),message=(- f"Skill '{name}' stored. It will appear in "+ f"Skill '{parsed.name}' stored. It will appear in ""<available_skills> on the next turn."),session_id=session_id,diff --git a/autogpt_platform/backend/backend/copilot/tools/skills_test.py b/autogpt_platform/backend/backend/copilot/tools/skills_test.pyindex 817e0d4954..bdf03d4cea 100644--- a/autogpt_platform/backend/backend/copilot/tools/skills_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/skills_test.py@@ -35,6 +35,7 @@ from backend.copilot.tools.skills import (parse_skill_markdown,render_skill_markdown,render_skills_index,+ store_user_skill,)# ---------------------------------------------------------------------------@@ -571,6 +572,25 @@ async def test_store_skill_upsert_does_not_trip_cap():assert "new" in fake_manager.files["/skills/skill_0/SKILL.md"].decode()+async def test_store_user_skill_persists_version():+ """An uploaded skill's version must survive the write so a+ download → re-upload round-trip does not silently drop it."""+ fake_manager = _FakeWorkspaceManager()+ with _patch_skills_path(fake_manager):+ stored = await store_user_skill(+ "user-1",+ name="versioned_skill",+ description="desc",+ body="body",+ version="2",+ )+ assert stored.version == "2"+ written = fake_manager.files["/skills/versioned_skill/SKILL.md"].decode()+ assert parse_skill_markdown(written).version == "2"+ assert fake_manager.metadata["/skills/versioned_skill/SKILL.md"]["version"] == "2"++# ---------------------------------------------------------------------------# ReadSkillTool# ---------------------------------------------------------------------------diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/getSkillUploadError.test.ts b/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/getSkillUploadError.test.tsnew file mode 100644index 0000000000..47cf787952--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/getSkillUploadError.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test } from "vitest";+import {+ getSkillUploadError,+ MAX_SKILL_DESCRIPTION_CHARS,+} from "../components/UploadSkillButton/helpers";++function md(frontmatter: string, body = "# Body\n\ncontent"): string {+ return `---\n${frontmatter}\n---\n\n${body}`;+}++describe("getSkillUploadError", () => {+ test("returns null for a valid SKILL.md", () => {+ expect(+ getSkillUploadError(md("name: ok_skill\ndescription: A short hook.")),+ ).toBeNull();+ });++ test("flags a file with no frontmatter", () => {+ const err = getSkillUploadError("just prose, no frontmatter block");+ expect(err).toContain("not a valid SKILL.md");+ });++ test("reports the exact length when description is too long", () => {+ const desc = "x".repeat(MAX_SKILL_DESCRIPTION_CHARS + 1);+ const err = getSkillUploadError(md(`name: ok_skill\ndescription: ${desc}`));+ expect(err).toContain(`${MAX_SKILL_DESCRIPTION_CHARS + 1}/200`);+ expect(err).toContain("trim at least 1");+ });++ test("accepts a description exactly at the limit", () => {+ const desc = "x".repeat(MAX_SKILL_DESCRIPTION_CHARS);+ expect(+ getSkillUploadError(md(`name: ok_skill\ndescription: ${desc}`)),+ ).toBeNull();+ });++ test("strips surrounding quotes before measuring", () => {+ const desc = "x".repeat(MAX_SKILL_DESCRIPTION_CHARS);+ expect(+ getSkillUploadError(md(`name: ok_skill\ndescription: "${desc}"`)),+ ).toBeNull();+ });++ test("does not count escaped quotes in a JSON-style double-quoted description", () => {+ // `renderSkillMarkdown` emits `description: ${JSON.stringify(...)}`, so a+ // re-uploaded skill whose description contains quotes carries `\"` escapes.+ // The actual text is exactly at the limit; the escapes must not inflate it.+ const desc = `${"x".repeat(MAX_SKILL_DESCRIPTION_CHARS - 3)}"q"`;+ const line = `description: ${JSON.stringify(desc)}`;+ expect(desc.length).toBe(MAX_SKILL_DESCRIPTION_CHARS);+ expect(getSkillUploadError(md(`name: ok_skill\n${line}`))).toBeNull();+ });++ test("does not false-reject a block-scalar description it cannot measure", () => {+ const block = `name: ok_skill\ndescription: |\n ${"x".repeat(300)}`;+ // Block scalar is unmeasurable from one line — defer to the backend.+ expect(getSkillUploadError(md(block))).toBeNull();+ });++ test("flags an empty description", () => {+ const err = getSkillUploadError(md("name: ok_skill\ndescription:"));+ expect(err).toContain("non-empty name and description");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsxindex 6158bba675..ee91685e7d 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/__tests__/main.test.tsx@@ -4,6 +4,8 @@ import {getListCopilotSkillsMockHandler,getReadCopilotSkillMockHandler,getReadCopilotSkillMockHandler404,+ getUploadCopilotSkillMockHandler201,+ getUploadCopilotSkillMockHandler409,} from "@/app/api/__generated__/endpoints/skills/skills.msw";import type { CopilotSkillInfo } from "@/app/api/__generated__/models/copilotSkillInfo";import type { CopilotSkillDetail } from "@/app/api/__generated__/models/copilotSkillDetail";@@ -194,6 +196,142 @@ describe("SkillsPage", () => {expect(screen.queryByTestId("skill-view-body")).toBeNull();});+ test("Download button fetches the skill detail and triggers a file download", async () => {+ // jsdom doesn't implement these blob helpers — patch just the two+ // methods (not the whole URL constructor, which the fetch mutator needs).+ const createObjectURL = vi.fn(() => "blob:mock-url");+ const revokeObjectURL = vi.fn();+ const originalCreate = URL.createObjectURL;+ const originalRevoke = URL.revokeObjectURL;+ URL.createObjectURL = createObjectURL;+ URL.revokeObjectURL = revokeObjectURL;+ const clickSpy = vi+ .spyOn(HTMLAnchorElement.prototype, "click")+ .mockImplementation(() => {});++ try {+ const detail: CopilotSkillDetail = {+ name: "oauth_flow",+ description: "OAuth handshake recipe.",+ triggers: ["connect_integration"],+ body: "## Steps\n1. Hit /authorize",+ version: null,+ is_default: false,+ sibling_files: [],+ };+ server.use(+ getListCopilotSkillsMockHandler([makeSkill({ name: "oauth_flow" })]),+ getReadCopilotSkillMockHandler(detail),+ );++ render(<SkillsPage />);++ const downloadButton = await screen.findByTestId("skill-download-button");+ fireEvent.click(downloadButton);++ await vi.waitFor(() => {+ expect(createObjectURL).toHaveBeenCalled();+ expect(clickSpy).toHaveBeenCalled();+ });+ } finally {+ URL.createObjectURL = originalCreate;+ URL.revokeObjectURL = originalRevoke;+ clickSpy.mockRestore();+ }+ });++ test("Upload button sends the picked file and refreshes the list", async () => {+ server.use(+ getListCopilotSkillsMockHandler([]),+ getUploadCopilotSkillMockHandler201({+ name: "uploaded_skill",+ description: "An uploaded recipe.",+ triggers: [],+ }),+ );++ render(<SkillsPage />);++ await screen.findByTestId("skills-empty");++ const input = screen.getByTestId("skill-upload-input");+ const file = new File(+ [+ "---\nname: uploaded_skill\ndescription: An uploaded recipe.\n---\n\n# Body\n",+ ],+ "uploaded_skill.md",+ { type: "text/markdown" },+ );+ fireEvent.change(input, { target: { files: [file] } });++ await vi.waitFor(() => {+ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ title: expect.stringContaining("uploaded"),+ }),+ );+ });+ });++ test("Upload rejects an over-long description client-side with the exact length", async () => {+ // No upload handler registered — if the code POSTed, it would not match+ // and the test would surface a different failure. The client-side+ // pre-flight should short-circuit before any request.+ server.use(getListCopilotSkillsMockHandler([]));++ render(<SkillsPage />);+ await screen.findByTestId("skills-empty");++ const input = screen.getByTestId("skill-upload-input");+ const longDescription = "x".repeat(201);+ const file = new File(+ [`---\nname: too_long\ndescription: ${longDescription}\n---\n\nbody`],+ "too_long.md",+ { type: "text/markdown" },+ );+ fireEvent.change(input, { target: { files: [file] } });++ await vi.waitFor(() => {+ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Can't upload this skill",+ description: expect.stringContaining("201/200"),+ variant: "destructive",+ }),+ );+ });+ });++ test("Upload shows a destructive toast when the skill limit is reached", async () => {+ server.use(+ getListCopilotSkillsMockHandler([]),+ getUploadCopilotSkillMockHandler409(),+ );++ render(<SkillsPage />);++ await screen.findByTestId("skills-empty");++ const input = screen.getByTestId("skill-upload-input");+ const file = new File(+ ["---\nname: x\ndescription: y\n---\n\nbody"],+ "x.md",+ {+ type: "text/markdown",+ },+ );+ fireEvent.change(input, { target: { files: [file] } });++ await vi.waitFor(() => {+ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Failed to upload skill",+ variant: "destructive",+ }),+ );+ });+ });+test("shows a destructive toast when the delete API fails", async () => {server.use(getListCopilotSkillsMockHandler([makeSkill({ name: "oauth_flow" })]),diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/SkillListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/SkillListItem.tsxindex 381605d302..c2d38a0370 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/SkillListItem.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/SkillListItem.tsx@@ -4,7 +4,12 @@ import type { CopilotSkillInfo } from "@/app/api/__generated__/models/copilotSkiimport { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { Dialog } from "@/components/molecules/Dialog/Dialog";-import { BookOpenIcon, EyeIcon, TrashIcon } from "@phosphor-icons/react";+import {+ BookOpenIcon,+ DownloadSimpleIcon,+ EyeIcon,+ TrashIcon,+} from "@phosphor-icons/react";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import { useSkillListItem } from "./useSkillListItem";@@ -22,6 +27,8 @@ export function SkillListItem({ skill }: Props) {closeDelete,isDeleting,handleDelete,+ isDownloading,+ handleDownload,isViewOpen,openView,closeView,@@ -67,24 +74,32 @@ export function SkillListItem({ skill }: Props) {<div className="flex flex-shrink-0 items-center gap-2"><Button- variant="secondary"- size="small"+ variant="icon"+ size="icon"onClick={openView}data-testid="skill-view-button"aria-label="View skill">- <EyeIcon className="mr-1 h-4 w-4" />- View+ <EyeIcon className="h-4 w-4" /></Button><Button- variant="secondary"- size="small"+ variant="icon"+ size="icon"+ onClick={handleDownload}+ loading={isDownloading}+ data-testid="skill-download-button"+ aria-label="Download skill"+ >+ <DownloadSimpleIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="icon"+ size="icon"onClick={openDelete}data-testid="skill-delete-button"aria-label="Delete skill">- <TrashIcon className="mr-1 h-4 w-4" />- Delete+ <TrashIcon className="h-4 w-4" /></Button></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/helpers.tsindex 723101e941..e6960d757a 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/helpers.ts@@ -1,3 +1,4 @@+import type { CopilotSkillDetail } from "@/app/api/__generated__/models/copilotSkillDetail";import type { CopilotSkillInfo } from "@/app/api/__generated__/models/copilotSkillInfo";const DESCRIPTION_PREVIEW_MAX_LEN = 220;@@ -15,3 +16,36 @@ export function describeSkill(skill: CopilotSkillInfo) {return { descriptionPreview, triggers };}++// Rebuild a canonical, re-uploadable SKILL.md from a fetched skill detail.+// JSON string/array literals are valid YAML, so this round-trips cleanly back+// through the upload endpoint's `parse_skill_markdown` without a YAML lib.+export function renderSkillMarkdown(detail: CopilotSkillDetail): string {+ const frontmatter = [+ "---",+ `name: ${JSON.stringify(detail.name)}`,+ `description: ${JSON.stringify(detail.description)}`,+ ];+ const triggers = (detail.triggers ?? []).filter((t) => t.trim().length > 0);+ if (triggers.length > 0) {+ frontmatter.push(`triggers: ${JSON.stringify(triggers)}`);+ }+ if (detail.version) {+ frontmatter.push(`version: ${JSON.stringify(detail.version)}`);+ }+ frontmatter.push("---");++ return `${frontmatter.join("\n")}\n\n${(detail.body ?? "").trim()}\n`;+}++export function downloadTextFile(filename: string, text: string): void {+ const blob = new Blob([text], { type: "text/markdown;charset=utf-8" });+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = filename;+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ URL.revokeObjectURL(url);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/useSkillListItem.ts b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/useSkillListItem.tsindex 225c526a4c..10dc172c93 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/useSkillListItem.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/SkillListItem/useSkillListItem.ts@@ -1,5 +1,6 @@import {getListCopilotSkillsQueryKey,+ readCopilotSkill,useDeleteCopilotSkill,useReadCopilotSkill,} from "@/app/api/__generated__/endpoints/skills/skills";@@ -8,7 +9,11 @@ import type { CopilotSkillDetail } from "@/app/api/__generated__/models/copilotSimport { useToast } from "@/components/molecules/Toast/use-toast";import { useQueryClient } from "@tanstack/react-query";import { useState } from "react";-import { describeSkill } from "./helpers";+import {+ describeSkill,+ downloadTextFile,+ renderSkillMarkdown,+} from "./helpers";interface Args {skill: CopilotSkillInfo;@@ -19,6 +24,7 @@ export function useSkillListItem({ skill }: Args) {const queryClient = useQueryClient();const [isDeleteOpen, setIsDeleteOpen] = useState(false);const [isViewOpen, setIsViewOpen] = useState(false);+ const [isDownloading, setIsDownloading] = useState(false);const { mutateAsync: deleteSkill, isPending: isDeleting } =useDeleteCopilotSkill();@@ -66,6 +72,29 @@ export function useSkillListItem({ skill }: Args) {setIsViewOpen(open);}+ async function handleDownload() {+ setIsDownloading(true);+ try {+ const res = await readCopilotSkill(skill.name);+ if (res.status !== 200) {+ throw new Error(`Failed to download skill (HTTP ${res.status})`);+ }+ const skillDetail = res.data as CopilotSkillDetail;+ downloadTextFile(`${skill.name}.md`, renderSkillMarkdown(skillDetail));+ } catch (error) {+ toast({+ title: "Failed to download skill",+ description:+ error instanceof Error+ ? error.message+ : "An unexpected error occurred.",+ variant: "destructive",+ });+ } finally {+ setIsDownloading(false);+ }+ }+async function handleDelete() {try {await deleteSkill({ name: skill.name });@@ -94,6 +123,8 @@ export function useSkillListItem({ skill }: Args) {closeDelete,isDeleting,handleDelete,+ isDownloading,+ handleDownload,isViewOpen,openView,closeView,diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/UploadSkillButton.tsx b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/UploadSkillButton.tsxnew file mode 100644index 0000000000..225f1b350e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/UploadSkillButton.tsx@@ -0,0 +1,33 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { UploadSimpleIcon } from "@phosphor-icons/react";+import { useUploadSkillButton } from "./useUploadSkillButton";++export function UploadSkillButton() {+ const { fileInputRef, isUploading, openFilePicker, handleFileChange } =+ useUploadSkillButton();++ return (+ <>+ <input+ ref={fileInputRef}+ type="file"+ accept=".md,.markdown,text/markdown"+ className="hidden"+ onChange={handleFileChange}+ data-testid="skill-upload-input"+ />+ <Button+ variant="primary"+ size="small"+ onClick={openFilePicker}+ loading={isUploading}+ data-testid="skill-upload-button"+ >+ <UploadSimpleIcon className="mr-1 h-4 w-4" />+ Upload skill+ </Button>+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/helpers.tsnew file mode 100644index 0000000000..4af769bd89--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/helpers.ts@@ -0,0 +1,75 @@+// Mirrors backend limits in backend/copilot/tools/skills.py — kept in sync+// manually. These bound the per-turn `<available_skills>` index the copilot+// sees, so the cap is deliberate (see backend MAX_DESCRIPTION_CHARS).+export const MAX_SKILL_DESCRIPTION_CHARS = 200;++const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---/;++// Best-effort, dependency-free pre-flight for an uploaded SKILL.md. The+// backend remains the source of truth — this only catches the common,+// confidently-detectable cases (missing frontmatter, over-long single-line+// description) so the user gets an instant, specific message instead of a+// round-trip. Anything we can't parse confidently (e.g. YAML block scalars)+// returns `null` and falls through to the server's validation.+export function getSkillUploadError(content: string): string | null {+ const match = content.match(FRONTMATTER_RE);+ if (!match) {+ return "File is not a valid SKILL.md — expected YAML frontmatter (---) with a name and description.";+ }++ const frontmatter = match[1];+ const description = readScalarField(frontmatter, "description");+ const name = readScalarField(frontmatter, "name");++ // `parse_skill_markdown` rejects when name or description is missing. Only+ // assert this when we can see plain scalar lines — a block scalar would+ // read as absent here, so skip rather than false-reject.+ if (name === "" || description === "") {+ return "File is not a valid SKILL.md — frontmatter must include a non-empty name and description.";+ }++ if (description && description.length > MAX_SKILL_DESCRIPTION_CHARS) {+ const over = description.length - MAX_SKILL_DESCRIPTION_CHARS;+ return `Description is ${description.length}/${MAX_SKILL_DESCRIPTION_CHARS} characters — trim at least ${over}. It appears in the copilot's per-turn skills index, so it's kept short.`;+ }++ return null;+}++// Reads a single-line scalar value for `key` from a YAML frontmatter block.+// Returns the trimmed (and unquoted) value, "" when the key is present but+// empty, or `undefined` when the key is absent or uses a block scalar+// (`>`/`|`) we can't measure confidently.+function readScalarField(frontmatter: string, key: string): string | undefined {+ const line = frontmatter.match(new RegExp(`^${key}:[ \\t]*(.*)$`, "m"));+ if (!line) return undefined;++ const raw = line[1].trim();+ if (raw === "") return "";+ // Block scalars span multiple lines — not measurable from one line.+ if (+ raw === ">" ||+ raw === "|" ||+ raw.startsWith(">") ||+ raw.startsWith("|")+ ) {+ return undefined;+ }++ // Double-quoted YAML escapes inner quotes as `\"` (this is what+ // `renderSkillMarkdown`'s `JSON.stringify` emits on download). Decode with+ // `JSON.parse` so the measured length matches the backend's parsed value+ // instead of counting the backslash escapes.+ if (raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2) {+ try {+ return JSON.parse(raw);+ } catch {+ return raw.slice(1, -1);+ }+ }+ // Single-quoted YAML escapes a quote by doubling it (`''`).+ if (raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2) {+ return raw.slice(1, -1).replace(/''/g, "'");+ }+ return raw;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/useUploadSkillButton.ts b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/useUploadSkillButton.tsnew file mode 100644index 0000000000..7793a70f6a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/components/UploadSkillButton/useUploadSkillButton.ts@@ -0,0 +1,68 @@+import {+ getListCopilotSkillsQueryKey,+ useUploadCopilotSkill,+} from "@/app/api/__generated__/endpoints/skills/skills";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { useQueryClient } from "@tanstack/react-query";+import { useRef } from "react";+import { getSkillUploadError } from "./helpers";++export function useUploadSkillButton() {+ const { toast } = useToast();+ const queryClient = useQueryClient();+ const fileInputRef = useRef<HTMLInputElement>(null);++ const { mutateAsync: uploadSkill, isPending: isUploading } =+ useUploadCopilotSkill();++ function openFilePicker() {+ fileInputRef.current?.click();+ }++ async function handleFileChange(event: React.ChangeEvent<HTMLInputElement>) {+ const file = event.target.files?.[0];+ // Reset the input so re-picking the same file fires onChange again.+ event.target.value = "";+ if (!file) return;++ try {+ const content = await file.text();++ // Pre-flight the common rejections client-side so the user gets an+ // instant, specific message instead of waiting on a server round-trip.+ const validationError = getSkillUploadError(content);+ if (validationError) {+ toast({+ title: "Can't upload this skill",+ description: validationError,+ variant: "destructive",+ });+ return;+ }++ const result = await uploadSkill({ data: { content } });+ const name =+ result.status === 201 ? result.data.name : (file.name ?? "skill");+ toast({ title: `Skill "${name}" uploaded` });+ queryClient.invalidateQueries({+ queryKey: getListCopilotSkillsQueryKey(),+ });+ } catch (error) {+ toast({+ title: "Failed to upload skill",+ description:+ error instanceof Error+ ? error.message+ : "An unexpected error occurred.",+ variant: "destructive",+ });+ }+ }++ return {+ fileInputRef,+ isUploading,+ openFilePicker,+ handleFileChange,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/skills/page.tsx b/autogpt_platform/frontend/src/app/(platform)/library/skills/page.tsxindex a56217c753..7fe6ba0b26 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/skills/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/skills/page.tsx@@ -8,6 +8,7 @@ import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { EmptySkills } from "./components/EmptySkills/EmptySkills";import { SkillListItem } from "./components/SkillListItem/SkillListItem";+import { UploadSkillButton } from "./components/UploadSkillButton/UploadSkillButton";import { useSkillsPage } from "./useSkillsPage";export default function SkillsPage() {@@ -27,13 +28,18 @@ export default function SkillsPage() {<ArrowLeftIcon size={14} weight="bold" />Back to Library</Link>- <header className="flex flex-col gap-2">- <Text variant="h2">AutoPilot skills</Text>- <Text variant="body" className="!text-zinc-500">- Reusable procedures your AutoPilot has distilled from past sessions.- Review what it remembers, or delete a skill you no longer want it to- reach for.- </Text>+ <header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div className="flex flex-col gap-2">+ <Text variant="h2">AutoPilot skills</Text>+ <Text variant="body" className="!text-zinc-500">+ Reusable procedures your AutoPilot has distilled from past sessions.+ Review what it remembers, upload your own, download one to share, or+ delete a skill you no longer want it to reach for.+ </Text>+ </div>+ <div className="flex-shrink-0">+ <UploadSkillButton />+ </div></header>{error ? (diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 48650db67a..74144b3e9e 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -9606,6 +9606,46 @@}},"security": [{ "HTTPBearerJWT": [] }]+ },+ "post": {+ "tags": ["v1", "skills"],+ "summary": "Upload a copilot skill from a SKILL.md file",+ "description": "Create a user-distilled skill from an uploaded ``SKILL.md`` file.\n\nParses the canonical frontmatter + body, then reuses\n:func:`backend.copilot.tools.skills.store_user_skill` so an uploaded skill\nis validated, capped, and persisted exactly like one the copilot distils\nvia ``store_skill``. Malformed files return 400, the per-user cap returns\n409, and an existing slug is overwritten (upsert).",+ "operationId": "uploadCopilotSkill",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UploadCopilotSkillRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/CopilotSkillInfo" }+ }+ }+ },+ "400": { "description": "Malformed SKILL.md or validation error" },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "409": { "description": "Per-user skill limit reached" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]}},"/api/skills/{name}": {@@ -22090,6 +22130,13 @@"required": ["timezone"],"title": "UpdateTimezoneRequest"},+ "UploadCopilotSkillRequest": {+ "properties": { "content": { "type": "string", "title": "Content" } },+ "type": "object",+ "required": ["content"],+ "title": "UploadCopilotSkillRequest",+ "description": "Body for the library UI's \"upload skill\" action.\n\nCarries the raw ``SKILL.md`` text (YAML frontmatter + markdown body) the\nuser picked from disk; the server parses + validates it so the upload and\nthe copilot's ``store_skill`` tool share one source of truth."+ },"UsageWindowPublic": {"properties": {"percent_used": {diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.tsindex 8ce41fcf4b..bee48306a5 100644--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts@@ -42,7 +42,7 @@ const defaultFlags = {[Flag.ARTIFACTS_PAGE]: false,[Flag.CHAT_MODE_OPTION]: false,[Flag.BUILDER_CHAT_PANEL]: false,- [Flag.AGENT_BRIEFING]: false,+ [Flag.AGENT_BRIEFING]: true,[Flag.GENERIC_TRIGGER_AGENTS]: false,[Flag.CHAT_SEARCH]: false,[Flag.CHAT_SHARING]: false,