feat: services/skills — agenci: przypięcia, wersje, publikacja, import i eksport (E2.3, 3.5)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4a356b6d94
commit
dee27d91ce
+1
-1
@@ -17,7 +17,7 @@
|
||||
- [x] 3.2 Utwórz `backend/app/services/skills.py` (docstring opisujący świadome odstępstwo od „authz jedynym autorytetem”): `visible_to(db, user)` (właściciel ∪ `scope=firm`; cudze osobiste → `NotFoundError`), lista, odczyt, tworzenie skilla z wersją 1 i plikami, nowa wersja (zamrożenie, `n+1`, `content_sha256`), archiwizacja; każdy zapis przez `audit.record` (`skill.create`, `skill.version`, `skill.archive`). Testy jednostkowe na logice czystej (np. kolejny `n`, wybór akcji audytu, odmowa dla cudzego osobistego) bez bazy tam, gdzie to możliwe. Gotowe gdy: bramka zielona, w routerach brak nowego SQL, funkcje istnieją z docstringami.
|
||||
- [x] 3.3 W `services/skills.py` dodaj publikację: przy `approval` → `publish_request` na konkretną wersję, `current_version_id` skilla firmowego rusza dopiero po zgodzie (także dla każdej kolejnej wersji), przy `direct` → od razu; `approve`/`decline` dla administratora; lista oczekujących dla administratora (tylko tu administrator widzi cudze osobiste). Audyt `skill.publish_request`/`skill.publish_approve`/`skill.publish_decline`. Gotowe gdy: bramka zielona i funkcje są wołane z jednego miejsca rozstrzygającego ustawienie `skills_firm_publish`.
|
||||
- [x] 3.4 W `services/skills.py` dodaj import (przez `skill_pack.read_pack`; kopia osobista, `origin=imported`, `provenance`, wersja 1, kolizja sluga → `-2`, ta sama suma → odpowiedź „już masz, dodać jako wersję?” bez zapisu, lista rzeczy zapisanych tylko jako informacja) i eksport (`build_pack`; własne zawsze, firmowe wg `skills_firm_export`). Audyt `skill.import`/`skill.export` z sumą paczki, bez treści. Gotowe gdy: bramka zielona, test jednostkowy funkcji wyboru sluga (`x`, `x-2`, `x-3`) przechodzi.
|
||||
- [ ] 3.5 W `services/skills.py` dodaj agentów: tworzenie, nowa wersja z listą `skill_version_id` (tylko wersje widoczne dla osoby; agent firmowy tylko wersje skilli firmowych — inaczej `ValidationError`), archiwizacja, publikacja (ta sama ścieżka T1 co skille), eksport agenta z przypiętymi skillami (T2 obejmuje też firmowe skille w paczce), import paczki agenta. Audyt `agent.*` analogicznie do `skill.*`. Gotowe gdy: bramka zielona i reguła „agent firmowy tylko ze skillami firmowymi” jest w jednej funkcji z testem jednostkowym.
|
||||
- [x] 3.5 W `services/skills.py` dodaj agentów: tworzenie, nowa wersja z listą `skill_version_id` (tylko wersje widoczne dla osoby; agent firmowy tylko wersje skilli firmowych — inaczej `ValidationError`), archiwizacja, publikacja (ta sama ścieżka T1 co skille), eksport agenta z przypiętymi skillami (T2 obejmuje też firmowe skille w paczce), import paczki agenta. Audyt `agent.*` analogicznie do `skill.*`. Gotowe gdy: bramka zielona i reguła „agent firmowy tylko ze skillami firmowymi” jest w jednej funkcji z testem jednostkowym.
|
||||
|
||||
## Etap 4: API (E2.5)
|
||||
- [ ] 4.1 Utwórz `backend/app/routers/skills.py` (rejestracja w `main.py` jak pozostałe routery, schematy w `schemas.py`): `GET/POST /skills`, `GET /skills/{id}`, `POST /skills/{id}/versions` (JSON z treścią i plikami base64, limit łączny 10 MB), `GET /skills/{id}/versions/{n}`, `POST /skills/{id}/archive`, `POST /skills/{id}/publish`, `GET /skills/{id}/export` (`application/zip`), `POST /skills/import` (surowe ciało `application/zip`, `?filename=`, limit 10 MB czytany strumieniowo, bez `python-multipart`). Router bez SQL. Gotowe gdy: bramka zielona i test jednostkowy (np. przez `app.routes`) potwierdza, że wszystkie te trasy są zarejestrowane pod `/api/v1`.
|
||||
|
||||
@@ -21,3 +21,5 @@
|
||||
- Decyzje bez specu (drobne): przy `direct` audyt `skill.publish_approve` z detalem „direct” (spec nie ma osobnej akcji); zatwierdzenie wersji starszej niż aktualna firmowa = 409. Dla 3.5: `_resolve` i `_request_out` obsługują na razie tylko `kind=skill` (agent → NotImplementedError).
|
||||
- 3.4: `import_skills(data, filename, add_version=False)` — każdy SKILL.md paczki = osobny skill osobisty (`origin=imported`, v1, `free_slug` x/x-2/x-3 ≤64), `provenance` {filename, path, pack_sha256, content_sha256 źródła}; duplikat = własny AKTYWNY skill z wersją o tej sumie (`content_sha256` albo `provenance->>content_sha256`, bo `name`=slug i domyślna licencja zmieniają sumę) → `status: duplicate` bez zapisu, `add_version=True` dokłada wersję. Zwraca `info_only` per skill i `ignored` (pliki spoza folderów skilli, np. commands/ wtyczki). Nowe kody `pack_no_skill`, `pack_is_agent` (agent → 3.5). `may_export` (T2, czysta, do reużycia przez agenta) + `export_skill(n=None → aktualna)` → (nazwa, ZIP). Audyt z sumą paczki.
|
||||
- Bramka: `tests/test_deploy_init_add.py` wiesza się lokalnie (skrypty powłoki) — pełny zestaw zielony bez niego; venv: `projects/lw-venv-skille`. Ruff na całym repo ma 127 starych błędów, nowe pliki czyste.
|
||||
- 3.5: agenci w `services/skills.py` — `may_pin` (JEDNA reguła: agent firmowy = tylko AKTUALNA opublikowana wersja firmowego skilla; osobisty = wersja czytelna dla autora) + `_check_pins` (ValidationError `code=agent_pin_refused`, `skill_version_ids`); create/new_agent_version (None = przenieś, przypięcia sprawdzane ponownie)/archive/publish_agent (przez `_publish`, pinezki firmowe sprawdzane też przy zatwierdzeniu)/export_agent (T2 na agencie i każdym przypiętym skillu, foldery `free_slug`)/import_agent (skill o tej samej sumie przypinany bez kopii, reszta przez wydzielone `_import_one`). Nowe kody `pack_not_agent`, `pack_agent_kind` (tylko `assistant`).
|
||||
- Luka do decyzji przy konsoli/PR: model `agent` nie ma kolumny `description` — eksport wpisuje nazwę jako description agent.md, import gubi opis. Odstępstwo: starsza zatwierdzona wersja firmowego skilla nie da się przypiąć do agenta firmowego (ponytail w `may_pin`).
|
||||
|
||||
@@ -67,6 +67,10 @@ MESSAGES = {
|
||||
"pack_manifest_mismatch": ("Pliki paczki nie zgadzają się z sumami w atrium-pack.json.",
|
||||
"The pack's files do not match the sums in atrium-pack.json."),
|
||||
"pack_no_skill": ("Paczka nie zawiera pliku SKILL.md.", "The pack contains no SKILL.md."),
|
||||
"pack_not_agent": ("Paczka nie zawiera pliku agent.md — zaimportuj ją jako skill.",
|
||||
"The pack contains no agent.md — import it as a skill."),
|
||||
"pack_agent_kind": ("Ten rodzaj agenta nie jest obsługiwany (tylko assistant).",
|
||||
"This kind of agent is not supported (assistant only)."),
|
||||
"pack_is_agent": ("To paczka agenta — zaimportuj ją jako agenta.",
|
||||
"This is an agent pack — import it as an agent."),
|
||||
"skill_not_utf8": ("SKILL.md albo agent.md nie jest zapisany w UTF-8.",
|
||||
|
||||
+345
-33
@@ -26,8 +26,10 @@ its editors until then.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
@@ -35,9 +37,25 @@ from typing import Any
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..enums import CatalogStatus, PublishKind, PublishRequestStatus, SkillOrigin, SkillScope
|
||||
from ..errors import AuthorizationError, ConflictError, NotFoundError
|
||||
from ..models import AppUser, PublishRequest, Skill, SkillFile, SkillVersion
|
||||
from ..enums import (
|
||||
AgentKind,
|
||||
CatalogStatus,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
SkillScope,
|
||||
)
|
||||
from ..errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
|
||||
from ..models import (
|
||||
Agent,
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
AppUser,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
from . import audit, settings, skill_pack
|
||||
from .marketplace import _clean_note
|
||||
from .skill_pack import PackRejected, SkillContent
|
||||
@@ -348,7 +366,8 @@ def _resolve(db: DbSession, req: PublishRequest):
|
||||
if req.kind == PublishKind.skill:
|
||||
version = db.get(SkillVersion, req.version_id)
|
||||
return db.get(Skill, version.skill_id), version
|
||||
raise NotImplementedError(req.kind) # agents: services 3.5
|
||||
version = db.get(AgentVersion, req.version_id)
|
||||
return db.get(Agent, version.agent_id), version
|
||||
|
||||
|
||||
def refuses_older(item, current_n: int | None, version) -> bool:
|
||||
@@ -374,6 +393,9 @@ def decide_publish(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, appr
|
||||
current = db.get(type(version), item.current_version_id) if item.current_version_id else None
|
||||
if refuses_older(item, current.n if current else None, version):
|
||||
raise ConflictError("A newer version is already published; decline this one.")
|
||||
if req.kind == PublishKind.agent:
|
||||
# Asked for while the pins were checked; asked again, because approving is what exposes them.
|
||||
_check_pins(db, actor, SkillScope.firm, _pinned_ids(db, version.id))
|
||||
_make_current(item, version)
|
||||
req.status = (PublishRequestStatus.approved if approve else PublishRequestStatus.declined).value
|
||||
req.decided_by = actor.id
|
||||
@@ -392,15 +414,20 @@ def _request_out(db: DbSession, req: PublishRequest) -> dict:
|
||||
requester = db.get(AppUser, req.requested_by)
|
||||
base = None
|
||||
if item.scope == SkillScope.firm and item.current_version_id not in (None, version.id):
|
||||
current = db.get(SkillVersion, item.current_version_id)
|
||||
base = version_out(current, _files(db, current.id))
|
||||
base = _full_version(db, req.kind, db.get(type(version), item.current_version_id))
|
||||
return {"id": req.id, "kind": req.kind, "status": req.status, "note": req.note,
|
||||
"created_at": req.created_at, "decided_at": req.decided_at,
|
||||
"requested_by": {"id": requester.id, "email": requester.email,
|
||||
"full_name": requester.full_name},
|
||||
"item": {"id": item.id, "slug": item.slug, "name": item.name, "scope": item.scope,
|
||||
"status": item.status},
|
||||
"version": version_out(version, _files(db, version.id)), "base": base}
|
||||
"item": {"id": item.id, "slug": getattr(item, "slug", None), "name": item.name,
|
||||
"scope": item.scope, "status": item.status},
|
||||
"version": _full_version(db, req.kind, version), "base": base}
|
||||
|
||||
|
||||
def _full_version(db: DbSession, kind: str, version) -> dict:
|
||||
if kind == PublishKind.skill:
|
||||
return version_out(version, _files(db, version.id))
|
||||
return agent_version_out(version, _pins(db, version.id))
|
||||
|
||||
|
||||
def pending_publish_requests(db: DbSession, actor: AppUser) -> list[dict]:
|
||||
@@ -439,6 +466,36 @@ def _already_have(db: DbSession, actor: AppUser, sha: str) -> SkillVersion | Non
|
||||
.order_by(SkillVersion.created_at.desc()).limit(1))
|
||||
|
||||
|
||||
def _import_one(db: DbSession, actor: AppUser, doc, content: SkillContent, sha: str,
|
||||
match: SkillVersion | None, taken: set, *, filename: str | None, pack_sha: str,
|
||||
ip: str | None) -> tuple[Skill, SkillVersion]:
|
||||
"""One SKILL.md of a pack: a new version of `match`'s skill, or a new personal skill."""
|
||||
provenance = {"filename": filename, "path": doc.path, "pack_sha256": pack_sha,
|
||||
"content_sha256": sha}
|
||||
fields = dict(description=doc.description, body=doc.body,
|
||||
license=str(doc.frontmatter.get("license") or DEFAULT_LICENSE),
|
||||
meta={k: v for k, v in doc.frontmatter.items() if k not in _OWN_KEYS},
|
||||
files=content.files, provenance=provenance)
|
||||
if match is not None:
|
||||
skill = db.get(Skill, match.skill_id)
|
||||
latest = db.scalar(select(SkillVersion.n).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = _add_version(db, actor, skill, next_n(latest), **fields)
|
||||
else:
|
||||
slug = free_slug(taken, doc.name)
|
||||
taken.add(slug)
|
||||
skill = Skill(slug=slug, name=doc.name, owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, origin=SkillOrigin.imported)
|
||||
db.add(skill)
|
||||
db.flush()
|
||||
version = _add_version(db, actor, skill, 1, **fields)
|
||||
# The pack's own sum, so the audit row names the file that came in; never its content.
|
||||
audit.record(db, action="skill.import", entity_type="skill", entity_id=skill.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{skill.slug} v{version.n} {version.content_sha256} pack {pack_sha}")
|
||||
return skill, version
|
||||
|
||||
|
||||
def import_skills(db: DbSession, actor: AppUser, data: bytes, filename: str | None = None, *,
|
||||
add_version: bool = False, ip: str | None) -> dict:
|
||||
"""Every SKILL.md of an uploaded pack becomes a personal copy of `actor`'s: `origin=imported`,
|
||||
@@ -473,30 +530,8 @@ def import_skills(db: DbSession, actor: AppUser, data: bytes, filename: str | No
|
||||
taken = set(db.scalars(select(Skill.slug).where(Skill.owner_id == actor.id)))
|
||||
out = []
|
||||
for doc, content, sha in found:
|
||||
provenance = {"filename": filename, "path": doc.path, "pack_sha256": pack_sha,
|
||||
"content_sha256": sha}
|
||||
fields = dict(description=doc.description, body=doc.body,
|
||||
license=str(doc.frontmatter.get("license") or DEFAULT_LICENSE),
|
||||
meta={k: v for k, v in doc.frontmatter.items() if k not in _OWN_KEYS},
|
||||
files=content.files, provenance=provenance)
|
||||
match = matches[sha]
|
||||
if match is not None:
|
||||
skill = db.get(Skill, match.skill_id)
|
||||
latest = db.scalar(select(SkillVersion.n).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = _add_version(db, actor, skill, next_n(latest), **fields)
|
||||
else:
|
||||
slug = free_slug(taken, doc.name)
|
||||
taken.add(slug)
|
||||
skill = Skill(slug=slug, name=doc.name, owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, origin=SkillOrigin.imported)
|
||||
db.add(skill)
|
||||
db.flush()
|
||||
version = _add_version(db, actor, skill, 1, **fields)
|
||||
# The pack's own sum, so the audit row names the file that came in; never its content.
|
||||
audit.record(db, action="skill.import", entity_type="skill", entity_id=skill.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{skill.slug} v{version.n} {version.content_sha256} pack {pack_sha}")
|
||||
skill, version = _import_one(db, actor, doc, content, sha, matches[sha], taken,
|
||||
filename=filename, pack_sha=pack_sha, ip=ip)
|
||||
out.append({"path": doc.path, "content_sha256": version.content_sha256,
|
||||
"info_only": doc.info_only, "skill": skill_out(actor, skill), "n": version.n})
|
||||
return {"status": "imported", "ignored": ignored, "skills": out}
|
||||
@@ -524,3 +559,280 @@ def export_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | No
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{skill.slug} v{version.n} {version.content_sha256} pack {_sha(data)}")
|
||||
return f"{skill.slug}-v{version.n}.zip", data
|
||||
|
||||
|
||||
# ---- agents --------------------------------------------------------------------------------------
|
||||
# The same rules as skills — visibility (`can_see`/`can_edit`), frozen versions, publication through
|
||||
# `_publish`, T2 through `may_export` — plus one of their own: what a version may pin (`may_pin`).
|
||||
# ponytail: an agent has no description column; an exported agent.md carries its name there and an
|
||||
# imported one's description is not kept. Add a column (own revision) when the console needs one.
|
||||
|
||||
def may_pin(user: AppUser, agent_scope: str, skill: Skill | None, version: SkillVersion | None) -> bool:
|
||||
"""THE pinning rule. A firm agent pins only the firm's published skill versions (what everybody
|
||||
already reads), a personal one any skill version its author may read. Anything else would let
|
||||
an agent show people what they may not see."""
|
||||
if skill is None or version is None or version.skill_id != skill.id:
|
||||
return False
|
||||
if agent_scope == SkillScope.firm:
|
||||
# ponytail: only the CURRENT published version — an older approved one is refused too;
|
||||
# remembering which versions were approved would lift that, if repinning annoys.
|
||||
return skill.scope == SkillScope.firm and version.id == skill.current_version_id
|
||||
return can_see(user, skill) and bool(readable_version_ids(user, skill, [version.id]))
|
||||
|
||||
|
||||
def _check_pins(db: DbSession, user: AppUser, agent_scope: str, ids) -> list[SkillVersion]:
|
||||
"""`ids` as versions, in order, or a ValidationError naming every one `may_pin` refuses."""
|
||||
ids = list(ids)
|
||||
if len(set(ids)) != len(ids):
|
||||
raise ValidationError("A skill version is pinned twice.")
|
||||
versions = [db.get(SkillVersion, i) for i in ids]
|
||||
refused = [str(i) for i, v in zip(ids, versions, strict=True)
|
||||
if not may_pin(user, agent_scope, v and db.get(Skill, v.skill_id), v)]
|
||||
if refused:
|
||||
why = ("A firm agent pins only the firm's published skill versions."
|
||||
if agent_scope == SkillScope.firm else "Skill version not found.")
|
||||
raise ValidationError(why, extra={"code": "agent_pin_refused",
|
||||
"skill_version_ids": refused})
|
||||
return versions
|
||||
|
||||
|
||||
def _pinned_ids(db: DbSession, agent_version_id: uuid.UUID) -> list[uuid.UUID]:
|
||||
return list(db.scalars(select(AgentVersionSkill.skill_version_id)
|
||||
.where(AgentVersionSkill.agent_version_id == agent_version_id)
|
||||
.order_by(AgentVersionSkill.position)))
|
||||
|
||||
|
||||
def _pins(db: DbSession, agent_version_id: uuid.UUID) -> list[tuple[Skill, SkillVersion]]:
|
||||
out = []
|
||||
for vid in _pinned_ids(db, agent_version_id):
|
||||
version = db.get(SkillVersion, vid)
|
||||
out.append((db.get(Skill, version.skill_id), version))
|
||||
return out
|
||||
|
||||
|
||||
def agent_out(user: AppUser, agent: Agent) -> dict[str, Any]:
|
||||
return {"id": agent.id, "name": agent.name, "owner_id": agent.owner_id, "scope": agent.scope,
|
||||
"status": agent.status, "kind": agent.kind,
|
||||
"current_version_id": agent.current_version_id, "mine": agent.owner_id == user.id,
|
||||
"editable": can_edit(user, agent)}
|
||||
|
||||
|
||||
def agent_version_out(version: AgentVersion, pins: list[tuple[Skill, SkillVersion]]) -> dict:
|
||||
"""A version with its pins named; an archived skill stays pinned, and says so."""
|
||||
return {"id": version.id, "n": version.n, "instructions": version.instructions_md,
|
||||
"model_policy": version.model_policy, "tools_requested": list(version.tools_requested),
|
||||
"created_at": version.created_at, "created_by": version.created_by,
|
||||
"skills": [{"skill_id": s.id, "slug": s.slug, "name": s.name, "scope": s.scope,
|
||||
"status": s.status, "skill_version_id": v.id, "n": v.n,
|
||||
"description": v.description} for s, v in pins]}
|
||||
|
||||
|
||||
def _get_agent(db: DbSession, user: AppUser, agent_id: uuid.UUID) -> Agent:
|
||||
agent = db.get(Agent, agent_id)
|
||||
if agent is None or not can_see(user, agent):
|
||||
raise NotFoundError("Agent not found.")
|
||||
return agent
|
||||
|
||||
|
||||
def _get_agent_editable(db: DbSession, user: AppUser, agent_id: uuid.UUID) -> Agent:
|
||||
agent = _get_agent(db, user, agent_id)
|
||||
if not can_edit(user, agent):
|
||||
raise AuthorizationError("Only the owner or an administrator may change a firm agent.")
|
||||
return agent
|
||||
|
||||
|
||||
def _agent_version(db: DbSession, agent: Agent, n: int | None) -> AgentVersion | None:
|
||||
query = select(AgentVersion).where(AgentVersion.agent_id == agent.id)
|
||||
return db.scalar(query.where(AgentVersion.n == n) if n is not None
|
||||
else query.order_by(AgentVersion.n.desc()).limit(1))
|
||||
|
||||
|
||||
def _audit_agent(db: DbSession, actor: AppUser, action: str, agent: Agent,
|
||||
version: AgentVersion | None = None, extra: str = "", *, ip: str | None) -> None:
|
||||
detail = agent.name if version is None else f"{agent.name} v{version.n}"
|
||||
audit.record(db, action=action, entity_type="agent", entity_id=agent.id, actor_id=actor.id,
|
||||
detail=f"{detail} {extra}".strip(), ip=ip)
|
||||
|
||||
|
||||
def _add_agent_version(db: DbSession, actor: AppUser, agent: Agent, n: int, *, instructions: str,
|
||||
model_policy: dict | None, tools, skill_version_ids) -> AgentVersion:
|
||||
pinned = _check_pins(db, actor, agent.scope, skill_version_ids)
|
||||
version = AgentVersion(agent_id=agent.id, n=n, instructions_md=instructions,
|
||||
model_policy=model_policy, tools_requested=list(tools),
|
||||
created_by=actor.id)
|
||||
db.add(version)
|
||||
db.flush()
|
||||
for position, sv in enumerate(pinned):
|
||||
db.add(AgentVersionSkill(agent_version_id=version.id, skill_version_id=sv.id,
|
||||
position=position))
|
||||
if agent.scope == SkillScope.personal:
|
||||
agent.current_version_id = version.id
|
||||
# A firm agent's current version moves only through publication, as a firm skill's does.
|
||||
db.flush()
|
||||
return version
|
||||
|
||||
|
||||
def list_agents(db: DbSession, user: AppUser) -> list[dict]:
|
||||
"""Own agents and firm ones — `can_see` as SQL, the same rule `visible_to` applies to skills."""
|
||||
rows = db.scalars(select(Agent).where(or_(Agent.owner_id == user.id,
|
||||
Agent.scope == SkillScope.firm))
|
||||
.order_by(Agent.name, Agent.id))
|
||||
return [agent_out(user, a) for a in rows]
|
||||
|
||||
|
||||
def get_agent(db: DbSession, user: AppUser, agent_id: uuid.UUID) -> dict:
|
||||
"""The agent, its versions (an editor sees all, anybody else the current one) and the current
|
||||
one in full."""
|
||||
agent = _get_agent(db, user, agent_id)
|
||||
versions = list(db.scalars(select(AgentVersion).where(AgentVersion.agent_id == agent.id)
|
||||
.order_by(AgentVersion.n.desc())))
|
||||
if not can_edit(user, agent):
|
||||
versions = [v for v in versions if v.id == agent.current_version_id]
|
||||
current = next((v for v in versions if v.id == agent.current_version_id), None)
|
||||
return {**agent_out(user, agent),
|
||||
"versions": [{"n": v.n, "id": v.id, "created_at": v.created_at} for v in versions],
|
||||
"current": agent_version_out(current, _pins(db, current.id)) if current else None}
|
||||
|
||||
|
||||
def create_agent(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | None) -> dict:
|
||||
"""A personal agent with its version 1. `fields`: name, instructions, and optionally
|
||||
model_policy (a hint), tools (requested, never granted — D3) and skill_version_ids."""
|
||||
agent = Agent(name=fields["name"], owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, kind=AgentKind.assistant)
|
||||
db.add(agent)
|
||||
db.flush()
|
||||
version = _add_agent_version(db, actor, agent, 1, instructions=fields["instructions"],
|
||||
model_policy=fields.get("model_policy"),
|
||||
tools=fields.get("tools") or [],
|
||||
skill_version_ids=fields.get("skill_version_ids") or [])
|
||||
_audit_agent(db, actor, "agent.create", agent, version, ip=ip)
|
||||
return agent_out(actor, agent)
|
||||
|
||||
|
||||
def new_agent_version(db: DbSession, actor: AppUser, agent_id: uuid.UUID, fields: Mapping, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n + 1`; a field that is None is carried over from the newest version, the pins
|
||||
included (`[]` unpins everything). Carried-over pins are checked again: what a firm agent may
|
||||
pin is decided now, not when the list was first made."""
|
||||
agent = _get_agent_editable(db, actor, agent_id)
|
||||
if agent.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived agent takes no new versions.")
|
||||
latest = _agent_version(db, agent, None)
|
||||
if fields.get("name"):
|
||||
agent.name = fields["name"]
|
||||
pins = fields.get("skill_version_ids")
|
||||
version = _add_agent_version(
|
||||
db, actor, agent, next_n(latest.n),
|
||||
instructions=(fields["instructions"] if fields.get("instructions") is not None
|
||||
else latest.instructions_md),
|
||||
model_policy=(fields["model_policy"] if fields.get("model_policy") is not None
|
||||
else latest.model_policy),
|
||||
tools=fields["tools"] if fields.get("tools") is not None else latest.tools_requested,
|
||||
skill_version_ids=pins if pins is not None else _pinned_ids(db, latest.id))
|
||||
_audit_agent(db, actor, "agent.version", agent, version, ip=ip)
|
||||
return agent_version_out(version, _pins(db, version.id))
|
||||
|
||||
|
||||
def archive_agent(db: DbSession, actor: AppUser, agent_id: uuid.UUID, *, ip: str | None) -> dict:
|
||||
"""Archived, not deleted — like a skill."""
|
||||
agent = _get_agent_editable(db, actor, agent_id)
|
||||
if agent.status != CatalogStatus.archived:
|
||||
agent.status = CatalogStatus.archived
|
||||
db.flush()
|
||||
_audit_agent(db, actor, "agent.archive", agent, ip=ip)
|
||||
return agent_out(actor, agent)
|
||||
|
||||
|
||||
def publish_agent(db: DbSession, actor: AppUser, agent_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n` (default: the newest) to the firm, through the same T1 path as a skill. Its pins
|
||||
must already be the firm's: a firm agent never carries somebody's personal skill."""
|
||||
agent = _get_agent_editable(db, actor, agent_id)
|
||||
version = _agent_version(db, agent, n)
|
||||
if version is None:
|
||||
raise NotFoundError("Version not found.")
|
||||
_check_pins(db, actor, SkillScope.firm, _pinned_ids(db, version.id))
|
||||
return {**_publish(db, actor, PublishKind.agent, agent, version, ip=ip),
|
||||
"agent": agent_out(actor, agent)}
|
||||
|
||||
|
||||
def _slugish(name: str) -> str:
|
||||
"""A file name out of an agent's free-text name."""
|
||||
plain = unicodedata.normalize("NFKD", name.lower().replace("ł", "l")) # ó -> o, ł has no NFKD
|
||||
out = "-".join("".join(c if c.isascii() and c.isalnum() else " " if not unicodedata.combining(c)
|
||||
else "" for c in plain).split())
|
||||
return out[: skill_pack.MAX_NAME] or "agent"
|
||||
|
||||
|
||||
def export_agent(db: DbSession, actor: AppUser, agent_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> tuple[str, bytes]:
|
||||
"""agent.md and every pinned skill version in one pack. T2 covers the pinned skills too: a
|
||||
personal agent pinning a firm skill exports only where that skill would."""
|
||||
agent = _get_agent(db, actor, agent_id)
|
||||
version = (_agent_version(db, agent, n) if n is not None else
|
||||
db.get(AgentVersion, agent.current_version_id) if agent.current_version_id else None)
|
||||
if version is None or (not can_edit(actor, agent) and version.id != agent.current_version_id):
|
||||
raise NotFoundError("Version not found.")
|
||||
pins = _pins(db, version.id)
|
||||
firm_export = settings.get(db, "skills_firm_export")
|
||||
if not all(may_export(actor, item, firm_export) for item in [agent, *(s for s, _ in pins)]):
|
||||
raise AuthorizationError("Only an administrator may export the firm's skills and agents.")
|
||||
folders: set[str] = set()
|
||||
contents = []
|
||||
for skill, sv in pins:
|
||||
folder = free_slug(folders, skill.slug) # two owners' `nda` side by side
|
||||
folders.add(folder)
|
||||
contents.append(dataclasses.replace(version_content(skill, sv, _files(db, sv.id)),
|
||||
folder=folder))
|
||||
head = {"name": agent.name, "description": agent.name, "kind": agent.kind}
|
||||
if version.tools_requested:
|
||||
head["tools"] = list(version.tools_requested)
|
||||
if (version.model_policy or {}).get("model"):
|
||||
head["model"] = version.model_policy["model"]
|
||||
data = skill_pack.build_pack(contents, skill_pack.AgentDoc(
|
||||
name=agent.name, description=agent.name, body=version.instructions_md, frontmatter=head))
|
||||
_audit_agent(db, actor, "agent.export", agent, version, f"pack {_sha(data)}", ip=ip)
|
||||
return f"{_slugish(agent.name)}-v{version.n}.zip", data
|
||||
|
||||
|
||||
def import_agent(db: DbSession, actor: AppUser, data: bytes, filename: str | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""An agent pack becomes a personal agent of `actor`'s, version 1, pinning its skills: a skill
|
||||
`actor` already has (same sum) is pinned as it is, every other one is imported as a personal
|
||||
copy first. `tools` and `model` are kept as a request and a hint, never granted (D3)."""
|
||||
pack = skill_pack.read_pack(data)
|
||||
if pack.agent is None:
|
||||
raise PackRejected("pack_not_agent")
|
||||
head = pack.agent.frontmatter
|
||||
if head.get("kind", AgentKind.assistant) != AgentKind.assistant:
|
||||
raise PackRejected("pack_agent_kind", [skill_pack.AGENT_DOC])
|
||||
pack_sha = _sha(data)
|
||||
taken = set(db.scalars(select(Skill.slug).where(Skill.owner_id == actor.id)))
|
||||
pinned, skills_out = [], []
|
||||
for doc in pack.skills:
|
||||
content = skill_pack.skill_content(pack, doc)
|
||||
sha = skill_pack.content_sha256(content)
|
||||
version = _already_have(db, actor, sha)
|
||||
if version is None:
|
||||
skill, version = _import_one(db, actor, doc, content, sha, None, taken,
|
||||
filename=filename, pack_sha=pack_sha, ip=ip)
|
||||
else:
|
||||
skill = db.get(Skill, version.skill_id)
|
||||
if version.id not in pinned: # two folders of one pack with the same content
|
||||
pinned.append(version.id)
|
||||
skills_out.append({"path": doc.path, "content_sha256": sha, "info_only": doc.info_only,
|
||||
"skill": skill_out(actor, skill), "n": version.n})
|
||||
tools = head.get("tools")
|
||||
model = head.get("model")
|
||||
agent = Agent(name=pack.agent.name, owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, kind=AgentKind.assistant)
|
||||
db.add(agent)
|
||||
db.flush()
|
||||
version = _add_agent_version(
|
||||
db, actor, agent, 1, instructions=pack.agent.body,
|
||||
model_policy={"model": str(model)} if model else None,
|
||||
tools=[str(t) for t in tools] if isinstance(tools, list) else [],
|
||||
skill_version_ids=pinned)
|
||||
_audit_agent(db, actor, "agent.import", agent, version, f"pack {pack_sha}", ip=ip)
|
||||
return {"status": "imported", "agent": agent_out(actor, agent), "skills": skills_out,
|
||||
"info_only": {k: head[k] for k in ("tools", "model") if k in head}}
|
||||
|
||||
@@ -8,7 +8,7 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import AuthorizationError, ConflictError, NotFoundError
|
||||
from app.errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Skill
|
||||
from app.services import skill_pack, skills
|
||||
from app.services.skill_pack import PackRejected
|
||||
@@ -207,3 +207,86 @@ def test_an_agent_pack_or_a_pack_without_skill_md_is_not_a_skill_import():
|
||||
with pytest.raises(PackRejected) as err:
|
||||
skills.import_skills(None, OWNER, buf.getvalue(), ip=None)
|
||||
assert err.value.code == "pack_no_skill"
|
||||
|
||||
|
||||
# ---- agents ----
|
||||
|
||||
def _sv(skill, current=False):
|
||||
version = SimpleNamespace(id=uuid.uuid4(), skill_id=skill.id, n=1)
|
||||
if current:
|
||||
skill.current_version_id = version.id
|
||||
return version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("user, agent_scope, skill_scope, current, allowed", [
|
||||
(OWNER, "personal", "personal", True, True), # one's own working notes
|
||||
(OTHER, "personal", "personal", True, False), # somebody else's: invisible
|
||||
(OTHER, "personal", "firm", True, True), # the firm's published version
|
||||
(OTHER, "personal", "firm", False, False), # ...but not one still waiting for approval
|
||||
(OWNER, "personal", "firm", False, True), # its editor reads every version
|
||||
(OWNER, "firm", "personal", True, False), # a firm agent never carries a personal skill
|
||||
(ADMIN, "firm", "personal", True, False),
|
||||
(OWNER, "firm", "firm", True, True),
|
||||
(OWNER, "firm", "firm", False, False), # not even its editor's unapproved version
|
||||
])
|
||||
def test_a_firm_agent_pins_only_the_firms_skills(user, agent_scope, skill_scope, current, allowed):
|
||||
skill = _skill(skill_scope)
|
||||
assert skills.may_pin(user, agent_scope, skill, _sv(skill, current)) is allowed
|
||||
|
||||
|
||||
def test_a_pin_must_name_a_version_of_that_skill():
|
||||
skill = _skill("personal")
|
||||
assert not skills.may_pin(OWNER, "personal", skill, _sv(_skill("personal"), True))
|
||||
assert not skills.may_pin(OWNER, "personal", None, None)
|
||||
|
||||
|
||||
class _PinDb:
|
||||
def __init__(self, *pairs):
|
||||
self.rows = {}
|
||||
for skill, version in pairs:
|
||||
self.rows[skill.id], self.rows[version.id] = skill, version
|
||||
|
||||
def get(self, _model, key):
|
||||
return self.rows.get(key)
|
||||
|
||||
|
||||
def test_refused_pins_are_a_validation_error_naming_them():
|
||||
mine, firm = _skill("personal"), _skill("firm")
|
||||
v_mine, v_firm = _sv(mine, True), _sv(firm, True)
|
||||
db = _PinDb((mine, v_mine), (firm, v_firm))
|
||||
assert skills._check_pins(db, OWNER, "personal", [v_mine.id, v_firm.id]) == [v_mine, v_firm]
|
||||
unknown = uuid.uuid4()
|
||||
with pytest.raises(ValidationError) as err:
|
||||
skills._check_pins(db, OWNER, "firm", [v_mine.id, v_firm.id, unknown])
|
||||
assert err.value.extra == {"code": "agent_pin_refused",
|
||||
"skill_version_ids": [str(v_mine.id), str(unknown)]}
|
||||
with pytest.raises(ValidationError):
|
||||
skills._check_pins(db, OWNER, "personal", [v_mine.id, v_mine.id])
|
||||
|
||||
|
||||
def test_an_agent_is_published_through_the_same_path(monkeypatch, audited):
|
||||
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "approval")
|
||||
agent = SimpleNamespace(id=uuid.uuid4(), name="Asystent", scope="personal", status="active",
|
||||
current_version_id=None)
|
||||
out = skills._publish(_PublishDb(), OWNER, skills.PublishKind.agent, agent, _version(), ip=None)
|
||||
assert out["status"] == "pending" and audited == ["agent.publish_request"]
|
||||
|
||||
|
||||
def test_an_agent_import_takes_only_an_assistant_agent_pack():
|
||||
skill = skill_pack.build_pack([skill_pack.SkillContent(
|
||||
folder="nda", frontmatter={"name": "nda", "description": "d"}, body="b", files={})])
|
||||
with pytest.raises(PackRejected) as err:
|
||||
skills.import_agent(None, OWNER, skill, ip=None)
|
||||
assert err.value.code == "pack_not_agent"
|
||||
compass = skill_pack.build_pack([], skill_pack.AgentDoc(
|
||||
name="a", description="d", body="b",
|
||||
frontmatter={"name": "a", "description": "d", "kind": "compass.redlines"}))
|
||||
with pytest.raises(PackRejected) as err:
|
||||
skills.import_agent(None, OWNER, compass, ip=None)
|
||||
assert err.value.code == "pack_agent_kind"
|
||||
|
||||
|
||||
def test_an_agent_file_name_is_ascii_kebab():
|
||||
assert skills._slugish("Asystent umów NDA!") == "asystent-umow-nda"
|
||||
assert skills._slugish("Łódź") == "lodz"
|
||||
assert skills._slugish("—") == "agent"
|
||||
|
||||
Reference in New Issue
Block a user