Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(backend/copilot): give installed and saved skills separate per-expert budgets (#14786)

Nicholas Tindle01c0b600a9fa
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_db.py b/autogpt_platform/backend/backend/api/features/store/skill_db.py
index c9cee13c95..e73bbb203c 100644
--- a/autogpt_platform/backend/backend/api/features/store/skill_db.py
+++ b/autogpt_platform/backend/backend/api/features/store/skill_db.py
@@ -13,7 +13,12 @@ import prisma.enums
import prisma.models
import prisma.types
-from backend.copilot.tools.skills import SkillFile, list_user_skills, store_user_skill
+from backend.copilot.tools.skills import (
+ SKILL_ORIGIN_MARKETPLACE,
+ SkillFile,
+ list_user_skills,
+ store_user_skill,
+)
from backend.data.db import query_raw_with_schema
from backend.util.exceptions import NotFoundError
from backend.util.models import Pagination
@@ -201,6 +206,7 @@ async def install_marketplace_skill(
# keep a sibling only the previously installed version had.
files=await _read_version_files(active.id),
expert_id=expert_id,
+ origin=SKILL_ORIGIN_MARKETPLACE,
)
if is_new:
await prisma.models.SkillListing.prisma().update(
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_db_test.py b/autogpt_platform/backend/backend/api/features/store/skill_db_test.py
index 6841f3cf4c..f734df1486 100644
--- a/autogpt_platform/backend/backend/api/features/store/skill_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/skill_db_test.py
@@ -209,6 +209,8 @@ async def test_install_stores_under_the_listing_slug_and_counts(mocker, expert_i
assert stored.await_args.kwargs["name"] == listing.slug
assert stored.await_args.kwargs["expert_id"] == expert_id
assert stored.await_args.kwargs["body"] == "# do this\n"
+ # An install fills the platform's budget on that owner, not the owner's.
+ assert stored.await_args.kwargs["origin"] == "marketplace"
assert result.name == listing.slug
assert result.required_providers == ["google"]
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_routes.py b/autogpt_platform/backend/backend/api/features/store/skill_routes.py
index 5d59311f8f..de35df2e20 100644
--- a/autogpt_platform/backend/backend/api/features/store/skill_routes.py
+++ b/autogpt_platform/backend/backend/api/features/store/skill_routes.py
@@ -5,7 +5,7 @@ import fastapi
from fastapi import Depends, Path, Query, Security
from backend.api.features.experts import experts_db
-from backend.copilot.tools.skills import SkillLimitError
+from backend.copilot.tools.skills import SkillLimitError, SkillOwnedError
from backend.util.feature_flag import Flag, is_feature_enabled
from . import skill_db, skill_model, skill_submission_db
@@ -229,7 +229,12 @@ _TEXT_APPLICATION_TYPES = frozenset(
tags=["store", "private"],
responses={
404: {"description": "Skill or expert not found"},
- 409: {"description": "Per-user skill limit reached"},
+ 409: {
+ "description": (
+ "Skill limit reached, or the skill name is already used by an "
+ "owner-saved skill"
+ )
+ },
},
dependencies=[Security(autogpt_libs.auth.requires_user)],
)
@@ -247,7 +252,7 @@ async def install_marketplace_skill(
return await skill_db.install_marketplace_skill(
user_id, slug, expert_id=expert_id
)
- except SkillLimitError as exc:
+ except (SkillLimitError, SkillOwnedError) as exc:
raise fastapi.HTTPException(status_code=409, detail=str(exc))
except ValueError as exc:
raise fastapi.HTTPException(status_code=400, detail=str(exc))
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills.py b/autogpt_platform/backend/backend/copilot/tools/skills.py
index 38edf7ce10..a855271068 100644
--- a/autogpt_platform/backend/backend/copilot/tools/skills.py
+++ b/autogpt_platform/backend/backend/copilot/tools/skills.py
@@ -72,6 +72,9 @@ logger = logging.getLogger(__name__)
# (~50 tok), so 150 entries ≈ 7.5k tokens. Filling every description and
# trigger to the per-field caps below is roughly 66k tokens under the same
# estimate; actual token cost varies by content and tokenizer.
+# The cap is per owner folder and per origin: what the owner saves and what
+# the platform installs (a hire's bundle, a marketplace install) each get
+# MAX_SKILLS_PER_EXPERT, so a template's size never eats the owner's own room.
# Built-in seeded skills are tiny so first-touch users see well under
# 200 tokens of overhead.
# ---------------------------------------------------------------------------
@@ -121,7 +124,9 @@ def skill_folder(expert_id: str | None) -> str:
# 60s TTL with explicit invalidation gives near-zero index latency on warm
# turns without unbounded staleness for cross-instance edits.
SKILLS_INDEX_CACHE_TTL_S = 60
-SKILLS_INDEX_CACHE_KEY = "copilot:skills_index:{user_id}"
+# Versioned: an entry cached before origins were recorded would count every
+# installed skill as the owner's for a TTL after deploy.
+SKILLS_INDEX_CACHE_KEY = "copilot:skills_index:v2:{user_id}"
# A skill name on an expert's row that resolves to no folder in Otto's
# library — a marketplace attachment, or a skill deleted after assignment —
@@ -142,6 +147,16 @@ _META_VERSION = "version"
# The workspace has no mode bits, so a script's executable bit survives
# store → copy → sandbox as this flag.
_META_EXECUTABLE = "executable"
+# Where a skill in an owner's folder came from. Kept in the row's metadata
+# (server-written; the frontmatter is the author's to edit) so the per-owner
+# cap counts what the owner saved apart from what the platform installed.
+_META_SKILL_ORIGIN = "skill_origin"
+SKILL_ORIGIN_USER = "user"
+SKILL_ORIGIN_MARKETPLACE = "marketplace"
+# The built-in defaults: never stored, never counted, so not a storable origin.
+SKILL_ORIGIN_PLATFORM = "platform"
+_SKILL_ORIGINS = frozenset({SKILL_ORIGIN_USER, SKILL_ORIGIN_MARKETPLACE})
+_ORIGIN_LABELS = {SKILL_ORIGIN_USER: "saved", SKILL_ORIGIN_MARKETPLACE: "installed"}
# Skill names are slug-like — lowercase letters, digits, dashes, underscores.
# Must start and end with [a-z0-9] (no trailing/leading punctuation) so the
@@ -218,6 +233,17 @@ class ParsedSkill:
triggers: tuple[str, ...] = ()
version: str | None = None
extra: Mapping[str, Any] = field(default_factory=dict)
+ # Recorded on the row at store time, never parsed from the file. ``None``
+ # is a row stored before origins were recorded: it counts against the
+ # owner's budget (see :func:`budget_origin`) but is nobody's to defend,
+ # so a platform install may claim it.
+ origin: str | None = None
+
+
+def budget_origin(skill: ParsedSkill) -> str:
+ """The budget a stored skill fills: its recorded origin, or the owner's
+ for a row that has none."""
+ return skill.origin or SKILL_ORIGIN_USER
def parse_skill_markdown(text: str, fallback_name: str = "") -> ParsedSkill | None:
@@ -424,6 +450,7 @@ def get_default_skill_with_body(name: str) -> ParsedSkill | None:
description=default.description,
body=body,
triggers=default.triggers,
+ origin=SKILL_ORIGIN_PLATFORM,
)
@@ -558,7 +585,13 @@ class BuiltInSkillError(Exception):
class SkillLimitError(Exception):
- """Raised by :func:`store_user_skill` when the per-expert cap is reached."""
+ """Raised by :func:`store_user_skill` when the owner's cap for skills of
+ that origin is reached."""
+
+
+class SkillOwnedError(Exception):
+ """Raised by :func:`store_user_skill` when a platform install would
+ replace a skill the owner saved under that name."""
async def delete_user_skill(
@@ -666,6 +699,7 @@ async def store_user_skill(
files: list[SkillFile] | None = None,
expert_id: str | None = None,
scope: WorkspaceScope | None = None,
+ origin: str = SKILL_ORIGIN_USER,
) -> ParsedSkill:
"""Validate + persist a user-distilled skill, returning the stored skill.
@@ -673,9 +707,15 @@ async def store_user_skill(
``None``) and becomes that owner's skill. Shared by the ``store_skill``
copilot tool and the REST ``POST /skills`` upload endpoint so both honour
the same validation, per-owner cap, and write-lock semantics. Raises :class:`ValueError` for any validation
- failure, :class:`SkillLimitError` when the per-expert cap is reached, and
- propagates ``VirusDetectedError`` / ``VirusScanError`` (and any other
- workspace write error) to the caller.
+ failure, :class:`SkillLimitError` when the owner's cap for skills of
+ *origin* is reached, and propagates ``VirusDetectedError`` /
+ ``VirusScanError`` (and any other workspace write error) to the caller.
+
+ *origin* says who put the skill there — the owner
+ (``SKILL_ORIGIN_USER``, the default) or the platform
+ (``SKILL_ORIGIN_MARKETPLACE``: a hire's bundle, a marketplace install).
+ Each origin has a cap of its own, so a template's bundle never takes a
+ slot from the skills the owner saves to that expert.
*files* is the whole package: it replaces the folder's contents, so a
file the caller leaves out is deleted. ``None`` — every single-file
@@ -700,6 +740,8 @@ async def store_user_skill(
name_err = _validate_name(name)
if name_err:
raise ValueError(name_err)
+ if origin not in _SKILL_ORIGINS:
+ raise ValueError(f"origin must be one of {', '.join(sorted(_SKILL_ORIGINS))}")
validate_skill_content(description, body, triggers)
parsed = ParsedSkill(
@@ -709,6 +751,7 @@ async def store_user_skill(
triggers=tuple(triggers),
version=version,
extra=dict(extra or {}),
+ origin=origin,
)
rendered = render_skill_markdown(parsed)
if files is not None:
@@ -755,9 +798,21 @@ async def store_user_skill(
# No healing here: this call runs inside the per-owner write lock that
# the copy would need, so it would stall on itself for every name.
existing = await list_user_skills(user_id, expert_id, scope, heal_missing=False)
- existing_slugs = {s.name for s in existing}
- at_cap = len(existing_slugs) >= MAX_SKILLS_PER_EXPERT
- is_new = name not in existing_slugs
+ # One budget per origin: only skills of this origin fill this one,
+ # and only a name new to it takes a slot. A re-install of a bundled
+ # skill, or a rewrite of the owner's own, consumes nothing. The
+ # owner may take over a bundled name (it becomes theirs); the
+ # platform never replaces something the owner wrote.
+ same_origin = {s.name for s in existing if budget_origin(s) == origin}
+ if origin == SKILL_ORIGIN_MARKETPLACE and any(
+ s.name == name and s.origin == SKILL_ORIGIN_USER for s in existing
+ ):
+ raise SkillOwnedError(
+ f"'{name}' is one of the owner's own skills; rename or delete "
+ "it before installing a skill by that name."
+ )
+ at_cap = len(same_origin) >= MAX_SKILLS_PER_EXPERT
+ is_new = name not in same_origin
if at_cap and (is_new or not lock_held):
if not lock_held:
logger.warning(
@@ -768,14 +823,15 @@ async def store_user_skill(
is_new,
)
raise SkillLimitError(
- f"Skill limit reached ({MAX_SKILLS_PER_EXPERT}). "
- "Delete an unused skill first."
+ f"Skill limit reached ({MAX_SKILLS_PER_EXPERT} {_ORIGIN_LABELS[origin]} "
+ "skills). Delete an unused skill first."
)
metadata: dict[str, Any] = {
_META_KIND: _META_KIND_VALUE,
_META_DESCRIPTION: description,
_META_TRIGGERS: list(triggers),
+ _META_SKILL_ORIGIN: origin,
}
if version:
metadata[_META_VERSION] = version
@@ -903,9 +959,19 @@ def _index_entry_from_metadata(slug: str, meta: dict) -> ParsedSkill | None:
body="",
triggers=triggers,
version=str(version) if version else None,
+ origin=_skill_origin(meta),
)
+def _skill_origin(meta: Mapping[str, Any]) -> str | None:
+ """The origin recorded on a row, or ``None`` when none was."""
+ return _normalize_origin(meta.get(_META_SKILL_ORIGIN))
+
+
+def _normalize_origin(value: object) -> str | None:
+ return value if isinstance(value, str) and value in _SKILL_ORIGINS else None
+
+
async def _list_user_skills_from_workspace(
user_id: str,
expert_id: str | None = None,
@@ -928,25 +994,26 @@ async def _list_user_skills_from_workspace(
folder = skill_folder(expert_id)
skills: list[ParsedSkill] = []
- needs_read: list[Any] = []
+ needs_read: list[tuple[Any, dict[str, Any]]] = []
for f, slug in await _list_skill_roots(manager, folder):
meta = f.metadata if isinstance(f.metadata, dict) else {}
entry = _index_entry_from_metadata(slug, meta)
if entry is not None:
skills.append(entry)
else:
- needs_read.append(f)
+ needs_read.append((f, meta))
if needs_read:
parsed = await asyncio.gather(
- *(_parse_skill_from_workspace(manager, f.path) for f in needs_read),
+ *(_parse_skill_from_workspace(manager, f.path) for f, _ in needs_read),
)
- for p in parsed:
+ for (_, meta), p in zip(needs_read, parsed):
if p is None:
continue
# Index never needs the body — drop it so the cache payload
# stays small (defaults are already body-less, fast-path
- # entries are body-less, keep the contract uniform).
+ # entries are body-less, keep the contract uniform). The
+ # origin is the row's, whatever the file says.
skills.append(
ParsedSkill(
name=p.name,
@@ -954,6 +1021,7 @@ async def _list_user_skills_from_workspace(
body="",
triggers=p.triggers,
version=p.version,
+ origin=_skill_origin(meta),
)
)
@@ -988,6 +1056,7 @@ async def _read_skills_cache(
body="",
triggers=tuple(str(t) for t in item.get("triggers", [])),
version=item.get("version"),
+ origin=_normalize_origin(item.get("origin")),
)
for item in payload
if isinstance(item, dict) and "name" in item and "description" in item
@@ -1009,6 +1078,7 @@ async def _write_skills_cache(
"description": s.description,
"triggers": list(s.triggers),
"version": s.version,
+ "origin": s.origin,
}
for s in skills
]
@@ -1341,6 +1411,10 @@ async def copy_skill_to_expert(user_id: str, expert_id: str, name: str) -> str |
source = await read_user_skill_with_body(user_id, slug)
if source is None:
return None
+ # The origin lives on the row, not in the file the parse above read; a
+ # bundled skill copied into an expert stays a bundled one there.
+ root = await manager.get_file_info_by_path(_skill_md_path(slug))
+ meta = root.metadata if root is not None and isinstance(root.metadata, dict) else {}
stored = await store_user_skill(
user_id,
name=slug,
@@ -1351,6 +1425,7 @@ async def copy_skill_to_expert(user_id: str, expert_id: str, name: str) -> str |
extra=source.extra,
files=await _read_package_files(manager, SKILL_FOLDER, slug),
expert_id=expert_id,
+ origin=_skill_origin(meta) or SKILL_ORIGIN_USER,
)
return stored.name
@@ -1423,6 +1498,7 @@ def get_default_skills_for_index() -> list[ParsedSkill]:
description=default.description,
body="",
triggers=default.triggers,
+ origin=SKILL_ORIGIN_PLATFORM,
)
for default in DEFAULT_SKILLS
]
@@ -1453,6 +1529,7 @@ def get_default_skills() -> list[ParsedSkill]:
description=default.description,
body=body,
triggers=default.triggers,
+ origin=SKILL_ORIGIN_PLATFORM,
)
)
return result
@@ -1791,7 +1868,7 @@ class StoreSkillTool(BaseTool):
error=str(exc),
session_id=session_id,
)
- except (ValueError, SkillLimitError, ConflictError) as exc:
+ except (ValueError, SkillLimitError, SkillOwnedError, ConflictError) as exc:
return ErrorResponse(message=str(exc), session_id=session_id)
except Exception as exc:
logger.exception("[skills] failed to store skill %s", name)
@@ -2145,6 +2222,7 @@ class ListSkillsTool(BaseTool):
"description": s.description,
"triggers": list(s.triggers),
"is_default": s.name in _DEFAULT_SKILLS_BY_NAME,
+ "origin": budget_origin(s),
}
for s in skills
]
@@ -2166,7 +2244,9 @@ class ListSkillsTool(BaseTool):
# the query but depth cannot, so a page of newest-first rows can be entirely
# nested SKILL.md files and yield no roots at all; the bound is the most a
# compliant folder can hold, every allowed skill carrying a full package.
-_MAX_ROOT_SCAN = MAX_SKILLS_PER_EXPERT * (MAX_PACKAGE_FILES + 1)
+# Roots one folder can hold: a full budget for every origin.
+_MAX_ROOTS_PER_FOLDER = MAX_SKILLS_PER_EXPERT * len(_SKILL_ORIGINS)
+_MAX_ROOT_SCAN = _MAX_ROOTS_PER_FOLDER * (MAX_PACKAGE_FILES + 1)
async def _list_skill_roots(
@@ -2179,10 +2259,10 @@ async def _list_skill_roots(
the page and hide older skills, which is the defect this listing exists
to avoid.
"""
- page = MAX_SKILLS_PER_EXPERT * 4 # over-fetch in case of strays
+ page = _MAX_ROOTS_PER_FOLDER * 4 # over-fetch in case of strays
roots: list[tuple[Any, str]] = []
offset = 0
- while offset < _MAX_ROOT_SCAN and len(roots) <= MAX_SKILLS_PER_EXPERT:
+ while offset < _MAX_ROOT_SCAN and len(roots) <= _MAX_ROOTS_PER_FOLDER:
rows = await manager.list_files(
path=f"{folder}/",
limit=page,
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills_test.py b/autogpt_platform/backend/backend/copilot/tools/skills_test.py
index fbafaa377f..3b9989a86e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/skills_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/skills_test.py
@@ -16,6 +16,7 @@ from backend.copilot.model import ChatMessage, ChatSession
from backend.copilot.sdk.service import _maybe_prepend_skills_update
from backend.copilot.tools.models import ErrorResponse
from backend.copilot.tools.skills import (
+ _MAX_ROOTS_PER_FOLDER,
DEFAULT_SKILLS,
MAX_BODY_CHARS,
MAX_DESCRIPTION_CHARS,
@@ -26,6 +27,9 @@ from backend.copilot.tools.skills import (
MAX_SKILLS_PER_EXPERT,
MAX_TRIGGER_CHARS,
MAX_TRIGGERS,
+ SKILL_ORIGIN_MARKETPLACE,
+ SKILL_ORIGIN_PLATFORM,
+ SKILL_ORIGIN_USER,
BuiltInSkillError,
DeleteSkillResponse,
DeleteSkillTool,
@@ -35,20 +39,26 @@ from backend.copilot.tools.skills import (
ReadSkillResponse,
ReadSkillTool,
SkillFile,
+ SkillLimitError,
SkillNotFoundError,
+ SkillOwnedError,
SkillPackage,
SkillPackageError,
StoreSkillResponse,
StoreSkillTool,
_is_safe_relative,
_list_user_skills_from_workspace,
+ _read_skills_cache,
_validate_name,
+ _write_skills_cache,
+ budget_origin,
build_skills_context,
build_skills_update_notice,
copy_skill_to_expert,
delete_user_skill,
find_user_skill_slugs,
get_default_skills,
+ get_default_skills_for_index,
list_all_skills,
list_user_skill_files,
parse_skill_markdown,
@@ -292,6 +302,7 @@ class _FakeWorkspaceManager:
info = MagicMock()
info.path = path
info.id = f"id-{path}"
+ info.metadata = self.metadata.get(path, {})
return info
async def delete_file(self, file_id):
@@ -595,6 +606,233 @@ async def test_store_skill_enforces_max_skills_per_expert_cap():
assert "limit" in result.message.lower()
+def _seed_skill(
+ fake: _FakeWorkspaceManager, slug: str, *, origin: str, folder: str = "/skills"
+) -> None:
+ """A skill stored the way ``store_user_skill`` stores one: file plus the
+ row metadata the index fast path reads, origin included."""
+ path = f"{folder}/{slug}/SKILL.md"
+ fake.files[path] = render_skill_markdown(
+ ParsedSkill(name=slug, description="desc", body="body")
+ ).encode()
+ fake.metadata[path] = {
+ "kind": "copilot_skill",
+ "description": "desc",
+ "triggers": [],
+ "skill_origin": origin,
+ }
+
+
+async def test_installed_skills_do_not_take_the_owners_saved_slots():
+ """A hire's bundle and marketplace installs have a budget of their own:
+ an expert shipping MAX_SKILLS_PER_EXPERT skills still leaves the owner every
+ slot for the skills they save to it."""
+ fake = _FakeWorkspaceManager()
+ for i in range(MAX_SKILLS_PER_EXPERT):
+ _seed_skill(fake, f"bundled_{i}", origin=SKILL_ORIGIN_MARKETPLACE)
+ with _patch_skills_path(fake):
+ stored = await store_user_skill(
+ "user-1", name="mine", description="ok", body="ok"
+ )
+ assert stored.name == "mine" and stored.origin == SKILL_ORIGIN_USER
+ assert fake.metadata["/skills/mine/SKILL.md"]["skill_origin"] == "user"
+
+
+async def test_saved_skills_do_not_take_the_installed_slots():
+ """The mirror: an owner at their own cap can still be given a bundled
+ skill, and a skill stored before origins were recorded is the owner's."""
+ fake = _FakeWorkspaceManager()
+ for i in range(MAX_SKILLS_PER_EXPERT):
+ slug = f"skill_{i}"
+ fake.files[f"/skills/{slug}/SKILL.md"] = render_skill_markdown(
+ ParsedSkill(name=slug, description="desc", body="body")
+ ).encode()
+ with _patch_skills_path(fake):
+ with pytest.raises(SkillLimitError, match="saved"):
+ await store_user_skill("user-1", name="mine", description="ok", body="ok")
+ stored = await store_user_skill(
+ "user-1",
+ name="bundled",
+ description="ok",
+ body="ok",
+ origin=SKILL_ORIGIN_MARKETPLACE,
+ )
+ assert stored.origin == SKILL_ORIGIN_MARKETPLACE
+ assert fake.metadata["/skills/bundled/SKILL.md"]["skill_origin"] == "marketplace"
+
+
+async def test_installed_skills_have_a_cap_of_their_own():
+ fake = _FakeWorkspaceManager()
+ for i in range(MAX_SKILLS_PER_EXPERT):
+ _seed_skill(fake, f"bundled_{i}", origin=SKILL_ORIGIN_MARKETPLACE)
+ with _patch_skills_path(fake):
+ with pytest.raises(SkillLimitError, match="installed"):
+ await store_user_skill(
+ "user-1",
+ name="one_more",
+ description="ok",
+ body="ok",
+ origin=SKILL_ORIGIN_MARKETPLACE,
+ )
+ # A re-install of a bundled skill takes no slot.
+ stored = await store_user_skill(
+ "user-1",
+ name="bundled_0",
+ description="newer",
+ body="newer",
+ origin=SKILL_ORIGIN_MARKETPLACE,
+ )
+ assert stored.description == "newer"
+
+
+async def test_an_install_never_replaces_the_owners_own_skill():
+ """The owner may take over a bundled name; the platform may not take
+ over the owner's. Refused as a conflict, and the owner's row is left."""
+ fake = _FakeWorkspaceManager()
+ _seed_skill(fake, "triage", origin=SKILL_ORIGIN_USER)
+ _seed_skill(fake, "bundled_x", origin=SKILL_ORIGIN_MARKETPLACE)
+ with _patch_skills_path(fake):
+ with pytest.raises(SkillOwnedError, match="triage"):
+ await store_user_skill(
+ "user-1",
+ name="triage",
+ description="theirs",
+ body="theirs",
+ origin=SKILL_ORIGIN_MARKETPLACE,
+ )
+ taken_over = await store_user_skill(
+ "user-1", name="bundled_x", description="mine", body="mine"
+ )
+ assert fake.metadata["/skills/triage/SKILL.md"]["skill_origin"] == "user"
+ assert taken_over.origin == SKILL_ORIGIN_USER
+ assert fake.metadata["/skills/bundled_x/SKILL.md"]["skill_origin"] == "user"
+
+
+async def test_an_install_may_claim_a_skill_stored_before_origins_were_recorded():
+ """A row with no recorded origin counts against the owner's budget but is
+ nobody's to defend: a re-install of a skill installed before origins were
+ recorded must succeed and stamp the row, or it could never migrate."""
+ fake = _FakeWorkspaceManager()
+ path = "/skills/legacy/SKILL.md"
+ fake.files[path] = render_skill_markdown(
+ ParsedSkill(name="legacy", description="old", body="old")
+ ).encode()
+ with _patch_skills_path(fake):
+ skills = await _list_user_skills_from_workspace("user-1")
+ assert skills[0].origin is None and budget_origin(skills[0]) == "user"
+ stored = await store_user_skill(
+ "user-1",
+ name="legacy",
+ description="new",
+ body="new",
+ origin=SKILL_ORIGIN_MARKETPLACE,
+ )
+ assert stored.origin == SKILL_ORIGIN_MARKETPLACE
+ assert fake.metadata[path]["skill_origin"] == "marketplace"
+
+
+async def test_a_row_read_back_from_its_file_keeps_the_rows_origin():
+ """A row without a usable description in its metadata is rebuilt from the
+ file; the origin still comes from the row, never defaults to the owner's."""
+ fake = _FakeWorkspaceManager()
+ path = "/skills/bundled/SKILL.md"
+ fake.files[path] = render_skill_markdown(
+ ParsedSkill(name="bundled", description="desc", body="body")
+ ).encode()
+ fake.metadata[path] = {"kind": "copilot_skill", "skill_origin": "marketplace"}
+ with _patch_skills_path(fake):
+ skills = await _list_user_skills_from_workspace("user-1")
+ assert [(s.name, s.origin) for s in skills] == [("bundled", "marketplace")]
+
+
+def test_default_skills_are_platform_origin_not_the_owners():
+ assert {s.origin for s in get_default_skills_for_index()} == {SKILL_ORIGIN_PLATFORM}
+
+
+async def test_store_user_skill_rejects_an_unknown_origin():
+ with _patch_skills_path(_FakeWorkspaceManager()):
+ with pytest.raises(ValueError, match="origin"):
+ await store_user_skill(
+ "user-1", name="x", description="ok", body="ok", origin="platform"
+ )
+
+
+async def test_copy_to_expert_keeps_the_installed_origin():
+ """A bundled skill healed into an expert's folder stays a bundled one
+ there, so the heal never spends the owner's saved slots either."""
+ fake = _FakeWorkspaceManager()
+ _seed_skill(fake, "bundled", origin=SKILL_ORIGIN_MARKETPLACE)
+ # Storing into an expert's folder records the name on the expert's row.
+ experts = MagicMock()
+ experts.add_expert_skill_name = AsyncMock()
+ with (
+ _patch_skills_path(fake),
+ patch("backend.copilot.tools.skills.experts_db", return_value=experts),
+ ):
+ slug = await copy_skill_to_expert("user-1", "expert-1", "bundled")
+ assert slug == "bundled"
+ experts.add_expert_skill_name.assert_awaited_once_with(
+ "user-1", "expert-1", "bundled"
+ )
+ copied = fake.metadata["/experts/expert-1/skills/bundled/SKILL.md"]
+ assert copied["skill_origin"] == "marketplace"
+
+
+class _FakeRedis:
+ def __init__(self):
+ self.store: dict[str, str] = {}
+
+ async def get(self, key):
+ return self.store.get(key)
+
+ async def set(self, key, value, ex=None):
+ self.store[key] = value
+
+ async def delete(self, *keys):
+ for key in keys:
+ self.store.pop(key, None)
+
+
+async def test_origin_survives_the_index_cache():
+ """The cap counts from the cached index on a warm turn, so a cache that
+ dropped the origin would count every bundled skill as the owner's."""
+ with patch(
+ "backend.copilot.tools.skills.get_redis_async",
+ new=AsyncMock(return_value=_FakeRedis()),
+ ):
+ await _write_skills_cache(
+ "user-1",
+ [
+ ParsedSkill(
+ name="bundled",
+ description="d",
+ body="",
+ origin=SKILL_ORIGIN_MARKETPLACE,
+ ),
+ ParsedSkill(
+ name="mine", description="d", body="", origin=SKILL_ORIGIN_USER
+ ),
+ ParsedSkill(name="legacy", description="d", body=""),
+ ],
+ )
+ cached = await _read_skills_cache("user-1")
+ assert cached is not None
+ assert {s.name: s.origin for s in cached} == {
+ "bundled": SKILL_ORIGIN_MARKETPLACE,
+ "mine": SKILL_ORIGIN_USER,
+ "legacy": None,
+ }
+
+
@pytest.mark.asyncio
async def test_store_skill_at_cap_refuses_when_lock_not_held():
"""When ``AsyncClusterLock.try_acquire`` returns a DIFFERENT owner
@@ -2380,7 +2618,7 @@ async def test_nested_skill_md_files_cannot_hide_a_root_skill():
"""A package shipping its own example SKILL.md files fills the capped,
newest-first page; the listing must page past them to the real roots."""
fake = _package_manager(slug="aaa-oldest")
- for i in range(MAX_SKILLS_PER_EXPERT * 4 + 10):
+ for i in range(_MAX_ROOTS_PER_FOLDER * 4 + 10):
fake.files[f"/skills/aaa-oldest/references/e{i:04d}/SKILL.md"] = b"example"
with _patch_skills_path(fake):
skills = await _list_user_skills_from_workspace("user-1")
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 07e6413c61..43791b8c93 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -15726,7 +15726,9 @@
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
},
"404": { "description": "Skill or expert not found" },
- "409": { "description": "Per-user skill limit reached" },
+ "409": {
+ "description": "Skill limit reached, or the skill name is already used by an owner-saved skill"
+ },
"422": {
"description": "Validation Error",
"content": {