AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend/copilot): make the session's skills first-class find_capability candidates (#14779)
Nicholas Tindlea339fd2e5512
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/__init__.py b/autogpt_platform/backend/backend/copilot/capabilities/__init__.pyindex c66aad2c6b..e97bd68ba9 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/__init__.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/__init__.py@@ -1,6 +1,6 @@-"""Unified capability registry for the copilot: tools, blocks and MCP servers-behind one index, searched by ``find_capability`` and executed by-``run_capability`` (both added in the follow-up change)."""+"""Unified capability registry for the copilot: tools, blocks, MCP servers+and the session owner's skills behind one index, searched by+``find_capability`` and executed by ``run_capability``."""from .index import CapabilityIndex, SearchHit, SearchResultfrom .models import CapabilityEntry, Connection, Implementationdiff --git a/autogpt_platform/backend/backend/copilot/capabilities/dispatch.py b/autogpt_platform/backend/backend/copilot/capabilities/dispatch.pyindex 4e2bcdce5d..0a8008a40c 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/dispatch.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/dispatch.py@@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Any, NamedTuplefrom backend.copilot.capabilities.registry import configured_tool, get_registryfrom backend.copilot.capabilities.resolve import resolve_entry+from backend.copilot.capabilities.sources import SKILL_TOOL, skill_nameif TYPE_CHECKING:from backend.copilot.tools.base import BaseTool@@ -34,6 +35,10 @@ def resolve_tool_dispatch("""The platform tool a ``run_capability`` call runs, or None when the callis not one — another tool, a block or MCP id, or ``validate_only``.+ A ``skill:<name>`` id is the ``read_skill`` call that loads the skill,+ with the name taken from the id, so a skill found by search is loaded+ through the one tool path like any other skill.+Never raises: it runs on the streaming path, where a bad id must degrade tothe dispatcher's own "unknown capability" answer rather than break the turn."""@@ -42,10 +47,15 @@ def resolve_tool_dispatch(if args.get("validate_only"):return Nonetry:- entry = resolve_entry(get_registry(), str(args.get("id") or ""))- if entry is None or entry.kind != "tool" or not entry.implementations:- return None- name = entry.implementations[0].ref+ capability_id = str(args.get("id") or "")+ skill = skill_name(capability_id)+ if skill is not None:+ name, bound = SKILL_TOOL, {"name": skill}+ else:+ entry = resolve_entry(get_registry(), capability_id)+ if entry is None or entry.kind != "tool" or not entry.implementations:+ return None+ name, bound = entry.implementations[0].ref, {}tool = configured_tool(name)except Exception:logger.warning("Could not resolve capability dispatch", exc_info=True)@@ -57,4 +67,4 @@ def resolve_tool_dispatch(# Coercing it to {} would run the tool on its defaults; the dispatcher# owns the "input must be an object" answer, so leave the call to it.return None- return DispatchedToolCall(tool, name, dict(payload or {}))+ return DispatchedToolCall(tool, name, {**dict(payload or {}), **bound})diff --git a/autogpt_platform/backend/backend/copilot/capabilities/dispatch_test.py b/autogpt_platform/backend/backend/copilot/capabilities/dispatch_test.pyindex c35bd4fe72..1260ce4c94 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/dispatch_test.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/dispatch_test.py@@ -17,6 +17,7 @@ from backend.copilot.baseline.service import (_BaselineStreamState,)from backend.copilot.capabilities.dispatch import resolve_tool_dispatch+from backend.copilot.capabilities.models import SKILL_TOOLfrom backend.copilot.model import ChatSessionfrom backend.copilot.permissions import ALL_TOOL_NAMES, CopilotPermissionsfrom backend.copilot.response_model import (@@ -90,11 +91,26 @@ def test_resolver_yields_the_inner_call():assert call.args == ARGS+def test_resolver_turns_a_skill_id_into_the_read_skill_call():+ """A skill found by search is loaded the way every skill is: the+ dispatch is the ``read_skill`` call, named by the id, so the engine+ records and gates that tool. The id wins over a ``name`` in the input."""+ tool = _StubTool(SKILL_TOOL)+ with _dispatch_of(tool):+ call = resolve_tool_dispatch(+ "run_capability",+ {"id": "skill:Triage-Tickets", "input": {"name": "other", "x": "1"}},+ )+ assert call is not None and call.tool is tool and call.name == SKILL_TOOL+ assert call.args == {"name": "triage-tickets", "x": "1"}++@pytest.mark.parametrize("tool_name,args",[# validate_only describes the call; it must not run the tool.("run_capability", {"id": f"tool:{INNER}", "input": {}, "validate_only": True}),+ ("run_capability", {"id": "skill:", "input": {}}),("run_capability", {"id": "block:1234", "input": {}}),("run_capability", {"id": "https://mcp.example/sse", "input": {}}),("run_capability", {"id": "", "input": {}}),diff --git a/autogpt_platform/backend/backend/copilot/capabilities/index.py b/autogpt_platform/backend/backend/copilot/capabilities/index.pyindex 9425645e2c..1a7bb0fb15 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/index.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/index.py@@ -17,7 +17,7 @@ from typing import TYPE_CHECKINGfrom pydantic import BaseModelfrom rank_bm25 import BM25Okapi-from .models import CapabilityContext, CapabilityEntry, CapabilityKindName+from .models import SKILL_TOOL, CapabilityContext, CapabilityEntry, CapabilityKindNamefrom .ranking import ConnectionState, class_weight, resolve_connected, tierfrom .text import normalize_name, query_groups, tokenize@@ -65,12 +65,20 @@ class SearchResult(BaseModel):class CapabilityIndex:- def __init__(self, entries: Sequence[CapabilityEntry]):+ def __init__(+ self,+ entries: Sequence[CapabilityEntry],+ *,+ documents: Sequence[list[str]] | None = None,+ ):self.entries: list[CapabilityEntry] = list(entries)self._by_id = {entry.id: entry for entry in self.entries}- self._by_ref = {- impl.ref: entry for entry in self.entries for impl in entry.implementations- }+ # First entry wins a bare ref: the platform's ``web_search`` stays+ # reachable by name when a session's skill is called the same.+ self._by_ref: dict[str, CapabilityEntry] = {}+ for entry in self.entries:+ for impl in entry.implementations:+ self._by_ref.setdefault(impl.ref, entry)self._by_name: dict[str, list[int]] = defaultdict(list)self._service_tags: dict[str, set[int]] = defaultdict(set)for idx, entry in enumerate(self.entries):@@ -87,13 +95,28 @@ class CapabilityIndex:self._service_words = max((tag.count("_") + 1 for tag in self._service_tags), default=1)- documents = [_document(e) for e in self.entries]- self._token_sets = [frozenset(doc) for doc in documents]- self._bm25 = BM25Okapi(documents or [[""]])+ if documents is None:+ documents = [_document(e) for e in self.entries]+ if len(documents) != len(self.entries):+ raise ValueError("one document per entry")+ self._documents = list(documents)+ self._token_sets = [frozenset(doc) for doc in self._documents]+ self._bm25 = BM25Okapi(self._documents or [[""]])def __len__(self) -> int:return len(self.entries)+ def with_entries(self, extra: Sequence[CapabilityEntry]) -> CapabilityIndex:+ """This index plus *extra*: the per-session layer (the owner's+ skills) over the platform registry. The platform documents are+ reused, so only *extra* is tokenised; this index is left as is."""+ if not extra:+ return self+ return CapabilityIndex(+ [*self.entries, *extra],+ documents=[*self._documents, *(_document(e) for e in extra)],+ )+def get(self, capability_id: str) -> CapabilityEntry | None:"""Look up by entry id, or by a bare implementation ref (block uuid,tool name) so callers holding legacy identifiers still resolve."""@@ -142,8 +165,14 @@ class CapabilityIndex:rest = [idx for idx in scores if idx not in exact]fallback: list[SearchHit] = []if service_indices is not None:- main = [idx for idx in rest if idx in service_indices]- others = [idx for idx in rest if idx not in service_indices]+ # A skill is not a service, but the one written for the named+ # service is the best answer there is, so skills stay in.+ main = [+ idx+ for idx in rest+ if idx in service_indices or self.entries[idx].kind == "skill"+ ]+ others = [idx for idx in rest if idx not in main]fallback = _ranked([to_hit(idx, "search")@@ -169,7 +198,9 @@ class CapabilityIndex:allowed_tools: frozenset[str] | None = Noneif permissions is not None:all_tools = frozenset(e.name for e in self.entries if e.kind == "tool")- allowed_tools = permissions.effective_allowed_tools(all_tools)+ allowed_tools = permissions.effective_allowed_tools(+ all_tools | {SKILL_TOOL}+ )allowed: set[int] = set()for idx, entry in enumerate(self.entries):if not entry.available_in(context):@@ -187,6 +218,14 @@ class CapabilityIndex:and entry.name not in allowed_tools):continue+ # A skill runs through ``read_skill``; a turn that may not+ # call it may not be shown skills either.+ if (+ entry.kind == "skill"+ and allowed_tools is not None+ and SKILL_TOOL not in allowed_tools+ ):+ continueallowed.add(idx)return alloweddiff --git a/autogpt_platform/backend/backend/copilot/capabilities/index_test.py b/autogpt_platform/backend/backend/copilot/capabilities/index_test.pyindex c3235edb6c..727bd95381 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/index_test.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/index_test.py@@ -230,3 +230,71 @@ def test_save_query_reaches_a_store_entry_through_the_synonym(index):def test_eager_tools_are_flagged_in_listing(index):hit = index.search("web search").hits[0]assert hit.entry.listing()["eager"] is True+++# ------------------------------------------------- the per-session skill layer+++def _skill(name: str, description: str) -> CapabilityEntry:+ return CapabilityEntry(+ id=f"skill:{name}",+ kind="skill",+ name=name,+ purpose=description,+ description=description,+ tags=["skill"],+ context="direct",+ implementations=[Implementation(kind="skill", ref=name, context="direct")],+ )+++TRIAGE = _skill("triage-linear-issues", "Triage and prioritise a Linear issue.")+PLAYBOOK = _skill("issue-playbook", "Create an issue the way this team does.")+++def test_with_entries_layers_skills_without_touching_the_base_index(index):+ layered = index.with_entries([TRIAGE])+ assert len(layered) == len(index) + 1+ assert layered.get(TRIAGE.id) is TRIAGE and index.get(TRIAGE.id) is None+ assert index.with_entries([]) is index+++def test_a_skill_matching_as_well_as_a_block_ranks_with_connected_services(index):+ layered = index.with_entries([PLAYBOOK])+ # Nothing connected: the skill leads both unconnected issue blocks.+ assert layered.search("create issue").names[0] == "issue-playbook"+ state = ConnectionState(providers=frozenset({"github"}))+ top = layered.search("create issue", connections=state).names[:2]+ assert set(top) == {"issue-playbook", "GithubMakeIssueBlock"}+ assert layered.search("create issue").hits[0].coverage == 2.0+++def test_skills_stay_in_the_main_list_of_a_service_query(index):+ layered = index.with_entries([TRIAGE])+ result = layered.search("linear issue")+ assert result.service == "linear"+ assert set(result.names) == {"LinearCreateIssueBlock", "triage-linear-issues"}+ assert "triage-linear-issues" not in [h.entry.name for h in result.fallback]+++def test_skills_answer_to_the_read_skill_permission(index):+ layered = index.with_entries([TRIAGE])+ denied = CopilotPermissions(tools=["read_skill"])+ assert (+ "triage-linear-issues" not in layered.search("triage", permissions=denied).names+ )+ allowed = CopilotPermissions(tools=["web_search"])+ assert "triage-linear-issues" in layered.search("triage", permissions=allowed).names+++def test_kind_filter_selects_skills(index):+ layered = index.with_entries([TRIAGE, PLAYBOOK])+ assert layered.search("issue", kind="skill").ids == [PLAYBOOK.id, TRIAGE.id]+++def test_a_platform_entry_keeps_a_bare_ref_a_skill_shares(index):+ clone = _skill("web_search", "How this team searches the web.")+ layered = index.with_entries([clone])+ shared = layered.get("web_search")+ assert shared is not None and shared.kind == "tool"+ assert layered.get("skill:web_search") is clonediff --git a/autogpt_platform/backend/backend/copilot/capabilities/models.py b/autogpt_platform/backend/backend/copilot/capabilities/models.pyindex 4389daa9f8..449e3325d0 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/models.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/models.py@@ -1,9 +1,10 @@"""Data model for the copilot capability registry.One :class:`CapabilityEntry` describes one thing the copilot can do: a-platform tool, a block, an MCP server from the catalog, or (phase 2) a-library agent. The registry indexes entries by name, description and-tags; argument schemas are fetched on demand and never indexed.+platform tool, a block, an MCP server from the catalog, a skill of the+session's owner, or (phase 2) a library agent. The registry indexes+entries by name, description and tags; argument schemas are fetched on+demand and never indexed."""from __future__ import annotations@@ -12,7 +13,9 @@ from typing import Literalfrom pydantic import BaseModel, Field-CapabilityKindName = Literal["tool", "block", "mcp_server", "mcp_tool", "agent"]+CapabilityKindName = Literal[+ "tool", "block", "mcp_server", "mcp_tool", "agent", "skill"+]CapabilityClass = Literal["service", "primitive"]CapabilityContext = Literal["direct", "graph", "both"]ConnectionKeyType = Literal["provider", "server_url", "host", "none"]@@ -22,6 +25,9 @@ PURPOSE_MAX_CHARS = 160# text (the longest block description is under 1,000 chars), and a ceiling on# what a runaway one can add to the index and its memory.DESCRIPTION_MAX_CHARS = 4000+# The tool a skill runs through. A turn that may not call it may not see+# skills either, and a ``skill:`` dispatch is a call to it.+SKILL_TOOL = "read_skill"class Implementation(BaseModel):diff --git a/autogpt_platform/backend/backend/copilot/capabilities/ranking.py b/autogpt_platform/backend/backend/copilot/capabilities/ranking.pyindex f990ff7fcc..05f2903167 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/ranking.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/ranking.py@@ -49,6 +49,10 @@ def resolve_connected(def tier(entry: CapabilityEntry, connected: bool | None) -> int:"""0 = connected service ... 3 = bare primitive; used for tie-breaks."""+ if entry.kind == "skill":+ # The owner's own procedure: nothing to connect, written for this+ # user, so it ranks with the services they have connected.+ return 0if entry.klass == "service":return 0 if connected else 1# A host-keyed primitive resolves its credential from the request URL atdiff --git a/autogpt_platform/backend/backend/copilot/capabilities/registry.py b/autogpt_platform/backend/backend/copilot/capabilities/registry.pyindex 6deb4407b7..f0c17a9451 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/registry.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/registry.py@@ -1,9 +1,9 @@"""Assemble the capability index from its sources.The platform-wide index (tools + blocks + MCP catalog) is static for the-life of the process, so it is built once and reused. Per-user entries (MCP-servers the user has registered) are layered on top per request by a later-change; nothing here depends on the user.+life of the process, so it is built once and reused. Per-session entries+(the owner's skills) are layered on top per call by+``tools.session_registry``; nothing here depends on the user.``backend.copilot.tools`` imports the registry tools, which import thispackage, so the tools package hands over its registry withdiff --git a/autogpt_platform/backend/backend/copilot/capabilities/sources/__init__.py b/autogpt_platform/backend/backend/copilot/capabilities/sources/__init__.pyindex d6deb9409d..f0f6e14749 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/sources/__init__.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/__init__.py@@ -1,15 +1,21 @@"""Capability sources: each yields ``CapabilityEntry`` objects from one backing-registry (platform tools, blocks, the MCP catalog). Per-user sources (MCP-servers the user has registered) are layered on top by the registry."""+registry (platform tools, blocks, the MCP catalog, the session owner's+skills). The first three make the process-wide registry; skills are per+session and layered on top by ``tools.session_registry``."""from .blocks import block_entriesfrom .mcp_catalog import mcp_catalog_entries+from .skills import SKILL_ID_PREFIX, SKILL_TOOL, skill_entries, skill_namefrom .static_tools import EAGER_CORE, RETIRED_TOOLS, tool_entries__all__ = ["EAGER_CORE","RETIRED_TOOLS",+ "SKILL_ID_PREFIX",+ "SKILL_TOOL","block_entries","mcp_catalog_entries",+ "skill_entries",+ "skill_name","tool_entries",]diff --git a/autogpt_platform/backend/backend/copilot/capabilities/sources/skills.py b/autogpt_platform/backend/backend/copilot/capabilities/sources/skills.pynew file mode 100644index 0000000000..cee2e70e57--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/skills.py@@ -0,0 +1,67 @@+"""The session owner's skills as capability entries.++Skills belong to a user, and within a user to one owner folder — an+expert's, or personal Otto's — so unlike the other sources they cannot sit+in the process-wide registry: ``tools.session_registry`` layers them onto+it per call. Entries are metadata only. Running one loads it through+``read_skill``, exactly as the ``<available_skills>`` index tells the+model to; the index injection stays, this makes the same skills reachable+through search as well.+"""++from collections.abc import Iterable+from typing import TYPE_CHECKING++from backend.copilot.capabilities.models import (+ SKILL_TOOL,+ CapabilityEntry,+ Implementation,+ clip_purpose,+ normalize_text,+)+from backend.copilot.capabilities.text import tokenize++if TYPE_CHECKING:+ from backend.copilot.tools.skills import ParsedSkill++__all__ = ["SKILL_ID_PREFIX", "SKILL_TOOL", "skill_entries", "skill_name"]++SKILL_ID_PREFIX = "skill:"+++def skill_entries(skills: "Iterable[ParsedSkill]") -> list[CapabilityEntry]:+ return [_skill_entry(skill) for skill in skills]+++def skill_name(capability_id: str) -> str | None:+ """The skill a ``skill:<name>`` id names, or None for any other id."""+ key = capability_id.strip()+ if not key.lower().startswith(SKILL_ID_PREFIX):+ return None+ name = key[len(SKILL_ID_PREFIX) :].strip().lower()+ return name or None+++def _skill_entry(skill: "ParsedSkill") -> CapabilityEntry:+ # Triggers ride in the description: they are what the skill says it is+ # for, so they should match a query and show in describe_capability.+ description = skill.description+ if skill.triggers:+ description += " Triggers: " + ", ".join(skill.triggers) + "."+ tags = sorted(set(tokenize(skill.name)))+ tags.append("skill")+ return CapabilityEntry(+ id=f"{SKILL_ID_PREFIX}{skill.name}",+ kind="skill",+ klass="service",+ name=skill.name,+ purpose=clip_purpose(skill.description),+ description=normalize_text(description),+ tags=tags,+ context="direct",+ implementations=[+ Implementation(+ kind="skill", ref=skill.name, name=skill.name, context="direct"+ )+ ],+ )diff --git a/autogpt_platform/backend/backend/copilot/capabilities/sources/skills_test.py b/autogpt_platform/backend/backend/copilot/capabilities/sources/skills_test.pynew file mode 100644index 0000000000..85790c52d8--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/skills_test.py@@ -0,0 +1,49 @@+"""Skills as capability entries: what the index sees and how ids read."""++import pytest++from backend.copilot.tools.skills import ParsedSkill++from .skills import SKILL_ID_PREFIX, skill_entries, skill_name++TRIAGE = ParsedSkill(+ name="triage-and-prioritize",+ description="Triage a support ticket and set its priority.",+ body="1. read the ticket\n2. set the priority",+ triggers=("triage", "prioritise ticket"),+)+++def test_skill_entry_indexes_description_and_triggers_but_lists_the_purpose():+ (entry,) = skill_entries([TRIAGE])+ assert entry.id == f"{SKILL_ID_PREFIX}triage-and-prioritize"+ assert entry.kind == "skill" and entry.context == "direct"+ assert entry.implementations[0].ref == "triage-and-prioritize"+ assert entry.purpose == TRIAGE.description+ assert entry.description.endswith("Triggers: triage, prioritise ticket.")+ assert "skill" in entry.tags+ listing = entry.listing()+ assert listing["kind"] == "skill" and "description" not in listing+ assert "connected" not in listing+++def test_a_skill_without_triggers_indexes_its_description_alone():+ (entry,) = skill_entries(+ [ParsedSkill(name="notes", description="Take notes.", body="")]+ )+ assert entry.description == "Take notes."+++ "raw,expected",+ [+ ("skill:triage", "triage"),+ ("Skill: Triage ", "triage"),+ ("skill:", None),+ ("tool:read_skill", None),+ ("triage", None),+ ("", None),+ ],+)+def test_skill_name_reads_only_skill_ids(raw: str, expected: str | None):+ assert skill_name(raw) == expecteddiff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.pyindex 6561f9028c..7baf594a13 100644--- a/autogpt_platform/backend/backend/copilot/prompting.py+++ b/autogpt_platform/backend/backend/copilot/prompting.py@@ -256,7 +256,10 @@ before signing off.The `<available_skills>` block injected at the start of the first usermessage is the discovery index for **reusable procedures** (built-inguides + user-distilled know-how). Treat it as the canonical answer to-"do we already have a recipe for this?"+"do we already have a recipe for this?" `find_capability` returns the+same skills too (kind `skill`, id `skill:<name>`), ranked next to blocks+and tools, so a search for a task surfaces a saved procedure as well;+`run_capability` on one loads it.**Load before acting.** When the user's request matches a skill'sdescription or triggers, run `tool:read_skill` with its `name` BEFORE planning thediff --git a/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py b/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.pyindex fccf6b0124..b3cd7d5684 100644--- a/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py@@ -13,6 +13,7 @@ from prisma.enums import ReviewStatusfrom backend.copilot.capabilities.mcp_review import COPILOT_MCP_NODE_PREFIXfrom backend.copilot.capabilities.ranking import ConnectionState+from backend.copilot.capabilities.registry import get_registryfrom backend.copilot.capabilities.sources import EAGER_COREfrom backend.copilot.constants import COPILOT_SESSION_PREFIXfrom backend.copilot.context import set_execution_context@@ -40,9 +41,17 @@ from .models import ()from .resume_capability import ResumeCapabilityToolfrom .run_capability import RunCapabilityTool+from .session_registry import session_registry+from .skills import ParsedSkill, ReadSkillResponseUSER = "user-cap-tools"LINEAR_STATE = ConnectionState(providers=frozenset({"linear"}))+TRIAGE = ParsedSkill(+ name="triage-and-prioritize",+ description="Triage a support ticket and set its priority.",+ body="1. read the ticket\n2. set the priority",+ triggers=("triage ticket",),+)@pytest.fixture(autouse=True)@@ -53,6 +62,24 @@ def _clean_context():set_execution_context(None, None)[email protected](autouse=True)+def skills():+ """The session's skill list is per user and read through Redis and the+ workspace; stub it empty so no test here reaches either. A test that+ wants skills sets ``skills.return_value``."""+ with (+ patch(+ "backend.copilot.tools.session_registry.is_skills_feature_enabled",+ AsyncMock(return_value=True),+ ),+ patch(+ "backend.copilot.tools.session_registry.list_all_skills",+ AsyncMock(return_value=[]),+ ) as listed,+ ):+ yield listed++# ---------------------------------------------------------------- registry@@ -313,9 +340,97 @@ async def test_find_capability_no_results_points_to_open_world():assert any("MCP server" in s for s in result.suggestions)+async def test_find_capability_returns_the_session_owner_s_skill(skills):+ skills.return_value = [TRIAGE]+ session = make_session(USER, expert_id="expert-1")+ with patch(+ "backend.copilot.tools.find_capability.load_connection_state",+ AsyncMock(return_value=ConnectionState()),+ ):+ result = await FindCapabilityTool()._execute(+ USER, session, query="triage a support ticket"+ )+ assert isinstance(result, CapabilityListResponse)+ assert result.capabilities[0]["id"] == "skill:triage-and-prioritize"+ assert result.capabilities[0]["kind"] == "skill"+ assert "kind=skill" in result.message+ # The owner's folder, never another expert's.+ skills.assert_awaited_with(USER, "expert-1")+++async def test_the_layered_index_is_reused_while_the_skills_are_the_same(skills):+ """Layering rebuilds BM25 over the whole corpus, so the result is kept for+ the skill-cache window; a changed skill, or no skills, gets its own."""+ skills.return_value = [TRIAGE]+ session = make_session(USER)+ first = await session_registry(USER, session)+ second = await session_registry(USER, session)+ assert first is second and first is not get_registry()+ skills.return_value = [+ ParsedSkill(name=TRIAGE.name, description="Rewritten.", body="", triggers=())+ ]+ assert await session_registry(USER, session) is not first+ skills.return_value = []+ assert await session_registry(USER, session) is get_registry()+++async def test_find_capability_kind_skill_lists_skills_only(skills):+ skills.return_value = [TRIAGE]+ with patch(+ "backend.copilot.tools.find_capability.load_connection_state",+ AsyncMock(return_value=ConnectionState()),+ ):+ result = await FindCapabilityTool()._execute(+ USER, make_session(USER), query="ticket", kind="skill"+ )+ assert isinstance(result, CapabilityListResponse)+ assert [c["kind"] for c in result.capabilities] == ["skill"]+++async def test_find_capability_survives_a_skill_listing_failure(skills):+ skills.side_effect = RuntimeError("redis down")+ with patch(+ "backend.copilot.tools.find_capability.load_connection_state",+ AsyncMock(return_value=LINEAR_STATE),+ ):+ result = await FindCapabilityTool()._execute(+ USER, make_session(USER), query="linear issue"+ )+ assert isinstance(result, CapabilityListResponse)+ assert result.capabilities[0]["name"].startswith("Linear")++# -------------------------------------------------------- describe_capability+async def test_describe_skill_points_at_run_capability(skills):+ skills.return_value = [TRIAGE]+ result = await DescribeCapabilityTool()._execute(+ USER, make_session(USER), id="skill:triage-and-prioritize"+ )+ assert isinstance(result, CapabilityDetailsResponse)+ assert "run_capability(id='skill:triage-and-prioritize'" in result.message+ assert "Triggers: triage ticket." in result.message+ assert result.capability["kind"] == "skill"+ assert result.parameters == {"type": "object", "properties": {}}+++async def test_describe_unknown_skill_names_the_id_shape(skills):+ result = await DescribeCapabilityTool()._execute(+ USER, make_session(USER), id="skill:nope"+ )+ assert isinstance(result, ErrorResponse) and "skill:<name>" in result.message+++async def test_a_skill_id_never_resolves_to_the_platform_tool_of_that_name(skills):+ """``resolve_entry`` falls back to matching a bare name, which would let+ ``skill:web_search`` describe the platform's ``web_search`` tool."""+ result = await DescribeCapabilityTool()._execute(+ USER, make_session(USER), id="skill:web_search"+ )+ assert isinstance(result, ErrorResponse)++async def test_describe_tool_returns_parameters():result = await DescribeCapabilityTool()._execute(USER, make_session(USER), id="tool:list_schedules"@@ -442,6 +557,60 @@ async def test_run_tool_respects_turn_hidden_tools():stub._execute.assert_not_awaited()+async def test_run_skill_validate_only_describes_without_loading(skills):+ skills.return_value = [TRIAGE]+ with patch("backend.copilot.tools.run_capability.ReadSkillTool") as reader:+ result = await RunCapabilityTool()._execute(+ USER,+ make_session(USER),+ id="skill:triage-and-prioritize",+ input={},+ validate_only=True,+ )+ assert isinstance(result, CapabilityDetailsResponse)+ assert result.capability["id"] == "skill:triage-and-prioritize"+ reader.assert_not_called()+++async def test_run_skill_loads_it_through_the_skill_reader(skills):+ """Off the engine path (``dispatch.py`` resolves the call there), the+ dispatcher itself loads the skill by name."""+ skills.return_value = [TRIAGE]+ session = make_session(USER)+ loaded = ReadSkillResponse(+ name=TRIAGE.name,+ description=TRIAGE.description,+ body=TRIAGE.body,+ message="Loaded",+ session_id=session.session_id,+ )+ with patch("backend.copilot.tools.run_capability.ReadSkillTool") as reader:+ reader.return_value._execute = AsyncMock(return_value=loaded)+ result = await RunCapabilityTool()._execute(+ USER, session, id="skill:triage-and-prioritize", input={}+ )+ assert result is loaded+ reader.return_value._execute.assert_awaited_once_with(+ USER, session, name="triage-and-prioritize"+ )+++async def test_run_skill_honours_the_read_skill_gate(skills):+ skills.return_value = [TRIAGE]+ session = make_session(USER)+ set_execution_context(USER, session, hidden_tools=frozenset({"read_skill"}))+ with patch("backend.copilot.tools.run_capability.ReadSkillTool") as reader:+ result = await RunCapabilityTool()._execute(+ USER, session, id="skill:triage-and-prioritize", input={}+ )+ assert isinstance(result, ErrorResponse) and result.error == "tool_disabled"+ reader.assert_not_called()+ described = await DescribeCapabilityTool()._execute(+ USER, session, id="skill:triage-and-prioritize"+ )+ assert isinstance(described, ErrorResponse) and described.error == "tool_disabled"++async def test_run_block_honours_the_run_block_gate():session = make_session(USER)set_execution_context(@@ -484,12 +653,15 @@ async def test_run_mcp_catalog_write_runs_without_review():out = MCPToolOutputResponse(message="done", server_url="u", tool_name="create_issue")- with patch(- "backend.copilot.tools.run_capability.RunMCPToolTool._execute",- AsyncMock(return_value=out),- ) as run, patch(- "backend.copilot.tools.run_capability.open_mcp_review", AsyncMock()- ) as review:+ with (+ patch(+ "backend.copilot.tools.run_capability.RunMCPToolTool._execute",+ AsyncMock(return_value=out),+ ) as run,+ patch(+ "backend.copilot.tools.run_capability.open_mcp_review", AsyncMock()+ ) as review,+ ):result = await RunCapabilityTool()._execute(USER,make_session(USER),@@ -503,11 +675,14 @@ async def test_run_mcp_catalog_write_runs_without_review():async def test_run_mcp_open_world_write_pauses_for_review():- with patch(- "backend.copilot.tools.run_capability.RunMCPToolTool._execute", AsyncMock()- ) as run, patch(- "backend.copilot.tools.run_capability.open_mcp_review",- AsyncMock(return_value="copilot-mcp-x:1"),+ with (+ patch(+ "backend.copilot.tools.run_capability.RunMCPToolTool._execute", AsyncMock()+ ) as run,+ patch(+ "backend.copilot.tools.run_capability.open_mcp_review",+ AsyncMock(return_value="copilot-mcp-x:1"),+ ),):result = await RunCapabilityTool()._execute(USER,@@ -598,12 +773,13 @@ async def test_resume_mcp_review_replays_the_approved_call():out = MCPToolOutputResponse(message="done", server_url="u", tool_name="delete_thing")- with patch(- "backend.copilot.tools.resume_capability.review_db", return_value=db- ), patch(- "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",- AsyncMock(return_value=out),- ) as run:+ with (+ patch("backend.copilot.tools.resume_capability.review_db", return_value=db),+ patch(+ "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",+ AsyncMock(return_value=out),+ ) as run,+ ):result = await ResumeCapabilityTool()._execute(USER, session, review_id=review_id)@@ -634,15 +810,17 @@ async def test_resume_mcp_review_reopens_when_overrides_change_a_write():db = MagicMock()db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})db.delete_review_by_node_exec_id = AsyncMock()- with patch(- "backend.copilot.tools.resume_capability.review_db", return_value=db- ), patch(- "backend.copilot.tools.resume_capability.open_mcp_review",- AsyncMock(return_value="copilot-mcp-mcp.example.com:ef56"),- ) as opened, patch(- "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",- AsyncMock(),- ) as run:+ with (+ patch("backend.copilot.tools.resume_capability.review_db", return_value=db),+ patch(+ "backend.copilot.tools.resume_capability.open_mcp_review",+ AsyncMock(return_value="copilot-mcp-mcp.example.com:ef56"),+ ) as opened,+ patch(+ "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",+ AsyncMock(),+ ) as run,+ ):result = await ResumeCapabilityTool()._execute(USER, session, review_id=review_id, input_overrides={"force": True})@@ -675,15 +853,17 @@ async def test_resume_mcp_review_reopens_even_when_the_call_would_not_be_gated()db = MagicMock()db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})db.delete_review_by_node_exec_id = AsyncMock()- with patch(- "backend.copilot.tools.resume_capability.review_db", return_value=db- ), patch(- "backend.copilot.tools.resume_capability.open_mcp_review",- AsyncMock(return_value="copilot-mcp-mcp.example.com:ef56"),- ), patch(- "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",- AsyncMock(),- ) as run:+ with (+ patch("backend.copilot.tools.resume_capability.review_db", return_value=db),+ patch(+ "backend.copilot.tools.resume_capability.open_mcp_review",+ AsyncMock(return_value="copilot-mcp-mcp.example.com:ef56"),+ ),+ patch(+ "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",+ AsyncMock(),+ ) as run,+ ):result = await ResumeCapabilityTool()._execute(USER, session, review_id=review_id, input_overrides={"id": 2})diff --git a/autogpt_platform/backend/backend/copilot/tools/describe_capability.py b/autogpt_platform/backend/backend/copilot/tools/describe_capability.pyindex 8612f08e98..dd21cc1068 100644--- a/autogpt_platform/backend/backend/copilot/tools/describe_capability.py+++ b/autogpt_platform/backend/backend/copilot/tools/describe_capability.py@@ -4,9 +4,8 @@ search index never carries schemas."""import loggingfrom typing import Any-from backend.copilot.capabilities.models import CapabilityEntry-from backend.copilot.capabilities.registry import configured_tool, get_registry-from backend.copilot.capabilities.resolve import resolve_entry+from backend.copilot.capabilities.models import SKILL_TOOL, CapabilityEntry+from backend.copilot.capabilities.registry import configured_toolfrom backend.copilot.capabilities.schema_trim import collapse_large_enumsfrom backend.copilot.capabilities.sources.mcp_catalog import setup_hintfrom backend.copilot.model import ChatSession@@ -23,14 +22,18 @@ from .models import ()from .run_block import RunBlockToolfrom .run_mcp_tool import RunMCPToolTool+from .session_registry import resolve_session_entrylogger = logging.getLogger(__name__)UNKNOWN_ID_HINT = ("Unknown capability id. Use the exact 'id' from a find_capability result "- "(tool:<name>, block:<uuid>, mcp:<host>)."+ "(tool:<name>, block:<uuid>, mcp:<host>, skill:<name>).")+# A skill takes no input: running it is loading it.+NO_INPUT: dict[str, Any] = {"type": "object", "properties": {}}+# Input shape for run_capability on an MCP server entry.MCP_RUN_PARAMETERS: dict[str, Any] = {"type": "object",@@ -97,7 +100,7 @@ class DescribeCapabilityTool(BaseTool):return ErrorResponse(message="Authentication required", session_id=session_id)- entry = resolve_entry(get_registry(), id)+ entry = await resolve_session_entry(user_id, session, id)if entry is None:return ErrorResponse(message=UNKNOWN_ID_HINT, session_id=session_id)# Describing answers to the gate that running does. An MCP@@ -108,6 +111,10 @@ class DescribeCapabilityTool(BaseTool):if gate_denied(BLOCK_GATE):return gate_denied_error("blocks", session_id)return await _describe_block(entry, user_id, session, expand)+ if entry.kind == "skill":+ if gate_denied(SKILL_TOOL):+ return gate_denied_error(SKILL_TOOL, session_id)+ return describe_skill(entry, session_id)if entry.kind == "tool":name = entry.implementations[0].refif gate_denied(name):@@ -141,6 +148,21 @@ async def _describe_block(return result+def describe_skill(entry: CapabilityEntry, session_id: str) -> ToolResponseBase:+ """What a skill is for. Its body is not repeated here: running the+ capability loads it, package files included."""+ return CapabilityDetailsResponse(+ message=(+ f"Skill '{entry.name}': {entry.description} Load it with "+ f"run_capability(id='{entry.id}', input={{}}) and read the body "+ "before acting on the task it covers."+ ),+ capability=entry.listing(),+ parameters=NO_INPUT,+ session_id=session_id,+ )++def _describe_tool(entry: CapabilityEntry, session_id: str, expand: bool) -> ToolResponseBase:diff --git a/autogpt_platform/backend/backend/copilot/tools/find_capability.py b/autogpt_platform/backend/backend/copilot/tools/find_capability.pyindex 2669458776..fdd2291969 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_capability.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_capability.py@@ -1,12 +1,12 @@-"""Search the capability registry: integrations, blocks, MCP servers and-platform tools behind one query."""+"""Search the capability registry: integrations, blocks, MCP servers,+platform tools and the session owner's skills behind one query."""+import asyncioimport loggingfrom typing import Anyfrom backend.copilot.capabilities.index import SearchHitfrom backend.copilot.capabilities.models import CapabilityKindName-from backend.copilot.capabilities.registry import get_registryfrom backend.copilot.capabilities.resolve import load_connection_statefrom backend.copilot.context import get_current_permissionsfrom backend.copilot.model import ChatSession@@ -18,15 +18,17 @@ from .models import (NoResultsResponse,ToolResponseBase,)+from .session_registry import session_registrylogger = logging.getLogger(__name__)CONTEXTS = ("direct", "graph")-KINDS = ("tool", "block", "mcp_server")+KINDS = ("tool", "block", "mcp_server", "skill")_KIND_ARG: dict[str, CapabilityKindName] = {"tool": "tool","block": "block","mcp_server": "mcp_server",+ "skill": "skill",}@@ -41,10 +43,11 @@ class FindCapabilityTool(BaseTool):def description(self) -> str:return ("Search everything the platform can do: integrations, blocks, MCP "- "servers and platform tools, by service name or action. Results are "- "ranked and show whether the user has connected each one. Call this "- "before saying something is not possible. Then describe_capability(id) "- "to see inputs, and run_capability(id, input) to act."+ "servers, platform tools and skills, by service name or action. "+ "Results are ranked and show whether the user has connected each "+ "one. Call this before saying something is not possible. Then "+ "describe_capability(id) to see inputs, and run_capability(id, "+ "input) to act.")@property@@ -109,8 +112,10 @@ class FindCapabilityTool(BaseTool):message="Authentication required", session_id=session_id)- connections = await load_connection_state(user_id)- result = get_registry().search(+ connections, index = await asyncio.gather(+ load_connection_state(user_id), session_registry(user_id, session)+ )+ result = index.search(query,context="graph" if context == "graph" else "direct",kind=_KIND_ARG.get(kind or ""),@@ -128,7 +133,12 @@ class FindCapabilityTool(BaseTool):session_id=session_id,)return CapabilityListResponse(- message=_message(result.service, len(result.hits), len(result.fallback)),+ message=_message(+ result.service,+ len(result.hits),+ len(result.fallback),+ skills=any(hit.entry.kind == "skill" for hit in result.hits),+ ),query=query,capabilities=[_listing(hit) for hit in result.hits],count=len(result.hits),@@ -145,15 +155,24 @@ def _listing(hit: SearchHit) -> dict[str, Any]:return listing-def _message(service: str | None, hits: int, fallback: int) -> str:+def _message(+ service: str | None, hits: int, fallback: int, *, skills: bool = False+) -> str:parts = [f"Found {hits} capabilit{'y' if hits == 1 else 'ies'}"]if service:parts.append(f"for {service}")text = " ".join(parts) + "."if fallback:text += f" {fallback} generic fallback(s) listed separately."- return (- f"{text} Call describe_capability(id) before first use, then "+ text += (+ " Call describe_capability(id) before first use, then ""run_capability(id, input). connected=false means the user must sign in ""first: run_capability returns the sign-in card.")+ if skills:+ text += (+ " A kind=skill result is a saved procedure: "+ "run_capability(id, input={}) loads its body and package files; "+ "read it before acting."+ )+ return textdiff --git a/autogpt_platform/backend/backend/copilot/tools/run_capability.py b/autogpt_platform/backend/backend/copilot/tools/run_capability.pyindex 10f8313e0d..959247d6bc 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_capability.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_capability.py@@ -1,9 +1,11 @@-"""Run one capability by id: a block, a platform tool or an MCP server.+"""Run one capability by id: a block, a platform tool, an MCP server or a+skill.Dispatches to the existing implementations (``RunBlockTool``,-``RunMCPToolTool``, the tool's own ``_execute``) so credential resolution,-pickers, human review, spend approval, dry-run and error hints all keep-working; this module only adds the id resolution and the per-kind gates.+``RunMCPToolTool``, ``ReadSkillTool``, the tool's own ``_execute``) so+credential resolution, pickers, human review, spend approval, dry-run and+error hints all keep working; this module only adds the id resolution and+the per-kind gates."""import logging@@ -15,7 +17,7 @@ from backend.copilot.capabilities.mcp_review import (needs_review,open_mcp_review,)-from backend.copilot.capabilities.models import CapabilityEntry+from backend.copilot.capabilities.models import SKILL_TOOL, CapabilityEntryfrom backend.copilot.capabilities.registry import configured_tool, get_registryfrom backend.copilot.capabilities.resolve import resolve_entryfrom backend.copilot.capabilities.sources.mcp_catalog import setup_hint@@ -27,7 +29,7 @@ from backend.data.activity_event import ActivityEventDraftfrom .base import BaseToolfrom .capability_gates import gate_denied, gate_denied_error-from .describe_capability import MCP_RUN_PARAMETERS, UNKNOWN_ID_HINT+from .describe_capability import MCP_RUN_PARAMETERS, UNKNOWN_ID_HINT, describe_skillfrom .models import (CapabilityDetailsResponse,ErrorResponse,@@ -36,6 +38,8 @@ from .models import ()from .run_block import RunBlockToolfrom .run_mcp_tool import RunMCPToolTool+from .session_registry import resolve_session_entry+from .skills import ReadSkillToollogger = logging.getLogger(__name__)@@ -51,7 +55,8 @@ class RunCapabilityTool(BaseTool):def description(self) -> str:return ("Run a capability by id with its input (blocks: the block's inputs; "- "MCP servers: {tool, arguments}; platform tools: their parameters). "+ "MCP servers: {tool, arguments}; platform tools: their parameters; "+ "skills: {}). ""Never guess ids: take them from find_capability. An unconnected ""capability returns a sign-in card: show it and stop. review_required ""means wait for approval, then resume_capability(review_id). "@@ -117,7 +122,7 @@ class RunCapabilityTool(BaseTool):message="input must be an object", session_id=session_id)payload: dict[str, Any] = dict(input or {})- entry = resolve_entry(get_registry(), id)+ entry = await resolve_session_entry(user_id, session, id)if entry is None and id.strip().lower().startswith("https://"):# Open world: a server URL the catalog does not know. The MCP# path validates the host; writes pause for review.@@ -141,6 +146,8 @@ class RunCapabilityTool(BaseTool):return await _run_block(entry, user_id, session, payload, validate_only)if entry.kind == "tool":return await _describe_tool(entry, session)+ if entry.kind == "skill":+ return await _run_skill(entry, user_id, session, validate_only)if entry.kind == "mcp_server":server_url = entry.implementations[0].refif not server_url:@@ -201,6 +208,24 @@ async def _describe_tool()+async def _run_skill(+ entry: CapabilityEntry, user_id: str, session: ChatSession, validate_only: bool+) -> ToolResponseBase:+ """Load a skill: running one is reading it.++ The engines resolve the dispatch into the ``read_skill`` call it is+ (``capabilities/dispatch.py``) and run that through the one tool path,+ so this answers ``validate_only`` and any engine that did not.+ """+ if gate_denied(SKILL_TOOL):+ return gate_denied_error(SKILL_TOOL, session.session_id)+ if validate_only:+ return describe_skill(entry, session.session_id)+ return await ReadSkillTool()._execute(+ user_id, session, name=entry.implementations[0].ref+ )++async def _run_mcp(entry: CapabilityEntry | None,server_url: str,diff --git a/autogpt_platform/backend/backend/copilot/tools/session_registry.py b/autogpt_platform/backend/backend/copilot/tools/session_registry.pynew file mode 100644index 0000000000..840294a68f--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/session_registry.py@@ -0,0 +1,99 @@+"""The capability index a session searches: the platform registry plus the+session owner's skills.++Skills belong to a user, and within a user to one owner folder — the+expert's, or personal Otto's — so they cannot sit in the process-wide+registry. They are layered on per call from the same cached list that+builds ``<available_skills>``, so a search costs no extra storage reads.+"""++import logging+import time+from collections import OrderedDict++from backend.copilot.capabilities.index import CapabilityIndex+from backend.copilot.capabilities.models import CapabilityEntry+from backend.copilot.capabilities.registry import get_registry+from backend.copilot.capabilities.resolve import resolve_entry+from backend.copilot.capabilities.sources import skill_entries, skill_name+from backend.copilot.model import ChatSession++from .skills import SKILLS_INDEX_CACHE_TTL_S, is_skills_feature_enabled, list_all_skills++logger = logging.getLogger(__name__)++# Layering reuses the platform documents but BM25 re-derives its corpus+# statistics over all of them: some 40 ms of CPU on the event loop per+# search. A skill list changes rarely and is itself cached for+# ``SKILLS_INDEX_CACHE_TTL_S``, so the layered index is kept for the same+# window, keyed by the platform index (a new one after a block reload) and+# by what the skills say, so a rewritten skill is re-indexed at once.+_LAYERED_MAX = 128+_layered: OrderedDict[+ tuple[int, int, tuple[tuple[str, str], ...]], tuple[float, CapabilityIndex]+] = OrderedDict()+++async def session_registry(user_id: str, session: ChatSession) -> CapabilityIndex:+ """The platform index with this session's skills layered on."""+ return layered_index(get_registry(), await session_skill_entries(user_id, session))+++def layered_index(+ base: CapabilityIndex, skills: list[CapabilityEntry]+) -> CapabilityIndex:+ """*base* with *skills* layered on, reused within the skill-cache window+ for the same platform index and the same skills."""+ if not skills:+ return base+ key = (id(base), len(base), tuple((e.id, e.description) for e in skills))+ now = time.monotonic()+ cached = _layered.get(key)+ if cached is not None and cached[0] > now:+ _layered.move_to_end(key)+ return cached[1]+ index = base.with_entries(skills)+ _layered[key] = (now + SKILLS_INDEX_CACHE_TTL_S, index)+ _layered.move_to_end(key)+ while len(_layered) > _LAYERED_MAX:+ _layered.popitem(last=False)+ return index+++async def resolve_session_entry(+ user_id: str, session: ChatSession, capability_id: str+) -> CapabilityEntry | None:+ """``resolve_entry`` over the platform registry, plus the session's+ skills by ``skill:<name>`` id.++ A skill id is looked up among the skills only: falling through to the+ registry's name match would let ``skill:web_search`` resolve to the+ platform tool of that name.+ """+ name = skill_name(capability_id)+ if name is None:+ return resolve_entry(get_registry(), capability_id)+ return next(+ (+ entry+ for entry in await session_skill_entries(user_id, session)+ if entry.implementations[0].ref == name+ ),+ None,+ )+++async def session_skill_entries(+ user_id: str, session: ChatSession+) -> list[CapabilityEntry]:+ """The session owner's skills as entries; ``[]`` when the feature is off+ for the user or the list cannot be read, so a skills hiccup never takes+ capability search down with it."""+ try:+ if not await is_skills_feature_enabled(user_id):+ return []+ skills = await list_all_skills(user_id, session.expert_id)+ except Exception:+ logger.warning("Could not load skills for capability search", exc_info=True)+ return []+ return skill_entries(skills)diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/FindCapabilities.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/FindCapabilities.test.tsxindex d9a966b62b..7638a75228 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/FindCapabilities.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/FindCapabilities.test.tsx@@ -70,6 +70,28 @@ describe("FindCapabilitiesTool", () => {expect(screen.queryAllByText(/^(connected|sign in)$/)).toHaveLength(2);});+ it("labels a skill as one, not as an action", () => {+ const withSkill = {+ ...OUTPUT,+ count: 1,+ capabilities: [+ {+ id: "skill:triage-and-prioritize",+ name: "triage-and-prioritize",+ purpose: "Triage a support ticket",+ kind: "skill",+ },+ ],+ fallback: [],+ };+ render(<FindCapabilitiesTool part={part({ output: withSkill })} />);+ fireEvent.click(screen.getByText("Results"));++ expect(screen.getByText("triage-and-prioritize")).toBeDefined();+ expect(screen.getByText("skill")).toBeDefined();+ expect(screen.queryByText("action")).toBeNull();+ });+it("singularises a lone result", () => {const single = {...OUTPUT,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/helpers.tsindex 463fd1d8f4..b3d00d153a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/helpers.ts@@ -85,6 +85,7 @@ export function getAnimationText(part: FindCapabilityToolPart): string {export function kindLabel(item: CapabilityListing): string {if (item.kind === "mcp_server") return "integration";+ if (item.kind === "skill") return "skill";if (item.class === "primitive") return "building block";if (item.kind === "tool") return "tool";return "action";