Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(acl): enforce skill resource access

Maxvint134ca34f87ed
diff --git a/core/services/skills.py b/core/services/skills.py
index 3928d28cc..65e338505 100644
--- a/core/services/skills.py
+++ b/core/services/skills.py
@@ -25,9 +25,11 @@ the project folder.
from __future__ import annotations
import asyncio
+import hashlib
import json
import logging
import os
+import re
from typing import Any, Optional
logger = logging.getLogger(__name__)
@@ -41,6 +43,7 @@ BACKEND_TO_AGENT: dict[str, str] = {
"codex": "codex",
}
AGENT_TO_BACKEND: dict[str, str] = {agent: backend for backend, agent in BACKEND_TO_AGENT.items()}
+_SKILL_RESOURCE_SCOPES = frozenset({"global", "project"})
class SkillsError(Exception):
@@ -53,6 +56,13 @@ class SkillsError(Exception):
self.details = details
+class SkillAccessError(SkillsError):
+ """Raised when a remote caller cannot use or manage a Skill resource."""
+
+ def __init__(self) -> None:
+ super().__init__("resource_access_forbidden", "Skill access is not permitted.")
+
+
def _subprocess_env(askill_path: str) -> dict[str, str]:
"""Env for the askill subprocess with the binary's own dir leading PATH.
@@ -177,6 +187,375 @@ def _cwd_for(scope: str, project_dir: Optional[str]) -> Optional[str]:
return project_dir if scope != "global" else None
+def resolve_resource_access_context(user_context: Any = None):
+ """Resolve request ACL context while preserving trusted local Skill use."""
+
+ from storage import resource_access_service
+
+ if isinstance(user_context, resource_access_service.ResourceUserContext):
+ return user_context
+ if user_context is not None:
+ return resource_access_service.current_resource_context(user_context, is_remote=True)
+
+ context = resource_access_service.current_resource_context()
+ if context.is_remote or context.is_trusted_local:
+ return context
+ return resource_access_service.ResourceUserContext(is_trusted_local=True)
+
+
+def _normalize_skill_name(name: Any) -> str:
+ normalized = re.sub(r"[^a-z0-9]+", "-", str(name or "").strip().lower()).strip("-")
+ if not normalized:
+ raise SkillsError("invalid_skill", "skill name is required")
+ return normalized
+
+
+def _backend_from_agent_ref(value: Any) -> str | None:
+ candidates: list[Any]
+ if isinstance(value, dict):
+ candidates = [value.get("backend"), value.get("id"), value.get("name")]
+ else:
+ candidates = [value]
+ for candidate in candidates:
+ normalized = str(candidate or "").strip().lower()
+ if normalized in BACKEND_TO_AGENT:
+ return normalized
+ if normalized in AGENT_TO_BACKEND:
+ return AGENT_TO_BACKEND[normalized]
+ return None
+
+
+def _normalized_backends(backends: Optional[list[str]]) -> list[str]:
+ result: list[str] = []
+ for backend in backends or []:
+ normalized = _backend_from_agent_ref(backend)
+ if normalized is None:
+ raise SkillsError("invalid_backend", f"unknown backend: {backend}")
+ if normalized not in result:
+ result.append(normalized)
+ return result
+
+
+def _project_resource_segment(scope: str, project_dir: Optional[str]) -> str:
+ if scope == "global":
+ return "global"
+ if scope != "project":
+ raise SkillsError("invalid_scope", f"unknown scope: {scope}")
+ if not project_dir:
+ raise SkillsError("project_required", "a project is required for project-scoped skills")
+ canonical_path = os.path.normcase(os.path.realpath(os.path.abspath(project_dir)))
+ return f"project-{hashlib.sha256(canonical_path.encode('utf-8')).hexdigest()[:24]}"
+
+
+def skill_resource_id(
+ backend: str,
+ *,
+ scope: str,
+ project_dir: Optional[str],
+ name: str,
+) -> str:
+ """Return the stable local ACL descriptor for one backend-specific Skill."""
+
+ normalized_backend = _backend_from_agent_ref(backend)
+ if normalized_backend is None:
+ raise SkillsError("invalid_backend", f"unknown backend: {backend}")
+ if scope not in _SKILL_RESOURCE_SCOPES:
+ raise SkillsError("invalid_scope", f"unknown scope: {scope}")
+ return ":".join(
+ [
+ normalized_backend,
+ scope,
+ _project_resource_segment(scope, project_dir),
+ _normalize_skill_name(name),
+ ]
+ )
+
+
+def _skill_scope(skill: dict[str, Any], requested_scope: str) -> str | None:
+ scope = str(skill.get("scope") or "").strip().lower()
+ if scope in _SKILL_RESOURCE_SCOPES:
+ return scope
+ if requested_scope in _SKILL_RESOURCE_SCOPES:
+ return requested_scope
+ return None
+
+
+def _skill_backend_entries(skill: dict[str, Any], selected_backends: Optional[list[str]]) -> list[tuple[str, int | None]]:
+ raw_agents = skill.get("agents")
+ if isinstance(raw_agents, list):
+ result: list[tuple[str, int | None]] = []
+ for index, agent in enumerate(raw_agents):
+ backend = _backend_from_agent_ref(agent)
+ if backend is not None:
+ result.append((backend, index))
+ if selected_backends:
+ selected = set(_normalized_backends(selected_backends))
+ result = [item for item in result if item[0] in selected]
+ return result
+ return [(backend, None) for backend in _normalized_backends(selected_backends)]
+
+
+def _skill_resource_descriptors(
+ skills: list[dict[str, Any]],
+ *,
+ requested_scope: str,
+ project_dir: Optional[str],
+ backends: Optional[list[str]],
+) -> list[dict[str, Any]]:
+ descriptors: list[dict[str, Any]] = []
+ for skill_index, skill in enumerate(skills):
+ scope = _skill_scope(skill, requested_scope)
+ name = skill.get("name")
+ if scope is None or not isinstance(name, str):
+ continue
+ try:
+ entries = _skill_backend_entries(skill, backends)
+ for backend, agent_index in entries:
+ descriptors.append(
+ {
+ "id": skill_resource_id(
+ backend,
+ scope=scope,
+ project_dir=project_dir,
+ name=name,
+ ),
+ "skill_index": skill_index,
+ "agent_index": agent_index,
+ }
+ )
+ except SkillsError:
+ # A malformed askill row must not become visible to a remote caller.
+ continue
+ return descriptors
+
+
+def _filter_skill_listing(
+ result: dict[str, Any],
+ *,
+ scope: str,
+ project_dir: Optional[str],
+ backends: Optional[list[str]],
+ user_context: Any = None,
+) -> dict[str, Any]:
+ """Filter askill's value-free list payload through local Skill ACLs."""
+
+ if not result.get("ok") or not isinstance(result.get("skills"), list):
+ return result
+ context = resolve_resource_access_context(user_context)
+ if context.is_trusted_local:
+ return result
+
+ raw_skills = [dict(skill) for skill in result["skills"] if isinstance(skill, dict)]
+ descriptors = _skill_resource_descriptors(
+ raw_skills,
+ requested_scope=scope,
+ project_dir=project_dir,
+ backends=backends,
+ )
+ if not descriptors:
+ filtered_skills: list[dict[str, Any]] = []
+ else:
+ from storage import resource_access_service
+ from storage.db import get_cached_sqlite_engine
+
+ engine = get_cached_sqlite_engine()
+ with engine.connect() as connection:
+ accessible = resource_access_service.filter_accessible_resources(
+ context,
+ "skill",
+ descriptors,
+ connection=connection,
+ )
+ allowed = {(item["skill_index"], item["agent_index"]) for item in accessible}
+ filtered_skills = []
+ for skill_index, skill in enumerate(raw_skills):
+ matching = [item for item in descriptors if item["skill_index"] == skill_index]
+ if not matching or not any((item["skill_index"], item["agent_index"]) in allowed for item in matching):
+ continue
+ raw_agents = skill.get("agents")
+ if isinstance(raw_agents, list):
+ skill["agents"] = [
+ agent
+ for agent_index, agent in enumerate(raw_agents)
+ if (skill_index, agent_index) in allowed
+ ]
+ if not skill["agents"]:
+ continue
+ filtered_skills.append(skill)
+
+ filtered = dict(result)
+ filtered["skills"] = filtered_skills
+ if isinstance(result.get("summary"), dict):
+ summary = dict(result["summary"])
+ summary["global"] = sum(1 for skill in filtered_skills if skill.get("scope") == "global")
+ summary["project"] = sum(1 for skill in filtered_skills if skill.get("scope") == "project")
+ filtered["summary"] = summary
+ return filtered
+
+
+def _resource_ids_for_skill_name(
+ name: str,
+ *,
+ scope: str,
+ project_dir: Optional[str],
+ backends: Optional[list[str]],
+) -> list[str]:
+ return [
+ skill_resource_id(backend, scope=scope, project_dir=project_dir, name=name)
+ for backend in _normalized_backends(backends) or list(BACKEND_TO_AGENT)
+ ]
+
+
+def _require_skill_management_access(
+ resource_ids: list[str],
+ *,
+ user_context: Any,
+ allow_missing_policy: bool,
+) -> None:
+ from storage import resource_access_service
+ from storage.db import get_cached_sqlite_engine
+
+ context = resolve_resource_access_context(user_context)
+ if context.is_trusted_local:
+ return
+ engine = get_cached_sqlite_engine()
+ with engine.connect() as connection:
+ for resource_id in resource_ids:
+ policy = resource_access_service.get_resource_policy("skill", resource_id, connection=connection)
+ if policy is None:
+ if allow_missing_policy or context.is_instance_owner:
+ continue
+ raise SkillAccessError()
+ if not resource_access_service.can_manage_resource_acl(
+ context,
+ "skill",
+ resource_id,
+ connection=connection,
+ ):
+ raise SkillAccessError()
+
+
+def _require_skill_create_access(user_context: Any) -> None:
+ context = resolve_resource_access_context(user_context)
+ if context.is_trusted_local or context.is_instance_owner:
+ return
+ if context.is_remote and context.is_active_organization_member and context.subject:
+ return
+ raise SkillAccessError()
+
+
+def _skill_names_from_payload(payload: dict[str, Any]) -> list[str]:
+ names: list[str] = []
+ direct = payload.get("skill")
+ if isinstance(direct, str):
+ names.append(direct)
+ for key in ("skills", "results"):
+ entries = payload.get(key)
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ if isinstance(entry, str):
+ names.append(entry)
+ continue
+ if not isinstance(entry, dict):
+ continue
+ for candidate in (entry.get("skill"), entry.get("name")):
+ if isinstance(candidate, str):
+ names.append(candidate)
+ break
+ return list(dict.fromkeys(name for name in names if name.strip()))
+
+
+def _result_backends(result: dict[str, Any], fallback: Optional[list[str]]) -> list[str]:
+ for key in ("selectedAgents", "agents", "removedAgents"):
+ raw_agents = result.get(key)
+ if not isinstance(raw_agents, list):
+ continue
+ resolved = [backend for agent in raw_agents if (backend := _backend_from_agent_ref(agent)) is not None]
+ if resolved:
+ return list(dict.fromkeys(resolved))
+ return _normalized_backends(fallback) or list(BACKEND_TO_AGENT)
+
+
+def _register_created_skill_policies(
+ names: list[str],
+ *,
+ scope: str,
+ project_dir: Optional[str],
+ backends: list[str],
+ user_context: Any,
+) -> None:
+ from storage import resource_access_service
+ from storage.db import get_cached_sqlite_engine
+
+ context = resolve_resource_access_context(user_context)
+ if not (context.is_remote and context.is_active_organization_member and context.subject):
+ return
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as connection:
+ for name in names:
+ for backend in backends:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="skill",
+ resource_id=skill_resource_id(
+ backend,
+ scope=scope,
+ project_dir=project_dir,
+ name=name,
+ ),
+ organization_id=context.organization_id,
+ owner_user_id=context.subject,
+ owner_email=context.email,
+ access_level="private",
+ created_by_user_id=context.subject,
+ updated_by_user_id=context.subject,
+ )
+
+
+async def _installed_skill_resource_ids(
+ askill_path: str,
+ name: str,
+ *,
+ scope: str,
+ project_dir: Optional[str],
+ backends: Optional[list[str]],
+) -> list[str]:
+ listing = await _run_askill(
+ askill_path,
+ ["list", *_list_scope_flag(scope), *_agent_flags(backends)],
+ cwd=_cwd_for(scope, project_dir),
+ )
+ raw_skills = listing.get("skills") if isinstance(listing.get("skills"), list) else []
+ target_name = _normalize_skill_name(name)
+ resource_ids: list[str] = []
+ for skill in raw_skills:
+ if not isinstance(skill, dict):
+ continue
+ try:
+ row_name = _normalize_skill_name(skill.get("name"))
+ except SkillsError:
+ continue
+ if row_name != target_name:
+ continue
+ row_scope = _skill_scope(skill, scope)
+ if row_scope is None:
+ continue
+ entries = _skill_backend_entries(skill, backends)
+ if not entries:
+ raise SkillAccessError()
+ for backend, _agent_index in entries:
+ resource_ids.append(
+ skill_resource_id(
+ backend,
+ scope=row_scope,
+ project_dir=project_dir,
+ name=str(skill["name"]),
+ )
+ )
+ return list(dict.fromkeys(resource_ids))
+
+
# --- public API -----------------------------------------------------------
@@ -186,6 +565,7 @@ async def list_skills(
scope: str = "all",
project_dir: Optional[str] = None,
backends: Optional[list[str]] = None,
+ user_context: Any = None,
) -> dict[str, Any]:
"""List installed skills. ``scope`` is ``all`` | ``global`` | ``project``.
@@ -194,7 +574,14 @@ async def list_skills(
source / installSource / timestamps natively (askill v0.1.13+).
"""
args = ["list", *_list_scope_flag(scope), *_agent_flags(backends)]
- return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
+ result = await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
+ return _filter_skill_listing(
+ result,
+ scope=scope,
+ project_dir=project_dir,
+ backends=backends,
+ user_context=user_context,
+ )
async def preview_source(
@@ -223,6 +610,7 @@ async def add_skill(
all_skills: bool = False,
skill: Optional[str] = None,
copy: bool = False,
+ user_context: Any = None,
) -> dict[str, Any]:
"""Install skill(s) from a source. Non-interactive (``-y``).
@@ -235,6 +623,25 @@ async def add_skill(
raise SkillsError("missing_source", "no source provided")
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "install scope must be global or project")
+ context = resolve_resource_access_context(user_context)
+ if not context.is_trusted_local:
+ _require_skill_create_access(context)
+ target_names = [skill] if skill else []
+ if not target_names:
+ preview = await _run_askill(askill_path, ["add", source, "--list"], cwd=_cwd_for(scope, project_dir))
+ if preview.get("ok"):
+ target_names = _skill_names_from_payload(preview)
+ for target_name in target_names:
+ _require_skill_management_access(
+ _resource_ids_for_skill_name(
+ target_name,
+ scope=scope,
+ project_dir=project_dir,
+ backends=backends,
+ ),
+ user_context=context,
+ allow_missing_policy=True,
+ )
args = ["add", source, *_target_scope_flag(scope), *_agent_flags(backends)]
if skill:
args += ["--skill", skill]
@@ -263,6 +670,18 @@ async def add_skill(
"message": "No matching skill was found in this source — nothing was installed.",
},
}
+ if result.get("ok"):
+ names = _skill_names_from_payload(result)
+ if not names and skill:
+ names = [skill]
+ if names:
+ _register_created_skill_policies(
+ names,
+ scope=scope,
+ project_dir=project_dir,
+ backends=_result_backends(result, backends),
+ user_context=context,
+ )
return result
@@ -273,6 +692,7 @@ async def remove_skill(
scope: str = "project",
project_dir: Optional[str] = None,
backends: Optional[list[str]] = None,
+ user_context: Any = None,
) -> dict[str, Any]:
"""Remove an installed skill, optionally from specific backends only.
@@ -282,6 +702,21 @@ async def remove_skill(
raise SkillsError("missing_skill", "no skill name provided")
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "remove scope must be global or project")
+ context = resolve_resource_access_context(user_context)
+ if not context.is_trusted_local:
+ resource_ids = await _installed_skill_resource_ids(
+ askill_path,
+ name,
+ scope=scope,
+ project_dir=project_dir,
+ backends=backends,
+ )
+ if resource_ids:
+ _require_skill_management_access(
+ resource_ids,
+ user_context=context,
+ allow_missing_policy=False,
+ )
args = ["remove", name, *_target_scope_flag(scope), *_agent_flags(backends)]
return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
@@ -320,9 +755,27 @@ async def update(
*,
scope: str = "project",
project_dir: Optional[str] = None,
+ user_context: Any = None,
) -> dict[str, Any]:
"""Update one installed skill. Maps to ``askill update <name> [-g] -y``."""
if not name:
raise SkillsError("missing_skill", "no skill name provided")
+ if scope not in ("global", "project"):
+ raise SkillsError("invalid_scope", "update scope must be global or project")
+ context = resolve_resource_access_context(user_context)
+ if not context.is_trusted_local:
+ resource_ids = await _installed_skill_resource_ids(
+ askill_path,
+ name,
+ scope=scope,
+ project_dir=project_dir,
+ backends=None,
+ )
+ if resource_ids:
+ _require_skill_management_access(
+ resource_ids,
+ user_context=context,
+ allow_missing_policy=False,
+ )
args = ["update", name, *_target_scope_flag(scope), "-y"]
return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
diff --git a/tests/test_skills_service.py b/tests/test_skills_service.py
index f52a53164..eb6506b07 100644
--- a/tests/test_skills_service.py
+++ b/tests/test_skills_service.py
@@ -12,6 +12,9 @@ import asyncio
import os
import pytest
+from storage import resource_access_service
+from storage.db import create_sqlite_engine
+from storage.models import metadata
from core.services import skills
@@ -32,6 +35,64 @@ class _Recorder:
return self.result
+class _SequenceRecorder(_Recorder):
+ def __init__(self, results):
+ super().__init__(None)
+ self.results = list(results)
+
+ async def __call__(self, askill_path, args, *, cwd=None, timeout=skills.DEFAULT_TIMEOUT):
+ self.calls.append({"path": askill_path, "args": list(args), "cwd": cwd})
+ return self.results.pop(0)
+
+
+def _organization_context(
+ subject: str,
+ *,
+ group_ids: frozenset[str] | None = frozenset({"group-engineering"}),
+ role: str = "member",
+) -> resource_access_service.ResourceUserContext:
+ return resource_access_service.ResourceUserContext(
+ subject=subject,
+ email=f"{subject}@example.com",
+ organization_id="org-1",
+ organization_member_id=f"member-{subject}",
+ organization_role=role,
+ group_ids=group_ids,
+ instance_access_source="organization_group",
+ is_remote=True,
+ )
+
+
+def _skills_engine(monkeypatch, tmp_path):
+ engine = create_sqlite_engine(tmp_path / "skills_acl.sqlite")
+ metadata.create_all(engine)
+ monkeypatch.setattr("storage.db.get_cached_sqlite_engine", lambda: engine)
+ return engine
+
+
+def _skill_row(name: str) -> dict:
+ return {
+ "name": name,
+ "scope": "global",
+ "path": f"/skills/{name}",
+ "agents": [{"id": "codex", "name": "Codex"}],
+ }
+
+
+def _seed_skill_policy(conn, name: str, *, access_level: str, group_ids: list[str] | None = None) -> str:
+ resource_id = skills.skill_resource_id("codex", scope="global", project_dir=None, name=name)
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="skill",
+ resource_id=resource_id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level=access_level,
+ group_ids=group_ids,
+ )
+ return resource_id
+
+
def test_list_global_uses_g_no_cwd(monkeypatch):
rec = _Recorder({"ok": True, "skills": []})
monkeypatch.setattr(skills, "_run_askill", rec)
@@ -153,6 +214,164 @@ def test_update_one_skill(monkeypatch):
assert rec.calls[1]["args"] == ["update", "pdf-tools", "-g", "-y"]
+def test_skill_resource_id_is_stable_and_backend_scoped(tmp_path) -> None:
+ global_id = skills.skill_resource_id("codex", scope="global", project_dir=None, name="Release Tools")
+ project_id = skills.skill_resource_id(
+ "codex",
+ scope="project",
+ project_dir=str(tmp_path / "project"),
+ name="Release Tools",
+ )
+
+ assert global_id == "codex:global:global:release-tools"
+ assert project_id.startswith("codex:project:project-")
+ assert project_id.endswith(":release-tools")
+ assert project_id == skills.skill_resource_id(
+ "codex",
+ scope="project",
+ project_dir=str(tmp_path / "project"),
+ name="Release Tools",
+ )
+
+
+def test_list_skills_filters_private_public_scope_and_missing_group_context(monkeypatch, tmp_path) -> None:
+ engine = _skills_engine(monkeypatch, tmp_path)
+ try:
+ with engine.begin() as connection:
+ _seed_skill_policy(connection, "private-skill", access_level="private")
+ _seed_skill_policy(connection, "public-skill", access_level="public")
+ _seed_skill_policy(
+ connection,
+ "scoped-skill",
+ access_level="scope",
+ group_ids=["group-engineering"],
+ )
+
+ rec = _Recorder(
+ {
+ "ok": True,
+ "summary": {"global": 3, "project": 0},
+ "skills": [_skill_row("private-skill"), _skill_row("public-skill"), _skill_row("scoped-skill")],
+ }
+ )
+ monkeypatch.setattr(skills, "_run_askill", rec)
+
+ owner = _run(skills.list_skills("askill", scope="global", user_context=_organization_context("owner-1")))
+ member = _run(skills.list_skills("askill", scope="global", user_context=_organization_context("member-1")))
+ missing_groups = _run(
+ skills.list_skills("askill", scope="global", user_context=_organization_context("member-2", group_ids=None))
+ )
+ finally:
+ engine.dispose()
+
+ assert [skill["name"] for skill in owner["skills"]] == ["private-skill", "public-skill", "scoped-skill"]
+ assert [skill["name"] for skill in member["skills"]] == ["public-skill", "scoped-skill"]
+ assert [skill["name"] for skill in missing_groups["skills"]] == ["public-skill"]
+ assert missing_groups["summary"] == {"global": 1, "project": 0}
+
+
+def test_remote_skill_mutations_require_owner_or_organization_admin(monkeypatch, tmp_path) -> None:
+ engine = _skills_engine(monkeypatch, tmp_path)
+ listing = {"ok": True, "skills": [_skill_row("private-skill")]}
+ try:
+ with engine.begin() as connection:
+ _seed_skill_policy(connection, "private-skill", access_level="private")
+
+ member_recorder = _SequenceRecorder([listing])
+ monkeypatch.setattr(skills, "_run_askill", member_recorder)
+ with pytest.raises(skills.SkillAccessError) as member_error:
+ _run(
+ skills.remove_skill(
+ "askill",
+ "private-skill",
+ scope="global",
+ user_context=_organization_context("member-1"),
+ )
+ )
+ assert member_error.value.code == "resource_access_forbidden"
+ assert [call["args"] for call in member_recorder.calls] == [["list", "-g"]]
+
+ owner_recorder = _SequenceRecorder([listing, {"ok": True}])
+ monkeypatch.setattr(skills, "_run_askill", owner_recorder)
+ assert _run(
+ skills.remove_skill(
+ "askill",
+ "private-skill",
+ scope="global",
+ user_context=_organization_context("owner-1"),
+ )
+ ) == {"ok": True}
+ assert [call["args"] for call in owner_recorder.calls] == [["list", "-g"], ["remove", "private-skill", "-g"]]
+
+ admin_recorder = _SequenceRecorder([listing, {"ok": True}])
+ monkeypatch.setattr(skills, "_run_askill", admin_recorder)
+ assert _run(
+ skills.update(
+ "askill",
+ "private-skill",
+ scope="global",
+ user_context=_organization_context("member-2", role="admin"),
+ )
+ ) == {"ok": True}
+ assert [call["args"] for call in admin_recorder.calls] == [["list", "-g"], ["update", "private-skill", "-g", "-y"]]
+
+ add_recorder = _Recorder({"ok": True, "action": "install", "summary": {"skills": 1}})
+ monkeypatch.setattr(skills, "_run_askill", add_recorder)
+ with pytest.raises(skills.SkillAccessError):
+ _run(
+ skills.add_skill(
+ "askill",
+ "gh:owner/repo",
+ scope="global",
+ skill="private-skill",
+ backends=["codex"],
+ user_context=_organization_context("member-1"),
+ )
+ )
+ assert add_recorder.calls == []
+ finally:
+ engine.dispose()
+
+
+def test_remote_skill_add_registers_private_policy(monkeypatch, tmp_path) -> None:
+ engine = _skills_engine(monkeypatch, tmp_path)
+ try:
+ rec = _Recorder(
+ {
+ "ok": True,
+ "action": "install",
+ "summary": {"skills": 1},
+ "selectedAgents": ["codex"],
+ "results": [{"skill": "new-skill", "success": True}],
+ }
+ )
+ monkeypatch.setattr(skills, "_run_askill", rec)
+
+ result = _run(
+ skills.add_skill(
+ "askill",
+ "gh:owner/repo",
+ scope="global",
+ skill="new-skill",
+ backends=["codex"],
+ user_context=_organization_context("member-1"),
+ )
+ )
+ with engine.connect() as connection:
+ policy = resource_access_service.get_resource_policy(
+ "skill",
+ skills.skill_resource_id("codex", scope="global", project_dir=None, name="new-skill"),
+ connection=connection,
+ )
+ finally:
+ engine.dispose()
+
+ assert result["ok"] is True
+ assert policy is not None
+ assert policy["owner_user_id"] == "member-1"
+ assert policy["access_level"] == "private"
+
+
def test_invalid_backend_raises(monkeypatch):
monkeypatch.setattr(skills, "_run_askill", _Recorder({"ok": True}))
with pytest.raises(skills.SkillsError) as info:
diff --git a/vibe/api.py b/vibe/api.py
index c0359aa00..abac90531 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -11305,10 +11305,21 @@ async def _skills_guarded(call):
async def list_skills(
- *, scope: str = "all", project_dir: Optional[str] = None, backends: Optional[List[str]] = None
+ *,
+ scope: str = "all",
+ project_dir: Optional[str] = None,
+ backends: Optional[List[str]] = None,
+ user_context: Any = None,
) -> dict:
+ context = resolve_resource_access_context() if user_context is None else user_context
return await _skills_guarded(
- lambda askill, svc: svc.list_skills(askill, scope=scope, project_dir=project_dir, backends=backends)
+ lambda askill, svc: svc.list_skills(
+ askill,
+ scope=scope,
+ project_dir=project_dir,
+ backends=backends,
+ user_context=context,
+ )
)
@@ -11325,7 +11336,9 @@ async def add_skill(
all_skills: bool = False,
skill: Optional[str] = None,
copy: bool = False,
+ user_context: Any = None,
) -> dict:
+ context = resolve_resource_access_context() if user_context is None else user_context
return await _skills_guarded(
lambda askill, svc: svc.add_skill(
askill,
@@ -11336,15 +11349,29 @@ async def add_skill(
all_skills=all_skills,
skill=skill,
copy=copy,
+ user_context=context,
)
)
async def remove_skill(
- name: str, *, scope: str = "project", project_dir: Optional[str] = None, backends: Optional[List[str]] = None
+ name: str,
+ *,
+ scope: str = "project",
+ project_dir: Optional[str] = None,
+ backends: Optional[List[str]] = None,
+ user_context: Any = None,
) -> dict:
+ context = resolve_resource_access_context() if user_context is None else user_context
return await _skills_guarded(
- lambda askill, svc: svc.remove_skill(askill, name, scope=scope, project_dir=project_dir, backends=backends)
+ lambda askill, svc: svc.remove_skill(
+ askill,
+ name,
+ scope=scope,
+ project_dir=project_dir,
+ backends=backends,
+ user_context=context,
+ )
)
@@ -11356,8 +11383,23 @@ async def check_skills(*, scope: str = "project", project_dir: Optional[str] = N
return await _skills_guarded(lambda askill, svc: svc.check(askill, scope=scope, project_dir=project_dir))
-async def update_skill(name: str, *, scope: str = "project", project_dir: Optional[str] = None) -> dict:
- return await _skills_guarded(lambda askill, svc: svc.update(askill, name, scope=scope, project_dir=project_dir))
+async def update_skill(
+ name: str,
+ *,
+ scope: str = "project",
+ project_dir: Optional[str] = None,
+ user_context: Any = None,
+) -> dict:
+ context = resolve_resource_access_context() if user_context is None else user_context
+ return await _skills_guarded(
+ lambda askill, svc: svc.update(
+ askill,
+ name,
+ scope=scope,
+ project_dir=project_dir,
+ user_context=context,
+ )
+ )
async def upload_skill_zip(payload: dict, *, project_dir: Optional[str] = None) -> dict: