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(platform): skills owned per expert or personal AutoPilot (#14414)

Abhimanyu Yadav09a30f91c278
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index 278c4e9ac0..2113756ae8 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -1,7 +1,7 @@
import asyncio
import logging
from collections import defaultdict
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from datetime import date, datetime, time, timedelta
from typing import Literal, cast
from zoneinfo import ZoneInfo
@@ -62,9 +62,13 @@ from backend.api.features.store.categories import category_match_values
from backend.blocks import get_output_block_ids
from backend.copilot.briefing.outcome import DEFAULT_AGENT_NAME, run_link
from backend.copilot.tools.skills import (
+ BuiltInSkillError,
+ SkillNotFoundError,
+ copy_skill_to_expert,
+ delete_user_skill,
+ find_user_skill_slugs,
get_default_skill_with_body,
- list_user_skills,
- read_user_skill_with_body,
+ skill_name_key,
)
from backend.data.db import prisma as db_client
from backend.data.db import query_raw_with_schema, transaction
@@ -81,6 +85,7 @@ from backend.data.model import NodeExecutionStats
from backend.data.user import get_user_by_id
from backend.util import type as type_utils
from backend.util.exceptions import (
+ ConflictError,
ExpertNotFoundError,
ExpertPrivateTenancyNotFoundError,
ExpertWriteNotReadableError,
@@ -419,6 +424,17 @@ async def owns_active_expert(user_id: str, expert_id: str) -> bool:
)
+async def owns_private_active_expert(user_id: str, expert_id: str) -> bool:
+ """True iff *user_id* owns *expert_id* as a live, private hire.
+
+ Stricter than :func:`owns_active_expert` by the visibility filter, which
+ is what the per-expert resource routes need: a TEAM/ORG expert has no
+ sharing rules yet, so writing its folder would mutate an expert the chat
+ side resolves to no grants at all.
+ """
+ return await _owned_active_expert(user_id, expert_id) is not None
+
+
async def get_expert(
user_id: str,
expert_id: str,
@@ -1000,6 +1016,20 @@ async def create_raised_expert(
weekly_budget=weekly_budget,
skills=resolved.skill_names,
)
+ failed_skills = await _copy_library_skills(user_id, expert.id, resolved.skill_names)
+ if failed_skills:
+ expert = (
+ await prisma.models.Expert.prisma().update(
+ where={"id": expert.id},
+ data={
+ "skills": [
+ s for s in (expert.skills or []) if s not in failed_skills
+ ]
+ },
+ include=_WORKFLOW_INCLUDE,
+ )
+ or expert
+ )
failed_attachments = await raise_attachments.install_workflows(
user_id, expert.id, resolved.workflows
)
@@ -1012,6 +1042,35 @@ async def create_raised_expert(
return RaiseResult(expert=hydrated, failed_attachments=failed_attachments)
+async def _copy_library_skills(
+ user_id: str, expert_id: str, names: list[str]
+) -> list[str]:
+ """Give a freshly raised expert its own copies of the Otto skills it
+ was raised with. Defaults and marketplace names have nothing to copy.
+ Returns the names whose copy failed so the caller can drop them from the
+ expert's row rather than list a skill the expert cannot read."""
+ candidates = [
+ name
+ for name in names
+ if get_default_skill_with_body(name.strip().lower()) is None
+ ]
+ folders = await find_user_skill_slugs(user_id, candidates)
+ failed: list[str] = []
+ for name in candidates:
+ folder = folders.get(name.strip().lower())
+ if folder is None:
+ # A marketplace attachment: no library folder to copy, and the
+ # name is legitimate, so it stays on the row.
+ continue
+ try:
+ if await copy_skill_to_expert(user_id, expert_id, folder) is None:
+ failed.append(name)
+ except Exception:
+ logger.exception(f"Failed to copy skill {name!r} to expert #{expert_id}")
+ failed.append(name)
+ return failed
+
+
async def _create_raised_expert_row(
user_id: str,
name: str,
@@ -1072,9 +1131,13 @@ async def update_skills(
skills: list[str],
marketplace_listing_ids: list[str] | None = None,
) -> Expert:
- """Replace an expert's skill list. Names the expert does not already
- carry must resolve to a library skill; the stored name is the skill's
- canonical one so display and lookup agree."""
+ """Replace an expert's skill list.
+
+ Names the expert does not already carry must resolve to a library skill.
+ A personal-Otto skill is copied into the expert's own folder so the
+ expert owns it from then on; names dropped from the list delete the
+ expert's copy. The stored name is the skill's canonical one so display
+ and lookup agree."""
row = await prisma.models.Expert.prisma().find_first(
where={
"id": expert_id,
@@ -1087,18 +1150,48 @@ async def update_skills(
if row is None:
raise ExpertNotFoundError(expert_id)
+ # Resolve every name before any write, so a bad name rejects the whole
+ # request instead of leaving a half-applied prefix of copies behind.
current = {name.lower(): name for name in row.skills or []}
- resolved = [
- current.get(name.lower()) or await _resolve_library_skill_name(user_id, name)
- for name in skills
+ # One library listing for the whole request: resolving per name turned a
+ # single PUT into a storage scan per name.
+ folders = await find_user_skill_slugs(
+ user_id, [current.get(name.lower()) or name for name in skills]
+ )
+ plan = [_plan_skill(current.get(name.lower()), name, folders) for name in skills]
+ marketplace = [
+ await _resolve_marketplace_skill_name(listing_id)
+ for listing_id in marketplace_listing_ids or []
]
- for listing_id in marketplace_listing_ids or []:
- name = await _resolve_marketplace_skill_name(listing_id)
+ resolved: list[str] = []
+ for canonical, folder in plan:
+ if folder is not None:
+ # Idempotent: also heals a name kept from before skills were
+ # owned per expert, which had no copy in the expert's folder.
+ if await copy_skill_to_expert(user_id, expert_id, folder) is None:
+ # Resolved moments ago and gone now. Keeping the name would
+ # leave the row listing a skill the expert cannot read, which
+ # is the one state this whole path exists to prevent.
+ logger.warning(
+ f"Skill {canonical!r} vanished before it could be copied "
+ f"to expert #{expert_id}; dropping it from the list"
+ )
+ continue
+ resolved.append(canonical)
+ for name in marketplace:
if name.lower() not in {r.lower() for r in resolved}:
resolved.append(name)
- await prisma.models.Expert.prisma().update(
- where={"id": row.id}, data={"skills": resolved}
- )
+ kept = {r.lower() for r in resolved}
+ for dropped in [name for name in current.values() if name.lower() not in kept]:
+ # delete_user_skill drops the row name itself — except for a built-in,
+ # where it raises first and _detach_expert_skill swallows that.
+ await _detach_expert_skill(user_id, expert_id, dropped)
+ await remove_expert_skill_name(user_id, expert_id, dropped)
+ # Per-name writes that each re-read the row, not one set computed up front:
+ # the expert can append to its own row with store_skill while the copies
+ # above run, and an overwrite from the pre-copy read would silently drop it.
+ for name in resolved:
+ await add_expert_skill_name(user_id, expert_id, name)
expert = await get_expert(user_id, expert_id)
if expert is None:
raise ExpertNotFoundError(expert_id)
@@ -1118,24 +1211,102 @@ async def _resolve_marketplace_skill_name(store_listing_version_id: str) -> str:
return listing.name
-async def _resolve_library_skill_name(user_id: str, name: str) -> str:
- slug = name.strip().lower()
+def _plan_skill(
+ kept_name: str | None, name: str, folders: dict[str, str]
+) -> tuple[str, str | None]:
+ """Decide the stored name and which Otto folder, if any, to copy.
+
+ A name the expert already carries is kept as is; its folder is looked up
+ so a legacy assignment without a copy gets one. A new name must be a
+ default skill or one of Otto's skills, resolved to its folder (a
+ hand-written skill may be listed under a frontmatter name that differs
+ from the folder). Raises ``NotFoundError`` before anything is written.
+ """
+ slug = (kept_name or name).strip().lower()
default = get_default_skill_with_body(slug)
if default is not None:
- return default.name
- stored = await read_user_skill_with_body(user_id, slug)
- if stored is not None:
- return stored.name
- # A skill whose frontmatter name differs from its folder slug (anything
- # not written through store_user_skill) is listed by the library UI under
- # the frontmatter name, so match on that too before giving up.
- listed = next(
- (s for s in await list_user_skills(user_id) if s.name.strip().lower() == slug),
- None,
- )
- if listed is None:
+ return default.name, None
+ folder = folders.get(slug)
+ if kept_name is not None:
+ return kept_name, folder
+ if folder is None:
raise NotFoundError(f"Skill '{name}' is not in your library")
- return listed.name
+ return folder, folder
+
+
+async def _detach_expert_skill(user_id: str, expert_id: str, name: str) -> None:
+ try:
+ await delete_user_skill(user_id, name, expert_id=expert_id)
+ except (SkillNotFoundError, BuiltInSkillError, ValueError):
+ return
+
+
+async def add_expert_skill_name(user_id: str, expert_id: str, name: str) -> None:
+ """Record a skill the expert now owns; idempotent, and a display name and
+ its slug count as one name."""
+ await _rewrite_skill_names(
+ {
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ },
+ lambda names: (
+ names
+ if skill_name_key(name) in {skill_name_key(n) for n in names}
+ else [*names, name]
+ ),
+ )
+
+
+async def remove_expert_skill_name(user_id: str, expert_id: str, name: str) -> None:
+ """Forget a skill the expert no longer owns, in any spelling of its name."""
+ await _rewrite_skill_names(
+ {"id": expert_id, "ownerUserId": user_id},
+ lambda names: [n for n in names if skill_name_key(n) != skill_name_key(name)],
+ )
+
+
+_SKILL_NAME_WRITE_ATTEMPTS = 5
+
+
+async def _rewrite_skill_names(
+ where: prisma.types.ExpertWhereInput,
+ rewrite: Callable[[list[str]], list[str]],
+) -> None:
+ """Compare-and-swap the row's skill list. store_skill can append to it
+ while update_skills runs, so a write that lands after the read fails the
+ ``equals`` guard and is re-read rather than overwritten."""
+ for _ in range(_SKILL_NAME_WRITE_ATTEMPTS):
+ row = await prisma.models.Expert.prisma().find_first(where=where)
+ if row is None:
+ return
+ names = rewrite(row.skills)
+ if names == row.skills:
+ return
+ if await prisma.models.Expert.prisma().update_many(
+ where={**where, "skills": {"equals": row.skills}},
+ data={"skills": {"set": names}},
+ ):
+ return
+ raise ConflictError(
+ "This expert's skills were changed by another update at the same time. "
+ "Try again."
+ )
+
+
+async def _owned_active_expert(
+ user_id: str, expert_id: str
+) -> prisma.models.Expert | None:
+ return await prisma.models.Expert.prisma().find_first(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ "visibility": ResourceVisibility.PRIVATE,
+ }
+ )
async def update_soul(user_id: str, expert_id: str, soul: ExpertSoulUpdate) -> Expert:
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index 2ffa93985d..171a587f9f 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -32,12 +32,13 @@ from backend.api.features.store.categories import StoreCategory
from backend.api.model import CreateGraph
from backend.blocks.io import AgentInputBlock
from backend.copilot.model import create_chat_session
+from backend.copilot.tools.skills_test import _FakeWorkspaceManager
from backend.data.db import prisma as db_client
from backend.data.graph import Graph, GraphSettings, Node
from backend.data.model import User
from backend.data.user import get_or_create_user
from backend.executor import utils as execution_utils
-from backend.util.exceptions import ExpertRunPausedError, NotFoundError
+from backend.util.exceptions import ConflictError, ExpertRunPausedError, NotFoundError
from backend.util.json import SafeJson
from backend.util.test import SpinTestServer
@@ -1268,6 +1269,45 @@ async def test_owns_active_expert_scopes_owner_and_archive_state(
assert not await experts_db.owns_active_expert(test_user.id, hired.expert.id)
[email protected](loop_scope="session")
+async def test_owns_private_active_expert_adds_the_visibility_filter(
+ server: SpinTestServer, test_user, other_user
+):
+ """The gate on the per-expert resource routes. A TEAM/ORG expert resolves
+ to no grants on the chat side, so writing its folder would mutate an
+ expert nothing can read — which is the whole delta from
+ ``owns_active_expert``."""
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ assert await experts_db.owns_private_active_expert(test_user.id, hired.expert.id)
+ assert not await experts_db.owns_private_active_expert(
+ other_user.id, hired.expert.id
+ )
+ assert not await experts_db.owns_private_active_expert(test_user.id, template.id)
+
+ for shared in (
+ prisma.enums.ResourceVisibility.TEAM,
+ prisma.enums.ResourceVisibility.ORG,
+ ):
+ await prisma.models.Expert.prisma().update(
+ where={"id": hired.expert.id}, data={"visibility": shared}
+ )
+ assert await experts_db.owns_active_expert(test_user.id, hired.expert.id)
+ assert not await experts_db.owns_private_active_expert(
+ test_user.id, hired.expert.id
+ )
+
+ await prisma.models.Expert.prisma().update(
+ where={"id": hired.expert.id},
+ data={"visibility": prisma.enums.ResourceVisibility.PRIVATE},
+ )
+ await experts_db.archive_expert(test_user.id, hired.expert.id)
+ assert not await experts_db.owns_private_active_expert(
+ test_user.id, hired.expert.id
+ )
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_archive_expert_rejects_cross_user(
server: SpinTestServer, test_user, other_user
@@ -1736,11 +1776,8 @@ async def test_update_skills_attaches_library_skills_and_keeps_existing(
async def test_update_skills_resolves_a_library_skill_by_its_listed_name(
server: SpinTestServer, test_user, monkeypatch
):
- from backend.copilot.tools.skills import ParsedSkill
-
- listed = ParsedSkill(name="Deep Research", description="Research anything", body="")
- monkeypatch.setattr(experts_db, "read_user_skill_with_body", _none_skill)
- monkeypatch.setattr(experts_db, "list_user_skills", _listing_skills([listed]))
+ monkeypatch.setattr(experts_db, "find_user_skill_slugs", _slugs("deep-research"))
+ monkeypatch.setattr(experts_db, "copy_skill_to_expert", _copied)
template = await _seed_template(name="Maria", preload_listings=[])
hired = await experts_db.hire_expert(test_user.id, template.id, None)
@@ -1748,18 +1785,18 @@ async def test_update_skills_resolves_a_library_skill_by_its_listed_name(
test_user.id, hired.expert.id, ["deep research"]
)
- assert updated.skills == ["Deep Research"]
+ assert updated.skills == ["deep-research"]
-async def _none_skill(*_args, **_kwargs):
- return None
+def _slugs(slug):
+ async def _find(_user_id, names):
+ return {name.strip().lower(): slug for name in names}
+ return _find
-def _listing_skills(skills):
- async def _list(*_args, **_kwargs):
- return skills
- return _list
+async def _copied(user_id, expert_id, name):
+ return name
@pytest.mark.asyncio(loop_scope="session")
@@ -4223,6 +4260,237 @@ def test_expert_soul_fields_patch_strips_and_preserves_none():
assert patch.identity is None
[email protected](loop_scope="session")
+async def test_update_skills_resolves_every_name_before_copying(
+ server: SpinTestServer, test_user, monkeypatch
+):
+ copies: list[str] = []
+
+ async def _find(user_id, names):
+ return {n.strip().lower(): n for n in names if n != "missing"}
+
+ async def _copy(user_id, expert_id, name):
+ copies.append(name)
+ return name
+
+ monkeypatch.setattr(experts_db, "find_user_skill_slugs", _find)
+ monkeypatch.setattr(experts_db, "copy_skill_to_expert", _copy)
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with pytest.raises(NotFoundError):
+ await experts_db.update_skills(
+ test_user.id, hired.expert.id, ["valid", "missing"]
+ )
+ assert copies == []
+
+
[email protected](loop_scope="session")
+async def test_update_skills_keeps_the_display_name_of_a_skill_already_carried(
+ server: SpinTestServer, test_user, monkeypatch
+):
+ """Copying returns the folder slug; a name the expert already carries must
+ not be renamed to it behind the user's back."""
+ monkeypatch.setattr(experts_db, "find_user_skill_slugs", _slugs("deep-research"))
+ monkeypatch.setattr(experts_db, "copy_skill_to_expert", _copied_slug)
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ await experts_db.add_expert_skill_name(
+ test_user.id, hired.expert.id, "Deep Research"
+ )
+
+ updated = await experts_db.update_skills(
+ test_user.id, hired.expert.id, ["Deep Research"]
+ )
+
+ assert updated.skills == ["Deep Research"]
+
+
+async def _copied_slug(user_id, expert_id, name):
+ return name.strip().lower()
+
+
[email protected](loop_scope="session")
+async def test_update_skills_drops_a_name_whose_source_vanished_before_the_copy(
+ server: SpinTestServer, test_user, monkeypatch
+):
+ """The library lookup and the copy are separate awaits, so a skill can be
+ deleted in between; the row must not end up listing it."""
+
+ async def _find(user_id, names):
+ return {n.strip().lower(): n for n in names}
+
+ async def _copy(user_id, expert_id, name):
+ return None if name == "vanishing" else name
+
+ monkeypatch.setattr(experts_db, "find_user_skill_slugs", _find)
+ monkeypatch.setattr(experts_db, "copy_skill_to_expert", _copy)
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ updated = await experts_db.update_skills(
+ test_user.id, hired.expert.id, ["kept", "vanishing"]
+ )
+
+ assert updated.skills == ["kept"]
+
+
[email protected](loop_scope="session")
+async def test_expert_skill_names_add_and_remove_atomically(
+ server: SpinTestServer, test_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ expert_id = hired.expert.id
+
+ await asyncio.gather(
+ experts_db.add_expert_skill_name(test_user.id, expert_id, "alpha"),
+ experts_db.add_expert_skill_name(test_user.id, expert_id, "beta"),
+ experts_db.add_expert_skill_name(test_user.id, expert_id, "Alpha"),
+ )
+ row = await prisma.models.Expert.prisma().find_unique(where={"id": expert_id})
+ assert row is not None
+ assert sorted(s.lower() for s in row.skills) == sorted(
+ {*(s.lower() for s in template.skills), "alpha", "beta"}
+ )
+
+ await experts_db.remove_expert_skill_name(test_user.id, expert_id, "ALPHA")
+ row = await prisma.models.Expert.prisma().find_unique(where={"id": expert_id})
+ assert row is not None
+ assert "alpha" not in {s.lower() for s in row.skills}
+
+
[email protected](loop_scope="session")
[email protected]("operation", ["add", "remove"])
+async def test_expert_skill_name_write_keeps_an_append_that_lands_mid_write(
+ server: SpinTestServer, test_user, operation
+):
+ """store_skill can append to the row between this write's read and its
+ update; the update must retry against the new list, never overwrite it."""
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ expert_id = hired.expert.id
+ await experts_db.add_expert_skill_name(test_user.id, expert_id, "stale")
+ real = prisma.models.Expert.prisma()
+ raced: list[bool] = []
+
+ async def read_then_race(**kwargs):
+ row = await real.find_first(**kwargs)
+ if not raced:
+ raced.append(True)
+ await real.update(
+ where={"id": expert_id}, data={"skills": {"push": ["from-the-chat"]}}
+ )
+ return row
+
+ manager = SimpleNamespace(find_first=read_then_race, update_many=real.update_many)
+ with patch.object(prisma.models.Expert, "prisma", return_value=manager):
+ if operation == "add":
+ await experts_db.add_expert_skill_name(
+ test_user.id, expert_id, "from-the-ui"
+ )
+ else:
+ await experts_db.remove_expert_skill_name(test_user.id, expert_id, "stale")
+
+ row = await prisma.models.Expert.prisma().find_unique(where={"id": expert_id})
+ assert row is not None and raced
+ names = {s.lower() for s in row.skills}
+ assert "from-the-chat" in names
+ if operation == "add":
+ assert "from-the-ui" in names
+ else:
+ assert "stale" not in names
+
+
[email protected](loop_scope="session")
[email protected]("name", ["old-skill", "agent_building_guide"])
+async def test_update_skills_dropping_a_skill_removes_the_copy_and_the_row_name(
+ server: SpinTestServer, test_user, name
+):
+ """A dropped skill loses its folder copy, or the listing, which reads the
+ folder, would keep offering it; a built-in has no copy, so only the row
+ write in update_skills removes its name."""
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ expert_id = hired.expert.id
+ fake = _FakeWorkspaceManager()
+ copy = f"/experts/{expert_id}/skills/{name}/SKILL.md"
+ if name == "old-skill":
+ fake.files[copy] = b"---\nname: old-skill\ndescription: d\n---\nsteps\n"
+ await experts_db.add_expert_skill_name(test_user.id, expert_id, name)
+
+ with patch(
+ "backend.copilot.tools.skills._get_user_skill_manager",
+ new=AsyncMock(return_value=fake),
+ ):
+ updated = await experts_db.update_skills(test_user.id, expert_id, [])
+
+ assert copy not in fake.files
+ assert name not in {s.lower() for s in updated.skills}
+
+
[email protected](loop_scope="session")
+async def test_expert_skill_names_treat_a_display_name_and_its_slug_as_one(
+ server: SpinTestServer, test_user
+):
+ """The row can hold a display name ("My Skill") for the skill stored as
+ "my-skill": recording the slug adds no second entry, and forgetting either
+ spelling removes the one entry."""
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ expert_id = hired.expert.id
+
+ await experts_db.add_expert_skill_name(test_user.id, expert_id, "My Skill")
+ await experts_db.add_expert_skill_name(test_user.id, expert_id, "my-skill")
+ row = await prisma.models.Expert.prisma().find_unique(where={"id": expert_id})
+ assert row is not None
+ assert [s for s in row.skills if s.lower() in ("my skill", "my-skill")] == [
+ "My Skill"
+ ]
+
+ await experts_db.remove_expert_skill_name(test_user.id, expert_id, "my-skill")
+ row = await prisma.models.Expert.prisma().find_unique(where={"id": expert_id})
+ assert row is not None
+ assert not [s for s in row.skills if s.lower() in ("my skill", "my-skill")]
+
+
[email protected](loop_scope="session")
[email protected]("operation", ["add", "remove"])
+async def test_expert_skill_name_write_gives_up_as_a_conflict_after_losing_every_race(
+ server: SpinTestServer, test_user, operation
+):
+ """A row that keeps changing under the write ends in the typed conflict the
+ API maps to 409, after a bounded number of attempts and with nothing written."""
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ expert_id = hired.expert.id
+ await experts_db.add_expert_skill_name(test_user.id, expert_id, "stale")
+ before = await prisma.models.Expert.prisma().find_unique(where={"id": expert_id})
+ assert before is not None
+ real = prisma.models.Expert.prisma()
+ attempts: list[int] = []
+
+ async def always_loses(**kwargs):
+ attempts.append(1)
+ return 0
+
+ manager = SimpleNamespace(find_first=real.find_first, update_many=always_loses)
+ with patch.object(prisma.models.Expert, "prisma", return_value=manager):
+ with pytest.raises(ConflictError):
+ if operation == "add":
+ await experts_db.add_expert_skill_name(
+ test_user.id, expert_id, "new-name"
+ )
+ else:
+ await experts_db.remove_expert_skill_name(
+ test_user.id, expert_id, "stale"
+ )
+
+ assert len(attempts) == experts_db._SKILL_NAME_WRITE_ATTEMPTS
+ row = await prisma.models.Expert.prisma().find_unique(where={"id": expert_id})
+ assert row is not None and row.skills == before.skills
+
+
async def _template(name: str, **fields) -> prisma.models.Expert:
return await prisma.models.Expert.prisma().create(
data={
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
index 8fa1a95bfa..b42a572015 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
@@ -38,11 +38,14 @@ from backend.api.features.experts.models import (
RaiseResult,
)
from backend.api.features.experts.routes import public_router, router
-from backend.util.exceptions import NotFoundError
+from backend.api.rest_api import app as rest_app
+from backend.util.exceptions import ConflictError, NotFoundError
app = fastapi.FastAPI()
app.include_router(public_router)
app.include_router(router)
+# The real app's mapping, so dropping it from rest_api.py fails here too.
+app.add_exception_handler(ConflictError, rest_app.exception_handlers[ConflictError])
client = fastapi.testclient.TestClient(app)
@@ -962,6 +965,24 @@ def test_update_expert_skills_unknown_skill_returns_404(
assert response.status_code == 404
+def test_update_expert_skills_conflict_returns_409(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_skills",
+ new_callable=AsyncMock,
+ side_effect=ConflictError(
+ "This expert's skills were changed by another update at the same time. "
+ "Try again."
+ ),
+ )
+
+ response = client.put("/experts/expert-1/skills", json={"skills": ["SEO"]})
+
+ assert response.status_code == 409
+ assert "Try again" in response.text
+
+
def test_update_expert_soul_not_found_returns_404(
mocker: pytest_mock.MockerFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index a1c53f1a90..393f1cff01 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -2774,6 +2774,17 @@ class UploadCopilotSkillRequest(BaseModel):
content: str
+async def _require_skill_owner(user_id: str, expert_id: str | None) -> None:
+ """A skill owner named on a REST call must be one of the caller's active
+ experts; personal Otto (``None``) needs no check."""
+ if expert_id is None:
+ return
+ if not await experts_db.owns_private_active_expert(user_id, expert_id):
+ raise HTTPException(
+ status_code=HTTP_404_NOT_FOUND, detail=f"Expert '{expert_id}' not found"
+ )
+
+
@v1_router.get(
path="/skills",
summary="List user-distilled copilot skills",
@@ -2783,15 +2794,20 @@ class UploadCopilotSkillRequest(BaseModel):
)
async def list_copilot_skills(
user_id: Annotated[str, Security(get_user_id)],
+ expert_id: str | None = Query(
+ default=None,
+ description="List this expert's own skills instead of personal Otto's.",
+ ),
) -> list[CopilotSkillInfo]:
- """Return user-stored skills for the current user.
+ """Return the skills owned by personal Otto, or by one expert.
Reuses :func:`backend.copilot.tools.skills.list_user_skills` so the
library UI sees the exact same set the copilot ``<available_skills>``
block surfaces, minus the built-in defaults (which are read-only and
handled separately by the copilot runtime).
"""
- skills = await list_user_skills(user_id)
+ await _require_skill_owner(user_id, expert_id)
+ skills = await list_user_skills(user_id, expert_id)
return [
CopilotSkillInfo(
name=s.name,
@@ -2817,6 +2833,9 @@ async def list_copilot_skills(
async def upload_copilot_skill(
user_id: Annotated[str, Security(get_user_id)],
body: UploadCopilotSkillRequest,
+ expert_id: str | None = Query(
+ default=None, description="Store the skill as this expert's own."
+ ),
) -> CopilotSkillInfo:
"""Create a user-distilled skill from an uploaded ``SKILL.md`` file.
@@ -2826,6 +2845,7 @@ async def upload_copilot_skill(
via ``store_skill``. Malformed files return 400, the per-user cap returns
409, and an existing slug is overwritten (upsert).
"""
+ await _require_skill_owner(user_id, expert_id)
parsed = parse_skill_markdown(body.content)
if parsed is None:
raise HTTPException(
@@ -2838,6 +2858,7 @@ async def upload_copilot_skill(
try:
stored = await store_user_skill(
user_id,
+ expert_id=expert_id,
name=parsed.name,
description=parsed.description,
body=parsed.body,
@@ -2871,6 +2892,9 @@ async def upload_copilot_skill(
async def read_copilot_skill(
user_id: Annotated[str, Security(get_user_id)],
name: str = Path(..., description="Slug of the skill to read"),
+ expert_id: str | None = Query(
+ default=None, description="Read this expert's own copy of the skill."
+ ),
) -> CopilotSkillDetail:
"""Return full SKILL.md content (name, description, triggers, body)
for the library UI's expand-to-view dialog.
@@ -2897,12 +2921,15 @@ async def read_copilot_skill(
is_default=True,
)
- parsed = await read_user_skill_with_body(user_id, slug)
+ await _require_skill_owner(user_id, expert_id)
+ parsed = await read_user_skill_with_body(user_id, slug, expert_id=expert_id)
if parsed is None:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND, detail=f"Skill '{slug}' not found"
)
- sibling_files = await list_user_skill_sibling_paths(user_id, slug)
+ sibling_files = await list_user_skill_sibling_paths(
+ user_id, slug, expert_id=expert_id
+ )
return CopilotSkillDetail(
name=parsed.name,
description=parsed.description,
@@ -2924,6 +2951,9 @@ async def read_copilot_skill(
async def delete_copilot_skill(
user_id: Annotated[str, Security(get_user_id)],
name: str = Path(..., description="Slug of the skill to delete"),
+ expert_id: str | None = Query(
+ default=None, description="Delete this expert's own copy of the skill."
+ ),
) -> dict[str, str]:
"""Delete a user-distilled skill by slug.
@@ -2931,8 +2961,9 @@ async def delete_copilot_skill(
returns 400. Missing skills return 404 so the UI can reconcile a
stale list.
"""
+ await _require_skill_owner(user_id, expert_id)
try:
- slug = await delete_user_skill(user_id, name)
+ slug = await delete_user_skill(user_id, name, expert_id=expert_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except BuiltInSkillError as exc:
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index 33cce075d6..cefcea78a1 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -1621,3 +1621,128 @@ def test_upload_copilot_skill_returns_400_on_virus_detection(
response = client.post("/skills", json={"content": _VALID_SKILL_MD})
assert response.status_code == 400
assert "virus scan" in response.json()["detail"]
+
+
+_EXPERT_SKILL_ROUTES = {
+ "list": lambda expert_id: client.get("/skills", params=_owner(expert_id)),
+ "upload": lambda expert_id: client.post(
+ "/skills", params=_owner(expert_id), json={"content": _VALID_SKILL_MD}
+ ),
+ "read": lambda expert_id: client.get(
+ "/skills/oauth_flow", params=_owner(expert_id)
+ ),
+ "delete": lambda expert_id: client.delete(
+ "/skills/oauth_flow", params=_owner(expert_id)
+ ),
+}
+
+_SKILL_LAYER = {
+ "list_user_skills": [],
+ "store_user_skill": ParsedSkill(name="oauth_flow", description="d", body="b"),
+ "read_user_skill_with_body": ParsedSkill(
+ name="oauth_flow", description="d", body="b"
+ ),
+ "delete_user_skill": "oauth_flow",
+}
+
+
[email protected]("route", list(_EXPERT_SKILL_ROUTES))
+def test_expert_skill_routes_refuse_an_expert_the_caller_does_not_own(
+ route: str,
+ mocker: pytest_mock.MockFixture,
+ test_user_id: str,
+) -> None:
+ """Every /skills route naming an expert goes through the same owner gate,
+ and a refusal is a 404 that never reaches the skills layer."""
+ owns = mocker.patch(
+ "backend.api.features.v1.experts_db.owns_private_active_expert",
+ AsyncMock(return_value=False),
+ )
+ downstream = {
+ name: mocker.patch(f"backend.api.features.v1.{name}", AsyncMock())
+ for name in _SKILL_LAYER
+ }
+
+ response = _EXPERT_SKILL_ROUTES[route]("expert-not-mine")
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "Expert 'expert-not-mine' not found"
+ owns.assert_awaited_once_with(test_user_id, "expert-not-mine")
+ for mock in downstream.values():
+ mock.assert_not_awaited()
+
+
+ "route,downstream",
+ [
+ ("list", "list_user_skills"),
+ ("upload", "store_user_skill"),
+ ("read", "read_user_skill_with_body"),
+ ("delete", "delete_user_skill"),
+ ],
+)
+def test_expert_skill_routes_forward_an_owned_expert(
+ route: str,
+ downstream: str,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """An owned PRIVATE expert passes the gate and its id reaches the skills
+ layer, so the call reads that expert's folder and not Otto's."""
+ mocker.patch(
+ "backend.api.features.v1.experts_db.owns_private_active_expert",
+ AsyncMock(return_value=True),
+ )
+ mocker.patch(
+ "backend.api.features.v1.list_user_skill_sibling_paths",
+ AsyncMock(return_value=[]),
+ )
+ target = mocker.patch(
+ f"backend.api.features.v1.{downstream}",
+ AsyncMock(return_value=_SKILL_LAYER[downstream]),
+ )
+
+ response = _EXPERT_SKILL_ROUTES[route]("expert-mine")
+
+ assert response.status_code in (200, 201)
+ assert _forwarded_expert_id(target) == "expert-mine"
+
+
[email protected]("route", list(_EXPERT_SKILL_ROUTES))
+def test_personal_autopilot_skill_routes_skip_the_expert_gate(
+ route: str,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """No expert named means personal Otto, which owns its own folder and
+ must never be refused by the expert gate."""
+ owns = mocker.patch(
+ "backend.api.features.v1.experts_db.owns_private_active_expert",
+ AsyncMock(return_value=False),
+ )
+ mocker.patch(
+ "backend.api.features.v1.list_user_skill_sibling_paths",
+ AsyncMock(return_value=[]),
+ )
+ for name, value in _SKILL_LAYER.items():
+ mocker.patch(f"backend.api.features.v1.{name}", AsyncMock(return_value=value))
+
+ response = _EXPERT_SKILL_ROUTES[route](None)
+
+ assert response.status_code in (200, 201)
+ owns.assert_not_awaited()
+
+
+# ``expert_id`` omitted entirely, not sent empty: an empty query value is a
+# str, which would take the expert branch of the gate rather than the
+# personal-Otto one.
+def _owner(expert_id: str | None) -> dict[str, str]:
+ return {} if expert_id is None else {"expert_id": expert_id}
+
+
+def _forwarded_expert_id(mock: AsyncMock) -> str | None:
+ """``list_user_skills`` takes the owner positionally, the rest by keyword."""
+ call = mock.await_args
+ if call is None:
+ return None
+ if "expert_id" in call.kwargs:
+ return call.kwargs["expert_id"]
+ return call.args[1] if len(call.args) > 1 else None
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index f6f8c9222b..43e2319ea0 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -88,6 +88,7 @@ from backend.monitoring.instrumentation import instrument_fastapi
from backend.util import json
from backend.util.cloud_storage import shutdown_cloud_storage_handler
from backend.util.exceptions import (
+ ConflictError,
MissingConfigError,
NotAuthorizedError,
NotFoundError,
@@ -364,6 +365,7 @@ async def validation_error_handler(
app.add_exception_handler(PrismaError, handle_internal_http_error(500))
app.add_exception_handler(FolderAlreadyExistsError, handle_internal_http_error(409))
+app.add_exception_handler(ConflictError, handle_internal_http_error(409))
app.add_exception_handler(FolderValidationError, handle_internal_http_error(400))
app.add_exception_handler(GraphActivationError, handle_internal_http_error(400))
app.add_exception_handler(NotFoundError, handle_internal_http_error(404))
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index e53b3f02a8..69761ac0fb 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -1985,7 +1985,9 @@ async def stream_chat_completion_baseline(
# here MUST NOT block the turn; log and proceed with empty index.
skills_ctx = ""
try:
- skills_ctx = await build_skills_context(user_id)
+ skills_ctx = await build_skills_context(
+ user_id, expert_id=session.expert_id
+ )
except Exception:
logger.exception(
"[skills] failed to build skills_ctx — proceeding without it"
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index c68480ddb5..de53fa8e7c 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -5221,7 +5221,9 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
# NOT block the turn — log and continue with an empty index.
skills_ctx_content = ""
try:
- skills_ctx_content = await build_skills_context(user_id)
+ skills_ctx_content = await build_skills_context(
+ user_id, expert_id=session.expert_id
+ )
except Exception:
logger.exception(
"[skills] failed to build skills_ctx — proceeding without it"
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills.py b/autogpt_platform/backend/backend/copilot/tools/skills.py
index dfae082bb0..db50b36007 100644
--- a/autogpt_platform/backend/backend/copilot/tools/skills.py
+++ b/autogpt_platform/backend/backend/copilot/tools/skills.py
@@ -31,13 +31,21 @@ from pathlib import Path
from typing import Any
import yaml
+from pydantic import BaseModel
from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError
from backend.copilot.model import ChatSession
from backend.copilot.service import strip_server_injected_tags
-from backend.data.db_accessors import workspace_db
+from backend.data.db_accessors import experts_db, workspace_db
from backend.data.redis_client import get_redis_async
+from backend.data.workspace_scope import (
+ EXPERT_SKILL_SCOPE_DENIED,
+ WorkspaceAccessDeniedError,
+ WorkspaceScope,
+ expert_skills_folder,
+)
from backend.executor.cluster_lock import AsyncClusterLock
+from backend.util.exceptions import ConflictError
from backend.util.feature_flag import Flag, is_feature_enabled
from backend.util.workspace import WorkspaceManager
@@ -69,12 +77,27 @@ MAX_TRIGGERS = 10
MAX_TRIGGER_CHARS = 64
SKILL_FOLDER = "/skills"
+
+def skill_folder(expert_id: str | None) -> str:
+ """Owner folder. Personal Otto's skills live under ``/skills``; each
+ expert's own skills under ``/experts/<id>/skills``. Ownership is the
+ folder — there is no separate assignment record."""
+ return SKILL_FOLDER if expert_id is None else expert_skills_folder(expert_id)
+
+
# Redis-cached index TTL. Skill content changes only on store/delete so a
# 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}"
+# 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 —
+# can never be copied, so the heal below remembers it and stops re-scanning.
+# The TTL bounds how long a name that becomes copyable waits for its backfill.
+SKILLS_HEAL_BACKOFF_TTL_S = 600
+SKILLS_HEAL_BACKOFF_KEY = "copilot:skills_heal_backoff:{user_id}:expert:{expert_id}"
+
# WorkspaceFile.metadata keys for the skill index fast path — avoids the
# storage read when the metadata was written at store time (anything
# pre-dating this change falls back to read+parse, see
@@ -231,9 +254,60 @@ def _validate_name(name: str) -> str | None:
# ---------------------------------------------------------------------------
-async def _get_user_skill_manager(user_id: str) -> WorkspaceManager:
+async def _get_user_skill_manager(
+ user_id: str, scope: WorkspaceScope | None = None
+) -> WorkspaceManager:
workspace = await workspace_db().get_or_create_workspace(user_id)
- return WorkspaceManager(user_id, workspace.id, session_id=None)
+ return WorkspaceManager(user_id, workspace.id, session_id=None, scope=scope)
+
+
+async def resolve_skill_scope(
+ user_id: str | None, expert_id: str | None
+) -> WorkspaceScope | None:
+ """Workspace grants for an expert session's skill folder.
+
+ ``None`` means unrestricted — personal Otto, REST callers, and
+ anonymous default-skill reads. The scope comes from the persisted expert
+ attribution on the session, never from a tool argument.
+ """
+ if not user_id or expert_id is None:
+ return None
+ return await workspace_db().resolve_expert_workspace_scope(user_id, expert_id)
+
+
+class SkillOwner(BaseModel):
+ """Whose skill folder a tool call operates on, plus the workspace scope
+ that call must run under."""
+
+ expert_id: str | None
+ scope: WorkspaceScope | None
+
+
+async def resolve_skill_owner(
+ user_id: str, session: ChatSession, requested_expert_id: str | None
+) -> SkillOwner | str:
+ """Decide the skill owner for a tool call, or return a denial message.
+
+ An expert session always operates on its own folder; naming any other
+ owner is refused. Personal Otto operates on its own folder by
+ default and may name one of the owner's active experts to manage that
+ expert's skills.
+ """
+ if session.expert_id is not None:
+ if requested_expert_id and requested_expert_id != session.expert_id:
+ return EXPERT_SKILL_SCOPE_DENIED
+ return SkillOwner(
+ expert_id=session.expert_id,
+ scope=await resolve_skill_scope(user_id, session.expert_id),
+ )
+ if not requested_expert_id:
+ return SkillOwner(expert_id=None, scope=None)
+ expert = await experts_db().get_expert(
+ user_id, requested_expert_id, include_workflows=False
+ )
+ if expert is None:
+ return f"Expert '{requested_expert_id}' was not found on this account."
+ return SkillOwner(expert_id=expert.id, scope=None)
# Redis lock key for serialising store_skill writes per user. A per-user
@@ -246,8 +320,8 @@ _SKILL_WRITE_LOCK_KEY_PREFIX = "copilot:skill_write:"
_SKILL_WRITE_LOCK_TTL_SECONDS = 30
-def _skill_md_path(name: str) -> str:
- return f"{SKILL_FOLDER}/{name}/SKILL.md"
+def _skill_md_path(name: str, expert_id: str | None = None) -> str:
+ return f"{skill_folder(expert_id)}/{name}/SKILL.md"
def _load_default_body(skill: _DefaultSkill) -> str:
@@ -291,8 +365,15 @@ 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.
+async def delete_user_skill(
+ user_id: str,
+ name: str,
+ *,
+ expert_id: str | None = None,
+ scope: WorkspaceScope | None = None,
+) -> str:
+ """Delete a user-distilled skill folder by slug from *expert_id*'s folder
+ (personal Otto's when ``None``).
Returns the normalised slug on success so callers can echo it back.
Raises :class:`BuiltInSkillError` for default skills,
@@ -308,9 +389,13 @@ async def delete_user_skill(user_id: str, name: str) -> str:
if slug in _DEFAULT_SKILLS_BY_NAME:
raise BuiltInSkillError(f"'{slug}' is a built-in skill and cannot be deleted")
- manager = await _get_user_skill_manager(user_id)
- info = await manager.get_file_info_by_path(_skill_md_path(slug))
+ manager = await _get_user_skill_manager(user_id, scope)
+ info = await manager.get_file_info_by_path(_skill_md_path(slug, expert_id))
if info is None:
+ if expert_id is not None:
+ # A stale name from an earlier failed delete: drop it so the row
+ # never lists a skill the expert cannot read.
+ await experts_db().remove_expert_skill_name(user_id, expert_id, slug)
raise SkillNotFoundError(f"Skill '{slug}' not found")
# Audit-log the delete BEFORE the workspace mutation runs so the
@@ -320,7 +405,7 @@ async def delete_user_skill(user_id: str, name: str) -> str:
# correlate later support requests.
description_for_log = ""
try:
- raw = await manager.read_file(_skill_md_path(slug))
+ raw = await manager.read_file(_skill_md_path(slug, expert_id))
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
@@ -342,7 +427,7 @@ async def delete_user_skill(user_id: str, name: str) -> str:
try:
siblings = await manager.list_files(
- path=f"{SKILL_FOLDER}/{slug}/",
+ path=f"{skill_folder(expert_id)}/{slug}/",
limit=50,
include_all_sessions=True,
)
@@ -360,7 +445,9 @@ async def delete_user_skill(user_id: str, name: str) -> str:
sibling.path,
exc_info=True,
)
- await invalidate_skills_index_cache(user_id)
+ await invalidate_skills_index_cache(user_id, expert_id)
+ if expert_id is not None:
+ await experts_db().remove_expert_skill_name(user_id, expert_id, slug)
return slug
@@ -372,12 +459,15 @@ async def store_user_skill(
body: str,
triggers: list[str] | None = None,
version: str | None = None,
+ expert_id: str | None = None,
+ scope: WorkspaceScope | 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
+ The skill lands in *expert_id*'s folder (personal Otto's when
+ ``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-user cap is reached, and
propagates ``VirusDetectedError`` / ``VirusScanError`` (and any other
workspace write error) to the caller.
@@ -435,7 +525,7 @@ async def store_user_skill(
try:
lock = AsyncClusterLock(
redis=await get_redis_async(),
- key=f"{_SKILL_WRITE_LOCK_KEY_PREFIX}{user_id}",
+ key=f"{_SKILL_WRITE_LOCK_KEY_PREFIX}{user_id}:{expert_id or 'autopilot'}",
owner_id=uuid.uuid4().hex,
timeout=_SKILL_WRITE_LOCK_TTL_SECONDS,
)
@@ -452,13 +542,15 @@ async def store_user_skill(
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
+ manager = await _get_user_skill_manager(user_id, scope)
+ # Enforce the per-owner 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)
+ # 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_USER_SKILLS
is_new = name not in existing_slugs
@@ -494,12 +586,14 @@ async def store_user_skill(
await manager.write_file(
content=rendered.encode("utf-8"),
filename="SKILL.md",
- path=_skill_md_path(name),
+ path=_skill_md_path(name, expert_id),
mime_type="text/markdown",
overwrite=True,
metadata=metadata,
)
- await invalidate_skills_index_cache(user_id)
+ await invalidate_skills_index_cache(user_id, expert_id)
+ if expert_id is not None:
+ await experts_db().add_expert_skill_name(user_id, expert_id, name)
return parsed
finally:
if lock is not None and lock_held:
@@ -559,7 +653,11 @@ def _index_entry_from_metadata(slug: str, meta: dict) -> ParsedSkill | None:
)
-async def _list_user_skills_from_workspace(user_id: str) -> list[ParsedSkill]:
+async def _list_user_skills_from_workspace(
+ user_id: str,
+ expert_id: str | None = None,
+ scope: WorkspaceScope | None = None,
+) -> list[ParsedSkill]:
"""Workspace-side listing — no caching. Body fields are always empty
because the index never needs them; :func:`read_user_skill_with_body`
is the path for retrieving full content.
@@ -569,9 +667,9 @@ async def _list_user_skills_from_workspace(user_id: str) -> list[ParsedSkill]:
any file missing the metadata (older skills, or skills written by a
deployment before the metadata-cache change shipped).
"""
- manager = await _get_user_skill_manager(user_id)
+ manager = await _get_user_skill_manager(user_id, scope)
files = await manager.list_files(
- path=f"{SKILL_FOLDER}/",
+ path=f"{skill_folder(expert_id)}/",
limit=MAX_USER_SKILLS * 4, # over-fetch in case of strays
include_all_sessions=True,
)
@@ -612,14 +710,17 @@ async def _list_user_skills_from_workspace(user_id: str) -> list[ParsedSkill]:
return skills
-def _skills_cache_key(user_id: str) -> str:
- return SKILLS_INDEX_CACHE_KEY.format(user_id=user_id)
+def _skills_cache_key(user_id: str, expert_id: str | None = None) -> str:
+ base = SKILLS_INDEX_CACHE_KEY.format(user_id=user_id)
+ return base if expert_id is None else f"{base}:expert:{expert_id}"
-async def _read_skills_cache(user_id: str) -> list[ParsedSkill] | None:
+async def _read_skills_cache(
+ user_id: str, expert_id: str | None = None
+) -> list[ParsedSkill] | None:
try:
redis = await get_redis_async()
- raw = await redis.get(_skills_cache_key(user_id))
+ raw = await redis.get(_skills_cache_key(user_id, expert_id))
except Exception:
# Cache is best-effort — a redis blip must not break the turn.
return None
@@ -645,7 +746,9 @@ async def _read_skills_cache(user_id: str) -> list[ParsedSkill] | None:
return None
-async def _write_skills_cache(user_id: str, skills: list[ParsedSkill]) -> None:
+async def _write_skills_cache(
+ user_id: str, skills: list[ParsedSkill], expert_id: str | None = None
+) -> None:
try:
redis = await get_redis_async()
payload = json.dumps(
@@ -660,7 +763,7 @@ async def _write_skills_cache(user_id: str, skills: list[ParsedSkill]) -> None:
]
)
await redis.set(
- _skills_cache_key(user_id),
+ _skills_cache_key(user_id, expert_id),
payload,
ex=SKILLS_INDEX_CACHE_TTL_S,
)
@@ -669,22 +772,36 @@ async def _write_skills_cache(user_id: str, skills: list[ParsedSkill]) -> None:
pass
-async def invalidate_skills_index_cache(user_id: str) -> None:
+async def invalidate_skills_index_cache(
+ user_id: str, expert_id: str | None = None
+) -> None:
"""Drop the cached per-user skill index so the next turn rebuilds it.
Called by ``store_skill`` / ``delete_user_skill`` so an edit shows up
immediately rather than after the 60s TTL.
+
+ Also drops the expert's heal backoff: the folder just changed, so a name
+ that resolved to nothing before may resolve now.
"""
+ keys = [_skills_cache_key(user_id, expert_id)]
+ if expert_id is not None:
+ keys.append(_heal_backoff_key(user_id, expert_id))
try:
redis = await get_redis_async()
- await redis.delete(_skills_cache_key(user_id))
+ await redis.delete(*keys)
except Exception:
# Cache invalidate is best-effort — at worst the user sees stale
# state for up to ``SKILLS_INDEX_CACHE_TTL_S`` seconds.
pass
-async def list_user_skills(user_id: str) -> list[ParsedSkill]:
- """Return all skills the user has stored in workspace.
+async def list_user_skills(
+ user_id: str,
+ expert_id: str | None = None,
+ scope: WorkspaceScope | None = None,
+ *,
+ heal_missing: bool = True,
+) -> list[ParsedSkill]:
+ """Return the skills owned by *expert_id* (personal Otto when ``None``).
Two-level fast path: a 60s Redis cache covers warm turns, the
``WorkspaceFile.metadata`` index covers cold turns without any storage
@@ -693,16 +810,120 @@ async def list_user_skills(user_id: str) -> list[ParsedSkill]:
parse as valid SKILL.md so a stray file in ``/skills/`` cannot break
the index.
"""
- cached = await _read_skills_cache(user_id)
+ cached = await _read_skills_cache(user_id, expert_id)
if cached is not None:
return cached
- skills = await _list_user_skills_from_workspace(user_id)
- await _write_skills_cache(user_id, skills)
+ skills = await _list_user_skills_from_workspace(user_id, expert_id, scope)
+ if (
+ heal_missing
+ and expert_id is not None
+ and await _copy_assigned_skills_not_yet_owned(user_id, expert_id, skills)
+ ):
+ skills = await _list_user_skills_from_workspace(user_id, expert_id, scope)
+ await _write_skills_cache(user_id, skills, expert_id)
return skills
-async def read_user_skill_with_body(user_id: str, name: str) -> ParsedSkill | None:
- """Return a single user-stored skill with its body populated.
+async def _copy_assigned_skills_not_yet_owned(
+ user_id: str, expert_id: str, owned: list[ParsedSkill]
+) -> bool:
+ """Give the expert a copy of every skill its row lists but its folder
+ lacks, and report whether anything landed.
+
+ Assignments made before skills were owned per expert point at Otto's
+ library and have no copy anywhere, so without this an existing expert
+ silently drops to the built-in defaults. Runs only on a cache miss, and
+ only while something is actually missing. A name that resolves to nothing
+ is left on the row: a marketplace attachment has no folder to copy by
+ design, and a storage blip must not delete an assignment — but it is
+ remembered, so the next cold turn skips a scan that cannot succeed.
+ """
+ expert = await experts_db().get_expert(user_id, expert_id, include_workflows=False)
+ if expert is None:
+ return False
+ have = {skill_name_key(s.name) for s in owned}
+ missing = [
+ name
+ for name in expert.skills or []
+ if name.strip()
+ and skill_name_key(name) not in have
+ and name.strip().lower() not in _DEFAULT_SKILLS_BY_NAME
+ ]
+ if not missing or await _heal_backoff_covers(user_id, expert_id, missing):
+ return False
+ folders = await find_user_skill_slugs(user_id, missing)
+ copied = False
+ unresolved: list[str] = []
+ for name in missing:
+ folder = folders.get(name.strip().lower())
+ if folder is None:
+ unresolved.append(name.strip().lower())
+ continue
+ try:
+ if await copy_skill_to_expert(user_id, expert_id, folder):
+ copied = True
+ except Exception:
+ logger.exception(
+ "[skills] failed to copy assigned skill %r to expert #%s",
+ name,
+ expert_id,
+ )
+ # After the copies, so a copy's own cache invalidation cannot drop it.
+ await _set_heal_backoff(user_id, expert_id, unresolved)
+ return copied
+
+
+def skill_name_key(name: str) -> str:
+ """Compare key for skill names: the row may carry a display name ("Deep
+ Research") for the skill whose folder is ``deep-research``."""
+ return re.sub(r"[\s_-]+", "-", name.strip().lower())
+
+
+def _heal_backoff_key(user_id: str, expert_id: str) -> str:
+ return SKILLS_HEAL_BACKOFF_KEY.format(user_id=user_id, expert_id=expert_id)
+
+
+async def _heal_backoff_covers(
+ user_id: str, expert_id: str, missing: list[str]
+) -> bool:
+ """True when every still-missing name was already proved uncopyable, so
+ the scan can be skipped. A name outside the marker retries immediately —
+ including one whose copy failed transiently."""
+ try:
+ redis = await get_redis_async()
+ raw = await redis.get(_heal_backoff_key(user_id, expert_id))
+ known = set(json.loads(raw)) if raw else set()
+ except Exception:
+ # Losing the marker costs one repeat scan, never correctness.
+ return False
+ return all(name.strip().lower() in known for name in missing)
+
+
+async def _set_heal_backoff(user_id: str, expert_id: str, names: list[str]) -> None:
+ """Record the names that resolved to nothing, or clear the marker when
+ none did."""
+ key = _heal_backoff_key(user_id, expert_id)
+ try:
+ redis = await get_redis_async()
+ if not names:
+ await redis.delete(key)
+ return
+ await redis.set(
+ key, json.dumps(sorted(set(names))), ex=SKILLS_HEAL_BACKOFF_TTL_S
+ )
+ except Exception:
+ pass
+
+
+async def read_user_skill_with_body(
+ user_id: str,
+ name: str,
+ *,
+ expert_id: str | None = None,
+ scope: WorkspaceScope | None = None,
+) -> ParsedSkill | None:
+ """Return a single skill owned by *expert_id* (personal Otto when
+ ``None``) with its body populated.
Used by the ``read_skill`` MCP tool and the REST GET ``/skills/{name}``
endpoint that powers the library UI's expand-to-view dialog. Returns
@@ -712,11 +933,17 @@ async def read_user_skill_with_body(user_id: str, name: str) -> ParsedSkill | No
slug = name.strip().lower()
if not slug:
return None
- manager = await _get_user_skill_manager(user_id)
- return await _parse_skill_from_workspace(manager, _skill_md_path(slug))
+ manager = await _get_user_skill_manager(user_id, scope)
+ return await _parse_skill_from_workspace(manager, _skill_md_path(slug, expert_id))
-async def list_user_skill_sibling_paths(user_id: str, name: str) -> list[str]:
+async def list_user_skill_sibling_paths(
+ user_id: str,
+ name: str,
+ *,
+ expert_id: str | None = None,
+ scope: WorkspaceScope | None = None,
+) -> list[str]:
"""Return the workspace paths of files siblings to ``SKILL.md`` in a
user-stored skill's folder (``references/``, ``scripts/``, ``assets/``,
or anything the model stashed there at distillation time).
@@ -730,9 +957,9 @@ async def list_user_skill_sibling_paths(user_id: str, name: str) -> list[str]:
if not slug:
return []
try:
- manager = await _get_user_skill_manager(user_id)
+ manager = await _get_user_skill_manager(user_id, scope)
files = await manager.list_files(
- path=f"{SKILL_FOLDER}/{slug}/",
+ path=f"{skill_folder(expert_id)}/{slug}/",
limit=50,
include_all_sessions=True,
)
@@ -744,6 +971,96 @@ async def list_user_skill_sibling_paths(user_id: str, name: str) -> list[str]:
return []
+async def find_user_skill_slug(user_id: str, name: str) -> str | None:
+ """Folder slug of personal Otto's skill called *name*."""
+ return (await find_user_skill_slugs(user_id, [name])).get(name.strip().lower())
+
+
+async def find_user_skill_slugs(user_id: str, names: list[str]) -> dict[str, str]:
+ """Folder slug per requested name, keyed by the lowercased name.
+
+ Matches the folder first, then the frontmatter name — a skill written by
+ hand may be listed under a name that differs from its folder. One listing
+ covers the whole batch, and a folder carrying store-time metadata is
+ matched without reading it, so only hand-written skills cost a fetch.
+ """
+ wanted = {n.strip().lower() for n in names if n.strip()}
+ if not wanted:
+ return {}
+ manager = await _get_user_skill_manager(user_id)
+ files = await manager.list_files(
+ path=f"{SKILL_FOLDER}/", limit=MAX_USER_SKILLS * 4, include_all_sessions=True
+ )
+ found: dict[str, str] = {}
+ unnamed: list[Any] = []
+ for f in files:
+ if not f.path.endswith("/SKILL.md"):
+ continue
+ folder = f.path.rsplit("/", 2)[-2]
+ if folder.strip().lower() in wanted:
+ found[folder.strip().lower()] = folder
+ continue
+ meta = f.metadata if isinstance(f.metadata, dict) else {}
+ if meta.get(_META_KIND) != _META_KIND_VALUE:
+ unnamed.append(f)
+ missing = wanted - set(found)
+ if not missing or not unnamed:
+ return found
+ parsed = await asyncio.gather(
+ *(_parse_skill_from_workspace(manager, f.path) for f in unnamed)
+ )
+ for f, entry in zip(unnamed, parsed):
+ if entry is None:
+ continue
+ name = entry.name.strip().lower()
+ if name in missing:
+ found.setdefault(name, f.path.rsplit("/", 2)[-2])
+ return found
+
+
+async def copy_skill_to_expert(user_id: str, expert_id: str, name: str) -> str | None:
+ """Give *expert_id* its own copy of one of personal Otto's skills.
+
+ Returns the stored slug, or ``None`` when Otto has no such skill.
+ Idempotent: an expert that already owns the slug keeps its copy. The
+ SKILL.md is re-validated through :func:`store_user_skill`; sibling files
+ are copied best-effort afterwards.
+ """
+ slug = name.strip().lower()
+ if not slug:
+ return None
+ manager = await _get_user_skill_manager(user_id)
+ if await manager.get_file_info_by_path(_skill_md_path(slug, expert_id)):
+ # Reconcile a copy whose row update failed earlier; idempotent.
+ await experts_db().add_expert_skill_name(user_id, expert_id, slug)
+ return slug
+ source = await read_user_skill_with_body(user_id, slug)
+ if source is None:
+ return None
+ stored = await store_user_skill(
+ user_id,
+ name=slug,
+ description=source.description,
+ body=source.body,
+ triggers=list(source.triggers),
+ version=source.version,
+ expert_id=expert_id,
+ )
+ for path in await list_user_skill_sibling_paths(user_id, slug):
+ relative = path[len(f"{SKILL_FOLDER}/{slug}/") :]
+ try:
+ await manager.write_file(
+ content=await manager.read_file(path),
+ filename=relative.rsplit("/", 1)[-1],
+ path=f"{skill_folder(expert_id)}/{slug}/{relative}",
+ mime_type=None,
+ overwrite=True,
+ )
+ except Exception:
+ logger.warning("[skills] failed to copy %s for expert", path, exc_info=True)
+ return stored.name
+
+
def get_default_skills_for_index() -> list[ParsedSkill]:
"""Return the default seeded skills with **empty bodies** — suitable
for rendering the per-turn ``<available_skills>`` index, which only
@@ -791,17 +1108,25 @@ def get_default_skills() -> list[ParsedSkill]:
return result
-async def list_all_skills(user_id: str | None) -> list[ParsedSkill]:
- """Default seeded skills first, then user-distilled skills.
+async def list_all_skills(
+ user_id: str | None,
+ expert_id: str | None = None,
+ scope: WorkspaceScope | None = None,
+) -> list[ParsedSkill]:
+ """Default seeded skills first, then the owner's own skills.
Defaults always lead so the model sees the built-in agent-building
guide before any user customisation. Index-only — default bodies
are NOT loaded; :tool:`read_skill` re-reads them on demand via
:func:`get_default_skills`.
+
+ *expert_id* selects whose skills follow the defaults: an expert's own
+ folder, or personal Otto's when ``None``. Neither ever sees the
+ other's skills.
"""
skills = get_default_skills_for_index()
if user_id:
- skills.extend(await list_user_skills(user_id))
+ skills.extend(await list_user_skills(user_id, expert_id, scope))
return skills
@@ -837,7 +1162,9 @@ async def is_skills_feature_enabled(user_id: str | None) -> bool:
return await is_feature_enabled(Flag.COPILOT_SKILLS, user_id, default=True)
-async def build_skills_context(user_id: str | None) -> str:
+async def build_skills_context(
+ user_id: str | None, expert_id: str | None = None
+) -> str:
"""Build the body of the ``<available_skills>`` block injected into
the first user message. Returns ``""`` if there are no skills to
show — :func:`inject_user_context` then omits the block entirely so
@@ -846,10 +1173,13 @@ async def build_skills_context(user_id: str | None) -> str:
Also returns ``""`` when the ``COPILOT_SKILLS`` LD flag is off for
this user, so the kill-switch fully suppresses the per-turn index
cost (no list query, no Redis hit, nothing to cache).
+
+ ``expert_id`` is the session's persisted expert attribution; the index
+ then holds platform defaults plus that expert's own skills.
"""
if not await is_skills_feature_enabled(user_id):
return ""
- skills = await list_all_skills(user_id)
+ skills = await list_all_skills(user_id, expert_id)
index = render_skills_index(skills)
if not index:
return ""
@@ -868,11 +1198,18 @@ async def build_skills_context(user_id: str | None) -> str:
# ---------------------------------------------------------------------------
+_EXPERT_ID_PARAM = {
+ "type": "string",
+ "description": "Manage this expert's skills (Otto only).",
+}
+
+
class StoreSkillResponse(ToolResponseBase):
type: ResponseType = ResponseType.SKILL_STORED
name: str
description: str
triggers: list[str] = []
+ expert_id: str | None = None
class ReadSkillResponse(ToolResponseBase):
@@ -883,16 +1220,19 @@ class ReadSkillResponse(ToolResponseBase):
triggers: list[str] = []
sibling_files: list[str] = []
is_default: bool = False
+ expert_id: str | None = None
class DeleteSkillResponse(ToolResponseBase):
type: ResponseType = ResponseType.SKILL_DELETED
name: str
+ expert_id: str | None = None
class ListSkillsResponse(ToolResponseBase):
type: ResponseType = ResponseType.SKILL_LIST
skills: list[dict[str, Any]]
+ expert_id: str | None = None
class StoreSkillTool(BaseTool):
@@ -940,6 +1280,7 @@ class StoreSkillTool(BaseTool):
"items": {"type": "string"},
"description": "Optional tool/keyword triggers.",
},
+ "expert_id": _EXPERT_ID_PARAM,
},
"required": ["name", "description", "body"],
}
@@ -956,6 +1297,7 @@ class StoreSkillTool(BaseTool):
description: str = "",
body: str = "",
triggers: list[str] | None = None,
+ expert_id: str | None = None,
**kwargs,
) -> ToolResponseBase:
session_id = session.session_id
@@ -963,6 +1305,11 @@ class StoreSkillTool(BaseTool):
return ErrorResponse(
message="Authentication required", session_id=session_id
)
+ owner = await resolve_skill_owner(user_id, session, expert_id)
+ if isinstance(owner, str):
+ return ErrorResponse(
+ message=owner, error="access_denied", session_id=session_id
+ )
if not await is_skills_feature_enabled(user_id):
return ErrorResponse(
message=(
@@ -982,6 +1329,8 @@ class StoreSkillTool(BaseTool):
description=description,
body=body,
triggers=triggers,
+ expert_id=owner.expert_id,
+ scope=owner.scope,
)
except (VirusDetectedError, VirusScanError) as exc:
logger.warning("[skills] virus scan failed for %s: %s", name, exc)
@@ -990,7 +1339,7 @@ class StoreSkillTool(BaseTool):
error=str(exc),
session_id=session_id,
)
- except (ValueError, SkillLimitError) as exc:
+ except (ValueError, SkillLimitError, 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)
@@ -1004,14 +1353,20 @@ class StoreSkillTool(BaseTool):
name=parsed.name,
description=parsed.description,
triggers=list(parsed.triggers),
+ expert_id=owner.expert_id,
message=(
- f"Skill '{parsed.name}' stored. It will appear in "
+ f"Skill '{parsed.name}' stored for "
+ f"{_owner_label(owner.expert_id)}. It will appear in "
"<available_skills> on the next turn."
),
session_id=session_id,
)
+def _owner_label(expert_id: str | None) -> str:
+ return "personal Otto" if expert_id is None else f"expert {expert_id}"
+
+
class ReadSkillTool(BaseTool):
"""Load a skill's body + sibling-file listing by name."""
@@ -1032,6 +1387,7 @@ class ReadSkillTool(BaseTool):
"type": "object",
"properties": {
"name": {"type": "string", "description": "Skill name."},
+ "expert_id": _EXPERT_ID_PARAM,
},
"required": ["name"],
}
@@ -1047,6 +1403,7 @@ class ReadSkillTool(BaseTool):
user_id: str | None,
session: ChatSession,
name: str = "",
+ expert_id: str | None = None,
**kwargs,
) -> ToolResponseBase:
session_id = session.session_id
@@ -1087,9 +1444,21 @@ class ReadSkillTool(BaseTool):
session_id=session_id,
)
+ owner = await resolve_skill_owner(user_id, session, expert_id)
+ if isinstance(owner, str):
+ return ErrorResponse(
+ message=owner, error="access_denied", session_id=session_id
+ )
+
try:
- manager = await _get_user_skill_manager(user_id)
- raw = await manager.read_file(_skill_md_path(name))
+ manager = await _get_user_skill_manager(user_id, owner.scope)
+ raw = await manager.read_file(_skill_md_path(name, owner.expert_id))
+ except WorkspaceAccessDeniedError:
+ return ErrorResponse(
+ message=EXPERT_SKILL_SCOPE_DENIED,
+ error="access_denied",
+ session_id=session_id,
+ )
except FileNotFoundError:
return ErrorResponse(
message=(
@@ -1130,7 +1499,7 @@ class ReadSkillTool(BaseTool):
# the model knows what else lives in the bundle.
try:
siblings = await manager.list_files(
- path=f"{SKILL_FOLDER}/{name}/",
+ path=f"{skill_folder(owner.expert_id)}/{name}/",
limit=50,
include_all_sessions=True,
)
@@ -1150,6 +1519,7 @@ class ReadSkillTool(BaseTool):
triggers=list(parsed.triggers),
sibling_files=sibling_paths,
is_default=False,
+ expert_id=owner.expert_id,
message=f"Loaded skill '{name}'.",
session_id=session_id,
)
@@ -1172,6 +1542,7 @@ class DeleteSkillTool(BaseTool):
"type": "object",
"properties": {
"name": {"type": "string", "description": "Skill name."},
+ "expert_id": _EXPERT_ID_PARAM,
},
"required": ["name"],
}
@@ -1185,6 +1556,7 @@ class DeleteSkillTool(BaseTool):
user_id: str | None,
session: ChatSession,
name: str = "",
+ expert_id: str | None = None,
**kwargs,
) -> ToolResponseBase:
session_id = session.session_id
@@ -1192,6 +1564,11 @@ class DeleteSkillTool(BaseTool):
return ErrorResponse(
message="Authentication required", session_id=session_id
)
+ owner = await resolve_skill_owner(user_id, session, expert_id)
+ if isinstance(owner, str):
+ return ErrorResponse(
+ message=owner, error="access_denied", session_id=session_id
+ )
if not await is_skills_feature_enabled(user_id):
return ErrorResponse(
message="Skill registry is currently disabled for this user.",
@@ -1199,13 +1576,23 @@ class DeleteSkillTool(BaseTool):
session_id=session_id,
)
try:
- slug = await delete_user_skill(user_id, name)
+ slug = await delete_user_skill(
+ user_id, name, expert_id=owner.expert_id, scope=owner.scope
+ )
+ except WorkspaceAccessDeniedError:
+ return ErrorResponse(
+ message=EXPERT_SKILL_SCOPE_DENIED,
+ error="access_denied",
+ session_id=session_id,
+ )
except ValueError as exc:
return ErrorResponse(message=str(exc), session_id=session_id)
except BuiltInSkillError as exc:
return ErrorResponse(message=str(exc), session_id=session_id)
except SkillNotFoundError as exc:
return ErrorResponse(message=str(exc), session_id=session_id)
+ except ConflictError as exc:
+ return ErrorResponse(message=str(exc), session_id=session_id)
except Exception as exc:
logger.exception("[skills] delete failed for %s", name)
return ErrorResponse(
@@ -1214,7 +1601,8 @@ class DeleteSkillTool(BaseTool):
return DeleteSkillResponse(
name=slug,
- message=f"Skill '{slug}' deleted.",
+ expert_id=owner.expert_id,
+ message=f"Skill '{slug}' deleted for {_owner_label(owner.expert_id)}.",
session_id=session_id,
)
@@ -1232,11 +1620,15 @@ class ListSkillsTool(BaseTool):
@property
def description(self) -> str:
- return "List all skills (defaults + user-distilled)."
+ return "List the skills available here (platform defaults + your own)."
@property
def parameters(self) -> dict[str, Any]:
- return {"type": "object", "properties": {}, "required": []}
+ return {
+ "type": "object",
+ "properties": {"expert_id": _EXPERT_ID_PARAM},
+ "required": [],
+ }
@property
def requires_auth(self) -> bool:
@@ -1246,6 +1638,7 @@ class ListSkillsTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ expert_id: str | None = None,
**kwargs,
) -> ToolResponseBase:
if not await is_skills_feature_enabled(user_id):
@@ -1254,7 +1647,17 @@ class ListSkillsTool(BaseTool):
error="feature_disabled",
session_id=session.session_id,
)
- skills = await list_all_skills(user_id)
+ owner_id: str | None = None
+ owner_scope: WorkspaceScope | None = None
+ if user_id:
+ owner = await resolve_skill_owner(user_id, session, expert_id)
+ if isinstance(owner, str):
+ return ErrorResponse(
+ message=owner, error="access_denied", session_id=session.session_id
+ )
+ owner_id = owner.expert_id
+ owner_scope = owner.scope
+ skills = await list_all_skills(user_id, owner_id, owner_scope)
payload = [
{
"name": s.name,
@@ -1266,6 +1669,7 @@ class ListSkillsTool(BaseTool):
]
return ListSkillsResponse(
skills=payload,
- message=f"{len(payload)} skill(s) available.",
+ expert_id=owner_id,
+ message=f"{len(payload)} skill(s) available for {_owner_label(owner_id)}.",
session_id=session.session_id,
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills_isolation_test.py b/autogpt_platform/backend/backend/copilot/tools/skills_isolation_test.py
new file mode 100644
index 0000000000..2e352a0229
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/skills_isolation_test.py
@@ -0,0 +1,414 @@
+"""Skill ownership: every skill belongs to one expert or to personal
+Otto. Experts see and manage only their own; Otto runs only its own
+but may manage any expert's."""
+
+from contextlib import contextmanager
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+import backend.copilot.tools.skills as skills
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import ErrorResponse
+from backend.copilot.tools.skills import (
+ DeleteSkillResponse,
+ DeleteSkillTool,
+ ListSkillsResponse,
+ ListSkillsTool,
+ ParsedSkill,
+ ReadSkillResponse,
+ ReadSkillTool,
+ StoreSkillResponse,
+ StoreSkillTool,
+ build_skills_context,
+ copy_skill_to_expert,
+ find_user_skill_slugs,
+ invalidate_skills_index_cache,
+ list_user_skills,
+ render_skill_markdown,
+)
+from backend.copilot.tools.skills_test import _FakeWorkspaceManager, _patch_skills_path
+from backend.data.workspace_scope import WorkspaceScope
+from backend.util.exceptions import ConflictError
+
+AUTOPILOT = "/skills/mine/SKILL.md"
+EXPERT_A = "/experts/expert-a/skills/own/SKILL.md"
+EXPERT_B = "/experts/expert-b/skills/theirs/SKILL.md"
+
+
+def _skill(name: str) -> bytes:
+ return render_skill_markdown(
+ ParsedSkill(name=name, description=f"{name} description", body="steps")
+ ).encode()
+
+
+def world():
+ fake = _FakeWorkspaceManager()
+ fake.files[AUTOPILOT] = _skill("mine")
+ fake.files[EXPERT_A] = _skill("own")
+ fake.files[EXPERT_B] = _skill("theirs")
+ workspace = MagicMock()
+ workspace.resolve_expert_workspace_scope = AsyncMock(
+ side_effect=lambda user_id, expert_id: WorkspaceScope(
+ expert_id=expert_id, owns_skills_folder=True
+ )
+ )
+ experts = MagicMock()
+ experts.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: (
+ MagicMock(id=expert_id) if expert_id in {"expert-a", "expert-b"} else None
+ )
+ )
+ experts.add_expert_skill_name = AsyncMock()
+ experts.remove_expert_skill_name = AsyncMock()
+ with (
+ _patch_skills_path(fake),
+ patch("backend.copilot.tools.skills.workspace_db", return_value=workspace),
+ patch("backend.copilot.tools.skills.experts_db", return_value=experts),
+ patch(
+ "backend.copilot.tools.skills.is_skills_feature_enabled",
+ new=AsyncMock(return_value=True),
+ ),
+ ):
+ yield fake, experts
+
+
+def _expert_session(expert_id: str = "expert-a") -> ChatSession:
+ return ChatSession.new("user-1", dry_run=False, expert_id=expert_id)
+
+
+def _personal_session() -> ChatSession:
+ return ChatSession.new("user-1", dry_run=False)
+
+
+async def test_library_lookup_resolves_by_folder_and_by_frontmatter_name(world):
+ """Only a hand-written skill can be listed under a name that differs from
+ its folder, and it is the one case that costs a read."""
+ fake, _ = world
+ fake.files["/skills/deep-research/SKILL.md"] = _skill("Deep Research")
+
+ found = await find_user_skill_slugs(
+ "user-1", ["mine", "Deep Research", "never-stored"]
+ )
+
+ assert found["mine"] == "mine"
+ assert found["deep research"] == "deep-research"
+ assert "never-stored" not in found
+
+
+async def test_library_lookup_skips_the_read_for_a_folder_carrying_metadata(world):
+ """The store-time metadata means folder == name, so the index never pays a
+ fetch to learn a name it already has."""
+ fake, _ = world
+ fake.metadata[AUTOPILOT] = {"kind": "copilot_skill", "description": "mine"}
+ reads: list[str] = []
+ original = fake.read_file
+
+ async def _counted(path: str) -> bytes:
+ reads.append(path)
+ return await original(path)
+
+ fake.read_file = _counted
+
+ assert await find_user_skill_slugs("user-1", ["absent"]) == {}
+ assert reads == []
+
+
+async def test_expert_index_heals_an_assignment_made_before_it_owned_skills(world):
+ """An expert hired before ownership existed lists names that live only in
+ Otto's folder; without a copy it would drop to the defaults."""
+ fake, experts = world
+ experts.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: MagicMock(
+ id=expert_id, skills=["mine"]
+ )
+ )
+
+ ctx = await build_skills_context("user-1", expert_id="expert-a")
+
+ assert "name: mine" in ctx
+ assert "/experts/expert-a/skills/mine/SKILL.md" in fake.files
+ # Otto keeps its own copy; ownership is a copy, never a move.
+ assert AUTOPILOT in fake.files
+
+
+async def test_storing_a_skill_does_not_backfill_under_its_own_write_lock(world):
+ """store_skill's cap check lists the owner's skills while holding the
+ per-owner write lock that copying would need, so it must not heal there."""
+ fake, experts = world
+ experts.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: MagicMock(
+ id=expert_id, skills=["mine"]
+ )
+ )
+
+ with patch(
+ "backend.copilot.tools.skills.copy_skill_to_expert", new=AsyncMock()
+ ) as copy:
+ result = await StoreSkillTool()._execute(
+ "user-1",
+ _expert_session(),
+ name="fresh",
+ description="a fresh skill",
+ body="steps",
+ )
+
+ assert isinstance(result, StoreSkillResponse)
+ assert "/experts/expert-a/skills/fresh/SKILL.md" in fake.files
+ copy.assert_not_awaited()
+
+
+async def test_expert_index_leaves_a_name_with_no_library_folder_on_the_row(world):
+ """A marketplace attachment has no folder to copy, and a storage blip is
+ indistinguishable from one, so the name must survive either way."""
+ fake, experts = world
+ experts.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: MagicMock(
+ id=expert_id, skills=["a-marketplace-skill"]
+ )
+ )
+
+ ctx = await build_skills_context("user-1", expert_id="expert-a")
+
+ assert "name: a-marketplace-skill" not in ctx
+ experts.remove_expert_skill_name.assert_not_awaited()
+
+
+async def test_a_name_that_can_never_resolve_is_scanned_for_once(world):
+ """A marketplace attachment resolves to no folder on any turn, so without
+ a memo every cache-cold turn re-scans Otto's whole library for it."""
+ _, experts = world
+ experts.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: MagicMock(
+ id=expert_id, skills=["a-marketplace-skill"]
+ )
+ )
+ scans, counted = _counting_slug_lookup()
+
+ with _cold_turns(_FakeRedis()), patch.object(
+ skills, "find_user_skill_slugs", counted
+ ):
+ first = await list_user_skills("user-1", "expert-a")
+ second = await list_user_skills("user-1", "expert-a")
+
+ assert len(scans) == 1
+ assert [s.name for s in first] == [s.name for s in second] == ["own"]
+ experts.remove_expert_skill_name.assert_not_awaited()
+
+
+async def test_a_folder_change_lets_the_heal_retry_a_remembered_name(world):
+ """The memo is dropped whenever the expert's folder changes, so a name
+ that only becomes copyable later still gets its backfill."""
+ fake, experts = world
+ experts.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: MagicMock(
+ id=expert_id, skills=["late-arrival"]
+ )
+ )
+ scans, counted = _counting_slug_lookup()
+ redis = _FakeRedis()
+
+ with _cold_turns(redis), patch.object(skills, "find_user_skill_slugs", counted):
+ await list_user_skills("user-1", "expert-a")
+ fake.files["/skills/late-arrival/SKILL.md"] = _skill("late-arrival")
+ await invalidate_skills_index_cache("user-1", "expert-a")
+ await list_user_skills("user-1", "expert-a")
+
+ assert len(scans) == 2
+ assert "/experts/expert-a/skills/late-arrival/SKILL.md" in fake.files
+
+
[email protected]("tool", ["store", "delete"])
+async def test_a_row_conflict_reaches_the_expert_as_a_retryable_error(world, tool):
+ """A lost compare-and-swap is a retryable conflict, not a failure: the tool
+ passes its message through and must not log it as an exception."""
+ _, experts = world
+ conflict = ConflictError("Changed at the same time. Try again.")
+ experts.add_expert_skill_name = AsyncMock(side_effect=conflict)
+ experts.remove_expert_skill_name = AsyncMock(side_effect=conflict)
+
+ with patch.object(skills.logger, "exception") as logged:
+ if tool == "store":
+ result = await StoreSkillTool()._execute(
+ "user-1", _expert_session(), name="fresh", description="d", body="b"
+ )
+ else:
+ result = await DeleteSkillTool()._execute(
+ "user-1", _expert_session(), name="own"
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert result.message == str(conflict)
+ logged.assert_not_called()
+
+
+async def test_the_heal_sees_a_display_name_as_owned_once_its_copy_exists(world):
+ """A row can carry a skill's display name ("Deep Research") while its copy
+ is stored as "deep-research"; after the first copy the heal must stop."""
+ fake, experts = world
+ fake.files["/skills/deep-research/SKILL.md"] = _skill("Deep Research")
+ experts.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: MagicMock(
+ id=expert_id, skills=["Deep Research"]
+ )
+ )
+ scans, counted = _counting_slug_lookup()
+
+ with _cold_turns(_FakeRedis()), patch.object(
+ skills, "find_user_skill_slugs", counted
+ ):
+ await list_user_skills("user-1", "expert-a")
+ await list_user_skills("user-1", "expert-a")
+
+ assert "/experts/expert-a/skills/deep-research/SKILL.md" in fake.files
+ assert len(scans) == 1
+
+
+class _FakeRedis:
+ """In-memory stand-in: the heal backoff is the one cache these tests have
+ to observe, and the fixture's MagicMock swallows every write."""
+
+ def __init__(self):
+ self.values: dict[str, str] = {}
+
+ async def get(self, key):
+ return self.values.get(key)
+
+ async def set(self, key, value, ex=None):
+ self.values[key] = value
+
+ async def delete(self, *keys):
+ for key in keys:
+ self.values.pop(key, None)
+
+
+@contextmanager
+def _cold_turns(redis):
+ """Make every listing a cache-cold turn, so the heal runs each time and
+ only the backoff can stop the scan."""
+ with (
+ patch(
+ "backend.copilot.tools.skills.get_redis_async",
+ new=AsyncMock(return_value=redis),
+ ),
+ patch(
+ "backend.copilot.tools.skills._read_skills_cache",
+ new=AsyncMock(return_value=None),
+ ),
+ ):
+ yield
+
+
+def _counting_slug_lookup():
+ scans: list[list[str]] = []
+ original = skills.find_user_skill_slugs
+
+ async def counted(user_id, names):
+ scans.append(list(names))
+ return await original(user_id, names)
+
+ return scans, counted
+
+
+async def test_expert_index_holds_defaults_plus_its_own_skills_only(world):
+ ctx = await build_skills_context("user-1", expert_id="expert-a")
+ assert "agent_building_guide" in ctx
+ assert "name: own" in ctx
+ assert "mine" not in ctx
+ assert "theirs" not in ctx
+
+
+async def test_autopilot_index_holds_defaults_plus_its_own_skills_only(world):
+ ctx = await build_skills_context("user-1")
+ assert "name: mine" in ctx
+ assert "own" not in ctx.replace("agent_building_guide", "")
+ assert "theirs" not in ctx
+
+
+async def test_expert_reads_its_own_skill_and_not_others(world):
+ own = await ReadSkillTool()._execute("user-1", _expert_session(), name="own")
+ assert isinstance(own, ReadSkillResponse) and own.expert_id == "expert-a"
+ for other in ("mine", "theirs"):
+ result = await ReadSkillTool()._execute("user-1", _expert_session(), name=other)
+ assert isinstance(result, ErrorResponse)
+ assert "not found" in result.message
+
+
+async def test_expert_cannot_name_another_owner(world):
+ for tool in (ReadSkillTool(), DeleteSkillTool(), ListSkillsTool()):
+ result = await tool._execute(
+ "user-1", _expert_session(), name="theirs", expert_id="expert-b"
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "access_denied"
+ stored = await StoreSkillTool()._execute(
+ "user-1",
+ _expert_session(),
+ name="sneaky",
+ description="d",
+ body="b",
+ expert_id="expert-b",
+ )
+ assert isinstance(stored, ErrorResponse) and stored.error == "access_denied"
+
+
+async def test_expert_creates_and_deletes_skills_in_its_own_folder(world):
+ fake, experts = world
+ stored = await StoreSkillTool()._execute(
+ "user-1", _expert_session(), name="learned", description="d", body="b"
+ )
+ assert isinstance(stored, StoreSkillResponse) and stored.expert_id == "expert-a"
+ assert "/experts/expert-a/skills/learned/SKILL.md" in fake.files
+ experts.add_expert_skill_name.assert_awaited_once_with(
+ "user-1", "expert-a", "learned"
+ )
+
+ deleted = await DeleteSkillTool()._execute(
+ "user-1", _expert_session(), name="learned"
+ )
+ assert isinstance(deleted, DeleteSkillResponse)
+ assert "/experts/expert-a/skills/learned/SKILL.md" not in fake.files
+ experts.remove_expert_skill_name.assert_awaited_once_with(
+ "user-1", "expert-a", "learned"
+ )
+ assert AUTOPILOT in fake.files and EXPERT_B in fake.files
+
+
+async def test_autopilot_runs_only_its_own_but_manages_any_expert(world):
+ fake, _ = world
+ listed = await ListSkillsTool()._execute("user-1", _personal_session())
+ assert isinstance(listed, ListSkillsResponse)
+ assert {s["name"] for s in listed.skills} >= {"mine", "agent_building_guide"}
+ assert not {"own", "theirs"} & {s["name"] for s in listed.skills}
+
+ theirs = await ReadSkillTool()._execute(
+ "user-1", _personal_session(), name="theirs", expert_id="expert-b"
+ )
+ assert isinstance(theirs, ReadSkillResponse) and theirs.expert_id == "expert-b"
+
+ stored = await StoreSkillTool()._execute(
+ "user-1",
+ _personal_session(),
+ name="gift",
+ description="d",
+ body="b",
+ expert_id="expert-b",
+ )
+ assert isinstance(stored, StoreSkillResponse)
+ assert "/experts/expert-b/skills/gift/SKILL.md" in fake.files
+
+ unknown = await ReadSkillTool()._execute(
+ "user-1", _personal_session(), name="theirs", expert_id="expert-zzz"
+ )
+ assert isinstance(unknown, ErrorResponse) and unknown.error == "access_denied"
+
+
+async def test_copy_gives_expert_its_own_copy_of_an_autopilot_skill(world):
+ fake, experts = world
+ fake.files["/skills/mine/references/notes.md"] = b"notes"
+ assert await copy_skill_to_expert("user-1", "expert-a", "mine") == "mine"
+ assert "/experts/expert-a/skills/mine/SKILL.md" in fake.files
+ assert fake.files["/experts/expert-a/skills/mine/references/notes.md"] == b"notes"
+ assert AUTOPILOT in fake.files
+ experts.add_expert_skill_name.assert_awaited_once_with("user-1", "expert-a", "mine")
+ assert await copy_skill_to_expert("user-1", "expert-a", "nope") is None
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 333de4d3e1..e88cd4917b 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -543,6 +543,8 @@ class DatabaseManager(AppService):
update_soul_if_current = _(experts_db.update_soul_if_current)
update_soul_fields = _(experts_db.update_soul_fields)
update_soul_fields_if_current = _(experts_db.update_soul_fields_if_current)
+ add_expert_skill_name = _(experts_db.add_expert_skill_name)
+ remove_expert_skill_name = _(experts_db.remove_expert_skill_name)
# Hire / raise from the copilot chat tools, plus the counts their
# preview step uses to refuse a change that could never land.
list_templates = _(experts_db.list_templates)
@@ -932,6 +934,8 @@ class DatabaseManagerAsyncClient(AppServiceClient):
update_soul_if_current = d.update_soul_if_current
update_soul_fields = d.update_soul_fields
update_soul_fields_if_current = d.update_soul_fields_if_current
+ add_expert_skill_name = d.add_expert_skill_name
+ remove_expert_skill_name = d.remove_expert_skill_name
list_templates = d.list_templates
hire_expert = d.hire_expert
create_raised_expert = d.create_raised_expert
diff --git a/autogpt_platform/backend/backend/data/workspace_scope.py b/autogpt_platform/backend/backend/data/workspace_scope.py
index 7fa530406b..13e3023dde 100644
--- a/autogpt_platform/backend/backend/data/workspace_scope.py
+++ b/autogpt_platform/backend/backend/data/workspace_scope.py
@@ -1,9 +1,9 @@
"""Trusted file scope for expert chat sessions.
Resolved from persisted session attribution, never from tool arguments. An
-expert session may read and write under its own conversations, read under
-conversations it delegated, and read the account's skills registry. ``None``
-scope means unrestricted: the account owner acting through personal
+expert session may read and write under its own conversations and its own
+skills folder, and read under conversations it delegated. ``None`` scope
+means unrestricted: the account owner acting through personal
Otto, REST endpoints, or system paths.
"""
@@ -17,12 +17,16 @@ from prisma.models import Expert as PrismaExpert
from pydantic import BaseModel, Field
SESSIONS_ROOT = "/sessions/"
-SKILLS_ROOT = "/skills/"
+EXPERTS_ROOT = "/experts/"
EXPERT_FILE_ACCESS_DENIED = (
"This file is outside this expert's scope. Experts can only access files "
- "from their own conversations. Open personal Otto to work with other "
- "files."
+ "from their own conversations and their own skills. Open personal Otto "
+ "to work with other files."
+)
+EXPERT_SKILL_SCOPE_DENIED = (
+ "Experts can only use and manage their own skills. Open personal Otto "
+ "to manage another expert's skills or the account's skills."
)
@@ -34,6 +38,10 @@ def session_path_prefix(session_id: str) -> str:
return f"{SESSIONS_ROOT}{session_id}/"
+def expert_skills_folder(expert_id: str) -> str:
+ return f"{EXPERTS_ROOT}{expert_id}/skills"
+
+
class WorkspaceScope(BaseModel):
"""Grants for one acting session. Safe for RPC transport.
@@ -44,23 +52,32 @@ class WorkspaceScope(BaseModel):
expert_id: str | None = None
session_ids: list[str] = Field(default_factory=list)
delegated_session_ids: list[str] = Field(default_factory=list)
+ # A carried grant, never inferred from ``expert_id``: this model crosses an
+ # RPC boundary and is rebuilt as this class, so a subclass that withheld the
+ # folder would come back granting it.
+ owns_skills_folder: bool = False
def with_session(self, session_id: str) -> "WorkspaceScope":
if session_id in self.session_ids:
return self
return self.model_copy(update={"session_ids": [*self.session_ids, session_id]})
+ @property
+ def skills_prefix(self) -> str | None:
+ if self.expert_id is None or not self.owns_skills_folder:
+ return None
+ return f"{expert_skills_folder(self.expert_id)}/"
+
@property
def write_prefixes(self) -> list[str]:
- return [session_path_prefix(s) for s in self.session_ids]
+ own = [session_path_prefix(s) for s in self.session_ids]
+ return own if self.skills_prefix is None else own + [self.skills_prefix]
@property
def read_prefixes(self) -> list[str]:
- return (
- self.write_prefixes
- + [session_path_prefix(s) for s in self.delegated_session_ids]
- + [SKILLS_ROOT]
- )
+ return self.write_prefixes + [
+ session_path_prefix(s) for s in self.delegated_session_ids
+ ]
def allows_path(self, path: str, *, write: bool = False) -> bool:
if not path.startswith("/") or "\\" in path or posixpath.normpath(path) != path:
@@ -107,6 +124,7 @@ async def resolve_expert_workspace_scope(
)
return WorkspaceScope(
expert_id=expert_id,
+ owns_skills_folder=True,
session_ids=[row.id for row in own_sessions],
delegated_session_ids=[
row.id for row in delegated_sessions if row.expertId != expert_id
diff --git a/autogpt_platform/backend/backend/data/workspace_scope_db_test.py b/autogpt_platform/backend/backend/data/workspace_scope_db_test.py
index ec5c73244a..2d1fd80bfa 100644
--- a/autogpt_platform/backend/backend/data/workspace_scope_db_test.py
+++ b/autogpt_platform/backend/backend/data/workspace_scope_db_test.py
@@ -73,8 +73,9 @@ async def test_resolver_collects_own_and_delegated_conversations(
assert not scope.allows_path(f"/sessions/{delegated.session_id}/x.txt", write=True)
assert not scope.allows_path(f"/sessions/{foreign.session_id}/x.txt")
assert not scope.allows_path(f"/sessions/{personal.session_id}/x.txt")
- assert scope.allows_path("/skills/autopilot/SKILL.md")
- assert not scope.allows_path("/skills/autopilot/SKILL.md", write=True)
+ assert not scope.allows_path("/skills/autopilot/SKILL.md")
+ assert scope.allows_path(f"/experts/{expert_a}/skills/mine/SKILL.md", write=True)
+ assert not scope.allows_path(f"/experts/{expert_b}/skills/theirs/SKILL.md")
@pytest.mark.asyncio(loop_scope="session")
@@ -97,6 +98,9 @@ async def test_resolver_fails_closed_for_foreign_or_archived_expert(
archived_scope = await resolve_expert_workspace_scope(stranger, expert)
assert archived_scope.session_ids == []
assert not archived_scope.allows_path(f"/sessions/{session.session_id}/x.txt")
+ # A revoked expert keeps no claim on the skills folder named after it.
+ for revoked in (foreign_scope, archived_scope):
+ assert not revoked.allows_path(f"/experts/{expert}/skills/x/SKILL.md")
@pytest.mark.asyncio(loop_scope="session")
diff --git a/autogpt_platform/backend/backend/data/workspace_scope_test.py b/autogpt_platform/backend/backend/data/workspace_scope_test.py
index 6a5996a6b6..e6de60bfb4 100644
--- a/autogpt_platform/backend/backend/data/workspace_scope_test.py
+++ b/autogpt_platform/backend/backend/data/workspace_scope_test.py
@@ -5,6 +5,7 @@ from backend.data.workspace_scope import WorkspaceScope, resolve_expert_workspac
SCOPE = WorkspaceScope(
expert_id="expert-a",
+ owns_skills_folder=True,
session_ids=["expert-a", "expert-a-old"],
delegated_session_ids=["sub-1"],
)
@@ -22,14 +23,18 @@ def test_own_conversations_are_readable_and_writable(path: str):
@pytest.mark.parametrize(
"path",
[
- "/sessions/sub-1/result.json",
- "/skills/autopilot-skill/SKILL.md",
- "/skills/autopilot-skill/references/notes.md",
+ "/experts/expert-a/skills/mine/SKILL.md",
+ "/experts/expert-a/skills/mine/references/notes.md",
],
)
-def test_delegated_conversations_and_skills_registry_are_read_only(path: str):
+def test_own_skills_folder_is_readable_and_writable(path: str):
assert SCOPE.allows_path(path)
- assert not SCOPE.allows_path(path, write=True)
+ assert SCOPE.allows_path(path, write=True)
+
+
+def test_delegated_conversations_are_read_only():
+ assert SCOPE.allows_path("/sessions/sub-1/result.json")
+ assert not SCOPE.allows_path("/sessions/sub-1/result.json", write=True)
@pytest.mark.parametrize(
@@ -43,8 +48,11 @@ def test_delegated_conversations_and_skills_registry_are_read_only(path: str):
"sessions/expert-a/file.txt",
"/sessions/expert-a/..\\expert-b/x",
"/skills",
+ "/skills/autopilot-skill/SKILL.md",
+ "/skills/autopilot-skill/references/notes.md",
"/skillsets/private.txt",
- "/experts/expert-a/skills/mine/SKILL.md",
+ "/experts/expert-b/skills/theirs/SKILL.md",
+ "/experts/expert-a/skillsets/mine.txt",
"/root-file.txt",
],
)
@@ -56,10 +64,26 @@ def test_everything_else_is_denied(path: str):
def test_session_only_scope_carries_no_expert_grants():
scope = WorkspaceScope(session_ids=["only"])
assert scope.expert_id is None
+ assert scope.skills_prefix is None
assert scope.allows_path("/sessions/only/file.txt", write=True)
assert not scope.allows_path("/sessions/other/file.txt")
+def test_denial_survives_the_rpc_round_trip():
+ """The scope is rebuilt as this class on the client side, so a denial that
+ lived in a subclass would come back as a grant."""
+ denied = WorkspaceScope(expert_id="expert-a")
+ rebuilt = WorkspaceScope.model_validate(denied.model_dump())
+
+ for scope in (denied, rebuilt):
+ assert scope.skills_prefix is None
+ assert not scope.allows_path("/experts/expert-a/skills/x/SKILL.md")
+ assert not scope.allows_path("/experts/expert-a/skills/x/SKILL.md", write=True)
+ assert WorkspaceScope.model_validate(SCOPE.model_dump()).allows_path(
+ "/experts/expert-a/skills/mine/SKILL.md", write=True
+ )
+
+
def test_resolver_is_reachable_through_the_direct_db_accessor():
assert (
workspace_module.resolve_expert_workspace_scope
diff --git a/autogpt_platform/backend/backend/util/exceptions.py b/autogpt_platform/backend/backend/util/exceptions.py
index f46ffaf749..6f18f05d5e 100644
--- a/autogpt_platform/backend/backend/util/exceptions.py
+++ b/autogpt_platform/backend/backend/util/exceptions.py
@@ -351,3 +351,7 @@ class ExpertRunPausedError(ValueError):
def __str__(self):
return self.message
+
+
+class ConflictError(Exception):
+ """The request lost to a concurrent change of the same resource; retrying may succeed."""
diff --git a/autogpt_platform/backend/backend/util/workspace_isolation_test.py b/autogpt_platform/backend/backend/util/workspace_isolation_test.py
index 8033586cf2..b46cc9a88d 100644
--- a/autogpt_platform/backend/backend/util/workspace_isolation_test.py
+++ b/autogpt_platform/backend/backend/util/workspace_isolation_test.py
@@ -11,6 +11,7 @@ from backend.util.workspace_test import _make_workspace_file
SCOPE = WorkspaceScope(
expert_id="expert-a",
+ owns_skills_folder=True,
session_ids=["expert-a", "expert-a-old"],
delegated_session_ids=["sub-1"],
)
@@ -82,12 +83,13 @@ async def test_explicit_paths_cannot_escape_scope(db, path: str):
@pytest.mark.parametrize(
"path",
- ["/skills/autopilot/SKILL.md", "/skills/autopilot/references/file.txt"],
+ [
+ "/experts/expert-a/skills/mine/SKILL.md",
+ "/experts/expert-a/skills/mine/references/file.txt",
+ ],
)
-async def test_skills_registry_is_readable_but_not_writable(db, storage, path: str):
+async def test_own_skills_folder_is_readable(db, storage, path: str):
assert await _skills_manager().read_file(path) == b"allowed"
- with pytest.raises(WorkspaceAccessDeniedError):
- await _skills_manager().write_file(b"x", "f", path=path, overwrite=True)
@pytest.mark.parametrize(
@@ -104,11 +106,18 @@ async def test_own_and_delegated_paths_are_readable(db, storage, path: str):
@pytest.mark.parametrize(
"path",
- ["/experts/expert-a/skills/mine/SKILL.md", "/root-file.txt"],
+ [
+ "/skills/autopilot/SKILL.md",
+ "/skills/autopilot/references/file.txt",
+ "/experts/expert-b/skills/theirs/SKILL.md",
+ "/root-file.txt",
+ ],
)
async def test_paths_outside_any_grant_are_denied(db, path: str):
with pytest.raises(WorkspaceAccessDeniedError):
await _skills_manager().read_file(path)
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await _skills_manager().write_file(b"x", "f", path=path, overwrite=True)
db.get_workspace_file_by_path.assert_not_awaited()
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/components/BriefingTabContent/components/CopilotLibrarySummary.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/components/BriefingTabContent/components/CopilotLibrarySummary.tsx
index 8a722c351e..316779876b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/components/BriefingTabContent/components/CopilotLibrarySummary.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/components/BriefingTabContent/components/CopilotLibrarySummary.tsx
@@ -11,7 +11,7 @@ export function CopilotLibrarySummary() {
// itself flag-gated. No second flag here because the count-based
// hide below already keeps the pill quiet for users who don't use
// the feature.
- const { data: skillsRes } = useListCopilotSkills({
+ const { data: skillsRes } = useListCopilotSkills(undefined, {
query: { staleTime: 30_000 },
});
const { data: followupsRes } = useListCopilotFollowupSchedules({
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts
index aae74dcb1c..e17d1ad306 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts
@@ -23,7 +23,7 @@ export function useSkillsSection({ category }: Args = {}) {
// An install lands under the listing's slug, so the user's own skill names
// are what says which shelf cards are already added.
- const installed = useListCopilotSkills({
+ const installed = useListCopilotSkills(undefined, {
query: { select: (res) => okData(res) ?? [], enabled: isLoggedIn },
});
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.ts
index a837d9a020..f202428136 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
@@ -36,7 +36,7 @@ export function useSkillPage(slug: string) {
// The install lands under the listing slug, so the user's own skill names
// are the truth about whether this one is already added — a reload no
// longer offers to install it again.
- const installedSkills = useListCopilotSkills({
+ const installedSkills = useListCopilotSkills(undefined, {
query: { select: (res) => okData(res) ?? [], enabled: isLoggedIn },
});
const isAdded = (installedSkills.data ?? []).some(
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/components/SkillsBrowsePage/useSkillsBrowsePage.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/components/SkillsBrowsePage/useSkillsBrowsePage.ts
index b8ff34e8f5..602a170e57 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/components/SkillsBrowsePage/useSkillsBrowsePage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/components/SkillsBrowsePage/useSkillsBrowsePage.ts
@@ -27,7 +27,7 @@ export function useSkillsBrowsePage() {
{ query: { getNextPageParam: getPaginationNextPageNumber } },
);
- const installed = useListCopilotSkills({
+ const installed = useListCopilotSkills(undefined, {
query: { select: (res) => okData(res) ?? [], enabled: isLoggedIn },
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/KitStep/useKitSearch.ts b/autogpt_platform/frontend/src/app/(platform)/raise/components/KitStep/useKitSearch.ts
index 90680d827d..4c60584de2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/raise/components/KitStep/useKitSearch.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/KitStep/useKitSearch.ts
@@ -37,7 +37,7 @@ export function useKitSearch(scope: KitSearchScope) {
},
},
);
- const skillsQuery = useListCopilotSkills({
+ const skillsQuery = useListCopilotSkills(undefined, {
query: {
enabled: scope === "skills",
select: (response) => okData(response) ?? [],
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
index 4b7f2d58ea..7313b72c31 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
@@ -620,6 +620,64 @@ describe("ExpertDetailPage", () => {
expect(within(stack).getByText("+3")).toBeDefined();
});
+ test("shows expert-owned skill metadata without claiming it belongs to the personal library", async () => {
+ server.use(
+ getGetExpertMockHandler(() => ({ ...maria, skills: ["expert-only"] })),
+ getListCopilotSkillsMockHandler200(({ request }) =>
+ new URL(request.url).searchParams.get("expert_id") === maria.id
+ ? [
+ {
+ name: "expert-only",
+ description: "Instructions owned by Maria",
+ triggers: ["expert task"],
+ },
+ ]
+ : [],
+ ),
+ );
+ render(<ExpertDetailPage />);
+ await openTab("Skills");
+ expect(
+ await screen.findByText("Instructions owned by Maria"),
+ ).toBeDefined();
+ expect(screen.getByText("expert task")).toBeDefined();
+ expect(screen.queryByText(/Marketplace skill/)).toBeNull();
+ expect(screen.queryByRole("link", { name: "Open in library" })).toBeNull();
+ });
+
+ test("falls back to the library entry for an expert assigned a skill before it owned one", async () => {
+ server.use(
+ getGetExpertMockHandler(() => ({
+ ...maria,
+ skills: ["content-strategy"],
+ })),
+ getListCopilotSkillsMockHandler200(({ request }) =>
+ new URL(request.url).searchParams.get("expert_id") === maria.id
+ ? []
+ : [
+ {
+ name: "content-strategy",
+ description: "How we plan the content calendar",
+ triggers: ["content plan"],
+ },
+ ],
+ ),
+ );
+ render(<ExpertDetailPage />);
+ await openTab("Skills");
+ expect(
+ await screen.findByText("How we plan the content calendar"),
+ ).toBeDefined();
+ expect(screen.getByText("content plan")).toBeDefined();
+ expect(screen.queryByText("Skill details unavailable.")).toBeNull();
+
+ // The row searches on the description it actually shows.
+ await userEvent
+ .setup()
+ .type(screen.getByPlaceholderText(/search/i), "content calendar");
+ expect(screen.getByText("How we plan the content calendar")).toBeDefined();
+ });
+
test("lists the expert's skills with library details and adds one", async () => {
const user = userEvent.setup();
const puts: string[][] = [];
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillListItem.tsx
index 46cd560955..165a8e2a55 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillListItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillListItem.tsx
@@ -20,7 +20,8 @@ export function ExpertSkillListItem({
isSaving,
onRemove,
}: Props) {
- const triggers = entry.library?.triggers ?? [];
+ const details = entry.skill ?? entry.library;
+ const triggers = details?.triggers ?? [];
return (
<div
className="flex w-full flex-col gap-3 rounded-2xl bg-white p-3.5 smooth-shadow-ring-sm sm:flex-row sm:items-center sm:justify-between"
@@ -41,8 +42,7 @@ export function ExpertSkillListItem({
{entry.name}
</Text>
<Text variant="small" tone="muted">
- {entry.library?.description ??
- "Marketplace skill. Not in your library yet."}
+ {details?.description ?? "Skill details unavailable."}
</Text>
{triggers.length > 0 ? (
<div className="mt-1 flex flex-wrap gap-1">
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.ts b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.ts
index 841f867303..d51e0ef7c0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.ts
@@ -2,7 +2,10 @@ import {
getGetExpertQueryKey,
useUpdateExpertSkills,
} from "@/app/api/__generated__/endpoints/experts/experts";
-import { useListCopilotSkills } from "@/app/api/__generated__/endpoints/skills/skills";
+import {
+ getListCopilotSkillsQueryKey,
+ useListCopilotSkills,
+} from "@/app/api/__generated__/endpoints/skills/skills";
import {
getV2GetSpecificAgent,
useGetV2ListStoreAgents,
@@ -21,6 +24,7 @@ import { useState } from "react";
export interface ExpertSkillEntry {
name: string;
library: CopilotSkillInfo | null;
+ skill: CopilotSkillInfo | null;
}
export function useExpertSkills(expert: Expert) {
@@ -40,17 +44,27 @@ export function useExpertSkills(expert: Expert) {
},
},
);
- const librarySkills = useListCopilotSkills({
+ const librarySkills = useListCopilotSkills(undefined, {
query: { select: (res) => okData(res) ?? [] },
});
+ const expertSkills = useListCopilotSkills(
+ { expert_id: expert.id },
+ {
+ query: { select: (res) => okData(res) ?? [] },
+ },
+ );
const { mutateAsync: updateSkills, isPending } = useUpdateExpertSkills();
const library = librarySkills.data ?? [];
const byName = new Map(
library.map((skill) => [skill.name.toLowerCase(), skill]),
);
+ const ownedByName = new Map(
+ (expertSkills.data ?? []).map((skill) => [skill.name.toLowerCase(), skill]),
+ );
const attached: ExpertSkillEntry[] = expert.skills.map((name) => ({
name,
+ skill: ownedByName.get(name.toLowerCase()) ?? null,
library: byName.get(name.toLowerCase()) ?? null,
}));
const attachedNames = new Set(
@@ -64,7 +78,9 @@ export function useExpertSkills(expert: Expert) {
? attached.filter(
(entry) =>
entry.name.toLowerCase().includes(needle) ||
- (entry.library?.description ?? "").toLowerCase().includes(needle),
+ (entry.skill?.description ?? entry.library?.description ?? "")
+ .toLowerCase()
+ .includes(needle),
)
: attached;
@@ -82,6 +98,9 @@ export function useExpertSkills(expert: Expert) {
queryClient.invalidateQueries({
queryKey: getGetExpertQueryKey(expert.id),
}),
+ queryClient.invalidateQueries({
+ queryKey: getListCopilotSkillsQueryKey({ expert_id: expert.id }),
+ }),
invalidateExpertRosterQueries(queryClient),
]);
toast({ title: successTitle, variant: "success" });
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotSkillsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotSkillsSection.tsx
index 695c2f6af9..31930b694b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotSkillsSection.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotSkillsSection.tsx
@@ -50,7 +50,7 @@ export function AutopilotSkillsSection({ skills }: Props) {
{visible.map((skill) => (
<li key={skill.name}>
<ExpertSkillListItem
- entry={{ name: skill.name, library: skill }}
+ entry={{ name: skill.name, skill, library: skill }}
accentClassName={AUTOPILOT_PILL_CLASS}
/>
</li>
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/autopilot/useAutopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/team/autopilot/useAutopilotPage.ts
index c202f30026..dcd9ac65c2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/autopilot/useAutopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/autopilot/useAutopilotPage.ts
@@ -31,7 +31,7 @@ export function useAutopilotPage({ enabled }: Args) {
{ page: 1, page_size: 100, is_hidden: false },
{ query: { getNextPageParam: getPaginationNextPageNumber, enabled } },
);
- const skillsQuery = useListCopilotSkills({
+ const skillsQuery = useListCopilotSkills(undefined, {
query: { select: (res) => okData(res) ?? [], enabled },
});
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 432414f927..2e5d03b988 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -13630,16 +13630,30 @@
"get": {
"tags": ["v1", "skills"],
"summary": "List user-distilled copilot skills",
- "description": "Return user-stored skills for the current user.\n\nReuses :func:`backend.copilot.tools.skills.list_user_skills` so the\nlibrary UI sees the exact same set the copilot ``<available_skills>``\nblock surfaces, minus the built-in defaults (which are read-only and\nhandled separately by the copilot runtime).",
+ "description": "Return the skills owned by personal Otto, or by one expert.\n\nReuses :func:`backend.copilot.tools.skills.list_user_skills` so the\nlibrary UI sees the exact same set the copilot ``<available_skills>``\nblock surfaces, minus the built-in defaults (which are read-only and\nhandled separately by the copilot runtime).",
"operationId": "listCopilotSkills",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "List this expert's own skills instead of personal Otto's.",
+ "title": "Expert Id"
+ },
+ "description": "List this expert's own skills instead of personal Otto's."
+ }
+ ],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
- "items": { "$ref": "#/components/schemas/CopilotSkillInfo" },
"type": "array",
+ "items": { "$ref": "#/components/schemas/CopilotSkillInfo" },
"title": "Response Listcopilotskills"
}
}
@@ -13647,24 +13661,45 @@
},
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
}
- },
- "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",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Store the skill as this expert's own.",
+ "title": "Expert Id"
+ },
+ "description": "Store the skill as this expert's own."
+ }
+ ],
"requestBody": {
+ "required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UploadCopilotSkillRequest"
}
}
- },
- "required": true
+ }
},
"responses": {
"201": {
@@ -13688,8 +13723,7 @@
}
}
}
- },
- "security": [{ "HTTPBearerJWT": [] }]
+ }
}
},
"/api/skills/{name}": {
@@ -13710,6 +13744,17 @@
"title": "Name"
},
"description": "Slug of the skill to delete"
+ },
+ {
+ "name": "expert_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Delete this expert's own copy of the skill.",
+ "title": "Expert Id"
+ },
+ "description": "Delete this expert's own copy of the skill."
}
],
"responses": {
@@ -13755,6 +13800,17 @@
"title": "Name"
},
"description": "Slug of the skill to read"
+ },
+ {
+ "name": "expert_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Read this expert's own copy of the skill.",
+ "title": "Expert Id"
+ },
+ "description": "Read this expert's own copy of the skill."
}
],
"responses": {
diff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.ts b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.ts
index 10dc172c93..4528c4365a 100644
--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.ts
+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/components/SkillListItem/useSkillListItem.ts
@@ -35,7 +35,7 @@ export function useSkillListItem({ skill }: Args) {
data: detailRes,
isLoading: isDetailLoading,
error: detailError,
- } = useReadCopilotSkill(skill.name, {
+ } = useReadCopilotSkill(skill.name, undefined, {
query: {
enabled: isViewOpen,
staleTime: 60_000,
diff --git a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/useSkillsPanel.ts b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/useSkillsPanel.ts
index 76626a64a8..6774e83008 100644
--- a/autogpt_platform/frontend/src/components/contextual/SkillsPanel/useSkillsPanel.ts
+++ b/autogpt_platform/frontend/src/components/contextual/SkillsPanel/useSkillsPanel.ts
@@ -4,7 +4,7 @@ import { useState } from "react";
export function useSkillsPanel() {
const [newSkillName, setNewSkillName] = useState<string | null>(null);
- const query = useListCopilotSkills({
+ const query = useListCopilotSkills(undefined, {
query: {
select: (res) => okData(res) ?? [],
},