Compare commits
67
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7f386f477 | ||
|
|
37b619337c | ||
|
|
4952a5361c | ||
|
|
05d9169421 | ||
|
|
8bc639c7ae | ||
|
|
0128f98e0e | ||
|
|
c74276555e | ||
|
|
8378152fb2 | ||
|
|
bf46fb5724 | ||
|
|
68a5f55eb6 | ||
|
|
89b0a4104a | ||
|
|
8cbd97084b | ||
|
|
0520eacd77 | ||
|
|
7542d76089 | ||
|
|
e330fd2cf3 | ||
|
|
ab8de6dc26 | ||
|
|
c10cb5bccd | ||
|
|
b3782d33a4 | ||
|
|
18623f0fee | ||
|
|
113eb1ed1a | ||
|
|
e67a4829a0 | ||
|
|
1c690e3e75 | ||
|
|
ce95d8a678 | ||
|
|
06123286f1 | ||
|
|
3dcec4631e | ||
|
|
b8324372b0 | ||
|
|
ab96fdef8a | ||
|
|
63901c29d0 | ||
|
|
8a2300d15e | ||
|
|
ea8818faf4 | ||
|
|
6760b4510e | ||
|
|
67cfc64a6a | ||
|
|
7c37d9e02a | ||
|
|
313fe660e9 | ||
|
|
b98b5557c5 | ||
|
|
4efa125f93 | ||
|
|
1adb783d4a | ||
|
|
d4855c01d3 | ||
|
|
951247ebf5 | ||
|
|
bb454f54ca | ||
|
|
236cfb71bc | ||
|
|
e2c8632d30 | ||
|
|
01f272207d | ||
|
|
e7f2b8d5f1 | ||
|
|
e37b915896 | ||
|
|
dac401c47f | ||
|
|
4330c13499 | ||
|
|
efd522a575 | ||
|
|
a8240c6fee | ||
|
|
dee27d91ce | ||
|
|
4a356b6d94 | ||
|
|
e341da9924 | ||
|
|
44b689943b | ||
|
|
7b402a10e0 | ||
|
|
7372f275d2 | ||
|
|
8cdf8ab70b | ||
|
|
7c38536059 | ||
|
|
c61d4d6f08 | ||
|
|
1081a1dba8 | ||
|
|
d0061dc517 | ||
|
|
0601a9d376 | ||
|
|
6a757cc1c7 | ||
|
|
3fa428b3a6 | ||
|
|
2db3565409 | ||
|
|
cba0eaf123 | ||
|
|
116279b917 | ||
|
|
439edfc611 |
@@ -18,3 +18,6 @@ deploy/db.env
|
||||
deploy/env/*.env
|
||||
# Parafa's signer (PKCS#12 + passphrase), mounted read-only into parafa-backend: never committed.
|
||||
deploy/parafa-signer/
|
||||
.meduza/CONTRACT.md
|
||||
.meduza/.budget-fired
|
||||
.meduza/.stub-script.json
|
||||
|
||||
+10
-10
@@ -1,30 +1,30 @@
|
||||
[submodule "deploy/modules/galena"]
|
||||
path = deploy/modules/galena
|
||||
url = https://github.com/Alpaq92/Galena
|
||||
url = ../Galena.git
|
||||
[submodule "deploy/modules/counsel"]
|
||||
path = deploy/modules/counsel
|
||||
url = https://github.com/Alpaq92/CounselScorecard
|
||||
url = ../CounselScorecard.git
|
||||
[submodule "deploy/modules/sygna"]
|
||||
path = deploy/modules/sygna
|
||||
url = https://github.com/Alpaq92/Sygna
|
||||
url = ../Sygna.git
|
||||
[submodule "deploy/modules/insider"]
|
||||
path = deploy/modules/insider
|
||||
url = https://github.com/Alpaq92/Insider.git
|
||||
url = ../Insider.git
|
||||
[submodule "deploy/modules/lexicon"]
|
||||
path = deploy/modules/lexicon
|
||||
url = https://github.com/Alpaq92/Lexicon
|
||||
url = ../Lexicon.git
|
||||
[submodule "deploy/modules/agora"]
|
||||
path = deploy/modules/agora
|
||||
url = https://github.com/Alpaq92/Agora
|
||||
url = ../Agora.git
|
||||
[submodule "deploy/modules/panorama"]
|
||||
path = deploy/modules/panorama
|
||||
url = https://github.com/Alpaq92/Panorama
|
||||
url = ../Panorama.git
|
||||
[submodule "deploy/modules/parafa"]
|
||||
path = deploy/modules/parafa
|
||||
url = https://github.com/Alpaq92/Parafa
|
||||
url = ../Parafa.git
|
||||
[submodule "deploy/modules/scribe"]
|
||||
path = deploy/modules/scribe
|
||||
url = https://github.com/Alpaq92/Scribe
|
||||
url = ../Scribe.git
|
||||
[submodule "deploy/modules/arbiter"]
|
||||
path = deploy/modules/arbiter
|
||||
url = https://github.com/Alpaq92/Arbiter
|
||||
url = ../Arbiter.git
|
||||
|
||||
@@ -25,6 +25,7 @@ gate (`backend/scripts/license_gate.py`) fails the build on GPL, AGPL or SSPL.
|
||||
|---|---|---|
|
||||
| [Open Color](https://yeun.github.io/open-color/) | MIT | the colour palette, light and dark |
|
||||
| [Tabler Icons](https://tabler.io/icons) | MIT | outline icon set — path data is **vendored** into `frontend/app.js`'s `ICN` map, never loaded from a CDN, because the console's CSP allows no third-party origins |
|
||||
| [Simple Icons](https://simpleicons.org) | CC0-1.0 | brand logotypes for model families and providers — path data **vendored** into `frontend/app.js`'s `BRAND` map at commit `e451c581` (no per-icon licence in the set's data): `anthropic`, `google` (Google Gemini), `qwen`, `meta`, `mistral` (Mistral AI), `openrouter`. OpenAI is not in the set, Bielik neither — those keep a monogram. The marks remain their owners' trademarks; they only name the vendor a model comes from |
|
||||
| [Inter](https://rsms.me/inter/) | SIL OFL 1.1 | the console font, `frontend/ui/v1/InterVariable.woff2` beside its licence (`LICENSE-Inter.txt`), served from this origin |
|
||||
| [legalwork](https://github.com/eigenweltlabs/legalwork) | MIT | the look: colour, shape, type and motion values read from its code (HEAD `8255eba9`) into `frontend/ui/v1/tokens.css`; no legalwork code is included |
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Skills and agents: seven tables in Atrium's own schema, and frozen versions the runtime cannot rewrite.
|
||||
|
||||
The tables are `app/models/skills.py`'s. `0001` builds from the live metadata, so on a fresh database
|
||||
they already exist and the `checkfirst` create is a no-op; on a database migrated before this
|
||||
revision it creates them. Their foreign keys to `app_user` are rendered unqualified and resolve
|
||||
through the search_path — to the shared identity schema on a platform (where `0004` dropped the local
|
||||
copy, and on a fresh platform install `0004`'s metadata-driven repoint already moved them), to
|
||||
Atrium's own schema standalone.
|
||||
|
||||
Then the grants, in two steps:
|
||||
|
||||
1. `runtime_grants_sql` with the same evidence tables as `0003` / `0008` / `0009`, `read_only`
|
||||
explicit (see 0008), so the runtime role gets its DML on the new tables.
|
||||
2. A separate `REVOKE UPDATE, DELETE, TRUNCATE` on the four version tables — `skill_version`,
|
||||
`skill_file`, `agent_version`, `agent_version_skill`. A version is frozen: changing content is a
|
||||
new version, never an edit, and an agent pins the exact version it was built on. Not through
|
||||
`read_only`, because that takes INSERT too, and inserting a version is the one thing the runtime
|
||||
does to these tables. The block then verifies, and raises if the runtime role still holds UPDATE
|
||||
(table- or column-level), DELETE or TRUNCATE some other way (PUBLIC, an inherited role).
|
||||
|
||||
**A later revision that re-runs `runtime_grants_sql` re-opens these tables** — its
|
||||
`GRANT ... ON ALL TABLES` hands UPDATE and DELETE back. Such a revision must run
|
||||
`immutable_versions_sql` again after it (copy the block; revisions are not importable).
|
||||
|
||||
The identity rows (`skill`, `agent`) and `publish_request` stay mutable: scope, status and
|
||||
`current_version_id` move through publication and archiving.
|
||||
|
||||
No `%` and no `:name` sequence in the SQL below (``op.execute`` wraps it in ``text()``); the role is a
|
||||
validated identifier, rendered.
|
||||
|
||||
Downgrade drops the seven tables, children first (`drop_all` drops the `use_alter` cycle constraints
|
||||
first). The grants die with them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core import Base
|
||||
from dredd_core.schema import runtime_grants_sql
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.identity_grants import _literal, _quoted
|
||||
from app.models import (
|
||||
Agent,
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
|
||||
revision = "0015"
|
||||
down_revision = "0014"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# The same evidence tables as 0003 / 0008 / 0009 (see 0008's note: a shorter list would re-open them).
|
||||
APPEND_ONLY = ("audit_log",)
|
||||
NO_DELETE: tuple[str, ...] = ()
|
||||
READ_ONLY = ("alembic_version",)
|
||||
|
||||
# Parents first, for the create; reversed for the drop.
|
||||
_TABLES = [Skill.__table__, SkillVersion.__table__, SkillFile.__table__, Agent.__table__,
|
||||
AgentVersion.__table__, AgentVersionSkill.__table__, PublishRequest.__table__]
|
||||
|
||||
#: Insert and read only: a version is never edited or removed by the runtime.
|
||||
IMMUTABLE = ("skill_version", "skill_file", "agent_version", "agent_version_skill")
|
||||
|
||||
|
||||
def immutable_versions_sql(app_role: str) -> str:
|
||||
"""REVOKE UPDATE/DELETE/TRUNCATE on the version tables from `app_role`, then prove it holds."""
|
||||
role, role_lit = _quoted(app_role), _literal(app_role)
|
||||
tables = ", ".join(IMMUTABLE)
|
||||
names = ", ".join(f"'{t}'" for t in IMMUTABLE)
|
||||
return f"""
|
||||
DO $$
|
||||
DECLARE
|
||||
t text;
|
||||
BEGIN
|
||||
REVOKE UPDATE, DELETE, TRUNCATE ON {tables} FROM {role};
|
||||
FOREACH t IN ARRAY ARRAY[{names}] LOOP
|
||||
IF has_table_privilege({role_lit}, quote_ident(t), 'UPDATE')
|
||||
OR has_any_column_privilege({role_lit}, quote_ident(t), 'UPDATE')
|
||||
OR has_table_privilege({role_lit}, quote_ident(t), 'DELETE')
|
||||
OR has_table_privilege({role_lit}, quote_ident(t), 'TRUNCATE') THEN
|
||||
RAISE EXCEPTION USING MESSAGE =
|
||||
'the runtime role {app_role} can still UPDATE, DELETE or TRUNCATE ' || t;
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
"""
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
Base.metadata.create_all(bind=op.get_bind(), tables=_TABLES, checkfirst=True)
|
||||
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
|
||||
no_delete=NO_DELETE, read_only=READ_ONLY))
|
||||
op.execute(immutable_versions_sql(settings.db_app_role))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
Base.metadata.drop_all(bind=op.get_bind(), tables=list(reversed(_TABLES)), checkfirst=True)
|
||||
@@ -60,6 +60,39 @@ class AccessRequestStatus(StrEnum):
|
||||
declined = "declined"
|
||||
|
||||
|
||||
# Skills and agents (`models/skills.py`): Text + CHECK for the same reason as the marketplace ones.
|
||||
class SkillScope(StrEnum):
|
||||
personal = "personal" # the owner's own; nobody else sees it, an administrator included
|
||||
firm = "firm" # published to everybody on the instance
|
||||
|
||||
|
||||
class CatalogStatus(StrEnum):
|
||||
"""Shared by skills and agents. No `draft`: a draft is simply a personal skill."""
|
||||
active = "active"
|
||||
archived = "archived"
|
||||
|
||||
|
||||
class SkillOrigin(StrEnum):
|
||||
authored = "authored"
|
||||
imported = "imported"
|
||||
bundled = "bundled"
|
||||
|
||||
|
||||
class AgentKind(StrEnum):
|
||||
assistant = "assistant"
|
||||
|
||||
|
||||
class PublishKind(StrEnum):
|
||||
skill = "skill"
|
||||
agent = "agent"
|
||||
|
||||
|
||||
class PublishRequestStatus(StrEnum):
|
||||
pending = "pending"
|
||||
approved = "approved"
|
||||
declined = "declined"
|
||||
|
||||
|
||||
__all__ = [
|
||||
# from dredd-core, unchanged
|
||||
"NodeRole",
|
||||
@@ -71,4 +104,10 @@ __all__ = [
|
||||
"ModuleStatus",
|
||||
"Availability",
|
||||
"AccessRequestStatus",
|
||||
"SkillScope",
|
||||
"CatalogStatus",
|
||||
"SkillOrigin",
|
||||
"AgentKind",
|
||||
"PublishKind",
|
||||
"PublishRequestStatus",
|
||||
]
|
||||
|
||||
@@ -24,10 +24,14 @@ with no chat type in `/api/v0` is left alone.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from app.errors import ValidationError
|
||||
|
||||
#: Loading an 11B model from disk took about a minute on the reference machine.
|
||||
LOAD_TIMEOUT = httpx.Timeout(connect=5.0, read=300.0, write=30.0, pool=10.0)
|
||||
LIST_TIMEOUT = httpx.Timeout(5.0)
|
||||
@@ -111,8 +115,12 @@ async def ensure_loaded(root: str, key: str | None, model: str, *, may_switch: b
|
||||
raise ModelBusy(instances[0][0] or instances[0][1])
|
||||
for _, instance_id in instances:
|
||||
await _json(client, "POST", f"{root}/api/v1/models/unload", key, {"instance_id": instance_id})
|
||||
# Never more than the model was trained on: Bielik 11B v3.x stops at 32 768, and asking for
|
||||
# DEFAULT_CONTEXT stretched it past what it reads well. LM Studio says so in `max_context_length`.
|
||||
trained = next((m.get("max_context_length") for m in typed.get("data", []) if m.get("id") == model), None)
|
||||
context = min(DEFAULT_CONTEXT, trained) if isinstance(trained, int) and trained > 0 else DEFAULT_CONTEXT
|
||||
await _json(client, "POST", f"{root}/api/v1/models/load", key,
|
||||
{"model": model, "context_length": DEFAULT_CONTEXT})
|
||||
{"model": model, "context_length": context})
|
||||
|
||||
|
||||
async def stream_chat(root: str, key: str | None, model: str, messages: list[dict],
|
||||
@@ -123,11 +131,149 @@ async def stream_chat(root: str, key: str | None, model: str, messages: list[dic
|
||||
body = {"model": model, "messages": messages, "max_tokens": max_tokens, "stream": True, **extra}
|
||||
async with httpx.AsyncClient(timeout=LOAD_TIMEOUT) as client:
|
||||
try:
|
||||
# Identity: the raw bytes pass through to the browser with no Content-Encoding of ours, and a
|
||||
# cloud API gzips by default (api.anthropic.com did, 2026-11-06) — the chat read garbage.
|
||||
async with client.stream("POST", f"{root}/v1/chat/completions",
|
||||
headers=_headers(key), json=body) as resp:
|
||||
headers={**_headers(key), "Accept-Encoding": "identity"},
|
||||
json=body) as resp:
|
||||
if resp.status_code != 200:
|
||||
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}.")
|
||||
# The server's own reason (OpenAI-shaped `error.message`), capped: a bare "HTTP 400"
|
||||
# left a refused parameter invisible. The key travels in a header, never echoed here.
|
||||
raw = b""
|
||||
async for chunk in resp.aiter_raw():
|
||||
raw += chunk
|
||||
if len(raw) > 4096:
|
||||
break
|
||||
try:
|
||||
why = json.loads(raw)["error"]["message"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
why = ""
|
||||
why = f": {str(why)[:300]}" if why else ""
|
||||
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}{why}")
|
||||
async for chunk in resp.aiter_raw():
|
||||
yield chunk
|
||||
except httpx.HTTPError as exc:
|
||||
raise GatewayError(f"Serwer modeli nie odpowiada ({type(exc).__name__}).") from exc
|
||||
|
||||
|
||||
# ── listing what a provider offers (the administrator's "discover" / "refresh") ──────────────────
|
||||
# An administrator-steered outbound call, SSRF-shaped like the module probe: no redirects, one
|
||||
# deadline for the whole exchange, and a capped body. The key travels only in a header and never
|
||||
# appears in an error.
|
||||
|
||||
LIST_DEADLINE = 10.0
|
||||
LIST_MAX_BYTES = 2 * 1024 * 1024
|
||||
#: Vendors whose address is a cloud API, not somebody's own server: no LM Studio listing to ask.
|
||||
CLOUD_VENDORS = frozenset({"openai", "openrouter", "anthropic"})
|
||||
# ponytail: a pattern, not a catalogue of model ids — extend it when a non-chat model leaks through.
|
||||
NON_CHAT = re.compile(r"embed|tts|whisper|dall-e|image|moderation|audio|transcribe|realtime|rerank", re.I)
|
||||
|
||||
|
||||
def _refusal(code: str, pl: str, en: str) -> ValidationError:
|
||||
return ValidationError(pl, {"code": code, "en": en})
|
||||
|
||||
|
||||
def _unreachable(why_pl: str, why_en: str) -> ValidationError:
|
||||
return _refusal("provider_unreachable", f"Serwer modeli nie odpowiada: {why_pl}.",
|
||||
f"The model server does not answer: {why_en}.")
|
||||
|
||||
|
||||
class _NotFound(Exception):
|
||||
"""A non-200 answer that is not a refusal of the key — for an optional listing, just absent."""
|
||||
|
||||
|
||||
async def _capped_json(client: httpx.AsyncClient, url: str, headers: dict[str, str]):
|
||||
# Raw bytes, identity only: a decoded read is a decompression bomb (one gzip chunk → many MB).
|
||||
async with client.stream("GET", url, headers={**headers, "Accept-Encoding": "identity"}) as resp:
|
||||
if resp.is_redirect:
|
||||
raise _unreachable("przekierowanie odrzucone", "redirect refused")
|
||||
if resp.status_code in (401, 403):
|
||||
raise _refusal("provider_key_refused", "Serwer modeli odrzucił klucz.",
|
||||
"The model server refused the key.")
|
||||
if resp.status_code != 200:
|
||||
raise _NotFound(resp.status_code)
|
||||
if resp.headers.get("content-encoding", "identity").lower() != "identity":
|
||||
raise _unreachable("odpowiedź jest skompresowana", "the answer is compressed")
|
||||
body = bytearray()
|
||||
async for chunk in resp.aiter_raw():
|
||||
body += chunk
|
||||
if len(body) > LIST_MAX_BYTES:
|
||||
raise _unreachable("odpowiedź jest za duża", "the answer is too large")
|
||||
try:
|
||||
return json.loads(body)
|
||||
except (ValueError, RecursionError): # 2 MB of `[` nests deeper than the decoder recurses
|
||||
raise _unreachable("odpowiedź nie jest JSON-em", "the answer is not JSON") from None
|
||||
|
||||
|
||||
def _data(listing) -> list:
|
||||
"""`listing["data"]` when somebody else's server answered the documented shape; anything else
|
||||
is a 422, never an AttributeError (a 500) on untrusted input."""
|
||||
data = listing.get("data") if isinstance(listing, dict) else None
|
||||
if not isinstance(data, list):
|
||||
raise _unreachable("nieoczekiwany kształt odpowiedzi", "unexpected answer shape")
|
||||
return data
|
||||
|
||||
|
||||
async def _openai_models(client: httpx.AsyncClient, base_url: str, key: str | None,
|
||||
vendor: str | None) -> list[dict]:
|
||||
root, headers = server_root(base_url), _headers(key)
|
||||
try:
|
||||
listing = await _capped_json(client, f"{root}/v1/models", headers)
|
||||
except _NotFound as exc:
|
||||
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
|
||||
models = [{"id": m["id"], "dialect": "openai",
|
||||
**({"context_window": m["max_model_len"]}
|
||||
if isinstance(m.get("max_model_len"), int) and m["max_model_len"] > 0 else {})}
|
||||
for m in _data(listing) if isinstance(m, dict) and isinstance(m.get("id"), str)]
|
||||
if vendor not in CLOUD_VENDORS:
|
||||
# LM Studio's own listing says which models chat; `/v1/models` lists embeddings too. Same
|
||||
# reading as `loaded_models`, but through the capped reader. Not LM Studio → no listing.
|
||||
# Optional: a server behind a login page answers this path with a 302, HTML or a 401, and
|
||||
# that says nothing about `/v1/models`, which already answered — any refusal = no listing.
|
||||
try:
|
||||
lm_data = _data(await _capped_json(client, f"{root}/api/v0/models", headers))
|
||||
except (_NotFound, ValidationError):
|
||||
lm_data = []
|
||||
types = {m.get("id"): m.get("type") for m in lm_data if isinstance(m, dict)}
|
||||
models = [m for m in models if types.get(m["id"], "llm") in CHAT_TYPES]
|
||||
return models
|
||||
|
||||
|
||||
#: https://platform.claude.com/docs/en/api/versioning (latest on 2026-11-06); the listing itself is
|
||||
#: https://platform.claude.com/docs/en/api/models-list — `lifecycle`, `max_input_tokens`.
|
||||
ANTHROPIC_VERSION = "2026-10-21"
|
||||
|
||||
|
||||
async def _anthropic_models(client: httpx.AsyncClient, base_url: str, key: str | None) -> list[dict]:
|
||||
headers = {"anthropic-version": ANTHROPIC_VERSION, **({"x-api-key": key} if key else {})}
|
||||
# ponytail: one page of 1000 (the maximum), no `after_id` paging — the catalogue is far smaller.
|
||||
try:
|
||||
listing = await _capped_json(client, f"{base_url.rstrip('/')}/models?limit=1000", headers)
|
||||
except _NotFound as exc:
|
||||
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
|
||||
# The default listing includes `deprecated` models, closed to new adopters: offer active only.
|
||||
return [{"id": m["id"], "dialect": "openai",
|
||||
**({"context_window": m["max_input_tokens"]}
|
||||
if isinstance(m.get("max_input_tokens"), int) and m["max_input_tokens"] > 0 else {})}
|
||||
for m in _data(listing)
|
||||
if isinstance(m, dict) and isinstance(m.get("id"), str) and m.get("lifecycle") == "active"]
|
||||
|
||||
|
||||
async def list_models(base_url: str, key: str | None, vendor: str | None, *,
|
||||
transport: httpx.AsyncBaseTransport | None = None) -> list[dict]:
|
||||
"""The chat models a provider offers under this key, as `{id, context_window?, dialect}`.
|
||||
Refusals are 422 Problem Details with `code` `provider_key_refused` / `provider_unreachable` /
|
||||
`provider_no_models`. `transport` exists for tests."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=LIST_DEADLINE, follow_redirects=False,
|
||||
transport=transport) as client:
|
||||
listing = (_anthropic_models(client, base_url, key) if vendor == "anthropic"
|
||||
else _openai_models(client, base_url, key, vendor))
|
||||
models = await asyncio.wait_for(listing, LIST_DEADLINE)
|
||||
except (httpx.HTTPError, TimeoutError) as exc:
|
||||
raise _unreachable(type(exc).__name__, type(exc).__name__) from None
|
||||
models = [m for m in models if not NON_CHAT.search(m["id"])]
|
||||
if not models:
|
||||
raise _refusal("provider_no_models", "Pod tym kluczem/adresem nie ma żadnego modelu czatu.",
|
||||
"There is no chat model under this key/address.")
|
||||
return models
|
||||
|
||||
+16
-3
@@ -3,8 +3,8 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from collections.abc import Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core.identity import (
|
||||
@@ -35,7 +35,19 @@ from .deps import refuse_cross_site_write
|
||||
from .errors import ProblemDetailErrorMiddleware, install_error_handlers, problem_response
|
||||
from .logging_config import configure_logging
|
||||
from .observability import setup_observability
|
||||
from .routers import admin, admin_modules, admin_providers, auth, health, marketplace, models, nodes, users
|
||||
from .routers import (
|
||||
admin,
|
||||
admin_modules,
|
||||
admin_providers,
|
||||
attachments,
|
||||
auth,
|
||||
health,
|
||||
marketplace,
|
||||
models,
|
||||
nodes,
|
||||
skills,
|
||||
users,
|
||||
)
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
@@ -157,7 +169,8 @@ async def _security_headers(request, call_next):
|
||||
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router, admin_modules.router,
|
||||
admin_providers.router, nodes.router, marketplace.router, models.router,
|
||||
admin_providers.router, nodes.router, marketplace.router, models.router, skills.router, attachments.router,
|
||||
skills.agents, skills.publish_requests,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
|
||||
@@ -40,11 +40,22 @@ from dredd_core import (
|
||||
from dredd_core.model_providers import ModelProvider, ModelProviderKey, ModelProviderPolicy
|
||||
|
||||
from .marketplace import AccessRequest, Module, ModuleAssignment
|
||||
from .skills import (
|
||||
Agent,
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Base", "TimestampMixin", "UUIDPkMixin", "SafeInet", "pg_enum",
|
||||
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
|
||||
"Node", "PermissionGrant", "Favorite",
|
||||
"Module", "ModuleAssignment", "AccessRequest",
|
||||
"Skill", "SkillVersion", "SkillFile", "Agent", "AgentVersion", "AgentVersionSkill",
|
||||
"PublishRequest",
|
||||
"ModelProvider", "ModelProviderPolicy", "ModelProviderKey",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Skills and agents: a person's own instructions, reference files and the agents built on them.
|
||||
|
||||
A stable identity (`skill`, `agent`) points at frozen versions (`skill_version`, `agent_version`):
|
||||
changing content is a new version, never an edit, which is why the runtime role holds no UPDATE or
|
||||
DELETE on the version tables (revision 0010). The identity rows stay mutable — scope, status and
|
||||
`current_version_id` move through publication and archiving.
|
||||
|
||||
These are NOT nodes of the org tree (the tree holds units only), so access is not `authz`'s: it is
|
||||
computed in one place, `services/skills.visible_to`. Every table lives in Atrium's own schema — no
|
||||
module reads the catalogue, and the shared schema is readable by every module.
|
||||
|
||||
Every foreign key to `app_user` is RESTRICT: an account is deactivated, never deleted, and a skill
|
||||
must not silently lose its author. Vocabularies are Text + CHECK built from `app/enums.py`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from dredd_core import Base, TimestampMixin, UUIDPkMixin
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
LargeBinary,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from ..enums import (
|
||||
AgentKind,
|
||||
CatalogStatus,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
SkillScope,
|
||||
)
|
||||
from .marketplace import _one_of
|
||||
|
||||
|
||||
def _user_fk(nullable: bool = False):
|
||||
return mapped_column(ForeignKey("app_user.id", ondelete="RESTRICT"), nullable=nullable)
|
||||
|
||||
|
||||
def _created_at():
|
||||
return mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
|
||||
|
||||
|
||||
class Skill(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "skill"
|
||||
|
||||
slug: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
owner_id: Mapped[uuid.UUID] = _user_fk()
|
||||
scope: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=SkillScope.personal.value)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=CatalogStatus.active.value)
|
||||
# For a firm skill: only the approved version. use_alter breaks the skill ↔ version cycle.
|
||||
current_version_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
ForeignKey("skill_version.id", ondelete="RESTRICT", use_alter=True))
|
||||
origin: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=SkillOrigin.authored.value)
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint(_one_of("scope", SkillScope), name="scope"),
|
||||
CheckConstraint(_one_of("status", CatalogStatus), name="status"),
|
||||
CheckConstraint(_one_of("origin", SkillOrigin), name="origin"),
|
||||
CheckConstraint(r"slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'", name="slug"),
|
||||
UniqueConstraint("owner_id", "slug", name="uq_skill_owner_slug"),
|
||||
Index("ix_skill_scope", "scope"),
|
||||
)
|
||||
|
||||
|
||||
class SkillVersion(UUIDPkMixin, Base):
|
||||
__tablename__ = "skill_version"
|
||||
|
||||
skill_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("skill.id", ondelete="RESTRICT"), nullable=False)
|
||||
n: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
description: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# 30 000 characters: the chat tool's result limit.
|
||||
body_md: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# An imported licence is the author's and is never overwritten (the service's rule).
|
||||
license: Mapped[str] = mapped_column(Text, nullable=False, server_default="proprietary")
|
||||
# Frontmatter outside the schema. `metadata` is reserved on declarative classes, hence `meta`.
|
||||
meta: Mapped[dict] = mapped_column(
|
||||
"metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
|
||||
content_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
provenance: Mapped[dict | None] = mapped_column(JSONB)
|
||||
created_at: Mapped[dt.datetime] = _created_at()
|
||||
created_by: Mapped[uuid.UUID] = _user_fk()
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("skill_id", "n", name="uq_skill_version_skill_n"),
|
||||
CheckConstraint("n >= 1", name="n_positive"),
|
||||
CheckConstraint("char_length(description) <= 1024", name="description_length"),
|
||||
CheckConstraint("char_length(body_md) <= 30000", name="body_length"),
|
||||
CheckConstraint("octet_length(metadata::text) <= 8192", name="metadata_size"),
|
||||
CheckConstraint("content_sha256 ~ '^[0-9a-f]{64}$'", name="content_sha256"),
|
||||
)
|
||||
|
||||
|
||||
class SkillFile(UUIDPkMixin, Base):
|
||||
__tablename__ = "skill_file"
|
||||
|
||||
skill_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("skill_version.id", ondelete="RESTRICT"), nullable=False)
|
||||
path: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
media_type: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# The original bytes, kept for export.
|
||||
content: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("skill_version_id", "path", name="uq_skill_file_version_path"),
|
||||
CheckConstraint("size >= 0", name="size"),
|
||||
CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="sha256"),
|
||||
)
|
||||
|
||||
|
||||
class Agent(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "agent"
|
||||
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
owner_id: Mapped[uuid.UUID] = _user_fk()
|
||||
scope: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=SkillScope.personal.value)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=CatalogStatus.active.value)
|
||||
kind: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=AgentKind.assistant.value)
|
||||
current_version_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
ForeignKey("agent_version.id", ondelete="RESTRICT", use_alter=True))
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint(_one_of("scope", SkillScope), name="scope"),
|
||||
CheckConstraint(_one_of("status", CatalogStatus), name="status"),
|
||||
CheckConstraint(_one_of("kind", AgentKind), name="kind"),
|
||||
Index("ix_agent_owner_id", "owner_id"),
|
||||
Index("ix_agent_scope", "scope"),
|
||||
)
|
||||
|
||||
|
||||
class AgentVersion(UUIDPkMixin, Base):
|
||||
__tablename__ = "agent_version"
|
||||
|
||||
agent_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("agent.id", ondelete="RESTRICT"), nullable=False)
|
||||
n: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
instructions_md: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# A hint, never a grant (D3): the platform decides which model and tools an agent gets.
|
||||
model_policy: Mapped[dict | None] = mapped_column(JSONB)
|
||||
tools_requested: Mapped[list[str]] = mapped_column(
|
||||
ARRAY(Text), nullable=False, server_default=text("'{}'::text[]"))
|
||||
created_at: Mapped[dt.datetime] = _created_at()
|
||||
created_by: Mapped[uuid.UUID] = _user_fk()
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("agent_id", "n", name="uq_agent_version_agent_n"),
|
||||
CheckConstraint("n >= 1", name="n_positive"),
|
||||
)
|
||||
|
||||
|
||||
class AgentVersionSkill(Base):
|
||||
"""A skill VERSION pinned to an agent version — a row, not a UUID array, so RESTRICT holds:
|
||||
archiving a skill leaves every agent running on the version it pinned."""
|
||||
__tablename__ = "agent_version_skill"
|
||||
|
||||
agent_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("agent_version.id", ondelete="RESTRICT"), primary_key=True)
|
||||
skill_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("skill_version.id", ondelete="RESTRICT"), primary_key=True)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("agent_version_id", "position",
|
||||
name="uq_agent_version_skill_version_position"),
|
||||
Index("ix_agent_version_skill_skill_version_id", "skill_version_id"),
|
||||
)
|
||||
|
||||
|
||||
class PublishRequest(UUIDPkMixin, TimestampMixin, Base):
|
||||
"""Asks an administrator to publish ONE version to the firm (T1: every version, not only the
|
||||
first). `version_id` names a `skill_version` or an `agent_version` according to `kind`, so it
|
||||
carries no foreign key; the service resolves it, and versions are never deleted."""
|
||||
__tablename__ = "publish_request"
|
||||
|
||||
kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
version_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
|
||||
requested_by: Mapped[uuid.UUID] = _user_fk()
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=PublishRequestStatus.pending.value)
|
||||
decided_by: Mapped[uuid.UUID | None] = _user_fk(nullable=True)
|
||||
decided_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
note: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint(_one_of("kind", PublishKind), name="kind"),
|
||||
CheckConstraint(_one_of("status", PublishRequestStatus), name="status"),
|
||||
# One open request per version; decided ones accumulate as history.
|
||||
Index("uq_publish_request_pending", "kind", "version_id", unique=True,
|
||||
postgresql_where=text("status = 'pending'")),
|
||||
Index("ix_publish_request_status", "status"),
|
||||
)
|
||||
@@ -5,8 +5,8 @@ sent for every module at once, so the platform-wide tier is the only one that ma
|
||||
module's moderator sees them read-only in that module, and its writes are 409s there).
|
||||
|
||||
Never returns a key: a key is write-only, set or replaced through `api_key`, removed with
|
||||
`clear: ["api_key"]`, and described by `has_key` / `key_prefix` alone. Nothing here calls a provider
|
||||
(`services/providers.py` says why there is no "test connection").
|
||||
`clear: ["api_key"]`, and described by `has_key` / `key_prefix` alone. Only `discover` and `refresh`
|
||||
call a provider — to list its models — and both end the DB transaction before they do.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -18,13 +18,19 @@ from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, require_administrator
|
||||
from ..models import AppUser
|
||||
from ..schemas import ProviderCreateIn, ProviderPolicyIn, ProviderUpdateIn
|
||||
from ..schemas import (
|
||||
ProviderCreateIn,
|
||||
ProviderDiscoverIn,
|
||||
ProviderDiscoverOut,
|
||||
ProviderPolicyIn,
|
||||
ProviderUpdateIn,
|
||||
)
|
||||
from ..services import providers as service
|
||||
|
||||
router = APIRouter(prefix="/admin/model-providers", tags=["admin: model providers"])
|
||||
|
||||
|
||||
# The policy routes come before `/{provider_id}`, so "policy" is never parsed as an id.
|
||||
# The policy and discover routes come before `/{provider_id}`, so neither word is parsed as an id.
|
||||
@router.get("/policy")
|
||||
def read_policy(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(require_administrator)) -> dict:
|
||||
@@ -40,6 +46,15 @@ def update_policy(body: ProviderPolicyIn, request: Request, db: Session = Depend
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/discover", response_model=ProviderDiscoverOut)
|
||||
async def discover_provider(body: ProviderDiscoverIn, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
db.commit() # no transaction held across the outbound call (up to model_server.LIST_DEADLINE)
|
||||
out = await service.discover(db, admin, body.input, body.key, ip=client_ip(request))
|
||||
db.commit() # the audit row
|
||||
return out
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_providers(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(require_administrator)) -> list[dict]:
|
||||
@@ -76,3 +91,19 @@ def disable_provider(provider_id: uuid.UUID, request: Request, db: Session = Dep
|
||||
out = service.disable(db, admin, provider_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.delete("/{provider_id}")
|
||||
def delete_provider(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
service.delete(db, admin, provider_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/{provider_id}/refresh")
|
||||
async def refresh_provider(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
out = await service.refresh(db, admin, provider_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""POST /chat/attachments: the text of a file attached to a Home chat question. Nothing is stored.
|
||||
|
||||
The body is the file's raw bytes (no multipart, so no parser dependency), its name in `?name=`. The
|
||||
audit row names the file and its size, never its content.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user
|
||||
from ..models import AppUser
|
||||
from ..services import attachments, audit
|
||||
|
||||
router = APIRouter(tags=["chat"])
|
||||
|
||||
|
||||
@router.post("/chat/attachments")
|
||||
async def extract(request: Request, name: str = Query(min_length=1, max_length=255),
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
data = bytearray()
|
||||
async for chunk in request.stream():
|
||||
data += chunk
|
||||
if len(data) > attachments.MAX_BYTES:
|
||||
break # extract() refuses it; nothing past the limit is read
|
||||
# A 300-page PDF parses for seconds: off the event loop, or every other request waits for it.
|
||||
# ponytail: no time budget per document; a subprocess with a timeout if a crafted PDF ever stalls a worker.
|
||||
out = await run_in_threadpool(attachments.extract, name, bytes(data))
|
||||
audit.record(db, action="chat.attachment", entity_type="attachment", actor_id=user.id, detail=name[:200],
|
||||
ip=client_ip(request), diff={"kind": out["kind"], "bytes": len(data), "pages": out["pages"],
|
||||
"chars": out["chars"]})
|
||||
db.commit()
|
||||
return out
|
||||
@@ -116,7 +116,7 @@ def prompt_size(body: AskIn) -> int:
|
||||
ensure_ascii=False))
|
||||
|
||||
|
||||
def _sampling(body: AskIn) -> dict:
|
||||
def _sampling(body: AskIn, vendor: str | None = None) -> dict:
|
||||
"""The person's sampling knobs, only those they set; the model's defaults otherwise.
|
||||
|
||||
`thinking=False` is `reasoning_effort: "none"`: against LM Studio with qwen/qwen3.5-9b (2026-10-29)
|
||||
@@ -130,6 +130,11 @@ def _sampling(body: AskIn) -> dict:
|
||||
exclude_none=True)
|
||||
if body.thinking is False:
|
||||
out["reasoning_effort"] = "none"
|
||||
if vendor == "anthropic":
|
||||
# Newer Claude models refuse `temperature` outright (400 "deprecated for this model",
|
||||
# claude-opus-5-5, 2026-11-06); the knobs were tuned for small local models anyway.
|
||||
for k in ("temperature", "top_p", "top_k"):
|
||||
out.pop(k, None)
|
||||
return out
|
||||
|
||||
|
||||
@@ -176,7 +181,7 @@ async def ask(body: AskIn, request: Request, db: Session = Depends(get_db),
|
||||
messages = [{"role": "system", "content": SYSTEM.format(today=date.today())},
|
||||
*(m.model_dump(exclude_none=True) for m in body.messages)]
|
||||
tools = {"tools": body.tools, "tool_choice": body.tool_choice} if body.tools else {}
|
||||
extra = {**tools, **_sampling(body)}
|
||||
extra = {**tools, **_sampling(body, providers.vendor_of(target["base_url"]))}
|
||||
max_tokens = body.max_tokens or MAX_ANSWER_TOKENS
|
||||
|
||||
async def events():
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""A person's skills and agents: list, read, write versions, archive, publish, export and import —
|
||||
and the administrator's queue of publish requests that the T1 setting (`skills_firm_publish`) fills.
|
||||
|
||||
No access rule lives here. Skills are not org-tree nodes, so `authz` has nothing to say about them;
|
||||
`services/skills.py` is the one place that decides who sees and changes what (its docstring says why
|
||||
that is a deliberate exception) — somebody else's personal skill is a 404 from the service.
|
||||
|
||||
Import takes the ZIP as the raw request body (`application/zip`, the name in `?filename=`) rather
|
||||
than a multipart form: one fewer dependency (`python-multipart`), and the 10 MB ceiling is enforced
|
||||
while reading, not after a whole upload sits in memory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request, Response
|
||||
from fastapi.routing import APIRoute
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user, require_administrator
|
||||
from ..models import AppUser
|
||||
from ..schemas import AgentCreateIn, AgentVersionIn, NoteIn, SkillCreateIn, SkillVersionIn
|
||||
from ..services import skills as service
|
||||
from ..services.skill_pack import MAX_PACK_BYTES, PackRejected
|
||||
|
||||
# A version with every file in base64: 10 MB of files is ~13.4 MB of JSON, plus the text fields.
|
||||
MAX_JSON_BODY_BYTES = 14 * 1024 * 1024
|
||||
|
||||
|
||||
class CappedBodyRoute(APIRoute):
|
||||
"""Reads a JSON body under `MAX_JSON_BODY_BYTES` while it streams, before FastAPI parses it.
|
||||
Without this the whole body (up to the front door's 100 MB) sits in memory before
|
||||
`_decoded_files` counts the 10 MB. The ZIP import is left to `zip_body`, which streams its own."""
|
||||
|
||||
def get_route_handler(self):
|
||||
handler = super().get_route_handler()
|
||||
|
||||
async def capped(request: Request) -> Response:
|
||||
if (request.method in ("POST", "PUT", "PATCH")
|
||||
and not request.headers.get("content-type", "").startswith("application/zip")):
|
||||
declared = request.headers.get("content-length", "")
|
||||
if declared.isdigit() and int(declared) > MAX_JSON_BODY_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
body = bytearray()
|
||||
async for chunk in request.stream():
|
||||
body += chunk
|
||||
if len(body) > MAX_JSON_BODY_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
request._body = bytes(body) # Starlette's cache: FastAPI's `request.body()` reads it
|
||||
return await handler(request)
|
||||
|
||||
return capped
|
||||
|
||||
|
||||
router = APIRouter(prefix="/skills", tags=["skills"], route_class=CappedBodyRoute)
|
||||
agents = APIRouter(prefix="/agents", tags=["agents"], route_class=CappedBodyRoute)
|
||||
publish_requests = APIRouter(prefix="/admin/publish-requests", tags=["admin: publish requests"])
|
||||
|
||||
_ZIP_BODY = {"requestBody": {"required": True, "content": {
|
||||
"application/zip": {"schema": {"type": "string", "format": "binary"}}}}}
|
||||
|
||||
|
||||
async def zip_body(request: Request, _: AppUser = Depends(get_current_user)) -> bytes:
|
||||
"""The raw body, refused as soon as it passes `MAX_PACK_BYTES` — the same `pack_too_large` an
|
||||
oversized pack gets from `read_pack`, so the console words both alike. Depends on the user so
|
||||
nobody unauthenticated makes us read 10 MB."""
|
||||
declared = request.headers.get("content-length", "")
|
||||
if declared.isdigit() and int(declared) > MAX_PACK_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
data = bytearray()
|
||||
async for chunk in request.stream():
|
||||
data += chunk
|
||||
if len(data) > MAX_PACK_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def zip_response(name: str, data: bytes) -> Response:
|
||||
# `name` is `<kebab slug>-v<n>.zip`, so it needs no quoting beyond the quotes.
|
||||
return Response(data, media_type="application/zip",
|
||||
headers={"Content-Disposition": f'attachment; filename="{name}"'})
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_skills(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
return service.list_skills(db, user)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def create_skill(body: SkillCreateIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.create_skill(db, user, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
# Before `/{skill_id}/...` only for readability: no other POST route has one segment.
|
||||
@router.post("/import", openapi_extra=_ZIP_BODY)
|
||||
def import_skills(request: Request, filename: str | None = Query(default=None, max_length=255),
|
||||
add_version: bool = False, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user),
|
||||
data: bytes = Depends(zip_body)) -> dict:
|
||||
out = service.import_skills(db, user, data, filename, add_version=add_version,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/{skill_id}")
|
||||
def get_skill(skill_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return service.get_skill(db, user, skill_id)
|
||||
|
||||
|
||||
@router.post("/{skill_id}/versions", status_code=201)
|
||||
def new_version(skill_id: uuid.UUID, body: SkillVersionIn, request: Request,
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
# model_dump(), not exclude_none: the service reads None as "carry over" per field.
|
||||
out = service.new_version(db, user, skill_id, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/{skill_id}/versions/{n}")
|
||||
def get_version(skill_id: uuid.UUID, n: int, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return service.get_version(db, user, skill_id, n)
|
||||
|
||||
|
||||
@router.post("/{skill_id}/archive")
|
||||
def archive_skill(skill_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.archive_skill(db, user, skill_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/{skill_id}/publish")
|
||||
def publish_skill(skill_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.publish_skill(db, user, skill_id, n, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/{skill_id}/export")
|
||||
def export_skill(skill_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
name, data = service.export_skill(db, user, skill_id, n, ip=client_ip(request))
|
||||
db.commit() # the export's audit row
|
||||
return zip_response(name, data)
|
||||
|
||||
|
||||
@agents.get("")
|
||||
def list_agents(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
return service.list_agents(db, user)
|
||||
|
||||
|
||||
@agents.post("", status_code=201)
|
||||
def create_agent(body: AgentCreateIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.create_agent(db, user, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.post("/import", openapi_extra=_ZIP_BODY)
|
||||
def import_agent(request: Request, filename: str | None = Query(default=None, max_length=255),
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
|
||||
data: bytes = Depends(zip_body)) -> dict:
|
||||
out = service.import_agent(db, user, data, filename, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.get("/{agent_id}")
|
||||
def get_agent(agent_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return service.get_agent(db, user, agent_id)
|
||||
|
||||
|
||||
@agents.post("/{agent_id}/versions", status_code=201)
|
||||
def new_agent_version(agent_id: uuid.UUID, body: AgentVersionIn, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.new_agent_version(db, user, agent_id, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.post("/{agent_id}/archive")
|
||||
def archive_agent(agent_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.archive_agent(db, user, agent_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.post("/{agent_id}/publish")
|
||||
def publish_agent(agent_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.publish_agent(db, user, agent_id, n, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.get("/{agent_id}/export")
|
||||
def export_agent(agent_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
name, data = service.export_agent(db, user, agent_id, n, ip=client_ip(request))
|
||||
db.commit()
|
||||
return zip_response(name, data)
|
||||
|
||||
|
||||
# The service checks the administrator again; the guard here is what keeps the routes out of reach
|
||||
# of anybody else before a database is touched.
|
||||
@publish_requests.get("")
|
||||
def pending_publish_requests(db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> list[dict]:
|
||||
return service.pending_publish_requests(db, admin)
|
||||
|
||||
|
||||
@publish_requests.post("/{request_id}/approve")
|
||||
def approve_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=True,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@publish_requests.post("/{request_id}/decline")
|
||||
def decline_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=False,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
+92
-3
@@ -6,15 +6,19 @@ field that is confirmed by sending mail to it anyway.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dredd_core.identity import MODULE_ROLES
|
||||
from dredd_core.moderation import USER
|
||||
from pydantic import AfterValidator, BaseModel, Field
|
||||
from pydantic import AfterValidator, BaseModel, BeforeValidator, Field
|
||||
|
||||
from .enums import NodeRole
|
||||
from .services.skill_pack import MAX_PACK_BYTES
|
||||
|
||||
_EMAIL = re.compile(r"^[^@\s]+@[^@\s.]+(\.[^@\s.]+)+$")
|
||||
|
||||
@@ -240,7 +244,7 @@ class ProviderUpdateIn(BaseModel):
|
||||
name: str | None = Field(default=None, max_length=120)
|
||||
kind: str | None = Field(default=None, max_length=20)
|
||||
base_url: str | None = Field(default=None, max_length=2000)
|
||||
models: list[Any] | None = Field(default=None, max_length=100)
|
||||
models: list[Any] | None = Field(default=None, max_length=1000) # OpenRouter lists hundreds; the 2 MB listing cap bounds the rest
|
||||
trains_on_data: bool | None = None
|
||||
api_key: str | None = Field(default=None, max_length=4096, repr=False)
|
||||
region: str | None = Field(default=None, max_length=8)
|
||||
@@ -258,7 +262,7 @@ class ProviderCreateIn(BaseModel):
|
||||
name: str = Field(max_length=120)
|
||||
kind: str = Field(max_length=20)
|
||||
base_url: str = Field(max_length=2000)
|
||||
models: list[Any] = Field(max_length=100)
|
||||
models: list[Any] = Field(max_length=1000)
|
||||
trains_on_data: bool
|
||||
api_key: str | None = Field(default=None, max_length=4096, repr=False)
|
||||
region: str | None = Field(default=None, max_length=8)
|
||||
@@ -268,6 +272,21 @@ class ProviderCreateIn(BaseModel):
|
||||
key_mode: str = Field(default="firm", max_length=20)
|
||||
|
||||
|
||||
class ProviderDiscoverIn(BaseModel):
|
||||
"""What the administrator pasted: an API key, or a server's address (with its key if it needs one)."""
|
||||
input: str = Field(min_length=1, max_length=4096, repr=False)
|
||||
key: str | None = Field(default=None, max_length=4096, repr=False)
|
||||
|
||||
|
||||
class ProviderDiscoverOut(BaseModel):
|
||||
"""What `discover` recognised. Nothing is stored; the console sends it back through `POST ""`."""
|
||||
vendor: str | None
|
||||
name: str
|
||||
kind: str
|
||||
base_url: str
|
||||
models: list[Any]
|
||||
|
||||
|
||||
class ProviderPolicyIn(BaseModel):
|
||||
"""`None` = leave as it is."""
|
||||
level: str | None = Field(default=None, max_length=20)
|
||||
@@ -277,3 +296,73 @@ class ProviderPolicyIn(BaseModel):
|
||||
class MyModelKeyIn(BaseModel):
|
||||
"""A person's own API key for a `key_mode = "user"` provider. Write-only, like the firm's."""
|
||||
api_key: str = Field(max_length=4096, repr=False)
|
||||
|
||||
|
||||
# ── skills ─────────────────────────────────────────────────────────────────────
|
||||
# Lengths and transport only. What a skill may say (kebab slug, description ≤ 1024, body ≤ 30 000,
|
||||
# file types and signatures) is `services/skill_pack.read_pack`'s, so a typed skill and an imported
|
||||
# one are refused with the same `code`; a second copy here would answer a bare 422 first.
|
||||
|
||||
def _decoded_files(v: Any) -> Any:
|
||||
"""path -> base64 in, path -> bytes out, at most `MAX_PACK_BYTES` in total — the same ceiling
|
||||
as an uploaded pack, so a skill typed in the console cannot grow past what it could export."""
|
||||
if not isinstance(v, dict):
|
||||
return v # None, or a wrong type the field's own validation refuses
|
||||
out, total = {}, 0
|
||||
for path, b64 in v.items():
|
||||
try:
|
||||
out[path] = base64.b64decode(b64, validate=True)
|
||||
except (binascii.Error, ValueError, TypeError):
|
||||
raise ValueError(f"{path}: not valid base64.") from None
|
||||
total += len(out[path])
|
||||
if total > MAX_PACK_BYTES:
|
||||
raise ValueError("The files come to more than 10 MB.")
|
||||
return out
|
||||
|
||||
|
||||
SkillFiles = Annotated[dict[str, bytes] | None, BeforeValidator(_decoded_files)]
|
||||
|
||||
MAX_JSON_FIELD_BYTES = 8 * 1024
|
||||
|
||||
|
||||
def _small_json(v: Any) -> Any:
|
||||
"""A free-form JSON object capped at 8 KB serialised — the bound `metadata`'s CHECK already
|
||||
keeps in the database, enforced here too so an oversized one is a 422, not a database error."""
|
||||
if v is not None and len(json.dumps(v, allow_nan=False).encode("utf-8")) > MAX_JSON_FIELD_BYTES:
|
||||
raise ValueError("More than 8 KB of JSON.")
|
||||
return v
|
||||
|
||||
|
||||
SmallJson = Annotated[dict[str, Any] | None, AfterValidator(_small_json)]
|
||||
|
||||
|
||||
class SkillVersionIn(BaseModel):
|
||||
"""A new version. `None` = carried over from the newest one; `files: {}` removes them all."""
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
description: str | None = Field(default=None, max_length=2000)
|
||||
body: str | None = Field(default=None, max_length=60_000)
|
||||
license: str | None = Field(default=None, max_length=200)
|
||||
metadata: SmallJson = None
|
||||
files: SkillFiles = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class SkillCreateIn(SkillVersionIn):
|
||||
slug: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
description: str = Field(min_length=1, max_length=2000)
|
||||
body: str = Field(max_length=60_000)
|
||||
|
||||
|
||||
class AgentVersionIn(BaseModel):
|
||||
"""A new agent version. `None` = carried over from the newest one; `skill_version_ids: []`
|
||||
unpins everything. `model_policy` and `tools` are a hint and a request, never a grant (D3)."""
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
instructions: str | None = Field(default=None, max_length=60_000)
|
||||
model_policy: SmallJson = None
|
||||
tools: list[Annotated[str, Field(max_length=200)]] | None = Field(default=None, max_length=50)
|
||||
skill_version_ids: list[uuid.UUID] | None = Field(default=None, max_length=100)
|
||||
|
||||
|
||||
class AgentCreateIn(AgentVersionIn):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
instructions: str = Field(max_length=60_000)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""A file attached to a Home chat question: its text, and nothing kept.
|
||||
|
||||
The bytes arrive, the text goes back, and neither is stored: the console holds the text for the
|
||||
conversation and sends it to the model as one more source, the way it sends a contract or a matter.
|
||||
So the privacy of an attachment is the privacy of the question itself (the provider's policy decides
|
||||
where it may go), and there is no file anywhere to delete afterwards.
|
||||
|
||||
PDF through pypdf (BSD-3, pure Python), DOCX through the standard library (it is a ZIP of XML),
|
||||
plain text decoded as UTF-8 and, failing that, as Windows-1250, which is what Polish text files
|
||||
from older Office installations are. Every page of a PDF is marked `[strona N]` so the model can say
|
||||
where it read something.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
from xml.etree import ElementTree
|
||||
|
||||
from ..errors import ValidationError
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PAGES = 300
|
||||
MAX_CHARS = 400_000 # more than any model here reads; the console trims to the model's budget
|
||||
_MAX_XML = 50 * 1024 * 1024 # word/document.xml unpacked: a ZIP bomb stops here, not in memory
|
||||
TEXT_TYPES = (".txt", ".md", ".csv")
|
||||
_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
|
||||
|
||||
|
||||
def _refuse(code: str, pl: str, en: str) -> ValidationError:
|
||||
return ValidationError(pl, {"code": code, "en": en})
|
||||
|
||||
|
||||
def _pdf(data: bytes) -> tuple[str, int]:
|
||||
from pypdf import PdfReader
|
||||
from pypdf.errors import PdfReadError
|
||||
try:
|
||||
reader = PdfReader(io.BytesIO(data))
|
||||
if reader.is_encrypted and not reader.decrypt(""):
|
||||
raise _refuse("attachment_encrypted", "Plik PDF jest zabezpieczony hasłem.",
|
||||
"The PDF is password-protected.")
|
||||
pages = reader.pages
|
||||
if len(pages) > MAX_PAGES:
|
||||
raise _refuse("attachment_too_long", f"Plik ma więcej niż {MAX_PAGES} stron.",
|
||||
f"The file has more than {MAX_PAGES} pages.")
|
||||
parts, total = [], 0
|
||||
for n, page in enumerate(pages, 1):
|
||||
text = (page.extract_text() or "").strip()
|
||||
parts.append(f"[strona {n}]\n{text}")
|
||||
total += len(text)
|
||||
if total > MAX_CHARS:
|
||||
break
|
||||
except PdfReadError as exc:
|
||||
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku PDF.",
|
||||
"This PDF cannot be read.") from exc
|
||||
if not total:
|
||||
raise _refuse("attachment_no_text",
|
||||
"Ten PDF nie ma warstwy tekstu (to skan). Potrzebne jest rozpoznanie tekstu (OCR).",
|
||||
"This PDF has no text layer (a scan). It needs OCR.")
|
||||
return "\n\n".join(parts), len(pages)
|
||||
|
||||
|
||||
def _docx(data: bytes) -> str:
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||||
info = z.getinfo("word/document.xml")
|
||||
if info.file_size > _MAX_XML:
|
||||
raise _refuse("attachment_too_long", "Dokument jest za duży.", "The document is too large.")
|
||||
xml = z.read(info)
|
||||
# Word never writes a DTD; without one there are no entities to expand (XXE, billion laughs).
|
||||
if b"<!DOCTYPE" in xml or b"<!ENTITY" in xml:
|
||||
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
|
||||
"This DOCX cannot be read.")
|
||||
root = ElementTree.fromstring(xml)
|
||||
except (zipfile.BadZipFile, KeyError, ElementTree.ParseError) as exc:
|
||||
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
|
||||
"This DOCX cannot be read.") from exc
|
||||
lines = []
|
||||
for p in root.iter(f"{_W}p"):
|
||||
bits = []
|
||||
for el in p.iter():
|
||||
if el.tag == f"{_W}t":
|
||||
bits.append(el.text or "")
|
||||
elif el.tag == f"{_W}tab":
|
||||
bits.append("\t")
|
||||
elif el.tag in (f"{_W}br", f"{_W}cr"):
|
||||
bits.append("\n")
|
||||
lines.append("".join(bits))
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def _plain(data: bytes) -> str:
|
||||
try:
|
||||
return data.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
return data.decode("cp1250", errors="replace")
|
||||
|
||||
|
||||
def extract(name: str, data: bytes) -> dict:
|
||||
"""`{name, kind, pages, chars, text}` of one attached file, or a 422 saying why not."""
|
||||
if len(data) > MAX_BYTES:
|
||||
raise _refuse("attachment_too_large", "Plik jest większy niż 10 MB.", "The file is larger than 10 MB.")
|
||||
lower = name.lower()
|
||||
pages = None
|
||||
if lower.endswith(".pdf") and data.startswith(b"%PDF"):
|
||||
kind = "pdf"
|
||||
text, pages = _pdf(data)
|
||||
elif lower.endswith(".docx") and data.startswith(b"PK"):
|
||||
kind, text = "docx", _docx(data)
|
||||
elif lower.endswith(TEXT_TYPES) and b"\x00" not in data[:4096]:
|
||||
kind, text = "text", _plain(data)
|
||||
else:
|
||||
raise _refuse("attachment_type", "Ten rodzaj pliku nie jest obsługiwany. Dołącz PDF, DOCX, TXT, MD albo CSV.",
|
||||
"This kind of file is not supported. Attach a PDF, DOCX, TXT, MD or CSV.")
|
||||
text = text.strip()
|
||||
if not text:
|
||||
raise _refuse("attachment_empty", "W pliku nie ma tekstu.", "The file has no text.")
|
||||
return {"name": name, "kind": kind, "pages": pages, "chars": len(text), "text": text[:MAX_CHARS]}
|
||||
@@ -20,24 +20,29 @@ Three things this file adds, and only these:
|
||||
* **The shape out.** A key never leaves: not to the administrator, not in a list, not in a diff.
|
||||
The card says `has_key` and `key_prefix` (core's six-character, non-secret prefix) and nothing else.
|
||||
|
||||
**Nothing here calls a provider.** These endpoints store configuration; there is deliberately no
|
||||
"test connection", because a hub that fetches an administrator-typed URL is an SSRF primitive with
|
||||
an administrator's reach.
|
||||
**One thing here calls a provider: `discover`**, which lists the models under a pasted key or address.
|
||||
It is an administrator-typed outbound request (SSRF by nature), so it is held like the module probe:
|
||||
administrator only, the address through core's `check_base_url`, the limits in
|
||||
`integrations/model_server.list_models`, and an audit row naming the host — never the key.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from dredd_core import model_providers as core
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from .. import provider_keys
|
||||
from ..config import get_settings
|
||||
from ..errors import ConflictError, NotFoundError
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..integrations import model_server
|
||||
from ..models import AppUser, ModelProvider
|
||||
from . import audit
|
||||
|
||||
KEY_SECRET_MISSING = "model_provider_secret_missing"
|
||||
KEY_UNREADABLE = "model_provider_key_unreadable"
|
||||
|
||||
|
||||
def _secret() -> str:
|
||||
@@ -113,6 +118,12 @@ def disable(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str |
|
||||
return out(provider)
|
||||
|
||||
|
||||
def delete(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str | None) -> None:
|
||||
"""Core's `delete_unused`: only a disabled provider no run points at (409 otherwise)."""
|
||||
provider = core.get_or_404(db, provider_id)
|
||||
core.delete_unused(db, actor=actor, provider=provider, ip=ip)
|
||||
|
||||
|
||||
def policy_out(db: DbSession) -> dict:
|
||||
return {"level": core.policy(db), "eu_only": core.eu_only(db), "levels": list(core.POLICIES),
|
||||
"kinds": list(core.KINDS), "dialects": list(core.DIALECTS),
|
||||
@@ -126,12 +137,76 @@ def set_policy(db: DbSession, actor: AppUser, *, level: str | None, eu_only: boo
|
||||
return policy_out(db)
|
||||
|
||||
|
||||
# ── discovering a provider: paste a key or an address, get its models ────────
|
||||
# Longest prefix first: `sk-` would swallow the other two. The console does not repeat this table.
|
||||
KEY_PREFIXES: tuple[tuple[str, str, str, str], ...] = (
|
||||
# prefix, vendor, name, base_url
|
||||
("sk-ant-", "anthropic", "Anthropic", "https://api.anthropic.com/v1"),
|
||||
("sk-or-", "openrouter", "OpenRouter", "https://openrouter.ai/api/v1"),
|
||||
("sk-", "openai", "OpenAI", "https://api.openai.com/v1"),
|
||||
)
|
||||
|
||||
|
||||
def recognise(text: str, key: str | None) -> tuple[str | None, str, str, str, str | None]:
|
||||
"""`(vendor, name, kind, base_url, key)` for what the administrator pasted. Anything with `://`
|
||||
is an address and goes through core's `check_base_url` (http(s) only, no credentials, a sane
|
||||
host); a local host is `kind=local` by core's own `LOCAL_HOSTS`."""
|
||||
text = (text or "").strip()
|
||||
if "://" in text:
|
||||
host = (urlsplit(text).hostname or "").lower() if text.lower().startswith(("http://", "https://")) else ""
|
||||
kind = "local" if host in core.LOCAL_HOSTS else "api"
|
||||
base_url = core.check_base_url(text, kind)
|
||||
# A pasted cloud address is asked the way its vendor answers (Anthropic is not Bearer).
|
||||
return vendor_of(base_url), host, kind, base_url, (key or "").strip() or None
|
||||
for prefix, vendor, name, base_url in KEY_PREFIXES:
|
||||
if text.startswith(prefix):
|
||||
return vendor, name, "api", base_url, text
|
||||
raise ValidationError("Nie rozpoznaję tego klucza — wklej adres serwera.",
|
||||
{"code": "provider_unknown_key",
|
||||
"en": "I don't recognise this key — paste the server's address."})
|
||||
|
||||
|
||||
async def discover(db: DbSession, actor: AppUser, text: str, key: str | None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""The provider a pasted key or address names, with its chat models. Stores no provider; the
|
||||
audit row (host only) is the caller's to commit. Call it with no transaction open — the
|
||||
outbound request can take up to `model_server.LIST_DEADLINE`."""
|
||||
vendor, name, kind, base_url, key = recognise(text, key)
|
||||
# ponytail: a refused discovery is not audited — the 422 rolls the row back; record it in its
|
||||
# own transaction if failed attempts need to be answerable.
|
||||
models = await model_server.list_models(base_url, key, vendor)
|
||||
audit.record(db, action="model_provider.discover", entity_type="model_provider",
|
||||
actor_id=actor.id, detail=urlsplit(base_url).hostname, ip=ip)
|
||||
return {"vendor": vendor, "name": name, "kind": kind, "base_url": base_url, "models": models}
|
||||
|
||||
|
||||
def vendor_of(base_url: str) -> str | None:
|
||||
"""The vendor whose address this row has (`list_models` asks Anthropic differently)."""
|
||||
host = urlsplit(base_url).hostname
|
||||
return next((v for _p, v, _n, url in KEY_PREFIXES if urlsplit(url).hostname == host), None)
|
||||
|
||||
|
||||
async def refresh(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str | None) -> dict:
|
||||
"""Re-read a stored provider's models from the provider itself and store them through `update`
|
||||
(audited like any change). A refused listing — empty included — raises before anything is
|
||||
written, so the old list stays. Ends the read transaction before the outbound call."""
|
||||
provider = core.get_or_404(db, provider_id)
|
||||
base_url, name = provider.base_url, provider.name
|
||||
key = core.api_key(db, provider, decrypt) if provider.key_prefix is not None else None
|
||||
if provider.key_prefix is not None and key is None:
|
||||
raise ConflictError(
|
||||
f"Klucza API dostawcy {name} nie da się odczytać. Zapisz go ponownie.",
|
||||
{"code": KEY_UNREADABLE, "en": f"The API key of {name} cannot be read. Store it again."})
|
||||
db.commit() # nothing written yet: only closes the transaction the outbound call must not hold
|
||||
models = await model_server.list_models(base_url, key, vendor_of(base_url))
|
||||
return update(db, actor, provider_id, {"models": models}, ip=ip)
|
||||
|
||||
|
||||
# ── using a provider: Home's "ask the model" ─────────────────────────────────
|
||||
# Who may use what is core's `_use_filter` (policy, `allowed_for`, `eu_only`); the hub passes the
|
||||
# platform administrator as `is_admin`. Only `openai`-dialect models: Home speaks chat completions.
|
||||
|
||||
CHAT_DIALECT = "openai"
|
||||
KEY_UNREADABLE = "model_provider_key_unreadable"
|
||||
USER_KEY_MISSING = "model_provider_user_key_missing"
|
||||
USER_KEY_UNREADABLE = "model_provider_user_key_unreadable"
|
||||
|
||||
@@ -141,7 +216,7 @@ def usable_models(db: DbSession, user: AppUser) -> list[dict]:
|
||||
tells Home that a `user` provider needs the person's own key (Settings → My model keys)."""
|
||||
return [
|
||||
{"id": m["id"], "provider": p.name, "kind": p.kind, "stays_in_the_eu": core.stays_in_the_eu(p),
|
||||
"key_mode": p.key_mode}
|
||||
"key_mode": p.key_mode, "context_window": m.get("context_window")}
|
||||
for p in core.usable_providers(db, is_admin=bool(user.is_admin))
|
||||
for m in p.models or [] if m.get("dialect", CHAT_DIALECT) == CHAT_DIALECT
|
||||
]
|
||||
|
||||
@@ -50,6 +50,11 @@ SPECS: dict[str, Spec] = {
|
||||
# The availability a newly added module starts with.
|
||||
"default_availability": Spec(CHOICE, Availability.everyone.value,
|
||||
choices=tuple(a.value for a in Availability)),
|
||||
# Whether a firm skill or agent (and each of its later versions) waits for an administrator's
|
||||
# approval before the firm sees it, or is published at once.
|
||||
"skills_firm_publish": Spec(CHOICE, "approval", choices=("approval", "direct")),
|
||||
# Who may export a firm skill or agent as a pack. Your own you may always export.
|
||||
"skills_firm_export": Spec(CHOICE, "administrator", choices=("administrator", "everyone")),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
"""A skill pack (ZIP) — pure functions, no database.
|
||||
|
||||
`read_pack` is the ONE gate an uploaded archive passes before anything of it is kept. It refuses
|
||||
the whole pack, never a part of it: a pack that silently loses a file is a pack whose author and
|
||||
importer disagree about what it says. Every refusal is a `PackRejected` carrying a machine-readable
|
||||
`code` (and the offending paths), the same shape as `module_admission_refused`, so the console can
|
||||
word it in the reader's language.
|
||||
|
||||
The archive rules are checked on the central directory BEFORE a single byte is decompressed, and
|
||||
on the raw names (`ZipInfo.orig_filename`): on Windows `zipfile` rewrites `\\` to `/` in
|
||||
`filename`, which would let a backslash path through on a developer machine and not in CI.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import stat
|
||||
import struct
|
||||
import unicodedata
|
||||
import zipfile
|
||||
import zlib
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
import yaml
|
||||
|
||||
from app.errors import ValidationError
|
||||
|
||||
MAX_PACK_BYTES = 10 * 1024 * 1024
|
||||
MAX_FILES = 200
|
||||
MAX_UNPACKED_BYTES = 50 * 1024 * 1024
|
||||
MAX_RATIO = 100
|
||||
|
||||
#: code -> (PL, EN). The console words a refusal by `code`; keep `frontend/app.js` in step.
|
||||
MESSAGES = {
|
||||
"pack_too_large": ("Paczka jest większa niż 10 MB.", "The pack is larger than 10 MB."),
|
||||
"pack_not_zip": ("Plik nie jest poprawnym archiwum ZIP.", "The file is not a valid ZIP archive."),
|
||||
"pack_zip64": ("Archiwa ZIP64 nie są przyjmowane.", "ZIP64 archives are not accepted."),
|
||||
"pack_too_many_files": ("Paczka ma więcej niż 200 plików.", "The pack has more than 200 files."),
|
||||
"pack_unpacked_too_large": ("Po rozpakowaniu paczka przekracza 50 MB.",
|
||||
"The pack exceeds 50 MB once unpacked."),
|
||||
"pack_compression_ratio": ("Plik jest skompresowany ponad 100:1.",
|
||||
"A file is compressed more than 100:1."),
|
||||
"pack_bad_path": ("Niedozwolona ścieżka pliku (.., ścieżka absolutna albo \\).",
|
||||
"Forbidden file path (.., absolute path or \\)."),
|
||||
"pack_link": ("Paczka zawiera dowiązanie.", "The pack contains a link."),
|
||||
"pack_duplicate_name": ("Paczka zawiera dwa pliki o tej samej nazwie.",
|
||||
"The pack contains two files with the same name."),
|
||||
"pack_case_collision": ("Paczka zawiera nazwy różniące się tylko wielkością liter.",
|
||||
"The pack contains names that differ only in letter case."),
|
||||
"pack_file_type": ("Niedozwolony typ pliku (dozwolone: .md .txt .docx .pdf .xlsx .csv .json "
|
||||
".yaml .yml).",
|
||||
"Forbidden file type (allowed: .md .txt .docx .pdf .xlsx .csv .json "
|
||||
".yaml .yml)."),
|
||||
"pack_signature_mismatch": ("Treść pliku nie zgadza się z jego rozszerzeniem.",
|
||||
"A file's content does not match its extension."),
|
||||
"pack_macros": ("Dokument zawiera makra (vbaProject.bin).",
|
||||
"A document contains macros (vbaProject.bin)."),
|
||||
"pack_nested_zip": ("Paczka zawiera archiwum ZIP, które nie jest dokumentem Word ani Excel.",
|
||||
"The pack contains a ZIP archive that is not a Word or Excel document."),
|
||||
"pack_plugin_code": ("Wtyczka zawiera skrypty, hooki albo serwery MCP.",
|
||||
"The plugin contains scripts, hooks or MCP servers."),
|
||||
"pack_manifest_invalid": ("Plik atrium-pack.json jest uszkodzony.",
|
||||
"The atrium-pack.json file is malformed."),
|
||||
"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.",
|
||||
"SKILL.md or agent.md is not UTF-8."),
|
||||
"skill_frontmatter_too_large": ("Nagłówek SKILL.md albo agent.md jest większy niż 8 KB.",
|
||||
"The SKILL.md or agent.md frontmatter is larger than 8 KB."),
|
||||
"skill_frontmatter_alias": ("Nagłówek SKILL.md albo agent.md używa aliasów albo kotwic YAML.",
|
||||
"The SKILL.md or agent.md frontmatter uses YAML aliases or anchors."),
|
||||
"skill_frontmatter_invalid": ("Nagłówek SKILL.md albo agent.md nie jest poprawnym YAML.",
|
||||
"The SKILL.md or agent.md frontmatter is not valid YAML."),
|
||||
"skill_frontmatter_not_mapping": ("Nagłówek SKILL.md albo agent.md nie jest mapą klucz: wartość.",
|
||||
"The SKILL.md or agent.md frontmatter is not a key: value mapping."),
|
||||
"skill_missing_field": ("SKILL.md albo agent.md nie ma pola name albo description.",
|
||||
"SKILL.md or agent.md lacks a name or a description."),
|
||||
"skill_bad_name": ("Pole name musi być w formacie kebab-case, najwyżej 64 znaki.",
|
||||
"The name must be kebab-case, at most 64 characters."),
|
||||
"skill_description_too_long": ("Opis (description) jest dłuższy niż 1024 znaki.",
|
||||
"The description is longer than 1024 characters."),
|
||||
"skill_body_too_long": ("Treść SKILL.md jest dłuższa niż 30 000 znaków.",
|
||||
"The SKILL.md body is longer than 30,000 characters."),
|
||||
}
|
||||
|
||||
TEXT_TYPES = {".md", ".txt", ".csv", ".json", ".yaml", ".yml"}
|
||||
OFFICE_TYPES = {".docx", ".xlsx"}
|
||||
ALLOWED_TYPES = TEXT_TYPES | OFFICE_TYPES | {".pdf"}
|
||||
MAX_MANIFEST_BYTES = 1024 * 1024
|
||||
#: Content types that make an OOXML document carry code (VBA, macro sheets, ActiveX), lower-cased.
|
||||
_MACRO_TYPES = ("vbaproject", "macroenabled", "macrosheet", "activex")
|
||||
_ZIP_MAGIC = (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")
|
||||
|
||||
|
||||
class PackRejected(ValidationError):
|
||||
"""The whole pack is refused. `code` is a key of `MESSAGES`; `files` names what caused it."""
|
||||
|
||||
def __init__(self, code: str, files=()):
|
||||
self.code = code
|
||||
self.files = sorted(set(files))
|
||||
self.message_pl, self.message_en = MESSAGES[code]
|
||||
# Polish `detail` + English `en`, the shape of dredd-core's refusals: the console's
|
||||
# `coreRefusal` words it in either language without a second copy of MESSAGES.
|
||||
super().__init__(self.message_pl, extra={"code": code, "files": self.files,
|
||||
"en": self.message_en})
|
||||
|
||||
|
||||
MAX_FRONTMATTER_BYTES = 8 * 1024
|
||||
MAX_NAME = 64
|
||||
MAX_DESCRIPTION = 1024
|
||||
MAX_BODY = 30_000 # the chat tool's result limit
|
||||
_KEBAB = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
|
||||
#: D3: kept as information, never granted. The platform decides what a skill may do.
|
||||
INFO_ONLY_KEYS = ("allowed-tools", "model", "hooks", "mcpServers", "permissionMode")
|
||||
#: Plugin manifest keys that declare code inline (D1).
|
||||
_PLUGIN_CODE_KEYS = ("hooks", "mcpServers")
|
||||
_PLUGIN_CODE_DIRS = ("hooks/", "scripts/", "bin/")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SkillDoc:
|
||||
path: str # of its SKILL.md inside the pack
|
||||
name: str
|
||||
description: str
|
||||
body: str
|
||||
frontmatter: dict # every key, the info-only ones included
|
||||
info_only: dict # D3: what the file asked for and was not given
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentDoc:
|
||||
name: str
|
||||
description: str
|
||||
body: str # the instructions
|
||||
frontmatter: dict # `kind`, `tools`, `model` (a hint) — the service decides what to keep
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Pack:
|
||||
files: dict[str, bytes] # path -> content, directories and the manifest left out
|
||||
skills: tuple[SkillDoc, ...] = () # one per SKILL.md, in path order
|
||||
agent: AgentDoc | None = None # from a root `agent.md`
|
||||
kind: str | None = None # the manifest's `type`; None for a pack without one
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SkillContent:
|
||||
"""One skill as it is hashed and packed: its folder name, frontmatter, body and the files beside
|
||||
its SKILL.md (paths relative to the folder). The service builds it from a stored version."""
|
||||
folder: str
|
||||
frontmatter: dict
|
||||
body: str
|
||||
files: dict[str, bytes]
|
||||
|
||||
|
||||
MANIFEST = "atrium-pack.json"
|
||||
FORMAT_VERSION = 1
|
||||
AGENT_DOC = "agent.md"
|
||||
|
||||
|
||||
_ZIP64_EXTRA = 0x0001
|
||||
_LOCAL_HEADER = struct.Struct("<4s2B4HL2L2H") # zipfile's own `structFileHeader`
|
||||
|
||||
|
||||
def _extra_ids(extra: bytes) -> set[int]:
|
||||
ids, i = set(), 0
|
||||
while i + 4 <= len(extra):
|
||||
tag, size = struct.unpack_from("<HH", extra, i)
|
||||
ids.add(tag)
|
||||
i += 4 + size
|
||||
return ids
|
||||
|
||||
|
||||
def _is_zip64(data: bytes, infos: list[zipfile.ZipInfo]) -> bool:
|
||||
# ponytail: a ZIP64 locator signature anywhere in the tail refuses, a comment quoting it included
|
||||
# — fail closed. The local headers are read too: `force_zip64` writes the extra only there.
|
||||
if b"PK\x06\x07" in data[-(65535 + 22 + 20):]:
|
||||
return True
|
||||
for info in infos:
|
||||
if _ZIP64_EXTRA in _extra_ids(info.extra):
|
||||
return True
|
||||
head = data[info.header_offset:info.header_offset + _LOCAL_HEADER.size]
|
||||
if len(head) < _LOCAL_HEADER.size:
|
||||
continue # a truncated header fails the read below
|
||||
fields = _LOCAL_HEADER.unpack(head)
|
||||
start = info.header_offset + _LOCAL_HEADER.size + fields[10]
|
||||
if _ZIP64_EXTRA in _extra_ids(data[start:start + fields[11]]):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def bad_path(name: str) -> bool:
|
||||
return (not name or "\\" in name or "\0" in name or name.startswith("/")
|
||||
or (len(name) > 1 and name[1] == ":")
|
||||
or any(part == ".." for part in name.split("/")))
|
||||
|
||||
|
||||
def _open_archive(data: bytes) -> tuple[zipfile.ZipFile, list[zipfile.ZipInfo]]:
|
||||
"""Every archive rule, on the central directory alone — nothing is decompressed here. Shared by
|
||||
the pack and by each DOCX/XLSX inside it ("the same limits")."""
|
||||
if len(data) > MAX_PACK_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(data))
|
||||
except (zipfile.BadZipFile, ValueError, EOFError):
|
||||
raise PackRejected("pack_not_zip") from None
|
||||
infos = zf.infolist()
|
||||
if _is_zip64(data, infos):
|
||||
raise PackRejected("pack_zip64")
|
||||
members = [i for i in infos if not i.is_dir()]
|
||||
if len(members) > MAX_FILES:
|
||||
raise PackRejected("pack_too_many_files")
|
||||
|
||||
names = [i.orig_filename for i in infos]
|
||||
bad = [n for n in names if bad_path(n)]
|
||||
if bad:
|
||||
raise PackRejected("pack_bad_path", bad)
|
||||
links = [i.orig_filename for i in infos if stat.S_ISLNK(i.external_attr >> 16)]
|
||||
if links:
|
||||
raise PackRejected("pack_link", links)
|
||||
seen, dupes = set(), set()
|
||||
for n in names:
|
||||
(dupes if n in seen else seen).add(n)
|
||||
if dupes:
|
||||
raise PackRejected("pack_duplicate_name", dupes)
|
||||
folded: dict[str, str] = {}
|
||||
clashes = set()
|
||||
for n in names:
|
||||
other = folded.setdefault(n.rstrip("/").casefold(), n)
|
||||
if other != n:
|
||||
clashes |= {n, other}
|
||||
if clashes:
|
||||
raise PackRejected("pack_case_collision", clashes)
|
||||
|
||||
if sum(i.file_size for i in members) > MAX_UNPACKED_BYTES:
|
||||
raise PackRejected("pack_unpacked_too_large")
|
||||
steep = [i.orig_filename for i in members if i.file_size > MAX_RATIO * max(i.compress_size, 1)]
|
||||
if steep:
|
||||
raise PackRejected("pack_compression_ratio", steep)
|
||||
return zf, members
|
||||
|
||||
|
||||
def _suffix(path: str) -> str:
|
||||
name = path.rsplit("/", 1)[-1]
|
||||
return name[name.rfind("."):].lower() if "." in name else ""
|
||||
|
||||
|
||||
def _bounded_read(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> bytes:
|
||||
"""A member's bytes, never inflating more than its declared size + 1. `zf.read(info)` is NOT
|
||||
bounded: `ZipExtFile.read()` with no size decompresses the whole stream (up to ~2 GB) and only
|
||||
then trims to the declared size, so a 300 KB member declaring 5 MB took 600 MB of memory. A
|
||||
sized read passes the size down to `decompress(max_length=...)`. A stream longer or shorter
|
||||
than declared is a lie about the size, refused like any other broken archive."""
|
||||
with zf.open(info) as member:
|
||||
data = member.read(info.file_size + 1)
|
||||
if len(data) != info.file_size:
|
||||
raise PackRejected("pack_not_zip")
|
||||
return data
|
||||
|
||||
|
||||
def _check_office(path: str, data: bytes) -> None:
|
||||
# Only `[Content_Types].xml` is ever inflated (capped first); no other part is read. The name
|
||||
# `vbaProject.bin` is a convention, not a rule — a renamed part still has to declare its content
|
||||
# type, so the manifest is searched too (as bytes: nothing here parses XML).
|
||||
# ponytail: an embedded document (word/embeddings/*.docm) is not recursed into; Word itself asks
|
||||
# before running its macros. Recurse here if that stops being enough.
|
||||
try:
|
||||
zf, parts = _open_archive(data)
|
||||
by_name = {p.orig_filename: p for p in parts}
|
||||
manifest = by_name.get("[Content_Types].xml")
|
||||
if manifest is None or manifest.file_size > MAX_MANIFEST_BYTES:
|
||||
raise PackRejected("pack_signature_mismatch")
|
||||
types = _bounded_read(zf, manifest)
|
||||
# Fail closed on anything a substring search could be fooled by: UTF-16/32 (NULs), XML
|
||||
# character references (`vbaProject`), bytes that are not UTF-8. Office writes none.
|
||||
if b"\0" in types or b"&#" in types:
|
||||
raise PackRejected("pack_signature_mismatch")
|
||||
types = types.decode("utf-8").lower()
|
||||
except PackRejected as inner:
|
||||
raise PackRejected(inner.code, [path]) from None
|
||||
except UnicodeDecodeError:
|
||||
raise PackRejected("pack_signature_mismatch", [path]) from None
|
||||
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, EOFError, zlib.error):
|
||||
raise PackRejected("pack_not_zip", [path]) from None
|
||||
if (any(n.rsplit("/", 1)[-1].lower() == "vbaproject.bin" for n in by_name)
|
||||
or any(marker in types for marker in _MACRO_TYPES)):
|
||||
raise PackRejected("pack_macros", [path])
|
||||
|
||||
|
||||
def _check_files(files: dict[str, bytes]) -> None:
|
||||
"""The file rules: an allowed extension, and content that is what the extension says. Nothing
|
||||
here reads text (variant b): a signature is checked, never parsed."""
|
||||
wrong_type = [p for p in files if _suffix(p) not in ALLOWED_TYPES]
|
||||
if wrong_type:
|
||||
raise PackRejected("pack_file_type", wrong_type)
|
||||
for path, data in files.items():
|
||||
kind = _suffix(path)
|
||||
if kind in OFFICE_TYPES:
|
||||
if not data.startswith(b"PK\x03\x04"):
|
||||
raise PackRejected("pack_signature_mismatch", [path])
|
||||
_check_office(path, data)
|
||||
elif kind == ".pdf":
|
||||
if not data.startswith(b"%PDF-"):
|
||||
raise PackRejected("pack_signature_mismatch", [path])
|
||||
elif data.startswith(_ZIP_MAGIC):
|
||||
raise PackRejected("pack_nested_zip", [path])
|
||||
elif b"\0" in data:
|
||||
# ponytail: "text" = no NUL byte, so any binary (and UTF-16) is refused while a
|
||||
# Windows-1250 CSV still passes; the encoding itself is SKILL.md's rule, not a resource's.
|
||||
raise PackRejected("pack_signature_mismatch", [path])
|
||||
|
||||
|
||||
def _check_plugin(files: dict[str, bytes]) -> None:
|
||||
"""A Claude Code plugin (a `.claude-plugin/` folder) is read for its `skills/*/SKILL.md`; code
|
||||
in it refuses the whole pack WITH the list of files (D1), never by quietly leaving it out — a
|
||||
skill may lean on its plugin's hook, and the importer must know it did not come along. Runs
|
||||
before the extension rule, so a plugin's `.sh` is named as plugin code, not as a wrong type."""
|
||||
# By path segment, every one of them: a plugin nested in another is judged against both roots.
|
||||
roots = set()
|
||||
for path in files:
|
||||
parts = path.split("/")
|
||||
roots |= {"/".join(parts[:i]) + "/" if i else "" for i, part in enumerate(parts[:-1])
|
||||
if part == ".claude-plugin"}
|
||||
code = []
|
||||
for path, data in files.items():
|
||||
for rel in (path[len(r):] for r in roots if path.startswith(r)):
|
||||
if (_suffix(rel) not in ALLOWED_TYPES or rel.startswith(_PLUGIN_CODE_DIRS)
|
||||
or rel.rsplit("/", 1)[-1] == ".mcp.json"):
|
||||
code.append(path)
|
||||
elif rel.startswith(".claude-plugin/") and rel.endswith(".json"):
|
||||
try:
|
||||
manifest = json.loads(data)
|
||||
except ValueError:
|
||||
raise PackRejected("pack_signature_mismatch", [path]) from None
|
||||
if isinstance(manifest, dict) and any(k in manifest for k in _PLUGIN_CODE_KEYS):
|
||||
code.append(path)
|
||||
if code:
|
||||
raise PackRejected("pack_plugin_code", code)
|
||||
|
||||
|
||||
class _JsonLoader(yaml.SafeLoader):
|
||||
"""SafeLoader that keeps `2025-01-01` a string. Frontmatter lands in a JSONB column, and the
|
||||
stock resolver turns dates into `datetime.date`, which JSON cannot carry (a 500 on save).
|
||||
Explicit tags that build non-JSON values (`!!binary`, `!!set`) are caught after loading."""
|
||||
|
||||
|
||||
_JsonLoader.yaml_implicit_resolvers = {
|
||||
first: [(tag, regexp) for tag, regexp in resolvers if tag != "tag:yaml.org,2002:timestamp"]
|
||||
for first, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items()
|
||||
}
|
||||
|
||||
|
||||
def _has_alias(text: str) -> bool:
|
||||
return any(isinstance(t, yaml.AliasToken | yaml.AnchorToken)
|
||||
for t in yaml.scan(text, Loader=yaml.SafeLoader))
|
||||
|
||||
|
||||
def _split_frontmatter(text: str) -> tuple[str, str]:
|
||||
"""`---` line, YAML, `---` line, body. No opening fence = no frontmatter (and so no name)."""
|
||||
if not text.startswith("---\n"):
|
||||
return "", text
|
||||
end = text.find("\n---\n", 3)
|
||||
if end == -1:
|
||||
return (text[4:], "") if text.endswith("\n---") else ("", text)
|
||||
return text[4:end + 1], text[end + 5:]
|
||||
|
||||
|
||||
_FLAT_KEY = re.compile(r"([A-Za-z][\w-]*):(?:[ \t]+(.*))?")
|
||||
_YAML_INDICATORS = set("[]{}!&*|>'\"%@`#,?-")
|
||||
|
||||
|
||||
def _flat_frontmatter(head: str) -> dict | None:
|
||||
"""Claude Code reads `description: Use when ... SKIP: x` as one string; strict YAML refuses the
|
||||
second `: `. Most real SKILL.md files are written that way, so when YAML fails we accept the
|
||||
shape only if every line is a top-level `key: text` or an indented continuation of one —
|
||||
every value a plain string. Anything nested still has to be valid YAML."""
|
||||
meta: dict = {}
|
||||
last = None
|
||||
for line in head.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
m = None if line[0] in " \t" else _FLAT_KEY.fullmatch(line.rstrip())
|
||||
if m and (m.group(2) or "")[:1] in _YAML_INDICATORS:
|
||||
# `paths: ["*.gs"]`, `hint: "[review]"`: that one value is YAML, read alone. A broken
|
||||
# one (`[x`, `!!python/...`, a dangling `*alias`) refuses the whole frontmatter.
|
||||
try:
|
||||
meta[m.group(1)] = yaml.load(m.group(2), Loader=_JsonLoader) # noqa: S506 - SafeLoader subclass
|
||||
except yaml.YAMLError:
|
||||
return None
|
||||
last = None # a structured value takes no continuation lines
|
||||
continue
|
||||
if m:
|
||||
last = m.group(1)
|
||||
meta[last] = (m.group(2) or "").strip()
|
||||
elif last is not None and line[0] in " \t":
|
||||
meta[last] = f"{meta[last]} {line.strip()}".strip()
|
||||
else:
|
||||
return None
|
||||
return meta
|
||||
|
||||
|
||||
def _read_doc(path: str, data: bytes) -> tuple[dict, str, str, str]:
|
||||
"""The frontmatter rules SKILL.md and agent.md share: -> (frontmatter, name, description, body)."""
|
||||
try:
|
||||
text = data.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
raise PackRejected("skill_not_utf8", [path]) from None
|
||||
head, body = _split_frontmatter(text.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
# The size gate comes first: it is what bounds the YAML parser's work.
|
||||
if len(head.encode("utf-8")) > MAX_FRONTMATTER_BYTES:
|
||||
raise PackRejected("skill_frontmatter_too_large", [path])
|
||||
try:
|
||||
# A billion-laughs bomb fits in 8 KB, and a skill's frontmatter has no use for aliases.
|
||||
try:
|
||||
if _has_alias(head):
|
||||
raise PackRejected("skill_frontmatter_alias", [path])
|
||||
meta = yaml.load(head, Loader=_JsonLoader) if head.strip() else {} # noqa: S506 - SafeLoader subclass
|
||||
except yaml.YAMLError:
|
||||
# Not YAML at all: flat text, never interpreted, so no alias can expand in it.
|
||||
meta = _flat_frontmatter(head)
|
||||
if meta is None:
|
||||
raise
|
||||
# What reaches JSONB must be JSON: `!!binary`, `!!set`, a timestamp tag, `.nan` (JSONB refuses NaN).
|
||||
json.dumps(meta, allow_nan=False)
|
||||
except (yaml.YAMLError, RecursionError, TypeError, ValueError): # 8 KB of `[` nests deeper than the composer recurses
|
||||
raise PackRejected("skill_frontmatter_invalid", [path]) from None
|
||||
if not isinstance(meta, dict):
|
||||
raise PackRejected("skill_frontmatter_not_mapping", [path])
|
||||
name, description = meta.get("name"), meta.get("description")
|
||||
if not (isinstance(name, str) and name and isinstance(description, str) and description.strip()):
|
||||
raise PackRejected("skill_missing_field", [path])
|
||||
return meta, name, description, body
|
||||
|
||||
|
||||
def _read_skill(path: str, data: bytes) -> SkillDoc:
|
||||
meta, name, description, body = _read_doc(path, data)
|
||||
if len(name) > MAX_NAME or not _KEBAB.fullmatch(name):
|
||||
raise PackRejected("skill_bad_name", [path])
|
||||
if len(description) > MAX_DESCRIPTION:
|
||||
raise PackRejected("skill_description_too_long", [path])
|
||||
if len(body) > MAX_BODY:
|
||||
raise PackRejected("skill_body_too_long", [path])
|
||||
return SkillDoc(path=path, name=name, description=description, body=body, frontmatter=meta,
|
||||
info_only={k: meta[k] for k in INFO_ONLY_KEYS if k in meta})
|
||||
|
||||
|
||||
def read_pack(data: bytes) -> Pack:
|
||||
"""Check an uploaded archive against every archive rule and every file rule, and return its
|
||||
files, or raise `PackRejected`. Sizes are trusted from the central directory only because
|
||||
`_bounded_read` never inflates past a member's declared size + 1 and refuses a member whose
|
||||
stream disagrees with it, so the declared total bounds what is actually inflated."""
|
||||
zf, members = _open_archive(data)
|
||||
try:
|
||||
files = {i.filename: _bounded_read(zf, i) for i in members}
|
||||
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, EOFError, zlib.error):
|
||||
# A CRC mismatch, an encrypted member, an unknown compression method, a truncated stream.
|
||||
raise PackRejected("pack_not_zip") from None
|
||||
_check_plugin(files)
|
||||
_check_files(files)
|
||||
kind = _check_manifest(files)
|
||||
# ponytail: a pack with no SKILL.md is not refused here — an agent pack may pin none; whether a
|
||||
# skill import needs one is the import's rule (services/skills.py).
|
||||
skills = tuple(_read_skill(p, d) for p, d in sorted(files.items())
|
||||
if p.rsplit("/", 1)[-1] == "SKILL.md")
|
||||
agent = None
|
||||
if AGENT_DOC in files:
|
||||
meta, name, description, body = _read_doc(AGENT_DOC, files[AGENT_DOC])
|
||||
agent = AgentDoc(name=name, description=description, body=body, frontmatter=meta)
|
||||
return Pack(files=files, skills=skills, agent=agent, kind=kind)
|
||||
|
||||
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _check_manifest(files: dict[str, bytes]) -> str | None:
|
||||
"""Verify `atrium-pack.json` and take it out of `files`. A pack without one (a skill ZIP from
|
||||
elsewhere) is accepted: the sums guard a pack against change on the way, they say nothing of
|
||||
its author, so their absence takes nothing away."""
|
||||
raw = files.pop(MANIFEST, None)
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
manifest = json.loads(raw)
|
||||
listed = {f["path"]: f["sha256"] for f in manifest["files"]}
|
||||
kind = manifest["type"]
|
||||
if manifest["format"] != FORMAT_VERSION or kind not in ("skill", "agent"):
|
||||
raise ValueError
|
||||
except (ValueError, KeyError, TypeError):
|
||||
raise PackRejected("pack_manifest_invalid", [MANIFEST]) from None
|
||||
# Both directions: a file added on the way is as much a change as one altered.
|
||||
wrong = {p for p in listed.keys() | files.keys()
|
||||
if p not in files or listed.get(p) != _sha(files[p])}
|
||||
if wrong:
|
||||
raise PackRejected("pack_manifest_mismatch", wrong)
|
||||
return kind
|
||||
|
||||
|
||||
def skill_content(pack: Pack, skill: SkillDoc) -> SkillContent:
|
||||
"""The skill as `content_sha256` and `build_pack` see it: everything under its SKILL.md's folder."""
|
||||
# ponytail: a SKILL.md nested inside another skill's folder is counted in both; packs this module
|
||||
# builds never nest, and an import keeps one skill per folder.
|
||||
prefix = skill.path[: -len("SKILL.md")]
|
||||
files = {p[len(prefix):]: d for p, d in pack.files.items()
|
||||
if p.startswith(prefix) and p != skill.path and not (prefix == "" and p == AGENT_DOC)}
|
||||
return SkillContent(folder=prefix.rstrip("/").rsplit("/", 1)[-1] or skill.name,
|
||||
frontmatter=skill.frontmatter, body=skill.body, files=files)
|
||||
|
||||
|
||||
def _document(frontmatter: dict, body: str) -> str:
|
||||
"""The canonical text: NFC, LF, the frontmatter re-dumped with its keys in alphabetical order —
|
||||
so a pack that went out and came back in hashes the same however its YAML was spelt."""
|
||||
head = yaml.safe_dump(frontmatter, sort_keys=True, allow_unicode=True, default_flow_style=False)
|
||||
text = f"---\n{head}---\n{body}".replace("\r\n", "\n").replace("\r", "\n")
|
||||
return unicodedata.normalize("NFC", text)
|
||||
|
||||
|
||||
def content_sha256(skill: SkillContent) -> str:
|
||||
"""SHA-256 of the canonical SKILL.md and the sorted `path\\0sha256` lines of its files."""
|
||||
listing = "\n".join(f"{p}\0{_sha(d)}" for p, d in sorted(skill.files.items()))
|
||||
return _sha(_document(skill.frontmatter, skill.body).encode("utf-8") + b"\0\0"
|
||||
+ listing.encode("utf-8"))
|
||||
|
||||
|
||||
def build_pack(skills: Sequence[SkillContent], agent: AgentDoc | None = None) -> bytes:
|
||||
"""A ZIP of one skill (`agent=None`) or of an agent with the skills it pins, each in its own
|
||||
folder, plus `atrium-pack.json` listing every file's sha256. What it writes, `read_pack` reads."""
|
||||
folders = [s.folder for s in skills]
|
||||
if len(set(folders)) != len(folders) or (agent is None and len(skills) != 1):
|
||||
raise ValueError("a pack holds one skill, or an agent with skills in distinct folders")
|
||||
files: dict[str, bytes] = {}
|
||||
for s in skills:
|
||||
files[f"{s.folder}/SKILL.md"] = _document(s.frontmatter, s.body).encode("utf-8")
|
||||
files.update({f"{s.folder}/{p}": d for p, d in s.files.items()})
|
||||
if agent is not None:
|
||||
files[AGENT_DOC] = _document(agent.frontmatter, agent.body).encode("utf-8")
|
||||
manifest = {"format": FORMAT_VERSION, "type": "skill" if agent is None else "agent",
|
||||
"files": [{"path": p, "sha256": _sha(d)} for p, d in sorted(files.items())]}
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for path, data in sorted(files.items()):
|
||||
zf.writestr(path, data)
|
||||
zf.writestr(MANIFEST, json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return buf.getvalue()
|
||||
@@ -0,0 +1,840 @@
|
||||
"""Skills: a person's own instructions and reference files, versioned and frozen.
|
||||
|
||||
A deliberate exception to "`authz` is the only access authority"
|
||||
-----------------------------------------------------------------
|
||||
Skills (and agents) are not nodes of the org tree — the tree holds units only — so
|
||||
`authz.assert_can_read` has nothing to say about them. Who may see one is decided HERE, in one
|
||||
rule: **the owner, plus everybody for a `firm` one**. `visible_to` is that rule as SQL (lists) and
|
||||
`can_see` the same rule on a loaded row (single reads); every read and write path goes through one
|
||||
of them. Somebody else's personal skill is a 404, never a 403 — its existence is the owner's
|
||||
business. An administrator gets no exception here: a personal skill is a lawyer's working notes,
|
||||
and an administrator sees one only inside a publish request (the publication path, not this one).
|
||||
|
||||
Who may CHANGE one (`can_edit`): the owner, and for a firm skill also an administrator. Everybody
|
||||
else makes a personal copy.
|
||||
|
||||
Versions are frozen
|
||||
-------------------
|
||||
Changing content is a new `skill_version` (`n + 1`), never an edit; the runtime role holds no
|
||||
UPDATE or DELETE on the version tables (revision 0010). Every version is validated the way an
|
||||
import is — it is packed with `skill_pack.build_pack` and read back with `skill_pack.read_pack` — so
|
||||
a skill typed in the console and one uploaded as a ZIP obey the same rules and hash the same way.
|
||||
|
||||
`current_version_id` of a PERSONAL skill follows its newest version. A FIRM skill's is the approved
|
||||
one, and only publication moves it — a new version of a firm skill stays invisible to everybody but
|
||||
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
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
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
|
||||
|
||||
DEFAULT_LICENSE = "proprietary"
|
||||
#: The frontmatter keys that have columns of their own; everything else is kept in `metadata`.
|
||||
_OWN_KEYS = ("name", "description", "license")
|
||||
MEDIA_TYPES = {
|
||||
".md": "text/markdown", ".txt": "text/plain", ".csv": "text/csv",
|
||||
".json": "application/json", ".yaml": "application/yaml", ".yml": "application/yaml",
|
||||
".pdf": "application/pdf",
|
||||
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
}
|
||||
|
||||
|
||||
# ---- who may see and change ------------------------------------------------------------------
|
||||
|
||||
def can_see(user: AppUser, item) -> bool:
|
||||
"""The visibility rule on a loaded skill (or agent: same columns)."""
|
||||
return item.owner_id == user.id or item.scope == SkillScope.firm
|
||||
|
||||
|
||||
def can_edit(user: AppUser, item) -> bool:
|
||||
"""Owner, or an administrator for a firm one; everybody else makes a personal copy."""
|
||||
return item.owner_id == user.id or (item.scope == SkillScope.firm and bool(user.is_admin))
|
||||
|
||||
|
||||
def visible_to(db: DbSession, user: AppUser) -> list[Skill]:
|
||||
"""Every skill `user` may see — `can_see` as SQL. Archived ones included: an agent may still pin
|
||||
one, and the console says so."""
|
||||
return list(db.scalars(
|
||||
select(Skill).where(or_(Skill.owner_id == user.id, Skill.scope == SkillScope.firm))
|
||||
.order_by(Skill.name, Skill.id)))
|
||||
|
||||
|
||||
def _get(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
skill = db.get(Skill, skill_id)
|
||||
if skill is None or not can_see(user, skill):
|
||||
raise NotFoundError("Skill not found.")
|
||||
return skill
|
||||
|
||||
|
||||
def _get_editable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
skill = _get(db, user, skill_id)
|
||||
if not can_edit(user, skill):
|
||||
# A firm skill is visible, so refusing to change it reveals nothing.
|
||||
raise AuthorizationError("Only the owner or an administrator may change a firm skill.")
|
||||
return skill
|
||||
|
||||
|
||||
def readable_version_ids(user: AppUser, skill: Skill, version_ids) -> set[uuid.UUID]:
|
||||
"""An editor reads every version; anybody else only the current (for a firm skill: approved)."""
|
||||
if can_edit(user, skill):
|
||||
return set(version_ids)
|
||||
return {skill.current_version_id} & set(version_ids)
|
||||
|
||||
|
||||
# ---- content -----------------------------------------------------------------------------------
|
||||
|
||||
def next_n(latest: int | None) -> int:
|
||||
"""The number of the next version; the (skill_id, n) constraint settles a race."""
|
||||
return (latest or 0) + 1
|
||||
|
||||
|
||||
def frontmatter(slug: str, description: str, license: str, meta: Mapping) -> dict:
|
||||
"""The SKILL.md frontmatter a version stands for: its own columns win over `metadata`."""
|
||||
head = {k: v for k, v in meta.items() if k not in _OWN_KEYS}
|
||||
head.update(name=slug, description=description, license=license)
|
||||
return head
|
||||
|
||||
|
||||
def version_content(skill: Skill, version: SkillVersion, files) -> SkillContent:
|
||||
"""A stored version as `content_sha256` and `build_pack` see it (export reads it the same way)."""
|
||||
return SkillContent(folder=skill.slug,
|
||||
frontmatter=frontmatter(skill.slug, version.description, version.license,
|
||||
version.meta),
|
||||
body=version.body_md, files={f.path: f.content for f in files})
|
||||
|
||||
|
||||
def checked(slug: str, description: str, body: str, license: str, meta: Mapping,
|
||||
files: Mapping[str, bytes]) -> tuple[skill_pack.SkillDoc, SkillContent, str]:
|
||||
"""Pack the content and read it back: every import rule applies, `PackRejected` otherwise.
|
||||
-> (the parsed SKILL.md, the content as it will be stored, its `content_sha256`)."""
|
||||
# Checked before packing: zipfile rewrites `\` to `/` on Windows, and an empty segment (`a//b`,
|
||||
# `/a`) would be stored under another name than the one it was given.
|
||||
bad = [p for p in files if skill_pack.bad_path(p) or "" in p.split("/")]
|
||||
if bad:
|
||||
raise PackRejected("pack_bad_path", bad)
|
||||
if "SKILL.md" in files: # build_pack would let it overwrite the document written from the fields
|
||||
raise PackRejected("pack_duplicate_name", ["SKILL.md"])
|
||||
content = SkillContent(folder=slug, frontmatter=frontmatter(slug, description, license, meta),
|
||||
body=body, files=dict(files))
|
||||
pack = skill_pack.read_pack(skill_pack.build_pack([content]))
|
||||
doc = pack.skills[0]
|
||||
stored = skill_pack.skill_content(pack, doc)
|
||||
return doc, stored, skill_pack.content_sha256(stored)
|
||||
|
||||
|
||||
def _media_type(path: str) -> str:
|
||||
name = path.rsplit("/", 1)[-1]
|
||||
return MEDIA_TYPES[name[name.rfind("."):].lower()] # read_pack has already refused the rest
|
||||
|
||||
|
||||
def _add_version(db: DbSession, actor: AppUser, skill: Skill, n: int, *, description: str,
|
||||
body: str, license: str, meta: Mapping, files: Mapping[str, bytes],
|
||||
provenance: dict | None = None) -> SkillVersion:
|
||||
doc, stored, sha = checked(skill.slug, description, body, license, meta, files)
|
||||
version = SkillVersion(
|
||||
skill_id=skill.id, n=n, description=doc.description, body_md=doc.body,
|
||||
license=doc.frontmatter["license"],
|
||||
meta={k: v for k, v in doc.frontmatter.items() if k not in _OWN_KEYS},
|
||||
content_sha256=sha, provenance=provenance, created_by=actor.id)
|
||||
db.add(version)
|
||||
db.flush()
|
||||
for path, data in sorted(stored.files.items()):
|
||||
db.add(SkillFile(skill_version_id=version.id, path=path, media_type=_media_type(path),
|
||||
size=len(data), sha256=hashlib.sha256(data).hexdigest(), content=data))
|
||||
if skill.scope == SkillScope.personal:
|
||||
skill.current_version_id = version.id
|
||||
# A firm skill's current version moves only through publication (`_make_current`).
|
||||
db.flush()
|
||||
return version
|
||||
|
||||
|
||||
def _audit(db: DbSession, actor: AppUser, action: str, skill: Skill,
|
||||
version: SkillVersion | None = None, *, ip: str | None) -> None:
|
||||
detail = skill.slug if version is None else f"{skill.slug} v{version.n} {version.content_sha256}"
|
||||
audit.record(db, action=action, entity_type="skill", entity_id=skill.id, actor_id=actor.id,
|
||||
detail=detail, ip=ip)
|
||||
|
||||
|
||||
# ---- output ------------------------------------------------------------------------------------
|
||||
|
||||
def _files(db: DbSession, version_id: uuid.UUID) -> list[SkillFile]:
|
||||
return list(db.scalars(select(SkillFile).where(SkillFile.skill_version_id == version_id)
|
||||
.order_by(SkillFile.path)))
|
||||
|
||||
|
||||
def skill_out(user: AppUser, skill: Skill) -> dict[str, Any]:
|
||||
"""The identity row as the API shows it, with what this person may do to it."""
|
||||
return {"id": skill.id, "slug": skill.slug, "name": skill.name, "owner_id": skill.owner_id,
|
||||
"scope": skill.scope, "status": skill.status, "origin": skill.origin,
|
||||
"current_version_id": skill.current_version_id, "mine": skill.owner_id == user.id,
|
||||
"editable": can_edit(user, skill)}
|
||||
|
||||
|
||||
def version_out(version: SkillVersion, files: list[SkillFile]) -> dict[str, Any]:
|
||||
"""One version in full, files listed without their bytes (export carries those)."""
|
||||
return {"id": version.id, "n": version.n, "description": version.description,
|
||||
"body": version.body_md, "license": version.license, "metadata": version.meta,
|
||||
"content_sha256": version.content_sha256, "provenance": version.provenance,
|
||||
"created_at": version.created_at, "created_by": version.created_by,
|
||||
"files": [{"path": f.path, "media_type": f.media_type, "size": f.size,
|
||||
"sha256": f.sha256} for f in files]}
|
||||
|
||||
|
||||
# ---- reads -------------------------------------------------------------------------------------
|
||||
|
||||
def list_skills(db: DbSession, user: AppUser) -> list[dict]:
|
||||
"""Own skills and firm ones; the console splits them into Mine / The firm's."""
|
||||
return [skill_out(user, s) for s in visible_to(db, user)]
|
||||
|
||||
|
||||
def get_skill(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> dict:
|
||||
"""The skill, the versions this person may read (newest first) and the current one in full."""
|
||||
skill = _get(db, user, skill_id)
|
||||
versions = list(db.scalars(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc())))
|
||||
readable = readable_version_ids(user, skill, (v.id for v in versions))
|
||||
current = next((v for v in versions if v.id == skill.current_version_id), None)
|
||||
return {**skill_out(user, skill),
|
||||
"versions": [{"n": v.n, "id": v.id, "created_at": v.created_at,
|
||||
"content_sha256": v.content_sha256}
|
||||
for v in versions if v.id in readable],
|
||||
"current": (version_out(current, _files(db, current.id))
|
||||
if current is not None and current.id in readable else None)}
|
||||
|
||||
|
||||
def get_version(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int) -> dict:
|
||||
"""Version `n`, if this person may read it — an unapproved firm version is a 404 to others."""
|
||||
skill = _get(db, user, skill_id)
|
||||
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.n == n))
|
||||
if version is None or not readable_version_ids(user, skill, [version.id]):
|
||||
raise NotFoundError("Version not found.")
|
||||
return version_out(version, _files(db, version.id))
|
||||
|
||||
|
||||
# ---- writes ------------------------------------------------------------------------------------
|
||||
|
||||
def create_skill(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | None) -> dict:
|
||||
"""A personal skill with its version 1. `fields`: slug, name, description, body, and optionally
|
||||
license, metadata (extra frontmatter) and files (path -> bytes)."""
|
||||
slug = fields["slug"]
|
||||
if db.scalar(select(Skill.id).where(Skill.owner_id == actor.id, Skill.slug == slug)):
|
||||
raise ConflictError(f"You already have a skill called {slug}.")
|
||||
skill = Skill(slug=slug, name=fields["name"], owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, origin=SkillOrigin.authored)
|
||||
db.add(skill)
|
||||
db.flush()
|
||||
version = _add_version(db, actor, skill, 1, description=fields["description"],
|
||||
body=fields["body"], license=fields.get("license") or DEFAULT_LICENSE,
|
||||
meta=fields.get("metadata") or {}, files=fields.get("files") or {})
|
||||
_audit(db, actor, "skill.create", skill, version, ip=ip)
|
||||
return skill_out(actor, skill)
|
||||
|
||||
|
||||
def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapping, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n + 1`. A field that is None is carried over from the newest version (`files`
|
||||
included — `{}` is how to remove them all). An imported licence is the author's: it stays."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
if skill.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived skill takes no new versions.")
|
||||
latest = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
license = fields.get("license") or latest.license
|
||||
if skill.origin == SkillOrigin.imported:
|
||||
license = latest.license
|
||||
files = fields.get("files")
|
||||
if files is None:
|
||||
files = {f.path: f.content for f in _files(db, latest.id)}
|
||||
if fields.get("name"):
|
||||
skill.name = fields["name"]
|
||||
version = _add_version(
|
||||
db, actor, skill, next_n(latest.n),
|
||||
description=fields.get("description") or latest.description,
|
||||
body=fields["body"] if fields.get("body") is not None else latest.body_md,
|
||||
license=license,
|
||||
meta=fields["metadata"] if fields.get("metadata") is not None else latest.meta,
|
||||
files=files)
|
||||
_audit(db, actor, "skill.version", skill, version, ip=ip)
|
||||
return version_out(version, _files(db, version.id))
|
||||
|
||||
|
||||
def archive_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, *, ip: str | None) -> dict:
|
||||
"""Archived, not deleted: agents keep running on the versions they pinned (FK RESTRICT)."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
if skill.status != CatalogStatus.archived:
|
||||
skill.status = CatalogStatus.archived
|
||||
db.flush()
|
||||
_audit(db, actor, "skill.archive", skill, ip=ip)
|
||||
return skill_out(actor, skill)
|
||||
|
||||
|
||||
# ---- publication (T1) --------------------------------------------------------------------------
|
||||
# One path for skills and agents: `_publish` is the ONLY reader of `skills_firm_publish`, and
|
||||
# `_make_current` the only place a firm item's current version moves.
|
||||
|
||||
def _make_current(item, version) -> None:
|
||||
item.scope = SkillScope.firm
|
||||
item.current_version_id = version.id
|
||||
|
||||
|
||||
def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
ip: str | None) -> dict:
|
||||
"""`approval` -> a request for THIS version (every version, not only the first); `direct` ->
|
||||
published now. The item stays where it was until an administrator says yes."""
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
if item.scope == SkillScope.firm and item.current_version_id == version.id:
|
||||
raise ConflictError("This version is already published.")
|
||||
target = f"{getattr(item, 'slug', item.name)} v{version.n}"
|
||||
if settings.get(db, "skills_firm_publish") == "direct":
|
||||
_make_current(item, version)
|
||||
db.flush()
|
||||
# No request and nobody else's yes: the setting is the approval, the detail says so.
|
||||
audit.record(db, action=f"{kind}.publish_approve", entity_type=str(kind),
|
||||
entity_id=item.id, actor_id=actor.id, detail=f"{target} direct", ip=ip)
|
||||
return {"status": "published", "request_id": None}
|
||||
if db.scalar(select(PublishRequest.id).where(
|
||||
PublishRequest.kind == kind, PublishRequest.version_id == version.id,
|
||||
PublishRequest.status == PublishRequestStatus.pending)):
|
||||
raise ConflictError("This version is already waiting for an administrator.")
|
||||
req = PublishRequest(kind=kind.value, version_id=version.id, requested_by=actor.id,
|
||||
status=PublishRequestStatus.pending.value)
|
||||
db.add(req)
|
||||
db.flush() # the partial unique index turns a double-submit race into a 409 here
|
||||
audit.record(db, action=f"{kind}.publish_request", entity_type=str(kind), entity_id=item.id,
|
||||
actor_id=actor.id, detail=target, ip=ip)
|
||||
return {"status": "pending", "request_id": req.id}
|
||||
|
||||
|
||||
def publish_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Publish version `n` (default: the newest) to the firm — by the owner, or for a firm skill
|
||||
also by an administrator."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = db.scalar(query)
|
||||
if version is None:
|
||||
raise NotFoundError("Version not found.")
|
||||
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip),
|
||||
"skill": skill_out(actor, skill)}
|
||||
|
||||
|
||||
def _require_administrator(actor: AppUser) -> None:
|
||||
# The router guards too; this is what keeps someone's personal skill out of other hands.
|
||||
if not actor.is_admin:
|
||||
raise AuthorizationError("Only an administrator decides publish requests.")
|
||||
|
||||
|
||||
def _resolve(db: DbSession, req: PublishRequest):
|
||||
"""-> (item, version) a request names; versions are never deleted, so both exist."""
|
||||
if req.kind == PublishKind.skill:
|
||||
version = db.get(SkillVersion, req.version_id)
|
||||
return db.get(Skill, version.skill_id), version
|
||||
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:
|
||||
"""Approving v2 after v3 went out would quietly roll the firm back: refuse it."""
|
||||
return item.scope == SkillScope.firm and current_n is not None and version.n < current_n
|
||||
|
||||
|
||||
def decide_publish(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, approve: bool,
|
||||
note: str | None = None, ip: str | None = None) -> dict:
|
||||
"""An administrator's yes or no. Yes moves the firm's current version to the requested one."""
|
||||
_require_administrator(actor)
|
||||
# Row lock: two administrators deciding the same request at once must not both "win".
|
||||
req = db.scalar(select(PublishRequest).where(PublishRequest.id == request_id)
|
||||
.with_for_update())
|
||||
if req is None:
|
||||
raise NotFoundError("Request not found.")
|
||||
if req.status != PublishRequestStatus.pending:
|
||||
raise ConflictError("This request has already been decided.")
|
||||
item, version = _resolve(db, req)
|
||||
if approve:
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
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
|
||||
req.decided_at = dt.datetime.now(dt.UTC)
|
||||
req.note = _clean_note(note)
|
||||
db.flush()
|
||||
audit.record(db, action=f"{req.kind}.publish_{'approve' if approve else 'decline'}",
|
||||
entity_type=req.kind, entity_id=item.id, actor_id=actor.id,
|
||||
detail=f"{getattr(item, 'slug', item.name)} v{version.n}", ip=ip)
|
||||
return _request_out(db, req)
|
||||
|
||||
|
||||
def _request_out(db: DbSession, req: PublishRequest) -> dict:
|
||||
"""A request with both sides of the diff: what is asked for, and what the firm has now."""
|
||||
item, version = _resolve(db, req)
|
||||
requester = db.get(AppUser, req.requested_by)
|
||||
base = None
|
||||
if item.scope == SkillScope.firm and item.current_version_id not in (None, version.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": 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]:
|
||||
"""Every pending request, oldest first — the one place an administrator sees somebody else's
|
||||
personal skill, and only the version put forward."""
|
||||
_require_administrator(actor)
|
||||
rows = db.scalars(select(PublishRequest).where(
|
||||
PublishRequest.status == PublishRequestStatus.pending).order_by(PublishRequest.created_at))
|
||||
return [_request_out(db, r) for r in rows]
|
||||
|
||||
|
||||
# ---- import and export -------------------------------------------------------------------------
|
||||
|
||||
def free_slug(taken, slug: str) -> str:
|
||||
"""`slug`, or the first of `slug-2`, `slug-3`… nobody in `taken` has — trimmed to stay ≤ 64."""
|
||||
n, candidate = 1, slug
|
||||
while candidate in taken:
|
||||
n += 1
|
||||
suffix = f"-{n}"
|
||||
candidate = slug[: skill_pack.MAX_NAME - len(suffix)].rstrip("-") + suffix
|
||||
return candidate
|
||||
|
||||
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _already_have(db: DbSession, actor: AppUser, sha: str) -> SkillVersion | None:
|
||||
"""A version of one of `actor`'s active skills with this content — stored as it was imported
|
||||
(`provenance`), or exported from here and coming back (`content_sha256`)."""
|
||||
return db.scalar(
|
||||
select(SkillVersion).join(Skill, Skill.id == SkillVersion.skill_id)
|
||||
.where(Skill.owner_id == actor.id, Skill.status == CatalogStatus.active,
|
||||
or_(SkillVersion.content_sha256 == sha,
|
||||
SkillVersion.provenance["content_sha256"].astext == sha))
|
||||
.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`,
|
||||
version 1, a free slug (`x`, `x-2`…). Nothing updates itself: if `actor` already has one of
|
||||
them (same `content_sha256`), nothing is written and the answer is `duplicate` — call again
|
||||
with `add_version=True` to add those as a new version of the skill they match.
|
||||
|
||||
-> {"status": "imported" | "duplicate", "skills": [one per SKILL.md: path, its sum, the match
|
||||
or the skill written, and `info_only` — what it asked for and was not given (D3)], "ignored":
|
||||
files of the pack that belong to no skill (a plugin's commands/, agents/…)}"""
|
||||
pack = skill_pack.read_pack(data)
|
||||
if pack.agent is not None or pack.kind == "agent":
|
||||
raise PackRejected("pack_is_agent", [skill_pack.AGENT_DOC])
|
||||
if not pack.skills:
|
||||
raise PackRejected("pack_no_skill")
|
||||
pack_sha = _sha(data)
|
||||
found = []
|
||||
for doc in pack.skills:
|
||||
content = skill_pack.skill_content(pack, doc)
|
||||
found.append((doc, content, skill_pack.content_sha256(content)))
|
||||
matches = {sha: _already_have(db, actor, sha) for _, _, sha in found}
|
||||
used = {doc.path[: -len("SKILL.md")] for doc in pack.skills}
|
||||
ignored = sorted(p for p in pack.files
|
||||
if p != skill_pack.AGENT_DOC and not any(p.startswith(u) for u in used))
|
||||
if any(matches.values()) and not add_version:
|
||||
return {"status": "duplicate", "ignored": ignored, "skills": [
|
||||
{"path": doc.path, "content_sha256": sha, "info_only": doc.info_only,
|
||||
"match": ({**skill_out(actor, db.get(Skill, matches[sha].skill_id)),
|
||||
"n": matches[sha].n} if matches[sha] else None)}
|
||||
for doc, _, sha in found]}
|
||||
|
||||
taken = set(db.scalars(select(Skill.slug).where(Skill.owner_id == actor.id)))
|
||||
out = []
|
||||
for doc, content, sha in found:
|
||||
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}
|
||||
|
||||
|
||||
def may_export(user: AppUser, item, firm_export: str) -> bool:
|
||||
"""T2. One's own: always. A firm one: an administrator, or everybody under `everyone`."""
|
||||
return (item.owner_id == user.id or bool(user.is_admin) or firm_export == "everyone")
|
||||
|
||||
|
||||
def export_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> tuple[str, bytes]:
|
||||
"""The pack of version `n` (default: the current one) -> (file name, ZIP bytes)."""
|
||||
skill = _get(db, actor, skill_id) # somebody else's personal one is a 404 before T2 is asked
|
||||
if not may_export(actor, skill, settings.get(db, "skills_firm_export")):
|
||||
raise AuthorizationError("Only an administrator may export the firm's skills.")
|
||||
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.where(SkillVersion.id == skill.current_version_id))
|
||||
version = db.scalar(query)
|
||||
if version is None or not readable_version_ids(actor, skill, [version.id]):
|
||||
raise NotFoundError("Version not found.")
|
||||
data = skill_pack.build_pack([version_content(skill, version, _files(db, version.id))])
|
||||
audit.record(db, action="skill.export", entity_type="skill", entity_id=skill.id,
|
||||
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:
|
||||
pl, en = (("Agent firmowy przypina tylko opublikowane wersje firmowych skilli.",
|
||||
"A firm agent pins only the firm's published skill versions.")
|
||||
if agent_scope == SkillScope.firm
|
||||
else ("Nie znaleziono wersji skilla.", "Skill version not found."))
|
||||
raise ValidationError(pl, extra={"code": "agent_pin_refused", "en": en,
|
||||
"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}}
|
||||
@@ -82,6 +82,9 @@ argon2-cffi==23.1.0 # Argon2id password hashing (MIT). dredd-core depe
|
||||
# AES-256-GCM for model-provider API keys (app/provider_keys.py). Apache-2.0 OR BSD-3-Clause. Same
|
||||
# pin as Arbiter, whose runs decrypt the keys the hub writes.
|
||||
cryptography==46.0.3
|
||||
# SKILL.md frontmatter in skill packs (app/services/skill_pack.py) — `yaml.safe_load` only, never the
|
||||
# full loader. MIT.
|
||||
PyYAML==6.0.3
|
||||
|
||||
|
||||
# OpenTelemetry (OTLP → OTel Collector) — optional, import-guarded in observability.py
|
||||
@@ -89,3 +92,4 @@ opentelemetry-sdk==1.42.1
|
||||
opentelemetry-exporter-otlp-proto-grpc==1.42.1
|
||||
opentelemetry-instrumentation-fastapi==0.63b1
|
||||
opentelemetry-instrumentation-sqlalchemy==0.63b1
|
||||
pypdf==6.21.4 # text of a PDF attached to a chat question (BSD-3-Clause, pure Python)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""A file attached to a Home chat question: its text back, nothing stored, and the refusals by code."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import types
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
from fastapi import Request
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import deps
|
||||
from app.db import get_db
|
||||
from app.errors import ValidationError
|
||||
from app.services import attachments, audit
|
||||
|
||||
|
||||
def _pdf(*pages: str) -> bytes:
|
||||
"""A real PDF with one text line per page (Helvetica, WinAnsi), xref offsets computed."""
|
||||
objs = ["<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [" + " ".join(f"{4 + 2 * i} 0 R" for i in range(len(pages)))
|
||||
+ f"] /Count {len(pages)} >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"]
|
||||
for i, text in enumerate(pages):
|
||||
stream = f"BT /F1 12 Tf 72 720 Td ({text}) Tj ET" if text else ""
|
||||
objs.append(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> "
|
||||
f"/Contents {5 + 2 * i} 0 R >>")
|
||||
objs.append(f"<< /Length {len(stream)} >>\nstream\n{stream}\nendstream")
|
||||
out, offsets = io.BytesIO(), []
|
||||
out.write(b"%PDF-1.4\n")
|
||||
for n, body in enumerate(objs, 1):
|
||||
offsets.append(out.tell())
|
||||
out.write(f"{n} 0 obj\n{body}\nendobj\n".encode("latin-1"))
|
||||
xref = out.tell()
|
||||
out.write(f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode())
|
||||
for o in offsets:
|
||||
out.write(f"{o:010d} 00000 n \n".encode())
|
||||
out.write(f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _docx(xml: str) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as z:
|
||||
z.writestr("word/document.xml", xml)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
|
||||
|
||||
|
||||
def test_a_pdf_comes_back_page_by_page():
|
||||
out = attachments.extract("Umowa.PDF", _pdf("Okres wypowiedzenia 3 miesiace", "Kara umowna 10 procent"))
|
||||
assert out["kind"] == "pdf" and out["pages"] == 2
|
||||
assert "[strona 1]\nOkres wypowiedzenia 3 miesiace" in out["text"]
|
||||
assert "[strona 2]\nKara umowna 10 procent" in out["text"]
|
||||
|
||||
|
||||
def test_a_scan_is_refused_with_its_reason():
|
||||
with pytest.raises(ValidationError) as refused:
|
||||
attachments.extract("skan.pdf", _pdf("", ""))
|
||||
assert refused.value.extra["code"] == "attachment_no_text"
|
||||
|
||||
|
||||
def test_a_docx_keeps_its_paragraphs_tabs_and_breaks():
|
||||
xml = (f'<w:document {W}><w:body><w:p><w:r><w:t>§ 1. Strony</w:t></w:r></w:p>'
|
||||
'<w:p><w:r><w:t>Najemca</w:t><w:tab/><w:t>ABC</w:t><w:br/><w:t>sp. z o.o.</w:t></w:r></w:p></w:body></w:document>')
|
||||
out = attachments.extract("najem.docx", _docx(xml))
|
||||
assert out["kind"] == "docx" and out["text"] == "§ 1. Strony\nNajemca\tABC\nsp. z o.o."
|
||||
|
||||
|
||||
def test_a_docx_with_a_dtd_is_refused_before_parsing():
|
||||
bomb = f'<!DOCTYPE w [<!ENTITY a "aaaa">]><w:document {W}><w:body><w:p><w:r><w:t>&a;</w:t></w:r></w:p></w:body></w:document>'
|
||||
with pytest.raises(ValidationError) as refused:
|
||||
attachments.extract("bomba.docx", _docx(bomb))
|
||||
assert refused.value.extra["code"] == "attachment_unreadable"
|
||||
|
||||
|
||||
def test_plain_text_falls_back_to_windows_1250():
|
||||
assert attachments.extract("notatka.txt", "Zażółć gęślą jaźń".encode("cp1250"))["text"] == "Zażółć gęślą jaźń"
|
||||
assert attachments.extract("a.md", "# Tytuł".encode("utf-8"))["text"] == "# Tytuł"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "data", "code"), [
|
||||
("obraz.png", b"\x89PNG\r\n", "attachment_type"),
|
||||
("udaje.pdf", b"PK\x03\x04 not a pdf", "attachment_type"), # the name says PDF, the bytes do not
|
||||
("binarny.txt", b"MZ\x00\x00", "attachment_type"),
|
||||
("pusty.txt", b" \n", "attachment_empty"),
|
||||
("duzy.txt", b"a" * (attachments.MAX_BYTES + 1), "attachment_too_large"),
|
||||
])
|
||||
def test_refusals_carry_a_code(name, data, code):
|
||||
with pytest.raises(ValidationError) as refused:
|
||||
attachments.extract(name, data)
|
||||
assert refused.value.extra["code"] == code and refused.value.extra["en"]
|
||||
|
||||
|
||||
def test_the_route_returns_the_text_and_audits_only_the_name(monkeypatch):
|
||||
from app.main import app
|
||||
audited = []
|
||||
monkeypatch.setattr(audit, "record", lambda *a, **k: audited.append(k))
|
||||
|
||||
def signed_in(request: Request):
|
||||
request.state.credential_id, request.state.credential_kind = uuid.uuid4(), "session"
|
||||
return types.SimpleNamespace(id=uuid.uuid4(), is_admin=False)
|
||||
|
||||
app.dependency_overrides[deps.get_current_user] = signed_in
|
||||
app.dependency_overrides[get_db] = lambda: types.SimpleNamespace(commit=lambda: None)
|
||||
try:
|
||||
r = TestClient(app).post("/api/v1/chat/attachments?name=tajne.txt", content="Treść poufna".encode())
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
assert r.status_code == 200 and r.json()["text"] == "Treść poufna"
|
||||
assert audited[0]["detail"] == "tajne.txt" and "Treść" not in repr(audited)
|
||||
@@ -254,6 +254,15 @@ class TestSettings:
|
||||
settings._normalize("support_contact", "ring\x07")
|
||||
assert settings._normalize("welcome_message", " line one\nline two ") == "line one\nline two"
|
||||
|
||||
def test_skills_settings_default_closed_and_refuse_other_values(self):
|
||||
assert settings.SPECS["skills_firm_publish"].default == "approval"
|
||||
assert settings.SPECS["skills_firm_export"].default == "administrator"
|
||||
assert settings._normalize("skills_firm_publish", "direct") == "direct"
|
||||
assert settings._normalize("skills_firm_export", "everyone") == "everyone"
|
||||
for key, bad in (("skills_firm_publish", "auto"), ("skills_firm_export", "owner")):
|
||||
with pytest.raises(ValidationError):
|
||||
settings._normalize(key, bad)
|
||||
|
||||
def test_the_catalog_marker_key_never_changes(self):
|
||||
"""Persisted in every instance: renamed, an instance whose administrator deleted every
|
||||
module loses its marker and gets the catalog back on the next deploy."""
|
||||
|
||||
@@ -28,9 +28,14 @@ def test_core_tables_are_registered():
|
||||
assert {"app_user", "session", "app_setting", "audit_log"} <= set(_metadata().tables)
|
||||
|
||||
|
||||
SKILL_TABLES = ("skill", "skill_version", "skill_file", "agent", "agent_version",
|
||||
"agent_version_skill", "publish_request")
|
||||
|
||||
|
||||
def test_the_apps_own_tables_are_registered():
|
||||
"""A model missing from `app/models/__init__.py` silently gets no table."""
|
||||
assert {"module", "module_assignment", "access_request"} <= set(_metadata().tables)
|
||||
assert set(SKILL_TABLES) <= set(_metadata().tables)
|
||||
assert "record" not in _metadata().tables
|
||||
|
||||
|
||||
@@ -52,14 +57,30 @@ def test_marketplace_vocabularies_are_check_constraints_not_enum_types():
|
||||
and each CHECK lists exactly the StrEnum's values, so the code and the database agree."""
|
||||
from sqlalchemy import CheckConstraint
|
||||
|
||||
from app.enums import AccessRequestStatus, Availability, ModuleStatus
|
||||
from app.enums import (
|
||||
AccessRequestStatus,
|
||||
AgentKind,
|
||||
Availability,
|
||||
CatalogStatus,
|
||||
ModuleStatus,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
SkillScope,
|
||||
)
|
||||
|
||||
tables = _metadata().tables
|
||||
for name in ("module", "module_assignment", "access_request"):
|
||||
for name in ("module", "module_assignment", "access_request", *SKILL_TABLES):
|
||||
assert not [c for c in tables[name].columns if isinstance(c.type, PGEnum)], name
|
||||
assert "record_status" not in enum_types(_metadata())
|
||||
expected = {("module", "status"): ModuleStatus, ("module", "availability"): Availability,
|
||||
("access_request", "status"): AccessRequestStatus}
|
||||
("access_request", "status"): AccessRequestStatus,
|
||||
("skill", "scope"): SkillScope, ("skill", "status"): CatalogStatus,
|
||||
("skill", "origin"): SkillOrigin,
|
||||
("agent", "scope"): SkillScope, ("agent", "status"): CatalogStatus,
|
||||
("agent", "kind"): AgentKind,
|
||||
("publish_request", "kind"): PublishKind,
|
||||
("publish_request", "status"): PublishRequestStatus}
|
||||
for (table, column), enum in expected.items():
|
||||
sql = [str(c.sqltext) for c in tables[table].constraints
|
||||
if isinstance(c, CheckConstraint) and str(c.sqltext).startswith(f"{column} IN")]
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Home's model picker: how a model id is shown and which family's mark it wears.
|
||||
|
||||
`prettyModel` and `modelFamily` are lifted out of `frontend/app.js` and run under Node, so the
|
||||
behaviour is asserted, not the source text. DB-free; skipped only where no `node` binary exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _fn(head: str) -> str:
|
||||
i = SRC.index(head)
|
||||
return SRC[i:SRC.index("\n}\n", i) + 3]
|
||||
|
||||
|
||||
def _run(fn: str, args: list[str]) -> list[str]:
|
||||
script = _fn(f"function {fn}(") + f"\nconsole.log(JSON.stringify({json.dumps(args)}.map({fn})));"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_pretty_model_reads_like_a_name() -> None:
|
||||
assert _run("prettyModel", ["claude-opus-5-5", "qwen/qwen3.5-9b", "claude-sonnet-4-5-20250929"]) == [
|
||||
"Claude Opus 5.5", "Qwen3.5 9B", "Claude Sonnet 4.5 20250929"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_model_family_by_id() -> None:
|
||||
cases = {
|
||||
"claude-opus-5-5": "anthropic", "anthropic/claude-haiku-5-5": "anthropic",
|
||||
"gpt-5": "openai", "o3-mini": "openai", "openai/o4": "openai",
|
||||
"gemini-2.5-pro": "google", "google/gemma-3-27b": "google",
|
||||
"qwen/qwen3.5-9b": "qwen", "speakleash/bielik-11b-v2.6": "bielik",
|
||||
"meta-llama/llama-3.3-70b": "meta", "mistral-large": "mistral", "mixtral-8x7b": "mistral",
|
||||
"deepseek-r1": "D", "phi-4": "P",
|
||||
}
|
||||
assert _run("modelFamily", list(cases)) == list(cases.values())
|
||||
|
||||
|
||||
def test_picker_groups_by_provider_and_escapes() -> None:
|
||||
body = _fn("function modelOptions(")
|
||||
assert "<optgroup label=\"${esc(g.provider)}\" data-no-i18n>" in body
|
||||
assert "${esc(prettyModel(m.id))}" in body and 'title="${esc(m.id)}"' in body
|
||||
assert "modelLabel" not in SRC
|
||||
|
||||
|
||||
def test_pick_is_remembered_and_the_icon_follows_it() -> None:
|
||||
change = _fn("function homeModelChange(")
|
||||
assert "saveModelPick(sel.value)" in change
|
||||
assert "$('homeModelIcon').innerHTML = familyIcon(sel.value)" in change
|
||||
assert "savedModelPick()" in SRC and "localStorage.setItem(modelPickKey()" in SRC
|
||||
assert '<span id="homeModelIcon">${familyIcon(picked)}</span>' in SRC
|
||||
assert "markSvg(fam, letter)" in _fn("function familyIcon(")
|
||||
assert "${esc(letter)}" in _fn("function markSvg(")
|
||||
|
||||
|
||||
def test_every_vendored_logotype_is_credited() -> None:
|
||||
import re
|
||||
|
||||
brand = SRC[SRC.index("const BRAND = {"):]
|
||||
brand = brand[:brand.index("\n};")]
|
||||
keys = re.findall(r"^ (\w+): '", brand, re.M)
|
||||
assert keys, "BRAND map is empty"
|
||||
credits = (ROOT / "CREDITS.md").read_text(encoding="utf-8")
|
||||
assert "Simple Icons" in credits and "CC0" in credits
|
||||
for key in keys:
|
||||
assert f"`{key}`" in credits, key
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_model_two_providers_offer_is_listed_once_under_the_one_that_answers() -> None:
|
||||
# The server routes an id to the FIRST provider offering it; a second option for the same id
|
||||
# would show one provider and send the question to another.
|
||||
start = SRC.index("const esc = ")
|
||||
esc = SRC[start:SRC.index("}[c]));", start) + len("}[c]));")]
|
||||
script = "\n".join([esc, _fn("function prettyModel("), _fn("function modelOptions(")]) + (
|
||||
"\nconsole.log(modelOptions([{id:'qwen3',provider:'Lokalny'},{id:'qwen3',provider:'OpenRouter'},"
|
||||
"{id:'gpt-5',provider:'OpenRouter'}], 'qwen3', 'Tylko szukaj'));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
|
||||
assert r.returncode == 0, r.stderr
|
||||
html = r.stdout
|
||||
assert html.count('value="qwen3"') == 1 and html.count(" selected") == 1
|
||||
assert html.index('value="qwen3"') < html.index('label="OpenRouter"')
|
||||
@@ -0,0 +1,183 @@
|
||||
"""`model_server.list_models` on a mocked transport: what counts as a chat model, the outbound limits
|
||||
(no redirects, 2 MB), the refusal codes, and that the key never appears in an error."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.integrations import model_server
|
||||
|
||||
KEY = "sk-secret-value-123"
|
||||
|
||||
|
||||
def _resp(status, json_=None, content=b"", headers=None):
|
||||
"""A STREAMED response, as the network gives one (`content=` would arrive already read)."""
|
||||
body = json.dumps(json_).encode() if json_ is not None else content
|
||||
return httpx.Response(status, headers=headers, stream=httpx.ByteStream(body))
|
||||
|
||||
|
||||
def _run(handler, base="http://gpu.example:8000/v1", key=KEY, vendor=None):
|
||||
return asyncio.run(model_server.list_models(base, key, vendor, transport=httpx.MockTransport(handler)))
|
||||
|
||||
|
||||
def _refused(handler, code, **kw):
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_run(handler, **kw)
|
||||
assert exc.value.extra["code"] == code
|
||||
assert KEY not in exc.value.detail and KEY not in json.dumps(exc.value.extra)
|
||||
return exc.value
|
||||
|
||||
|
||||
def test_vllm_max_model_len_becomes_the_context_window_and_the_key_is_a_bearer():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req)
|
||||
if req.url.path == "/v1/models":
|
||||
return _resp(200, json_={"data": [{"id": "qwen/qwen3.5-9b", "max_model_len": 32768},
|
||||
{"id": "bielik-11b"}]})
|
||||
return _resp(404)
|
||||
assert _run(handler) == [{"id": "qwen/qwen3.5-9b", "dialect": "openai", "context_window": 32768},
|
||||
{"id": "bielik-11b", "dialect": "openai"}]
|
||||
assert seen[0].headers["authorization"] == f"Bearer {KEY}"
|
||||
|
||||
|
||||
def test_lm_studio_drops_embeddings_and_keeps_models_not_loaded():
|
||||
def handler(req):
|
||||
if req.url.path == "/v1/models":
|
||||
return _resp(200, json_={"data": [{"id": "qwen3"}, {"id": "nomic-text-v1"}, {"id": "gemma"}]})
|
||||
return _resp(200, json_={"data": [
|
||||
{"id": "qwen3", "type": "llm", "state": "loaded"},
|
||||
{"id": "nomic-text-v1", "type": "embeddings", "state": "not-loaded"},
|
||||
{"id": "gemma", "type": "vlm", "state": "not-loaded"}]})
|
||||
assert [m["id"] for m in _run(handler, base="http://localhost:1234", key=None)] == ["qwen3", "gemma"]
|
||||
|
||||
|
||||
def test_non_chat_ids_are_dropped_by_pattern():
|
||||
def handler(req):
|
||||
return _resp(200, json_={"data": [{"id": "gpt-5"}, {"id": "text-embedding-3-large"},
|
||||
{"id": "whisper-1"}, {"id": "gpt-image-1"}]})
|
||||
assert [m["id"] for m in _run(handler, vendor="openai")] == ["gpt-5"]
|
||||
|
||||
|
||||
def test_a_redirect_is_refused():
|
||||
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
|
||||
"provider_unreachable")
|
||||
|
||||
|
||||
def test_an_answer_over_2_mb_is_cut_and_refused():
|
||||
big = b'{"data": [' + b" " * (model_server.LIST_MAX_BYTES + 1) + b"]}"
|
||||
_refused(lambda req: _resp(200, content=big), "provider_unreachable")
|
||||
|
||||
|
||||
def test_401_is_a_refused_key():
|
||||
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused")
|
||||
|
||||
|
||||
def test_no_answer_is_unreachable():
|
||||
def handler(req):
|
||||
raise httpx.ConnectError(f"cannot connect with {KEY}")
|
||||
_refused(handler, "provider_unreachable")
|
||||
|
||||
|
||||
def test_an_empty_list_after_the_filter_is_no_models():
|
||||
_refused(lambda req: _resp(200, json_={"data": [{"id": "text-embedding-3-small"}]}),
|
||||
"provider_no_models", vendor="openai")
|
||||
|
||||
|
||||
def test_a_compressed_answer_is_refused_and_identity_is_asked_for():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req.headers["accept-encoding"])
|
||||
return _resp(200, headers={"Content-Encoding": "gzip"}, content=b"\x1f\x8b")
|
||||
_refused(handler, "provider_unreachable")
|
||||
assert seen == ["identity"]
|
||||
|
||||
|
||||
ANTHROPIC = "https://api.anthropic.com/v1"
|
||||
|
||||
|
||||
def _anthropic(handler):
|
||||
return _run(handler, base=ANTHROPIC, vendor="anthropic")
|
||||
|
||||
|
||||
def test_anthropic_keeps_active_models_and_sends_its_own_headers():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req)
|
||||
return _resp(200, json_={"data": [
|
||||
{"id": "claude-opus-5-5", "lifecycle": "active", "max_input_tokens": 1000000},
|
||||
{"id": "claude-old-3", "lifecycle": "deprecated", "max_input_tokens": 200000},
|
||||
{"id": "claude-haiku-5-5", "lifecycle": "active", "max_input_tokens": 0}]})
|
||||
assert _anthropic(handler) == [
|
||||
{"id": "claude-opus-5-5", "dialect": "openai", "context_window": 1000000},
|
||||
{"id": "claude-haiku-5-5", "dialect": "openai"}]
|
||||
req, = seen
|
||||
assert req.url.path == "/v1/models" and req.url.params["limit"] == "1000"
|
||||
assert req.headers["x-api-key"] == KEY
|
||||
assert req.headers["anthropic-version"] == model_server.ANTHROPIC_VERSION
|
||||
assert "authorization" not in req.headers
|
||||
|
||||
|
||||
def test_anthropic_refusals_never_carry_the_key():
|
||||
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused",
|
||||
base=ANTHROPIC, vendor="anthropic")
|
||||
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
|
||||
"provider_unreachable", base=ANTHROPIC, vendor="anthropic")
|
||||
_refused(lambda req: _resp(200, json_={"data": [{"id": "claude-old-3", "lifecycle": "deprecated"}]}),
|
||||
"provider_no_models", base=ANTHROPIC, vendor="anthropic")
|
||||
|
||||
|
||||
def test_a_redirect_is_not_followed_one_request_and_no_second_host():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(str(req.url))
|
||||
return _resp(302, headers={"Location": "http://169.254.169.254/latest/meta-data/"})
|
||||
_refused(handler, "provider_unreachable")
|
||||
assert len(seen) == 1 and "169.254" not in seen[0]
|
||||
|
||||
|
||||
def test_one_deadline_covers_the_whole_exchange_not_each_read(monkeypatch):
|
||||
"""A body trickled slower than the deadline in total, but each chunk fast enough for a per-read
|
||||
timeout, must still end at the deadline."""
|
||||
import time
|
||||
|
||||
class Trickle(httpx.AsyncByteStream):
|
||||
async def __aiter__(self):
|
||||
yield b'{"data": ['
|
||||
for _ in range(50):
|
||||
await asyncio.sleep(0.05)
|
||||
yield b" "
|
||||
yield b"]}"
|
||||
monkeypatch.setattr(model_server, "LIST_DEADLINE", 0.5)
|
||||
started = time.monotonic()
|
||||
_refused(lambda req: httpx.Response(200, stream=Trickle()), "provider_unreachable")
|
||||
assert time.monotonic() - started < 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [
|
||||
lambda: _resp(302, headers={"Location": "/login"}),
|
||||
lambda: _resp(200, content=b"<html>login</html>"),
|
||||
lambda: _resp(401),
|
||||
], ids=["redirect", "html", "401"])
|
||||
def test_a_broken_optional_lm_studio_listing_does_not_sink_the_discovery(answer):
|
||||
def handler(req):
|
||||
if req.url.path == "/v1/models":
|
||||
return _resp(200, json_={"data": [{"id": "qwen3"}]})
|
||||
return answer()
|
||||
assert [m["id"] for m in _run(handler, key=None)] == ["qwen3"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [b"[]", b"null", b'"x"', b'{"data": null}', b'{"data": "x"}',
|
||||
b"[" * 100_000 + b"]" * 100_000],
|
||||
ids=["list", "null", "string", "data-null", "data-string", "deep-nesting"])
|
||||
@pytest.mark.parametrize("vendor", [None, "anthropic"])
|
||||
def test_an_unexpected_json_shape_is_a_422_not_a_500(body, vendor):
|
||||
_refused(lambda req: _resp(200, content=body), "provider_unreachable", vendor=vendor)
|
||||
@@ -169,9 +169,10 @@ def test_a_server_without_lm_studios_listing_is_never_loaded_by_hand(monkeypatch
|
||||
class _LmStudio:
|
||||
"""The two listings and the two writes of LM Studio, recording the writes."""
|
||||
|
||||
def __init__(self, loaded):
|
||||
def __init__(self, loaded, cold_max=None):
|
||||
self.loaded = dict(loaded) # {id: type}
|
||||
self.writes = []
|
||||
self.cold = {"max_context_length": cold_max} if cold_max else {}
|
||||
|
||||
async def __call__(self, _client, method, url, _key, body=None):
|
||||
if method == "POST":
|
||||
@@ -183,7 +184,7 @@ class _LmStudio:
|
||||
return {}
|
||||
if "/api/v0/" in url:
|
||||
return {"data": [{"id": m, "type": t, "state": "loaded"} for m, t in self.loaded.items()]
|
||||
+ [{"id": "cold", "type": "llm", "state": "not-loaded"}]}
|
||||
+ [{"id": "cold", "type": "llm", "state": "not-loaded", **self.cold}]}
|
||||
return {"models": [{"key": m, "loaded_instances": [{"id": m}]} for m in self.loaded]}
|
||||
|
||||
|
||||
@@ -254,6 +255,17 @@ def test_an_administrator_switches_and_the_embeddings_survive(asker):
|
||||
assert server.writes[-1] == ("load", {"model": "cold", "context_length": model_server.DEFAULT_CONTEXT})
|
||||
|
||||
|
||||
def test_a_model_is_loaded_with_no_more_context_than_it_was_trained_on(monkeypatch):
|
||||
server = _LmStudio({}, cold_max=32768)
|
||||
monkeypatch.setattr(model_server, "_json", server)
|
||||
asyncio.run(model_server.ensure_loaded("http://h", None, "cold", may_switch=False))
|
||||
assert server.writes == [("load", {"model": "cold", "context_length": 32768})]
|
||||
roomy = _LmStudio({}, cold_max=262144)
|
||||
monkeypatch.setattr(model_server, "_json", roomy)
|
||||
asyncio.run(model_server.ensure_loaded("http://h", None, "cold", may_switch=False))
|
||||
assert roomy.writes == [("load", {"model": "cold", "context_length": model_server.DEFAULT_CONTEXT})]
|
||||
|
||||
|
||||
def test_the_lock_decides_again_when_someone_ahead_loaded_another_model(monkeypatch):
|
||||
server = _LmStudio({"qwen": "llm"})
|
||||
monkeypatch.setattr(model_server, "_json", server)
|
||||
@@ -349,3 +361,45 @@ def test_there_is_no_door_for_modules_and_no_stored_choice():
|
||||
paths = {getattr(r, "path", "") for _, r in iter_routes(app.routes)}
|
||||
assert "/api/v1/models" in paths and "/api/v1/models/ask" in paths
|
||||
assert not any(p.startswith("/api/v1/gateway") or p == "/api/v1/models/choice" for p in paths)
|
||||
|
||||
|
||||
def test_claude_is_not_sent_the_knobs_it_refuses():
|
||||
# claude-opus-5-5 answered 400 "`temperature` is deprecated for this model" (2026-11-06).
|
||||
sent = models._sampling(_ask(temperature=0.2, top_p=0.9, top_k=40, presence_penalty=1.5, thinking=False),
|
||||
"anthropic")
|
||||
assert sent == {"presence_penalty": 1.5, "reasoning_effort": "none"}
|
||||
|
||||
|
||||
def test_a_refused_call_says_why(monkeypatch):
|
||||
import httpx
|
||||
|
||||
def handler(req):
|
||||
body = b'{"error": {"message": "`temperature` is deprecated for this model."}}'
|
||||
return httpx.Response(400, stream=httpx.ByteStream(body)) # streamed, as the network gives it
|
||||
real = httpx.AsyncClient
|
||||
monkeypatch.setattr(model_server.httpx, "AsyncClient",
|
||||
lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
|
||||
|
||||
async def run():
|
||||
async for _ in model_server.stream_chat("http://h", "k", "m", [], 64):
|
||||
pass
|
||||
with pytest.raises(model_server.GatewayError, match="temperature"):
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_the_answer_is_asked_for_uncompressed(monkeypatch):
|
||||
# The bytes are passed through raw with no Content-Encoding: a gzipped stream reached the chat
|
||||
# as garbage (api.anthropic.com, 2026-11-06).
|
||||
import httpx
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req.headers.get("accept-encoding"))
|
||||
return httpx.Response(200, stream=httpx.ByteStream(b"data: [DONE]\n\n"))
|
||||
real = httpx.AsyncClient
|
||||
monkeypatch.setattr(model_server.httpx, "AsyncClient",
|
||||
lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
|
||||
|
||||
async def run():
|
||||
return [c async for c in model_server.stream_chat("http://h", "k", "m", [], 64)]
|
||||
assert asyncio.run(run()) == [b"data: [DONE]\n\n"] and seen == ["identity"]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""The model-provider screen in the console (Platforma → Dostawcy modeli). DB-free.
|
||||
|
||||
Source-reading, like `test_app_token_console.py`, and honest about what that proves: the screen
|
||||
exists, calls only routes that exist, never renders or stores a key, offers nothing that fetches a
|
||||
provider, and is in both languages. That the routes really behave is
|
||||
exists, calls only routes that exist, never renders or stores a key, never reaches a provider
|
||||
itself (the model list comes through the hub's `discover`/`refresh`), and is in both languages. That the routes really behave is
|
||||
`test_providers_integration.py`'s job.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -66,23 +66,68 @@ def test_the_key_is_write_only_in_the_console_too(screen):
|
||||
assert "{ clear: ['api_key'] }" in screen
|
||||
|
||||
|
||||
def test_nothing_on_it_reaches_a_provider(screen):
|
||||
"""These endpoints store configuration; a "test connection" would make the hub fetch an
|
||||
administrator-typed URL."""
|
||||
def test_only_the_hub_reaches_a_provider(screen):
|
||||
"""The list of models is read by the hub, under its outbound limits; the console only asks for
|
||||
it through `discover`/`refresh` and never opens a connection of its own."""
|
||||
assert "fetch(" not in screen
|
||||
assert "XMLHttpRequest" not in screen
|
||||
# The header comment says why there is none; no control may offer one.
|
||||
assert "`/admin/model-providers/${enc(id)}/refresh`" in screen
|
||||
code = re.sub(r"/\*.*?\*/", "", screen, flags=re.S)
|
||||
assert not re.search(r"test.?connection|probe|połącz", code, re.I)
|
||||
|
||||
|
||||
def test_each_row_offers_refresh_details_and_disable(screen):
|
||||
rows = screen.split("rows.map((p) =>", 1)[1].split(".join('')", 1)[0]
|
||||
assert "providerIcon(p)" in rows
|
||||
assert "(p.models || []).length" in rows
|
||||
for action in ("refreshProvider(", "openProviderForm(", "disableProvider("):
|
||||
assert action in rows, action
|
||||
|
||||
|
||||
def test_only_a_disabled_row_offers_delete(screen):
|
||||
rows = screen.split("rows.map((p) =>", 1)[1].split(".join('')", 1)[0]
|
||||
active, disabled = rows.split("disableProvider(", 1)[1].split(": `", 1)
|
||||
assert "deleteProvider(" not in active and "deleteProvider(" in disabled
|
||||
assert "mutate('DELETE', '/admin/model-providers/' + enc(id)" in screen
|
||||
|
||||
|
||||
def test_details_have_no_models_field(screen):
|
||||
"""A provider's models are its own list (`discover`/`refresh`), never typed."""
|
||||
form = screen.split("function openProviderForm(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "Modele" not in form and "textarea" not in form
|
||||
edit = screen.split("function readProviderForm(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "models" not in edit
|
||||
|
||||
|
||||
def test_adding_goes_through_discover(console, screen):
|
||||
"""One field; the hub recognises it (`discover`), the console adds what was checked."""
|
||||
assert 'onclick="openAddProvider()"' in screen
|
||||
assert "'/admin/model-providers/discover'" in screen
|
||||
assert "reopen: showDiscovered" in screen
|
||||
add = screen.split("function addProvider(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "mutate('POST', '/admin/model-providers', body)" in add
|
||||
assert "models: r.models" in add and "kind: r.kind" in add and "base_url: r.base_url" in add
|
||||
# The second field shows only for an address.
|
||||
assert 'id="apKeyRow"' in screen and 'id="apKey" type="password"' in screen
|
||||
# The prefix catalogue is the backend's alone.
|
||||
assert "sk-ant-" not in console and "sk-or-" not in console
|
||||
|
||||
|
||||
def test_the_pasted_key_is_never_rendered_or_kept(screen):
|
||||
preview = screen.split("function showDiscovered(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "apInput" not in preview and "apKey" not in preview and "key" not in preview.lower()
|
||||
add = screen.split("function addProvider(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "state." not in add.split("const r = state._discovered;", 1)[1]
|
||||
assert not re.search(r"state[.]\w+\s*=\s*(?:key|input)", screen)
|
||||
|
||||
|
||||
def test_dynamic_values_are_escaped(screen):
|
||||
# Every interpolation goes through esc()/dat()/enc() or is markup built here.
|
||||
for expr in re.findall(r"\$\{([^}]*)\}", screen):
|
||||
if expr.strip().startswith(("esc(", "dat(", "enc(", "svg(", "lbl(", "choice(", "kindChip",
|
||||
"euChip", "keyCell", "p ?", "p &&", "writable", "rows.map",
|
||||
"p.is_active", "v.trains_on_data", "v.is_active",
|
||||
"policy.eu_only", "esc(")):
|
||||
if expr.strip().startswith(("esc(", "dat(", "enc(", "svg(", "lbl(", "choice(", "providerIcon(", "markSvg(",
|
||||
"hue", "writable", "rows.map",
|
||||
"p.is_active", "p.trains_on_data", "p.has_key",
|
||||
"policy.eu_only", "r.models.map", "esc(")):
|
||||
continue
|
||||
pytest.fail(f"unescaped interpolation: ${{{expr}}}")
|
||||
|
||||
@@ -92,16 +137,17 @@ def test_the_look_is_marked_as_replaceable(screen):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phrase", [
|
||||
"Dostawcy modeli", "Nowy dostawca", "Edytuj dostawcę", "Polityka użycia", "Kto może używać modeli",
|
||||
"Dostawcy modeli", "Szczegóły", "Polityka użycia", "Kto może używać modeli",
|
||||
"Tylko dostawcy z UE/EOG (lub lokalni)", "Zapisz politykę", "Brak dostawców modeli.",
|
||||
"Pozostaw puste, aby zachować obecny klucz", "Usuń klucz", "Wyłącz", "Włącz", "Nikt",
|
||||
"Tylko administratorzy", "Każdy", "Zgodnie z polityką", "Dostawca trenuje modele na przesłanych danych",
|
||||
"Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.",
|
||||
"Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.",
|
||||
"Jeden model w wierszu: identyfikator | okno kontekstu | dialekt (openai albo chatml).",
|
||||
"Usunąć zapisany klucz API tego dostawcy?",
|
||||
"Wyłączyć tego dostawcę? Moduły przestaną go oferować.",
|
||||
"API (zewnętrzny)", "lokalny", "Podmiot przetwarzający", "Adres umowy powierzenia (DPA)",
|
||||
"Dodaj dostawcę", "Wklej klucz API albo adres serwera", "Klucz (jeśli serwer go wymaga)", "Sprawdź",
|
||||
"Dodaj", "Znaleziono modele.", "Odśwież modele", "Odświeżono modele.",
|
||||
])
|
||||
def test_it_is_in_both_languages(console, screen, phrase):
|
||||
assert phrase in screen
|
||||
@@ -128,7 +174,7 @@ def my_keys(console) -> str:
|
||||
|
||||
def test_the_admin_card_shows_and_edits_key_mode(screen):
|
||||
assert "const KEY_MODE = { firm:" in screen and "user:" in screen and "none:" in screen
|
||||
assert "choice('pfKeyMode', KEY_MODE, v.key_mode || 'firm')" in screen
|
||||
assert "choice('pfKeyMode', KEY_MODE, p.key_mode || 'firm')" in screen
|
||||
assert "key_mode: $('pfKeyMode').value" in screen
|
||||
assert "KEY_MODE[p.key_mode]" in screen
|
||||
|
||||
@@ -171,3 +217,23 @@ def test_home_points_at_my_keys_when_a_personal_key_is_missing(console):
|
||||
assert 'href="#/my-keys"' in hint and "esc(p.name)" in hint
|
||||
# The chat says where to add the key instead of a bare "Nie udało się".
|
||||
assert "'model_provider_user_key_missing'" in console.split("const CHAT_REFUSALS", 1)[1].split(";", 1)[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", [
|
||||
"provider_key_refused", "provider_unreachable", "provider_no_models", "provider_unknown_key",
|
||||
])
|
||||
def test_discover_refusals_carry_their_english(code):
|
||||
"""These refusals are worded by `coreRefusal` from the Problem Details `code` + `en`, not by a
|
||||
dictionary entry: `provider_unreachable` carries the reason inside its sentence."""
|
||||
backend = ROOT / "backend" / "app"
|
||||
src = ((backend / "integrations" / "model_server.py").read_text(encoding="utf-8")
|
||||
+ (backend / "services" / "providers.py").read_text(encoding="utf-8"))
|
||||
assert "def _refusal(code: str, pl: str, en: str)" in src and '{"code": code, "en": en}' in src
|
||||
assert re.search(rf'_refusal\(\s*"{code}"|"code": "{code}",\s*"en": ', src), code
|
||||
|
||||
|
||||
def test_a_provider_the_eu_only_policy_hides_says_so_in_the_list() -> None:
|
||||
# Core drops a non-EU provider from every model list while `eu_only` is on; the list must not
|
||||
# call it plainly "aktywny" then, or its models vanish from the chat with no visible reason.
|
||||
src = (pathlib.Path(__file__).resolve().parents[2] / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
assert "policy.eu_only && !p.stays_in_the_eu" in src and "ukryty: tylko UE" in src
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""`providers.discover` with `list_models` replaced: the key-prefix table, address vs key, local vs
|
||||
external host, a non-http scheme refused, and an audit row that names the host and never the key."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import types
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.services import providers
|
||||
|
||||
MODELS = [{"id": "m-1", "dialect": "openai"}]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def calls(monkeypatch):
|
||||
seen = {"list": [], "audit": []}
|
||||
|
||||
async def fake_list(base_url, key, vendor):
|
||||
seen["list"].append((base_url, key, vendor))
|
||||
return MODELS
|
||||
|
||||
monkeypatch.setattr(providers.model_server, "list_models", fake_list)
|
||||
monkeypatch.setattr(providers.audit, "record", lambda db, **kw: seen["audit"].append(kw))
|
||||
return seen
|
||||
|
||||
|
||||
def _discover(text, key=None):
|
||||
actor = types.SimpleNamespace(id=uuid.uuid4())
|
||||
return asyncio.run(providers.discover(object(), actor, text, key, ip="10.0.0.1"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key, vendor, name, base", [
|
||||
("sk-ant-api03-abc", "anthropic", "Anthropic", "https://api.anthropic.com/v1"),
|
||||
("sk-or-v1-abc", "openrouter", "OpenRouter", "https://openrouter.ai/api/v1"),
|
||||
("sk-proj-abc", "openai", "OpenAI", "https://api.openai.com/v1"),
|
||||
])
|
||||
def test_each_key_prefix_names_its_vendor(calls, key, vendor, name, base):
|
||||
out = _discover(f" {key} ")
|
||||
assert out == {"vendor": vendor, "name": name, "kind": "api", "base_url": base, "models": MODELS}
|
||||
assert calls["list"] == [(base, key, vendor)]
|
||||
|
||||
|
||||
def test_an_unknown_key_asks_for_an_address(calls):
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_discover("xai-abcdef")
|
||||
assert exc.value.extra["code"] == "provider_unknown_key"
|
||||
assert calls["list"] == [] and calls["audit"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url, kind, host", [
|
||||
("http://localhost:1234/v1", "local", "localhost"),
|
||||
("http://127.0.0.1:1234", "local", "127.0.0.1"),
|
||||
("http://[::1]:8080", "local", "::1"),
|
||||
("http://host.docker.internal:1234/", "local", "host.docker.internal"),
|
||||
("https://gpu.example.com:8000/v1", "api", "gpu.example.com"),
|
||||
("http://localhost.evil.example", "api", "localhost.evil.example"),
|
||||
])
|
||||
def test_an_address_is_local_only_on_this_machine(calls, url, kind, host):
|
||||
out = _discover(url, key=" srv-key ")
|
||||
assert (out["vendor"], out["name"], out["kind"]) == (None, host, kind)
|
||||
assert out["base_url"] == url.rstrip("/")
|
||||
assert calls["list"] == [(url.rstrip("/"), "srv-key", None)]
|
||||
|
||||
|
||||
def test_an_address_without_a_key_sends_none(calls):
|
||||
_discover("http://localhost:1234")
|
||||
assert calls["list"][0][1] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", ["ftp://gpu.example.com", "file:///etc/passwd",
|
||||
"http://user:pw@gpu.example.com"])
|
||||
def test_a_non_http_address_or_one_with_credentials_is_refused(calls, url):
|
||||
with pytest.raises(ValidationError):
|
||||
_discover(url)
|
||||
assert calls["list"] == []
|
||||
|
||||
|
||||
def test_the_audit_names_the_host_and_never_the_key(calls):
|
||||
key = "sk-ant-api03-very-secret"
|
||||
_discover(key)
|
||||
(row,) = calls["audit"]
|
||||
assert row["action"] == "model_provider.discover"
|
||||
assert row["detail"] == "api.anthropic.com"
|
||||
assert key not in json.dumps(row, default=str)
|
||||
|
||||
|
||||
def test_a_refused_listing_propagates_and_writes_no_audit(monkeypatch, calls):
|
||||
async def refuse(*_a):
|
||||
raise ValidationError("x", {"code": "provider_key_refused"})
|
||||
|
||||
monkeypatch.setattr(providers.model_server, "list_models", refuse)
|
||||
with pytest.raises(ValidationError):
|
||||
_discover("sk-proj-abc")
|
||||
assert calls["audit"] == []
|
||||
|
||||
|
||||
# ── refresh: a stored provider's models re-read, through `update` ────────────
|
||||
KEY = "sk-ant-api03-SECRETVALUE"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stored(monkeypatch):
|
||||
row = types.SimpleNamespace(id=uuid.uuid4(), name="Anthropic", base_url="https://api.anthropic.com/v1",
|
||||
key_prefix="sk-ant-a", models=[{"id": "old", "dialect": "openai"}])
|
||||
seen = {"list": [], "update": [], "commits": 0, "listing": MODELS}
|
||||
|
||||
async def fake_list(base_url, key, vendor):
|
||||
seen["list"].append((base_url, key, vendor))
|
||||
if isinstance(seen["listing"], Exception):
|
||||
raise seen["listing"]
|
||||
return seen["listing"]
|
||||
|
||||
def fake_update(db, actor, provider_id, fields, *, ip):
|
||||
seen["update"].append(fields)
|
||||
row.models = fields["models"]
|
||||
return {"id": str(provider_id), "models": row.models}
|
||||
|
||||
db = types.SimpleNamespace(commit=lambda: seen.__setitem__("commits", seen["commits"] + 1))
|
||||
monkeypatch.setattr(providers.core, "get_or_404", lambda _db, _id: row)
|
||||
monkeypatch.setattr(providers.core, "api_key", lambda _db, _p, _decrypt: KEY)
|
||||
monkeypatch.setattr(providers.model_server, "list_models", fake_list)
|
||||
monkeypatch.setattr(providers, "update", fake_update)
|
||||
return row, seen, db
|
||||
|
||||
|
||||
def _refresh(row, db):
|
||||
actor = types.SimpleNamespace(id=uuid.uuid4())
|
||||
return asyncio.run(providers.refresh(db, actor, row.id, ip="10.0.0.1"))
|
||||
|
||||
|
||||
def test_refresh_replaces_the_models_and_ends_the_read_first(stored):
|
||||
row, seen, db = stored
|
||||
out = _refresh(row, db)
|
||||
assert out["models"] == MODELS and row.models == MODELS
|
||||
assert seen["list"] == [("https://api.anthropic.com/v1", KEY, "anthropic")]
|
||||
assert seen["commits"] == 1
|
||||
# Only the models go to `update`: its audit diff can never carry the key.
|
||||
assert seen["update"] == [{"models": MODELS}]
|
||||
assert KEY not in json.dumps(seen["update"])
|
||||
|
||||
|
||||
def test_a_refused_listing_keeps_the_old_models(stored):
|
||||
row, seen, db = stored
|
||||
seen["listing"] = ValidationError("Brak modeli.", {"code": "provider_no_models", "en": "No models."})
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_refresh(row, db)
|
||||
assert exc.value.extra["code"] == "provider_no_models"
|
||||
assert seen["update"] == [] and row.models == [{"id": "old", "dialect": "openai"}]
|
||||
|
||||
|
||||
def test_refresh_of_a_keyless_local_server_sends_no_key(stored):
|
||||
row, seen, db = stored
|
||||
row.base_url, row.key_prefix = "http://localhost:1234", None
|
||||
_refresh(row, db)
|
||||
assert seen["list"] == [("http://localhost:1234", None, None)]
|
||||
|
||||
|
||||
def test_an_unreadable_key_refuses_before_calling(stored, monkeypatch):
|
||||
row, seen, db = stored
|
||||
monkeypatch.setattr(providers.core, "api_key", lambda *_: None)
|
||||
with pytest.raises(providers.ConflictError) as exc:
|
||||
_refresh(row, db)
|
||||
assert exc.value.extra["code"] == providers.KEY_UNREADABLE
|
||||
assert seen["list"] == [] and seen["update"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url, vendor", [("https://api.anthropic.com/v1", "anthropic"),
|
||||
("https://api.openai.com/v1/", "openai")])
|
||||
def test_a_pasted_cloud_address_is_asked_the_way_its_vendor_answers(calls, url, vendor):
|
||||
out = _discover(url, key="k")
|
||||
assert out["vendor"] == vendor and calls["list"][0][2] == vendor
|
||||
|
||||
|
||||
def test_a_provider_with_hundreds_of_models_can_be_added():
|
||||
from app.schemas import ProviderCreateIn, ProviderUpdateIn
|
||||
models = [{"id": f"m-{i}", "dialect": "openai"} for i in range(400)]
|
||||
ProviderCreateIn(name="OpenRouter", kind="api", base_url="https://openrouter.ai/api/v1",
|
||||
models=models, trains_on_data=False)
|
||||
ProviderUpdateIn(models=models)
|
||||
@@ -5,8 +5,8 @@ Opt in with ATRIUM_RUN_INTEGRATION=1, like `test_integration.py`. The tables exi
|
||||
the same; run it with IDENTITY_SCHEMA set to exercise the hub's writer grant on `dredd`.
|
||||
`MODEL_PROVIDER_SECRET` must be set for the key tests (they are skipped otherwise).
|
||||
|
||||
Providers are never deleted (only disabled), so every name is suffixed per run, and the policy is put
|
||||
back exactly as it was found.
|
||||
Only a disabled provider no run points at may be deleted, and most tests leave theirs behind, so every
|
||||
name is suffixed per run, and the policy is put back exactly as it was found.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -68,6 +68,7 @@ def test_only_an_administrator_reaches_any_of_it(admin_client, client, make_user
|
||||
("GET", f"{BASE}/{provider['id']}", None),
|
||||
("PATCH", f"{BASE}/{provider['id']}", {"name": "x"}),
|
||||
("POST", f"{BASE}/{provider['id']}/disable", None),
|
||||
("DELETE", f"{BASE}/{provider['id']}", None),
|
||||
("GET", f"{BASE}/policy", None), ("PUT", f"{BASE}/policy", {"level": "everyone"})]:
|
||||
r = client.request(method, path, json=body, headers=bearer(plain["token"]))
|
||||
assert r.status_code == 403, (method, path, r.status_code)
|
||||
@@ -79,6 +80,7 @@ def test_a_missing_provider_is_404_with_cores_code(admin_client):
|
||||
r = admin_client.get(f"{BASE}/{uuid.uuid4()}")
|
||||
assert r.status_code == 404 and r.json()["code"] == "provider_not_found"
|
||||
assert admin_client.post(f"{BASE}/{uuid.uuid4()}/disable").status_code == 404
|
||||
assert admin_client.delete(f"{BASE}/{uuid.uuid4()}").status_code == 404
|
||||
|
||||
|
||||
def test_cookie_writes_from_another_site_are_refused():
|
||||
@@ -210,13 +212,39 @@ def test_disable_switches_off_and_is_audited_once(admin_client):
|
||||
for _ in range(2):
|
||||
r = admin_client.post(f"{BASE}/{pid}/disable")
|
||||
assert r.status_code == 200 and r.json()["is_active"] is False
|
||||
assert admin_client.delete(f"{BASE}/{pid}").status_code == 405 # there is no delete
|
||||
assert any(p["id"] == pid for p in admin_client.get(BASE).json()) # still listed
|
||||
rows = _audit(admin_client, "model_provider.disable", pid)
|
||||
assert len(rows) == 1 and rows[0]["diff"] == {"is_active": [True, False]}
|
||||
assert admin_client.patch(f"{BASE}/{pid}", json={"is_active": True}).json()["is_active"] is True
|
||||
|
||||
|
||||
def test_delete_takes_only_a_disabled_provider_and_its_key(admin_client):
|
||||
provider = _create(admin_client)
|
||||
pid = provider["id"]
|
||||
r = admin_client.delete(f"{BASE}/{pid}")
|
||||
assert r.status_code == 409 and r.json()["code"] == "provider_still_active"
|
||||
assert admin_client.post(f"{BASE}/{pid}/disable").status_code == 200
|
||||
assert admin_client.delete(f"{BASE}/{pid}").json() == {"status": "ok"}
|
||||
assert admin_client.get(f"{BASE}/{pid}").status_code == 404
|
||||
assert all(p["id"] != pid for p in admin_client.get(BASE).json())
|
||||
[row] = _audit(admin_client, "model_provider.delete", pid)
|
||||
assert row["detail"] == provider["name"]
|
||||
|
||||
|
||||
@needs_secret
|
||||
def test_deleting_a_provider_drops_its_stored_key(admin_client):
|
||||
provider = _create(admin_client, api_key="sk-delete-me-123456")
|
||||
pid = provider["id"]
|
||||
admin_client.post(f"{BASE}/{pid}/disable")
|
||||
assert admin_client.delete(f"{BASE}/{pid}").status_code == 200
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.db import SessionLocal
|
||||
with SessionLocal() as db:
|
||||
assert db.execute(text("SELECT count(*) FROM model_provider_key WHERE provider_id = :p"),
|
||||
{"p": pid}).scalar() == 0
|
||||
|
||||
|
||||
# ── the policy ────────────────────────────────────────────────────────────────
|
||||
def test_the_policy_round_trip(admin_client):
|
||||
r = admin_client.put(f"{BASE}/policy", json={"level": "nobody", "eu_only": False})
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""The two routes that call a provider: administrator-only, routed before `/{provider_id}`, and
|
||||
SQL-free (the router validates and calls the service, nothing else)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services import providers
|
||||
from tests.test_hub_gates_unit import _person, api # noqa: F401 (fixture)
|
||||
|
||||
ROUTER = pathlib.Path(__file__).resolve().parents[1] / "app" / "routers" / "admin_providers.py"
|
||||
BASE = "/api/v1/admin/model-providers"
|
||||
|
||||
|
||||
def test_both_routes_are_in_the_openapi_document():
|
||||
from app.main import app
|
||||
paths = app.openapi()["paths"]
|
||||
assert "post" in paths[f"{BASE}/discover"]
|
||||
assert "post" in paths[f"{BASE}/{{provider_id}}/refresh"]
|
||||
|
||||
|
||||
def test_the_router_holds_no_sql():
|
||||
assert not re.search(r"select\(|db\.execute|db\.add", ROUTER.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, body", [
|
||||
(f"{BASE}/discover", {"input": "sk-ant-secret"}),
|
||||
(f"{BASE}/{uuid.uuid4()}/refresh", None),
|
||||
])
|
||||
def test_a_plain_user_gets_what_other_admin_routes_answer(api, monkeypatch, path, body): # noqa: F811
|
||||
called = []
|
||||
monkeypatch.setattr(providers, "discover", lambda *a, **k: called.append(a))
|
||||
monkeypatch.setattr(providers, "refresh", lambda *a, **k: called.append(a))
|
||||
api.who(_person())
|
||||
reference = api.client.get(f"{BASE}/policy")
|
||||
r = api.client.post(path, json=body)
|
||||
assert r.status_code == reference.status_code and r.status_code in (403, 404)
|
||||
assert not called
|
||||
|
||||
|
||||
def test_discover_is_not_parsed_as_an_id(api, monkeypatch): # noqa: F811
|
||||
async def fake(db, actor, text, key, *, ip):
|
||||
return {"vendor": "anthropic", "name": "Anthropic", "kind": "api",
|
||||
"base_url": "https://api.anthropic.com/v1", "models": [{"id": "claude-x"}]}
|
||||
monkeypatch.setattr(providers, "discover", fake)
|
||||
api.who(_person(admin=True))
|
||||
r = api.client.post(f"{BASE}/discover", json={"input": "sk-ant-secret"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["vendor"] == "anthropic"
|
||||
assert api.db.calls == ["commit", "commit"]
|
||||
@@ -0,0 +1,470 @@
|
||||
"""`skill_pack.read_pack`: one test per archive rule, on ZIPs built in memory (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import stat
|
||||
import warnings
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services import skill_pack
|
||||
from app.services.skill_pack import PackRejected, read_pack
|
||||
|
||||
|
||||
def _zip(entries, *, compression=zipfile.ZIP_DEFLATED) -> bytes:
|
||||
"""`entries`: (name or ZipInfo, bytes). Names are written raw — see `_raw`."""
|
||||
buf = io.BytesIO()
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore") # the duplicate-name test writes one twice on purpose
|
||||
with zipfile.ZipFile(buf, "w", compression) as zf:
|
||||
for name, data in entries:
|
||||
zf.writestr(name, data)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _raw(name: str) -> zipfile.ZipInfo:
|
||||
# On Windows the ZipInfo constructor rewrites `\` to `/`; setting the attribute afterwards keeps
|
||||
# the name exactly as an attacker's archive would carry it.
|
||||
info = zipfile.ZipInfo("placeholder")
|
||||
info.filename = name
|
||||
return info
|
||||
|
||||
|
||||
def _code(data: bytes) -> str:
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(data)
|
||||
return caught.value.code
|
||||
|
||||
|
||||
SKILL = b"---\nname: nda\ndescription: Przeglad NDA\n---\n# NDA\n"
|
||||
|
||||
|
||||
def _lying_size(data: bytes, declared: int) -> bytes:
|
||||
"""Rewrite every header's uncompressed size to `declared` — a bomb's header lies about it."""
|
||||
out = bytearray(data)
|
||||
for sig, off in ((b"PK\x03\x04", 22), (b"PK\x01\x02", 24)):
|
||||
at = out.find(sig)
|
||||
while at != -1:
|
||||
out[at + off:at + off + 4] = declared.to_bytes(4, "little")
|
||||
at = out.find(sig, at + 4)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def test_a_member_lying_about_its_size_is_refused_without_inflating_it():
|
||||
import tracemalloc
|
||||
bomb = _lying_size(_zip([("s/notes.txt", b"\0" * (40 * 1024 * 1024))]), 1000)
|
||||
tracemalloc.start()
|
||||
try:
|
||||
assert _code(bomb) == "pack_not_zip"
|
||||
peak = tracemalloc.get_traced_memory()[1]
|
||||
finally:
|
||||
tracemalloc.stop()
|
||||
# An unbounded `zf.read` inflates all 40 MB before trimming to the declared 1000 bytes.
|
||||
assert peak < 5 * 1024 * 1024, peak
|
||||
|
||||
|
||||
def test_a_clean_pack_is_read():
|
||||
pack = read_pack(_zip([("nda/SKILL.md", SKILL), ("nda/resources/a.txt", b"x")]))
|
||||
assert pack.files == {"nda/SKILL.md": SKILL, "nda/resources/a.txt": b"x"}
|
||||
(skill,) = pack.skills
|
||||
assert (skill.path, skill.name, skill.description, skill.body, skill.info_only) \
|
||||
== ("nda/SKILL.md", "nda", "Przeglad NDA", "# NDA\n", {})
|
||||
|
||||
|
||||
def test_every_code_has_both_languages_and_rides_in_problem_details():
|
||||
err = PackRejected("pack_link", ["b", "a"])
|
||||
# Polish detail + English `en`, the shape the console's coreRefusal words in either language.
|
||||
assert err.extra == {"code": "pack_link", "files": ["a", "b"], "en": "The pack contains a link."}
|
||||
assert err.detail == "Paczka zawiera dowiązanie."
|
||||
assert err.status_code == 422
|
||||
for pl, en in skill_pack.MESSAGES.values():
|
||||
assert pl and en and pl != en
|
||||
|
||||
|
||||
def test_more_than_10_mb_is_refused():
|
||||
assert _code(b"\0" * (skill_pack.MAX_PACK_BYTES + 1)) == "pack_too_large"
|
||||
|
||||
|
||||
def test_not_a_zip_is_refused():
|
||||
assert _code(b"plain text, not an archive") == "pack_not_zip"
|
||||
|
||||
|
||||
def test_more_than_200_files_is_refused():
|
||||
data = _zip([(f"s/{i}.md", b"x") for i in range(skill_pack.MAX_FILES + 1)])
|
||||
assert _code(data) == "pack_too_many_files"
|
||||
|
||||
|
||||
def test_200_files_is_accepted():
|
||||
assert len(read_pack(_zip([(f"s/{i}.md", b"x") for i in range(200)])).files) == 200
|
||||
|
||||
|
||||
def test_more_than_50_mb_unpacked_is_refused():
|
||||
data = _zip([("s/big.txt", b"\0" * (skill_pack.MAX_UNPACKED_BYTES + 1))])
|
||||
assert len(data) < skill_pack.MAX_PACK_BYTES
|
||||
assert _code(data) == "pack_unpacked_too_large"
|
||||
|
||||
|
||||
def test_a_file_compressed_over_100_to_1_is_refused():
|
||||
assert _code(_zip([("s/bomb.txt", b"\0" * 1_000_000)])) == "pack_compression_ratio"
|
||||
|
||||
|
||||
def test_zip64_is_refused():
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as zf, zf.open("s/SKILL.md", "w", force_zip64=True) as f:
|
||||
f.write(b"# x")
|
||||
assert _code(buf.getvalue()) == "pack_zip64"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["s/../SKILL.md", "../SKILL.md"])
|
||||
def test_a_dot_dot_segment_is_refused(name):
|
||||
assert _code(_zip([(_raw(name), b"x")])) == "pack_bad_path"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["/etc/SKILL.md", "C:/SKILL.md"])
|
||||
def test_an_absolute_path_is_refused(name):
|
||||
assert _code(_zip([(_raw(name), b"x")])) == "pack_bad_path"
|
||||
|
||||
|
||||
def test_a_backslash_is_refused():
|
||||
assert _code(_zip([(_raw("s\\SKILL.md"), b"x")])) == "pack_bad_path"
|
||||
|
||||
|
||||
def test_a_symlink_is_refused():
|
||||
info = zipfile.ZipInfo("s/link.md")
|
||||
info.external_attr = (stat.S_IFLNK | 0o777) << 16
|
||||
assert _code(_zip([(info, b"/etc/passwd")])) == "pack_link"
|
||||
|
||||
|
||||
def test_a_duplicate_name_is_refused():
|
||||
assert _code(_zip([("s/SKILL.md", b"a"), ("s/SKILL.md", b"b")])) == "pack_duplicate_name"
|
||||
|
||||
|
||||
def test_names_differing_only_in_case_are_refused():
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([("s/Notes.md", b"a"), ("s/notes.md", b"b")]))
|
||||
assert caught.value.code == "pack_case_collision"
|
||||
assert caught.value.files == ["s/Notes.md", "s/notes.md"]
|
||||
|
||||
|
||||
# --- file rules (2.2) ---------------------------------------------------------------------------
|
||||
|
||||
def _office(*parts: str, content_types: bool = True) -> bytes:
|
||||
names = (["[Content_Types].xml"] if content_types else []) + list(parts)
|
||||
return _zip([(n, b"<x/>") for n in names])
|
||||
|
||||
|
||||
def _files_code(path: str, data: bytes) -> tuple[str, list[str]]:
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([("s/SKILL.md", b"# x"), (path, data)]))
|
||||
return caught.value.code, caught.value.files
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ext", sorted(skill_pack.ALLOWED_TYPES))
|
||||
def test_every_allowed_extension_is_accepted(ext):
|
||||
data = {".pdf": b"%PDF-1.7\n", ".docx": _office("word/document.xml"),
|
||||
".xlsx": _office("xl/workbook.xml")}.get(ext, "zażółć;gęślą".encode("cp1250"))
|
||||
assert read_pack(_zip([(f"s/r/a{ext}", data)])).files[f"s/r/a{ext}"] == data
|
||||
|
||||
|
||||
def test_the_extension_is_matched_case_insensitively():
|
||||
assert read_pack(_zip([("s/r/A.PDF", b"%PDF-1.4")]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["s/run.sh", "s/tool.py", "s/LICENSE", "s/inner.zip"])
|
||||
def test_an_extension_off_the_list_is_refused(path):
|
||||
assert _files_code(path, b"x") == ("pack_file_type", [path])
|
||||
|
||||
|
||||
def test_a_pdf_without_the_pdf_signature_is_refused():
|
||||
assert _files_code("s/r/a.pdf", b"MZ\x90\x00")[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ext", [".docx", ".xlsx"])
|
||||
def test_an_office_file_that_is_not_a_zip_is_refused(ext):
|
||||
assert _files_code(f"s/r/a{ext}", b"%PDF-1.7")[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ext", [".docx", ".xlsx"])
|
||||
def test_an_office_zip_without_content_types_is_refused(ext):
|
||||
assert _files_code(f"s/r/a{ext}", _office("x.xml", content_types=False))[0] \
|
||||
== "pack_signature_mismatch"
|
||||
|
||||
|
||||
def test_binary_content_under_a_text_extension_is_refused():
|
||||
assert _files_code("s/r/notes.txt", b"\x7fELF\x02\x01\x00")[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, part", [("s/r/a.docx", "word/vbaProject.bin"),
|
||||
("s/r/a.xlsx", "xl/VBAProject.bin")])
|
||||
def test_an_office_file_with_macros_is_refused(path, part):
|
||||
assert _files_code(path, _office(part)) == ("pack_macros", [path])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["s/r/a.txt", "s/r/a.json", "s/r/a.md"])
|
||||
def test_a_zip_under_a_text_extension_is_refused(path):
|
||||
assert _files_code(path, _zip([("x.txt", b"x")])) == ("pack_nested_zip", [path])
|
||||
|
||||
|
||||
def test_the_inside_of_an_office_file_obeys_the_compression_limit():
|
||||
data = _zip([("[Content_Types].xml", b"<x/>"), ("word/bomb.xml", b"\0" * 1_000_000)])
|
||||
assert _files_code("s/r/a.docx", data) == ("pack_compression_ratio", ["s/r/a.docx"])
|
||||
|
||||
|
||||
def test_the_inside_of_an_office_file_obeys_the_path_rules():
|
||||
data = _zip([("[Content_Types].xml", b"<x/>"), (_raw("../evil.xml"), b"x")])
|
||||
assert _files_code("s/r/a.xlsx", data) == ("pack_bad_path", ["s/r/a.xlsx"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("types", [
|
||||
b'<Default Extension="bin" ContentType="application/vnd.ms-office.vbaProject"/>',
|
||||
b'<Override PartName="/word/document.xml" ContentType="application/vnd.ms-word.document.'
|
||||
b'macroEnabled.main+xml"/>',
|
||||
b'<Override PartName="/word/activeX/a.xml" ContentType="application/vnd.ms-office.activeX+xml"/>',
|
||||
])
|
||||
def test_macros_declared_only_in_the_content_types_are_refused(types):
|
||||
data = _zip([("[Content_Types].xml", b"<Types>" + types + b"</Types>"),
|
||||
("word/renamed.dat", b"code")])
|
||||
assert _files_code("s/r/a.docx", data) == ("pack_macros", ["s/r/a.docx"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("manifest", [
|
||||
b'<Default Extension="bin" ContentType="application/vnd.ms-office.vbaProject"/>',
|
||||
'<Default ContentType="application/vnd.ms-office.vbaProject"/>'.encode("utf-16"),
|
||||
b"<Types>\xff\xfe</Types>",
|
||||
])
|
||||
def test_a_content_types_part_a_substring_search_could_misread_is_refused(manifest):
|
||||
data = _zip([("[Content_Types].xml", manifest)])
|
||||
assert _files_code("s/r/a.docx", data)[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
def test_an_oversized_content_types_part_is_refused():
|
||||
data = _zip([("[Content_Types].xml", os.urandom(skill_pack.MAX_MANIFEST_BYTES + 1))],
|
||||
compression=zipfile.ZIP_STORED)
|
||||
assert _files_code("s/r/a.docx", data)[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
def test_only_the_content_types_of_an_office_file_are_inflated(monkeypatch):
|
||||
calls = []
|
||||
pack = _zip([("s/r/a.docx", _office("word/document.xml"))]) # built before the spy: writes open too
|
||||
real = zipfile.ZipFile.open # every inflating read goes through `open` (`_bounded_read`)
|
||||
monkeypatch.setattr(zipfile.ZipFile, "open", lambda self, name, *a, **k: calls.append(name)
|
||||
or real(self, name, *a, **k))
|
||||
read_pack(pack)
|
||||
assert [getattr(c, "filename", c) for c in calls] == ["s/r/a.docx", "[Content_Types].xml"]
|
||||
|
||||
|
||||
# --- SKILL.md (2.3) -----------------------------------------------------------------------------
|
||||
|
||||
def _skill(text: str, path: str = "s/SKILL.md") -> tuple[str, list[str]]:
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([(path, text.encode("utf-8"))], compression=zipfile.ZIP_STORED))
|
||||
return caught.value.code, caught.value.files
|
||||
|
||||
|
||||
def _fm(**fields) -> str:
|
||||
return "---\n" + "".join(f"{k}: {v}\n" for k, v in fields.items()) + "---\nbody\n"
|
||||
|
||||
|
||||
def test_crlf_and_a_bom_are_read_like_lf():
|
||||
pack = read_pack(_zip([("s/SKILL.md", b"\xef\xbb\xbf" + SKILL.replace(b"\n", b"\r\n"))]))
|
||||
assert pack.skills[0].name == "nda" and pack.skills[0].body == "# NDA\n"
|
||||
|
||||
|
||||
def test_a_skill_md_that_is_not_utf8_is_refused():
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([("s/SKILL.md", "---\nname: zażółć\n---\n".encode("cp1250"))]))
|
||||
assert caught.value.code == "skill_not_utf8"
|
||||
|
||||
|
||||
def test_a_frontmatter_over_8_kb_is_refused():
|
||||
big = "x" * (skill_pack.MAX_FRONTMATTER_BYTES + 1)
|
||||
assert _skill(_fm(name="a", description=big)) == ("skill_frontmatter_too_large", ["s/SKILL.md"])
|
||||
|
||||
|
||||
def test_a_date_in_the_frontmatter_stays_a_string_jsonb_can_store():
|
||||
import json
|
||||
pack = read_pack(_zip([("s/SKILL.md", _fm(name="a", description="d", updated="2025-01-01").encode())]))
|
||||
assert pack.skills[0].frontmatter["updated"] == "2025-01-01"
|
||||
json.dumps(pack.skills[0].frontmatter, allow_nan=False)
|
||||
|
||||
|
||||
def test_a_claude_code_style_description_with_colons_is_read_as_one_string():
|
||||
# Strict YAML refuses the second `: `; Claude Code (and most real SKILL.md files) do not.
|
||||
doc = ("---\nname: tworzenie-skilli\ndescription: Use when X — `a: b`. SKIP: literówka\n"
|
||||
" ciąg dalszy\nallowed-tools: Read, Glob\n---\n# Body\n")
|
||||
s = read_pack(_zip([("s/SKILL.md", doc.encode())])).skills[0]
|
||||
assert s.description == "Use when X — `a: b`. SKIP: literówka ciąg dalszy"
|
||||
assert s.frontmatter["allowed-tools"] == "Read, Glob"
|
||||
|
||||
|
||||
def test_in_flat_text_a_quoted_or_list_value_is_still_read_as_yaml():
|
||||
doc = '---\nname: a\ndescription: d. SKIP: x\npaths: ["**/*.gs", "*.json"]\nargument-hint: "[review]"\n---\nb'
|
||||
fm = read_pack(_zip([("s/SKILL.md", doc.encode())])).skills[0].frontmatter
|
||||
assert fm["paths"] == ["**/*.gs", "*.json"] and fm["argument-hint"] == "[review]"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("head", ["name: a\ndescription: d: e\n- list item", "name: a\n orphan\nx: [unclosed",
|
||||
"name: a\ndescription: d: e\nx: !!python/object:os.system ls",
|
||||
"name: a\ndescription: d: e\nx: *undefined"])
|
||||
def test_a_broken_frontmatter_that_is_not_flat_text_is_still_refused(head):
|
||||
assert _skill(f"---\n{head}\n---\nbody")[0] == "skill_frontmatter_invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["!!binary aGVsbG8=", "!!set {a: null}", ".nan", "!!timestamp 2025-01-01"])
|
||||
def test_frontmatter_values_json_cannot_carry_are_refused(value):
|
||||
assert _skill(_fm(name="a", description="d", x=value))[0] == "skill_frontmatter_invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("yaml_text", [
|
||||
"name: &n a\ndescription: *n\n", # anchor + alias
|
||||
"name: a\ndescription: d\nx: &anchor 1\n", # an anchor alone is refused too
|
||||
])
|
||||
def test_yaml_anchors_and_aliases_are_refused(yaml_text):
|
||||
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_alias"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("yaml_text", ["name: [unclosed\n", "x: !!python/object:os.system ls\n",
|
||||
"[" * 5000 + "\n"])
|
||||
def test_a_frontmatter_that_is_not_safe_yaml_is_refused(yaml_text):
|
||||
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("yaml_text", ["- a\n- b\n", "just a string\n"])
|
||||
def test_a_frontmatter_that_is_not_a_mapping_is_refused(yaml_text):
|
||||
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_not_mapping"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["# no frontmatter at all\n", _fm(name="a"), _fm(description="d"),
|
||||
_fm(name="a", description='""'), _fm(name=1, description="d")])
|
||||
def test_a_missing_name_or_description_is_refused(text):
|
||||
assert _skill(text)[0] == "skill_missing_field"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["Nda", "nda_review", "nda--x", "-nda", "przegląd", "a" * 65])
|
||||
def test_a_name_that_is_not_kebab_up_to_64_is_refused(name):
|
||||
assert _skill(_fm(name=name, description="d"))[0] == "skill_bad_name"
|
||||
|
||||
|
||||
def test_a_64_character_name_is_accepted():
|
||||
assert read_pack(_zip([("s/SKILL.md", _fm(name="a" * 64, description="d").encode())]))
|
||||
|
||||
|
||||
def test_a_description_over_1024_characters_is_refused():
|
||||
assert _skill(_fm(name="a", description="d" * 1025))[0] == "skill_description_too_long"
|
||||
|
||||
|
||||
def test_a_body_over_30000_characters_is_refused():
|
||||
text = "---\nname: a\ndescription: d\n---\n" + "ż" * (skill_pack.MAX_BODY + 1)
|
||||
assert _skill(text)[0] == "skill_body_too_long"
|
||||
|
||||
|
||||
def test_permission_fields_are_kept_as_information_only():
|
||||
text = ("---\nname: a\ndescription: d\nallowed-tools: [Bash, WebFetch]\nmodel: opus\n"
|
||||
"permissionMode: bypassPermissions\nlicense: MIT\n---\n")
|
||||
(skill,) = read_pack(_zip([("s/SKILL.md", text.encode())])).skills
|
||||
assert skill.info_only == {"allowed-tools": ["Bash", "WebFetch"], "model": "opus",
|
||||
"permissionMode": "bypassPermissions"}
|
||||
assert skill.frontmatter["license"] == "MIT"
|
||||
|
||||
|
||||
def _plugin(*extra) -> bytes:
|
||||
return _zip([("p/.claude-plugin/plugin.json", b'{"name": "p"}'),
|
||||
("p/skills/nda/SKILL.md", SKILL), ("p/commands/review.md", b"# c"), *extra])
|
||||
|
||||
|
||||
def test_a_plugin_contributes_its_skills():
|
||||
assert [s.path for s in read_pack(_plugin()).skills] == ["p/skills/nda/SKILL.md"]
|
||||
|
||||
|
||||
def test_a_plugin_with_a_script_is_refused_with_the_list():
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_plugin(("p/scripts/run.sh", b"rm -rf /"), ("p/skills/nda/helper.py", b"x")))
|
||||
assert caught.value.code == "pack_plugin_code"
|
||||
assert caught.value.files == ["p/scripts/run.sh", "p/skills/nda/helper.py"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["p/hooks/hooks.json", "p/.mcp.json", "p/bin/tool.md"])
|
||||
def test_a_plugin_with_hooks_or_mcp_servers_is_refused(path):
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_plugin((path, b"{}")))
|
||||
assert (caught.value.code, caught.value.files) == ("pack_plugin_code", [path])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["hooks", "mcpServers"])
|
||||
def test_a_plugin_manifest_declaring_code_inline_is_refused(key):
|
||||
data = _zip([("p/.claude-plugin/plugin.json", f'{{"name": "p", "{key}": {{}}}}'.encode()),
|
||||
("p/skills/nda/SKILL.md", SKILL)])
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(data)
|
||||
assert (caught.value.code, caught.value.files) == ("pack_plugin_code",
|
||||
["p/.claude-plugin/plugin.json"])
|
||||
|
||||
|
||||
def test_a_plugin_nested_in_another_is_judged_against_its_own_root():
|
||||
data = _zip([(".claude-plugin/plugin.json", b'{"name": "outer"}'),
|
||||
("inner/.claude-plugin/plugin.json", b'{"name": "inner"}'),
|
||||
("inner/hooks/hooks.json", b"{}")])
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(data)
|
||||
assert (caught.value.code, caught.value.files) == ("pack_plugin_code", ["inner/hooks/hooks.json"])
|
||||
|
||||
|
||||
# --- content sum, build_pack, agent packs (2.4) ------------------------------------------------
|
||||
|
||||
_ORIGINAL = ("---\r\nname: nda\r\nmetadata: {version: 2, author: Zespół}\r\ndescription: Przeglăd\r\n"
|
||||
"license: proprietary\r\n---\r\n# Przeglăd NDA\r\n").encode()
|
||||
_DOCX = _office("word/document.xml")
|
||||
|
||||
|
||||
def _sum(pack, i=0):
|
||||
return skill_pack.content_sha256(skill_pack.skill_content(pack, pack.skills[i]))
|
||||
|
||||
|
||||
def test_a_skill_with_a_docx_hashes_the_same_after_export_and_import():
|
||||
original = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx", _DOCX)]))
|
||||
content = skill_pack.skill_content(original, original.skills[0])
|
||||
assert content.folder == "nda" and content.files == {"resources/playbook.docx": _DOCX}
|
||||
again = read_pack(skill_pack.build_pack([content]))
|
||||
assert again.kind == "skill" and "atrium-pack.json" not in again.files
|
||||
assert _sum(again) == _sum(original)
|
||||
# Only spelling is normalised away: a changed file is a changed skill.
|
||||
other = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx",
|
||||
_office("word/other.xml"))]))
|
||||
assert _sum(other) != _sum(original)
|
||||
|
||||
|
||||
def test_an_agent_pack_round_trips_with_its_skills():
|
||||
skills = [skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n",
|
||||
{"r/a.txt": b"x"}),
|
||||
skill_pack.SkillContent("dpa", {"name": "dpa", "description": "e"}, "# b\n", {})]
|
||||
agent = skill_pack.AgentDoc(name="Asystent umów", description="Przegląda umowy", body="Bądź zwięzły.\n",
|
||||
frontmatter={"name": "Asystent umów", "description": "Przegląda umowy",
|
||||
"kind": "assistant", "tools": ["search"], "model": "sonnet"})
|
||||
pack = read_pack(skill_pack.build_pack(skills, agent))
|
||||
assert pack.kind == "agent" and pack.agent == agent
|
||||
assert [skill_pack.skill_content(pack, s) for s in pack.skills] == sorted(skills, key=lambda s: s.folder)
|
||||
|
||||
|
||||
def _tampered(change) -> tuple[str, list[str]]:
|
||||
content = skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n", {"a.txt": b"x"})
|
||||
with zipfile.ZipFile(io.BytesIO(skill_pack.build_pack([content]))) as zf:
|
||||
entries = {n: zf.read(n) for n in zf.namelist()}
|
||||
change(entries)
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip(entries.items()))
|
||||
return caught.value.code, caught.value.files
|
||||
|
||||
|
||||
def test_a_file_whose_sum_differs_from_the_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"nda/a.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/a.txt"])
|
||||
|
||||
|
||||
def test_a_file_missing_from_the_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"nda/b.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/b.txt"])
|
||||
|
||||
|
||||
def test_a_malformed_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"atrium-pack.json": b'{"format": 1}'}))[0] \
|
||||
== "pack_manifest_invalid"
|
||||
@@ -0,0 +1,188 @@
|
||||
"""The skills HTTP surface, DB-free: the routes exist under /api/v1, and what the router itself
|
||||
decides — the streamed 10 MB ceiling on an import, base64 files, the ZIP response — reaches the
|
||||
service the way the service expects. The rules behind the routes are `test_skills_unit.py`'s."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import types
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from fastapi.routing import APIRoute
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import deps
|
||||
from app.db import get_db
|
||||
from app.main import app
|
||||
from app.services import skills as service
|
||||
from app.routers.skills import MAX_JSON_BODY_BYTES
|
||||
from app.services.skill_pack import MAX_PACK_BYTES
|
||||
|
||||
API = "/api/v1"
|
||||
SKILL_ID = uuid.uuid4()
|
||||
|
||||
|
||||
def test_every_skills_route_is_registered_under_the_api_prefix():
|
||||
bound = {(m, r.path) for r in app.routes if isinstance(r, APIRoute) for m in r.methods}
|
||||
for method, path in [
|
||||
("GET", "/skills"), ("POST", "/skills"), ("GET", "/skills/{skill_id}"),
|
||||
("POST", "/skills/{skill_id}/versions"), ("GET", "/skills/{skill_id}/versions/{n}"),
|
||||
("POST", "/skills/{skill_id}/archive"), ("POST", "/skills/{skill_id}/publish"),
|
||||
("GET", "/skills/{skill_id}/export"), ("POST", "/skills/import"),
|
||||
]:
|
||||
assert (method, API + path) in bound, (method, path)
|
||||
|
||||
|
||||
class _Db:
|
||||
def commit(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(monkeypatch):
|
||||
"""`calls` records what reached the service; nothing touches a database."""
|
||||
calls: dict = {}
|
||||
user = types.SimpleNamespace(id=uuid.uuid4(), is_admin=False)
|
||||
app.dependency_overrides[get_db] = _Db
|
||||
app.dependency_overrides[deps.get_current_user] = lambda: user
|
||||
|
||||
def fake(name, result):
|
||||
def _f(db, actor, *args, **kwargs):
|
||||
calls[name] = (args, kwargs)
|
||||
return result
|
||||
monkeypatch.setattr(service, name, _f)
|
||||
|
||||
fake("import_skills", {"status": "imported", "skills": [], "ignored": []})
|
||||
fake("new_version", {"n": 2})
|
||||
fake("export_skill", ("nda-v3.zip", b"PK\x05\x06" + bytes(18)))
|
||||
try:
|
||||
yield types.SimpleNamespace(client=TestClient(app), calls=calls)
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_import_passes_the_raw_body_and_its_name_to_the_service(api):
|
||||
r = api.client.post(f"{API}/skills/import?filename=nda.zip&add_version=true", content=b"PK-bytes",
|
||||
headers={"Content-Type": "application/zip"})
|
||||
assert r.status_code == 200, r.text
|
||||
args, kwargs = api.calls["import_skills"]
|
||||
assert args == (b"PK-bytes", "nda.zip") and kwargs["add_version"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunked", [False, True])
|
||||
def test_an_import_over_10_mb_is_refused_before_the_service(api, chunked):
|
||||
big = b"x" * (MAX_PACK_BYTES + 1)
|
||||
# A generator body goes out chunked, with no Content-Length: only the streamed count catches it.
|
||||
content = (big[i:i + 65536] for i in range(0, len(big), 65536)) if chunked else big
|
||||
r = api.client.post(f"{API}/skills/import", content=content,
|
||||
headers={"Content-Type": "application/zip"})
|
||||
assert r.status_code == 422 and r.json()["code"] == "pack_too_large"
|
||||
assert "import_skills" not in api.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, cap", [
|
||||
("/skills/import", MAX_PACK_BYTES), # zip_body
|
||||
(f"/skills/{SKILL_ID}/versions", MAX_JSON_BODY_BYTES), # CappedBodyRoute
|
||||
])
|
||||
def test_an_oversized_body_stops_being_read_at_the_cap(api, path, cap):
|
||||
"""Not only refused: reading STOPS at the cap. Buffering the whole body first and measuring it
|
||||
afterwards answers the same 422, so the result alone cannot tell the two apart. ASGI-level,
|
||||
because TestClient reads the whole request body before the app sees a byte."""
|
||||
import asyncio
|
||||
chunk, received, status = b"x" * 65536, [0], []
|
||||
ctype = b"application/zip" if path.endswith("import") else b"application/json"
|
||||
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "POST",
|
||||
"scheme": "http", "path": f"{API}{path}", "raw_path": f"{API}{path}".encode(),
|
||||
"root_path": "", "query_string": b"", "server": ("testserver", 80),
|
||||
"client": ("127.0.0.1", 1), "headers": [(b"host", b"testserver"), (b"content-type", ctype)]}
|
||||
|
||||
async def receive():
|
||||
received[0] += len(chunk)
|
||||
return {"type": "http.request", "body": chunk, "more_body": received[0] < 10 * cap}
|
||||
|
||||
async def send(message):
|
||||
if message["type"] == "http.response.start":
|
||||
status.append(message["status"])
|
||||
|
||||
asyncio.run(app(scope, receive, send))
|
||||
assert status == [422]
|
||||
assert received[0] < cap + 4 * len(chunk), received[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["metadata", "model_policy"])
|
||||
def test_free_form_json_over_8_kb_is_a_422(api, field):
|
||||
path = f"/skills/{SKILL_ID}/versions" if field == "metadata" else f"/agents/{SKILL_ID}/versions"
|
||||
r = api.client.post(f"{API}{path}", json={field: {"x": "y" * 9000}})
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
def test_a_new_version_decodes_files_and_leaves_absent_fields_none(api):
|
||||
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions",
|
||||
json={"body": "# v2", "files": {"a.txt": base64.b64encode(b"hi").decode()}})
|
||||
assert r.status_code == 201, r.text
|
||||
(skill_id, fields), _ = api.calls["new_version"]
|
||||
assert skill_id == SKILL_ID
|
||||
assert fields["files"] == {"a.txt": b"hi"} and fields["body"] == "# v2"
|
||||
assert fields["description"] is None and fields["metadata"] is None # None = carry over
|
||||
|
||||
|
||||
@pytest.mark.parametrize("files", [
|
||||
{"a.txt": "not base64!"},
|
||||
["a.txt"],
|
||||
{"a.txt": base64.b64encode(b"x" * (MAX_PACK_BYTES // 2 + 1)).decode(),
|
||||
"b.txt": base64.b64encode(b"x" * (MAX_PACK_BYTES // 2 + 1)).decode()},
|
||||
])
|
||||
def test_bad_or_oversized_files_are_a_422(api, files):
|
||||
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"files": files})
|
||||
assert r.status_code == 422
|
||||
assert "new_version" not in api.calls
|
||||
|
||||
|
||||
def test_export_answers_a_zip_attachment(api):
|
||||
r = api.client.get(f"{API}/skills/{SKILL_ID}/export?n=3")
|
||||
assert r.status_code == 200
|
||||
assert r.headers["content-type"] == "application/zip"
|
||||
assert r.headers["content-disposition"] == 'attachment; filename="nda-v3.zip"'
|
||||
assert api.calls["export_skill"][0] == (SKILL_ID, 3)
|
||||
|
||||
|
||||
def test_every_agent_and_publish_request_route_is_registered_under_the_api_prefix():
|
||||
bound = {(m, r.path) for r in app.routes if isinstance(r, APIRoute) for m in r.methods}
|
||||
for method, path in [
|
||||
("GET", "/agents"), ("POST", "/agents"), ("GET", "/agents/{agent_id}"),
|
||||
("POST", "/agents/{agent_id}/versions"), ("POST", "/agents/{agent_id}/archive"),
|
||||
("POST", "/agents/{agent_id}/publish"), ("GET", "/agents/{agent_id}/export"),
|
||||
("POST", "/agents/import"), ("GET", "/admin/publish-requests"),
|
||||
("POST", "/admin/publish-requests/{request_id}/approve"),
|
||||
("POST", "/admin/publish-requests/{request_id}/decline"),
|
||||
]:
|
||||
assert (method, API + path) in bound, (method, path)
|
||||
|
||||
|
||||
def _calls(dependant):
|
||||
for d in dependant.dependencies:
|
||||
yield d.call
|
||||
yield from _calls(d)
|
||||
|
||||
|
||||
def test_every_publish_request_route_depends_on_require_administrator():
|
||||
routes = [r for r in app.routes
|
||||
if isinstance(r, APIRoute) and r.path.startswith(API + "/admin/publish-requests")]
|
||||
assert len(routes) == 3
|
||||
for r in routes:
|
||||
assert deps.require_administrator in set(_calls(r.dependant)), r.path
|
||||
|
||||
|
||||
def test_a_non_administrator_is_refused_the_publish_queue(api):
|
||||
r = api.client.get(f"{API}/admin/publish-requests")
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_a_new_agent_version_passes_pins_and_leaves_absent_fields_none(api, monkeypatch):
|
||||
pin = uuid.uuid4()
|
||||
seen = {}
|
||||
monkeypatch.setattr(service, "new_agent_version",
|
||||
lambda db, actor, agent_id, fields, ip: seen.update(fields) or {"n": 2})
|
||||
r = api.client.post(f"{API}/agents/{SKILL_ID}/versions", json={"skill_version_ids": [str(pin)]})
|
||||
assert r.status_code == 201, r.text
|
||||
assert seen["skill_version_ids"] == [pin] and seen["instructions"] is None
|
||||
@@ -0,0 +1,238 @@
|
||||
"""The skills-and-agents screens in the console (Skille i agenci, Administracja → Prośby o publikację).
|
||||
DB-free.
|
||||
|
||||
Source-reading, like `test_providers_console.py`, and honest about what that proves: the screens are
|
||||
routed, call only routes the backend declares (method included), escape what they render, keep the
|
||||
publish queue behind the administrator check and never leave this module by a root-absolute
|
||||
address. That the routes behave is `test_skills_integration.py`'s job.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def console() -> str:
|
||||
return (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _section(console: str, start: str, end: str) -> str:
|
||||
assert start in console and end in console, (start, end)
|
||||
return console.split(start, 1)[1].split(end, 1)[0]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def screen(console) -> str:
|
||||
return (_section(console, "/* ── skills and agents ──", "function openTokenNew(")
|
||||
+ _section(console, "/* ── administration: publish requests", "/* ── administration: organization"))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def queue(console) -> str:
|
||||
return _section(console, "/* ── administration: publish requests", "/* ── administration: organization")
|
||||
|
||||
|
||||
def _declared() -> set[tuple[str, str]]:
|
||||
"""(METHOD, path) for every route in routers/skills.py, path parameters as `{}`."""
|
||||
src = (ROOT / "backend" / "app" / "routers" / "skills.py").read_text(encoding="utf-8")
|
||||
prefixes = dict(re.findall(r'^(\w+) = APIRouter[(]prefix="([^"]+)"', src, re.M))
|
||||
assert set(prefixes) == {"router", "agents", "publish_requests"}
|
||||
out = set()
|
||||
for name, method, path in re.findall(r'^@(\w+)[.](get|post)[(]"([^"]*)"', src, re.M):
|
||||
out.add((method.upper(), re.sub(r"\{[^}]+\}", "{}", prefixes[name] + path)))
|
||||
return out
|
||||
|
||||
|
||||
def _first_arg(src: str, at: int) -> str:
|
||||
"""The JS expression starting at `at`, up to the first top-level `,` or the closing `)`."""
|
||||
depth, i, quote = 0, at, None
|
||||
while i < len(src):
|
||||
c = src[i]
|
||||
if quote:
|
||||
if c == "\\":
|
||||
i += 1
|
||||
elif c == quote:
|
||||
quote = None
|
||||
elif quote == "`" and src.startswith("${", i):
|
||||
end = src.index("}", i) # interpolations here hold no braces
|
||||
i = end
|
||||
elif c in "'\"`":
|
||||
quote = c
|
||||
elif c in "([{":
|
||||
depth += 1
|
||||
elif c in ")]}":
|
||||
if depth == 0:
|
||||
break
|
||||
depth -= 1
|
||||
elif c == "," and depth == 0:
|
||||
break
|
||||
i += 1
|
||||
return src[at:i]
|
||||
|
||||
|
||||
def _path(expr: str) -> str:
|
||||
"""A JS path expression as a route template: every interpolation and every `+ <call>` piece
|
||||
becomes `{}`; a query (`?…`, `+ q`) is dropped."""
|
||||
expr = re.sub(r"\$\{[^}]*\}", "{}", expr)
|
||||
parts = [x.strip() for x in re.split(r"\s\+\s", expr)]
|
||||
out = ""
|
||||
for part in parts:
|
||||
if part[:1] in "'`":
|
||||
out += part.strip("'`")
|
||||
elif part == "API":
|
||||
continue
|
||||
elif re.fullmatch(r"enc[(][^)]*[)]", part):
|
||||
out += "{}"
|
||||
else:
|
||||
break # a query string built at run time
|
||||
return out.split("?", 1)[0]
|
||||
|
||||
|
||||
def _called(screen: str) -> set[tuple[str, str]]:
|
||||
calls = {(m.group(1), _path(_first_arg(screen, m.end())))
|
||||
for m in re.finditer(r"\b(?:api|mutate)[(]'([A-Z]+)', ", screen)}
|
||||
# Exports are plain links on API, not api() calls.
|
||||
calls |= {("GET", _path(_first_arg(screen, m.end()))) for m in re.finditer(r"esc[(](?=API \+)", screen)}
|
||||
# The decision dialog is shared with access requests and takes its queue as an argument, and its
|
||||
# last segment is `approve ? 'approve' : 'decline'` (pinned by test_the_decision_goes_...).
|
||||
out = set()
|
||||
for m, p in calls:
|
||||
p = p.replace("/admin/{}/", "/admin/publish-requests/")
|
||||
if p == "/admin/publish-requests/{}/{}":
|
||||
out |= {(m, "/admin/publish-requests/{}/approve"), (m, "/admin/publish-requests/{}/decline")}
|
||||
else:
|
||||
out.add((m, p))
|
||||
return out
|
||||
|
||||
|
||||
def test_the_screens_are_routed(console):
|
||||
nav = _section(console, "const NAV = [", "];")
|
||||
assert "'#/skills'" in nav
|
||||
assert "else if (seg[0] === 'skills' && seg[1] === 'skill' && seg[2]) await viewSkill(C, seg[2]);" in console
|
||||
assert "else if (seg[0] === 'skills' && seg[1] === 'agent' && seg[2]) await viewAgent(C, seg[2]);" in console
|
||||
assert "else if (seg[0] === 'skills') await viewSkills(C, seg[1] === 'firm' ? 'firm' : 'mine');" in console
|
||||
for fn in ("viewSkills", "viewSkill", "viewAgent", "viewAdminPublishRequests"):
|
||||
assert f"async function {fn}(" in console
|
||||
|
||||
|
||||
def test_the_publish_queue_is_administrator_only(console):
|
||||
admin_nav = _section(console, "const ADMIN_NAV = [", "\n];")
|
||||
assert "'#/admin/publish-requests'" in admin_nav
|
||||
assert "'#/admin/publish-requests'" not in _section(console, "const NAV = [", "];")
|
||||
# Reached only through adminRoute, which the router enters only for an administrator.
|
||||
assert "else if (seg[0] === 'admin' && isAdmin()) await adminRoute(C, seg.slice(1), q);" in console
|
||||
admin_route = _section(console, "async function adminRoute(", "\n}\n")
|
||||
assert "if (page === 'publish-requests') return viewAdminPublishRequests(C);" in admin_route
|
||||
assert console.count("viewAdminPublishRequests(") == 2 # its definition and that one call
|
||||
|
||||
|
||||
def test_it_calls_only_routes_that_exist(screen):
|
||||
declared = _declared()
|
||||
called = _called(screen)
|
||||
assert len(called) >= 15, called
|
||||
assert called <= declared, called - declared
|
||||
|
||||
|
||||
def test_the_route_reader_sees_every_kind_of_call():
|
||||
"""Guard the guard: each spelling the screens use turns into the right template."""
|
||||
sample = """
|
||||
api('GET', '/skills/' + enc(id));
|
||||
api('GET', `/skills/${enc(id)}/versions/${v.n}`);
|
||||
api('POST', '/skills/import' + q + (addVersion ? '&add_version=true' : ''), f);
|
||||
mutate('POST', `/admin/${queue}/${enc(id)}/${approve ? 'approve' : 'decline'}`, { note: 1 });
|
||||
href="${esc(API + '/agents/' + enc(a.id) + '/export')}"
|
||||
"""
|
||||
assert _called(sample) == {
|
||||
("GET", "/skills/{}"), ("GET", "/skills/{}/versions/{}"), ("POST", "/skills/import"),
|
||||
("POST", "/admin/publish-requests/{}/approve"), ("POST", "/admin/publish-requests/{}/decline"),
|
||||
("GET", "/agents/{}/export"),
|
||||
}
|
||||
|
||||
|
||||
def test_the_decision_goes_only_to_approve_or_decline(queue, console):
|
||||
send = _section(console, "function sendDecision(", "\n}\n")
|
||||
assert "${approve ? 'approve' : 'decline'}" in send
|
||||
assert {("POST", "/admin/publish-requests/{}/approve"), ("POST", "/admin/publish-requests/{}/decline")} <= _declared()
|
||||
assert queue.count("'publish-requests')") == 2
|
||||
|
||||
|
||||
def _text_builders(screen: str) -> str:
|
||||
"""Drop the helpers that build PLAIN TEXT (lines to diff, D3 notes): their output is escaped
|
||||
where it is rendered (`diffHtml` → esc, `infoNote` → dat), not where it is assembled."""
|
||||
for name in ("versionText", "agentVersionText", "infoLines"):
|
||||
screen = re.sub(rf"const {name} = .*?;\n(?=\S|\n)", "", screen, flags=re.S)
|
||||
return screen
|
||||
|
||||
|
||||
def test_dynamic_values_are_escaped(screen):
|
||||
"""No field of a response reaches markup bare: every `${x.field}` sits inside esc()/dat()/enc().
|
||||
Counts (`.length`) are numbers; the api()/mutate() lines build URLs, where enc() is the rule."""
|
||||
code = _text_builders(screen)
|
||||
assert "versionText = " not in code and "infoLines = " not in code
|
||||
code = "\n".join(line for line in code.splitlines() if not re.search(r"\b(?:api|mutate)[(]'", line))
|
||||
exprs = _interpolations(code)
|
||||
assert len(exprs) > 50, len(exprs)
|
||||
bare = []
|
||||
for e in exprs:
|
||||
if _wrapped(e):
|
||||
continue
|
||||
# Literals and nested templates are checked on their own; what is left is the top level.
|
||||
top = re.sub(r"'(?:[^'\\]|\\.)*'|`[^`]*`", "''", e).strip()
|
||||
# The whole expression, or a branch of a ternary/fallback, read straight off an object.
|
||||
# A part followed by `?` or `&&` is a condition, not what gets rendered.
|
||||
bits = re.split(r"(\?|:|\|\||&&)", top) + [""]
|
||||
for part, op in zip(bits[::2], bits[1::2], strict=False):
|
||||
part = part.strip()
|
||||
if op not in ("?", "&&") and re.fullmatch(r"[a-z]\w*(?:\.\w+|\[\d+\])+", part) and not part.endswith(".length"):
|
||||
bare.append(e)
|
||||
assert not bare, bare
|
||||
|
||||
|
||||
def _wrapped(e: str) -> bool:
|
||||
"""The whole expression is one esc()/dat()/enc() call."""
|
||||
m = re.match(r"(?:esc|dat|enc)[(]", e)
|
||||
if not m:
|
||||
return False
|
||||
depth = 0
|
||||
for i, c in enumerate(e[m.end() - 1:], m.end() - 1):
|
||||
depth += {"(": 1, ")": -1}.get(c, 0)
|
||||
if depth == 0:
|
||||
return i == len(e) - 1
|
||||
return False
|
||||
|
||||
|
||||
def _interpolations(code: str) -> list[str]:
|
||||
"""Every `${...}` expression, nested ones included, by brace depth."""
|
||||
out, i = [], 0
|
||||
while (i := code.find("${", i)) != -1:
|
||||
depth, j = 1, i + 2
|
||||
while depth and j < len(code):
|
||||
depth += {"{": 1, "}": -1}.get(code[j], 0)
|
||||
j += 1
|
||||
out.append(code[i + 2:j - 1])
|
||||
i += 2
|
||||
return out
|
||||
|
||||
|
||||
def test_no_root_absolute_href_or_src(screen):
|
||||
"""A leading slash would leave /atrium for a sibling's backend (CLAUDE.md, path-mounting)."""
|
||||
assert not re.search(r"""\b(?:href|src|action)=["'`]?/(?!/)""", screen)
|
||||
assert "location.href = '/" not in screen and "location.href = `/" not in screen
|
||||
# Downloads go through the derived API base, never a literal /api/v1.
|
||||
assert "/api/v1" not in screen
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phrase", [
|
||||
"Skille i agenci", "Moje", "Firmowe", "Prośby o publikację", "Brak próśb o publikację.",
|
||||
"Zatwierdź", "Odrzuć", "Pierwsza publikacja w firmie", "plik do pobrania, model go jeszcze nie czyta",
|
||||
"Zapisane tylko jako informacja:",
|
||||
])
|
||||
def test_it_is_in_both_languages(console, screen, phrase):
|
||||
assert phrase in screen
|
||||
block = console.split("const I18N = {", 1)[1].split("\n};", 1)[0]
|
||||
assert re.search(rf"""^ ['"]{re.escape(phrase)}['"]: """, block, re.M), f"no English for {phrase!r}"
|
||||
@@ -0,0 +1,401 @@
|
||||
"""Skills against a real, migrated database, as the runtime role.
|
||||
|
||||
Opt in with ATRIUM_RUN_INTEGRATION=1, like `test_integration.py`. Who sees what is decided in
|
||||
`services/skills.py` (skills are not org-tree nodes), so this suite pins that rule end to end: the
|
||||
visibility matrix, a firm skill's next version staying invisible until an administrator approves
|
||||
it, the `skills_firm_publish` switch, and the audit rows every write leaves. Then agents (a firm
|
||||
agent never pins a personal skill), T2 on export (`skills_firm_export`, for a skill and for an agent
|
||||
with everything it pins), import round trips keeping one content sum, a malicious pack answered as
|
||||
Problem Details with a `code`, and the database itself refusing to rewrite a frozen version.
|
||||
|
||||
Skills are never deleted (only archived), so every slug is suffixed per run, and every setting is
|
||||
put back exactly as it was found (`settings_set`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
from conftest import bearer, integration, settings_set
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import ProgrammingError
|
||||
|
||||
pytestmark = integration
|
||||
|
||||
RUN = uuid.uuid4().hex[:8]
|
||||
SKILLS = "/api/v1/skills"
|
||||
REQUESTS = "/api/v1/admin/publish-requests"
|
||||
|
||||
|
||||
def _slug(label: str) -> str:
|
||||
return f"{label}-{RUN}-{uuid.uuid4().hex[:4]}"
|
||||
|
||||
|
||||
def _create(client, headers=None, **over) -> dict:
|
||||
body = {"slug": _slug("skill"), "name": "Umowy NDA", "description": "Checks an NDA.",
|
||||
"body": "# NDA\n\nRead the definition of confidential information first.\n", **over}
|
||||
r = client.post(SKILLS, json=body, headers=headers)
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _audit(admin_client, action: str, entity_id: str) -> list[dict]:
|
||||
rows = admin_client.get("/api/v1/admin/audit", params={"action": action, "limit": 500}).json()
|
||||
return [row for row in rows if row.get("entity_id") == entity_id]
|
||||
|
||||
|
||||
def _approve(admin_client, skill_id: str) -> dict:
|
||||
pending = [r for r in admin_client.get(REQUESTS).json() if r["item"]["id"] == skill_id]
|
||||
assert len(pending) == 1, pending
|
||||
r = admin_client.post(f"{REQUESTS}/{pending[0]['id']}/approve")
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def owner(make_user):
|
||||
return make_user("skills-owner")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def other(make_user):
|
||||
return make_user("skills-other")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def firm_skill(admin_client, owner):
|
||||
"""A skill the owner wrote and an administrator approved for the firm (version 1)."""
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(admin_client, bearer(owner["token"]))
|
||||
r = admin_client.post(f"{SKILLS}/{skill['id']}/publish", headers=bearer(owner["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
_approve(admin_client, skill["id"])
|
||||
return skill
|
||||
|
||||
|
||||
# ── who sees what ─────────────────────────────────────────────────────────────
|
||||
def test_a_personal_skill_is_the_owners_alone(admin_client, client, owner, other):
|
||||
skill = _create(client, bearer(owner["token"]))
|
||||
sid = skill["id"]
|
||||
assert (skill["scope"], skill["mine"], skill["editable"]) == ("personal", True, True)
|
||||
|
||||
mine = client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"]))
|
||||
assert mine.status_code == 200 and mine.json()["current"]["n"] == 1
|
||||
assert any(s["id"] == sid for s in client.get(SKILLS, headers=bearer(owner["token"])).json())
|
||||
|
||||
# Another person and an administrator alike: a 404 on every path, and absent from the list.
|
||||
for who in (bearer(other["token"]), None):
|
||||
api = client if who else admin_client
|
||||
assert all(s["id"] != sid for s in api.get(SKILLS, headers=who).json())
|
||||
for method, path in [("GET", f"{SKILLS}/{sid}"), ("GET", f"{SKILLS}/{sid}/versions/1"),
|
||||
("POST", f"{SKILLS}/{sid}/versions"),
|
||||
("POST", f"{SKILLS}/{sid}/archive"),
|
||||
("POST", f"{SKILLS}/{sid}/publish"),
|
||||
("GET", f"{SKILLS}/{sid}/export")]:
|
||||
r = api.request(method, path, json={} if method == "POST" else None, headers=who)
|
||||
assert r.status_code == 404, (who is None, method, path, r.status_code, r.text)
|
||||
|
||||
|
||||
def test_a_firm_skill_is_everybodys_to_read(admin_client, client, owner, other, firm_skill):
|
||||
sid = firm_skill["id"]
|
||||
for api, who, editable in [(client, bearer(owner["token"]), True),
|
||||
(client, bearer(other["token"]), False),
|
||||
(admin_client, None, True)]:
|
||||
r = api.get(f"{SKILLS}/{sid}", headers=who)
|
||||
assert r.status_code == 200, r.text
|
||||
assert (r.json()["scope"], r.json()["editable"]) == ("firm", editable)
|
||||
assert r.json()["current"]["n"] == 1
|
||||
assert any(s["id"] == sid for s in api.get(SKILLS, headers=who).json())
|
||||
|
||||
# Reading is not changing: anybody else may not touch it.
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Hijacked\n"},
|
||||
headers=bearer(other["token"]))
|
||||
assert r.status_code == 403, r.text
|
||||
assert client.post(f"{SKILLS}/{sid}/archive",
|
||||
headers=bearer(other["token"])).status_code == 403
|
||||
|
||||
|
||||
def test_a_missing_skill_is_404(client, owner):
|
||||
assert client.get(f"{SKILLS}/{uuid.uuid4()}", headers=bearer(owner["token"])).status_code == 404
|
||||
|
||||
|
||||
# ── publication ───────────────────────────────────────────────────────────────
|
||||
def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client, owner, other,
|
||||
firm_skill):
|
||||
sid = firm_skill["id"]
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# NDA v2\n\nNew rule.\n"},
|
||||
headers=bearer(owner["token"]))
|
||||
assert r.status_code == 201, r.text
|
||||
n = r.json()["n"]
|
||||
|
||||
def seen_by_other():
|
||||
out = client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"])).json()
|
||||
return out["current"]["n"], [v["n"] for v in out["versions"]]
|
||||
|
||||
# Written is not published: everybody else still reads the approved version, only.
|
||||
assert seen_by_other() == (n - 1, [n - 1])
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/{n}",
|
||||
headers=bearer(other["token"])).status_code == 404
|
||||
owner_view = client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()
|
||||
assert owner_view["current"]["n"] == n - 1 and n in [v["n"] for v in owner_view["versions"]]
|
||||
|
||||
r = client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
again = client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
|
||||
assert again.status_code == 409 # already waiting
|
||||
assert seen_by_other() == (n - 1, [n - 1])
|
||||
|
||||
# The administrator's queue shows both sides of the diff.
|
||||
request = next(q for q in admin_client.get(REQUESTS).json() if q["item"]["id"] == sid)
|
||||
assert (request["version"]["n"], request["base"]["n"]) == (n, n - 1)
|
||||
assert client.get(REQUESTS, headers=bearer(owner["token"])).status_code == 403
|
||||
|
||||
decided = _approve(admin_client, sid)
|
||||
assert decided["status"] == "approved"
|
||||
assert seen_by_other() == (n, [n])
|
||||
assert admin_client.post(f"{REQUESTS}/{request['id']}/approve").status_code == 409
|
||||
|
||||
|
||||
def test_a_declined_request_leaves_the_firm_where_it_was(admin_client, client, owner, other):
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(owner["token"]))
|
||||
sid = skill["id"]
|
||||
client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
|
||||
request = next(q for q in admin_client.get(REQUESTS).json() if q["item"]["id"] == sid)
|
||||
assert request["base"] is None # never published: nothing to diff against
|
||||
r = admin_client.post(f"{REQUESTS}/{request['id']}/decline", json={"note": "Too broad."})
|
||||
assert r.status_code == 200 and r.json()["status"] == "declined", r.text
|
||||
assert client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"])).status_code == 404
|
||||
assert client.get(f"{SKILLS}/{sid}",
|
||||
headers=bearer(owner["token"])).json()["scope"] == "personal"
|
||||
|
||||
|
||||
def test_direct_publication_is_the_administrators_switch(admin_client, client, owner, other):
|
||||
r = client.put("/api/v1/admin/settings", json={"values": {"skills_firm_publish": "direct"}},
|
||||
headers=bearer(owner["token"]))
|
||||
assert r.status_code == 403 # only an administrator flips it
|
||||
bad = admin_client.put("/api/v1/admin/settings",
|
||||
json={"values": {"skills_firm_publish": "always"}})
|
||||
assert bad.status_code == 422, bad.text
|
||||
|
||||
with settings_set(admin_client, skills_firm_publish="direct"):
|
||||
skill = _create(client, bearer(owner["token"]))
|
||||
sid = skill["id"]
|
||||
r = client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
|
||||
assert r.status_code == 200, r.text
|
||||
assert (r.json()["status"], r.json()["request_id"]) == ("published", None)
|
||||
assert r.json()["skill"]["scope"] == "firm"
|
||||
assert all(q["item"]["id"] != sid for q in admin_client.get(REQUESTS).json())
|
||||
seen = client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"]))
|
||||
assert seen.status_code == 200 and seen.json()["current"]["n"] == 1
|
||||
|
||||
rows = _audit(admin_client, "skill.publish_approve", sid)
|
||||
assert len(rows) == 1 and rows[0]["detail"].endswith("direct")
|
||||
assert rows[0]["actor_id"] == str(owner["id"])
|
||||
assert _audit(admin_client, "skill.publish_request", sid) == []
|
||||
|
||||
|
||||
# ── the audit ─────────────────────────────────────────────────────────────────
|
||||
def test_every_write_leaves_one_audit_row(admin_client, client, owner):
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(owner["token"]))
|
||||
sid = skill["id"]
|
||||
v2 = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Two\n"},
|
||||
headers=bearer(owner["token"])).json()
|
||||
client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
|
||||
_approve(admin_client, sid)
|
||||
client.post(f"{SKILLS}/{sid}/archive", headers=bearer(owner["token"]))
|
||||
client.post(f"{SKILLS}/{sid}/archive", headers=bearer(owner["token"])) # nothing changes
|
||||
|
||||
expected = {"skill.create": str(owner["id"]), "skill.version": str(owner["id"]),
|
||||
"skill.publish_request": str(owner["id"]),
|
||||
"skill.publish_approve": None, # the administrator, whose id the fixture lacks
|
||||
"skill.archive": str(owner["id"])}
|
||||
for action, actor in expected.items():
|
||||
rows = _audit(admin_client, action, sid)
|
||||
assert len(rows) == 1, (action, rows)
|
||||
assert rows[0]["entity_type"] == "skill"
|
||||
if actor:
|
||||
assert rows[0]["actor_id"] == actor, action
|
||||
approve = _audit(admin_client, "skill.publish_approve", sid)[0]
|
||||
assert approve["actor_id"] != str(owner["id"])
|
||||
# The detail names the version and its content hash, never the content.
|
||||
version_row = _audit(admin_client, "skill.version", sid)[0]
|
||||
assert version_row["detail"] == f"{skill['slug']} v2 {v2['content_sha256']}"
|
||||
assert "# Two" not in str(_audit(admin_client, "skill.", sid))
|
||||
|
||||
|
||||
# ── agents ────────────────────────────────────────────────────────────────────
|
||||
AGENTS = "/api/v1/agents"
|
||||
|
||||
|
||||
def _agent(client, headers, pins: list[str]) -> dict:
|
||||
r = client.post(AGENTS, json={"name": f"Asystent {RUN}", "instructions": "Pomagaj.",
|
||||
"skill_version_ids": pins}, headers=headers)
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _current_version_id(api, sid: str, headers=None) -> str:
|
||||
return api.get(f"{SKILLS}/{sid}", headers=headers).json()["current"]["id"]
|
||||
|
||||
|
||||
def test_a_firm_agent_never_carries_a_personal_skill(admin_client, client, owner, firm_skill):
|
||||
me = bearer(owner["token"])
|
||||
personal = _create(client, me)
|
||||
agent = _agent(client, me, [_current_version_id(client, personal["id"], me)])
|
||||
|
||||
with settings_set(admin_client, skills_firm_publish="direct"):
|
||||
r = client.post(f"{AGENTS}/{agent['id']}/publish", headers=me)
|
||||
assert r.status_code == 422, r.text
|
||||
assert r.headers["content-type"].startswith("application/problem+json")
|
||||
assert r.json()["code"] == "agent_pin_refused"
|
||||
assert client.get(f"{AGENTS}/{agent['id']}", headers=me).json()["scope"] == "personal"
|
||||
|
||||
# Repinned to the firm's published version, the same agent goes through.
|
||||
firm_pin = _current_version_id(client, firm_skill["id"], me)
|
||||
r = client.post(f"{AGENTS}/{agent['id']}/versions",
|
||||
json={"skill_version_ids": [firm_pin]}, headers=me)
|
||||
assert r.status_code == 201, r.text
|
||||
r = client.post(f"{AGENTS}/{agent['id']}/publish", headers=me)
|
||||
assert r.status_code == 200 and r.json()["agent"]["scope"] == "firm", r.text
|
||||
|
||||
# Once firm, a new version may not bring a personal skill back in either.
|
||||
r = client.post(f"{AGENTS}/{agent['id']}/versions",
|
||||
json={"skill_version_ids": [_current_version_id(client, personal["id"], me)]},
|
||||
headers=me)
|
||||
assert r.status_code == 422 and r.json()["code"] == "agent_pin_refused", r.text
|
||||
|
||||
|
||||
def test_approving_a_firm_agent_checks_its_pins_again(admin_client, client, owner):
|
||||
"""A firm agent pins only the CURRENT firm version. If that skill moves on while the agent's
|
||||
request waits, the administrator's approval must refuse, not publish a stale pin."""
|
||||
me = bearer(owner["token"])
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, me)
|
||||
assert client.post(f"{SKILLS}/{skill['id']}/publish", headers=me).status_code == 200
|
||||
_approve(admin_client, skill["id"])
|
||||
agent = _agent(client, me, [_current_version_id(client, skill["id"], me)])
|
||||
r = client.post(f"{AGENTS}/{agent['id']}/publish", headers=me)
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
|
||||
# The skill's next version is approved first: the agent's pin is no longer current.
|
||||
r = client.post(f"{SKILLS}/{skill['id']}/versions", json={"body": "# NDA v2\n"}, headers=me)
|
||||
assert r.status_code == 201, r.text
|
||||
assert client.post(f"{SKILLS}/{skill['id']}/publish", headers=me).status_code == 200
|
||||
_approve(admin_client, skill["id"])
|
||||
|
||||
pending = [p for p in admin_client.get(REQUESTS).json() if p["item"]["id"] == agent["id"]]
|
||||
assert len(pending) == 1, pending
|
||||
r = admin_client.post(f"{REQUESTS}/{pending[0]['id']}/approve")
|
||||
assert r.status_code == 422 and r.json()["code"] == "agent_pin_refused", r.text
|
||||
assert client.get(f"{AGENTS}/{agent['id']}", headers=me).json()["scope"] == "personal"
|
||||
|
||||
|
||||
# ── T2: who may export ────────────────────────────────────────────────────────
|
||||
def test_exporting_a_firm_skill_follows_the_t2_setting(admin_client, client, owner, other,
|
||||
firm_skill):
|
||||
path = f"{SKILLS}/{firm_skill['id']}/export"
|
||||
with settings_set(admin_client, skills_firm_export="administrator"):
|
||||
assert client.get(path, headers=bearer(other["token"])).status_code == 403
|
||||
r = client.get(path, headers=bearer(owner["token"])) # one's own: always
|
||||
assert r.status_code == 200 and r.headers["content-type"] == "application/zip"
|
||||
assert admin_client.get(path).status_code == 200
|
||||
with settings_set(admin_client, skills_firm_export="everyone"):
|
||||
r = client.get(path, headers=bearer(other["token"]))
|
||||
assert r.status_code == 200 and r.content[:2] == b"PK"
|
||||
|
||||
|
||||
def test_exporting_an_agent_follows_t2_for_the_agent_and_every_pinned_skill(
|
||||
admin_client, client, owner, other, firm_skill):
|
||||
# The other person's own agent, pinning the owner's firm skill: theirs, but not all theirs.
|
||||
mine = bearer(other["token"])
|
||||
agent = _agent(client, mine, [_current_version_id(client, firm_skill["id"], mine)])
|
||||
path = f"{AGENTS}/{agent['id']}/export"
|
||||
with settings_set(admin_client, skills_firm_export="administrator"):
|
||||
assert client.get(path, headers=mine).status_code == 403
|
||||
assert admin_client.get(path).status_code == 404 # somebody's personal agent
|
||||
with settings_set(admin_client, skills_firm_export="everyone"):
|
||||
r = client.get(path, headers=mine)
|
||||
assert r.status_code == 200 and r.headers["content-type"] == "application/zip", r.text
|
||||
|
||||
# A firm agent: an administrator always, anybody else only under `everyone`.
|
||||
with settings_set(admin_client, skills_firm_publish="direct"):
|
||||
r = client.post(f"{AGENTS}/{agent['id']}/publish", headers=mine)
|
||||
assert r.status_code == 200 and r.json()["agent"]["scope"] == "firm", r.text
|
||||
with settings_set(admin_client, skills_firm_export="administrator"):
|
||||
assert client.get(path, headers=bearer(owner["token"])).status_code == 403
|
||||
assert admin_client.get(path).status_code == 200
|
||||
with settings_set(admin_client, skills_firm_export="everyone"):
|
||||
assert client.get(path, headers=bearer(owner["token"])).status_code == 200
|
||||
|
||||
|
||||
# ── import ────────────────────────────────────────────────────────────────────
|
||||
def _zip(files: dict[str, str]) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
||||
for name, body in files.items():
|
||||
z.writestr(name, body)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _import(client, headers, data: bytes, path: str = f"{SKILLS}/import"):
|
||||
return client.post(path, content=data, params={"filename": "pack.zip"},
|
||||
headers={**headers, "Content-Type": "application/zip"})
|
||||
|
||||
|
||||
def test_import_export_import_keeps_the_same_sum(client, owner, other):
|
||||
slug = _slug("imp")
|
||||
pack = _zip({f"{slug}/SKILL.md": f"---\nname: {slug}\ndescription: Checks an NDA.\n"
|
||||
"license: MIT\n---\n# NDA\n\nRead clause 1 first.\n",
|
||||
f"{slug}/reference.md": "# Clauses\n"})
|
||||
first = _import(client, bearer(owner["token"]), pack)
|
||||
assert first.status_code == 200 and first.json()["status"] == "imported", first.text
|
||||
imported = first.json()["skills"][0]
|
||||
assert imported["skill"]["slug"] == slug
|
||||
|
||||
exported = client.get(f"{SKILLS}/{imported['skill']['id']}/export",
|
||||
headers=bearer(owner["token"]))
|
||||
assert exported.status_code == 200, exported.text
|
||||
|
||||
# Into somebody else's library: a new skill with the very same content sum.
|
||||
again = _import(client, bearer(other["token"]), exported.content)
|
||||
assert again.status_code == 200 and again.json()["status"] == "imported", again.text
|
||||
assert again.json()["skills"][0]["content_sha256"] == imported["content_sha256"]
|
||||
# Back into the owner's own: recognised, nothing written.
|
||||
back = _import(client, bearer(owner["token"]), exported.content)
|
||||
assert back.status_code == 200 and back.json()["status"] == "duplicate", back.text
|
||||
assert back.json()["skills"][0]["match"]["id"] == imported["skill"]["id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("files", "code"), [
|
||||
({"../evil/SKILL.md": "---\nname: evil\ndescription: x\n---\n"}, "pack_bad_path"),
|
||||
({"evil/SKILL.md": "---\nname: evil\ndescription: x\n---\n", "evil/run.sh": "rm -rf /\n"},
|
||||
"pack_file_type"),
|
||||
({"not-a-zip": ""}, "pack_not_zip"),
|
||||
])
|
||||
def test_a_malicious_pack_is_refused_as_problem_details(client, owner, files, code):
|
||||
data = b"not a zip at all" if code == "pack_not_zip" else _zip(files)
|
||||
before = client.get(SKILLS, headers=bearer(owner["token"])).json()
|
||||
r = _import(client, bearer(owner["token"]), data)
|
||||
assert r.status_code == 422, r.text
|
||||
assert r.headers["content-type"].startswith("application/problem+json")
|
||||
assert r.json()["code"] == code
|
||||
assert client.get(SKILLS, headers=bearer(owner["token"])).json() == before
|
||||
|
||||
|
||||
# ── the database backs the rules ──────────────────────────────────────────────
|
||||
@pytest.mark.parametrize("statement", [
|
||||
"UPDATE skill_version SET body_md = 'rewritten'",
|
||||
"DELETE FROM skill_version",
|
||||
])
|
||||
def test_the_runtime_role_cannot_rewrite_a_frozen_version(client, statement):
|
||||
from app.db import engine
|
||||
|
||||
with engine.connect() as conn:
|
||||
with pytest.raises(ProgrammingError, match="permission denied"):
|
||||
conn.execute(text(statement))
|
||||
conn.rollback()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Revision 0010: the SQL that freezes skill and agent versions for the runtime role (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
FROZEN = ("skill_version", "skill_file", "agent_version", "agent_version_skill")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def revision():
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0015", BACKEND / "alembic" / "versions" / "0015_skills.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_it_follows_the_model_providers(revision):
|
||||
assert (revision.revision, revision.down_revision) == ("0015", "0014")
|
||||
|
||||
|
||||
def test_it_creates_all_seven_tables(revision):
|
||||
assert {t.name for t in revision._TABLES} == {
|
||||
"skill", "skill_version", "skill_file", "agent", "agent_version",
|
||||
"agent_version_skill", "publish_request"}
|
||||
|
||||
|
||||
def test_the_four_version_tables_lose_update_and_delete(revision):
|
||||
sql = revision.immutable_versions_sql("atrium_app")
|
||||
revoke = re.search(r"REVOKE UPDATE, DELETE, TRUNCATE ON (.+?) FROM \"atrium_app\";", sql)
|
||||
assert revoke, sql
|
||||
assert {t.strip() for t in revoke.group(1).split(",")} == set(FROZEN)
|
||||
# ...and the block proves it, rather than trusting the REVOKE.
|
||||
for privilege in ("UPDATE", "DELETE", "TRUNCATE"):
|
||||
assert f"has_table_privilege('atrium_app', quote_ident(t), '{privilege}')" in sql
|
||||
assert "has_any_column_privilege('atrium_app'" in sql
|
||||
assert "RAISE EXCEPTION" in sql
|
||||
|
||||
|
||||
def test_no_bind_parameter_or_percent_reaches_text(revision):
|
||||
sql = revision.immutable_versions_sql("app")
|
||||
assert "%" not in sql
|
||||
assert not re.search(r"(?<![:\w]):\w", sql)
|
||||
|
||||
|
||||
def test_a_role_that_is_not_a_plain_name_is_refused(revision):
|
||||
from app.identity_grants import GrantsRefused
|
||||
|
||||
with pytest.raises(GrantsRefused):
|
||||
revision.immutable_versions_sql('app"; DROP TABLE skill; --')
|
||||
@@ -0,0 +1,293 @@
|
||||
"""`services/skills.py`: the visibility rule, version numbering and content checks (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import uuid
|
||||
import zipfile
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
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
|
||||
|
||||
OWNER, OTHER, ADMIN = (SimpleNamespace(id=uuid.uuid4(), is_admin=a) for a in (False, False, True))
|
||||
|
||||
|
||||
def _skill(scope: str, current=None) -> Skill:
|
||||
return Skill(id=uuid.uuid4(), slug="nda", name="NDA", owner_id=OWNER.id, scope=scope,
|
||||
status="active", origin="authored", current_version_id=current)
|
||||
|
||||
|
||||
class _Db:
|
||||
def __init__(self, skill):
|
||||
self.skill = skill
|
||||
|
||||
def get(self, _model, _id):
|
||||
return self.skill
|
||||
|
||||
|
||||
@pytest.mark.parametrize("user, scope, sees, edits", [
|
||||
(OWNER, "personal", True, True),
|
||||
(OTHER, "personal", False, False),
|
||||
(ADMIN, "personal", False, False), # an administrator gets no look at working notes
|
||||
(OWNER, "firm", True, True),
|
||||
(OTHER, "firm", True, False),
|
||||
(ADMIN, "firm", True, True),
|
||||
])
|
||||
def test_visibility_matrix(user, scope, sees, edits):
|
||||
skill = _skill(scope)
|
||||
assert skills.can_see(user, skill) is sees
|
||||
assert skills.can_edit(user, skill) is edits
|
||||
|
||||
|
||||
def test_someone_elses_personal_skill_is_a_404_not_a_403():
|
||||
db = _Db(_skill("personal"))
|
||||
for user in (OTHER, ADMIN):
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_skill(db, user, db.skill.id)
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.archive_skill(db, user, db.skill.id, ip=None)
|
||||
|
||||
|
||||
def test_a_firm_skill_is_changed_only_by_its_editors():
|
||||
db = _Db(_skill("firm"))
|
||||
with pytest.raises(AuthorizationError):
|
||||
skills.new_version(db, OTHER, db.skill.id, {}, ip=None)
|
||||
|
||||
|
||||
def test_a_non_editor_reads_only_the_current_version():
|
||||
approved, pending = uuid.uuid4(), uuid.uuid4()
|
||||
skill = _skill("firm", current=approved)
|
||||
assert skills.readable_version_ids(OTHER, skill, [approved, pending]) == {approved}
|
||||
assert skills.readable_version_ids(OWNER, skill, [approved, pending]) == {approved, pending}
|
||||
|
||||
|
||||
def test_next_n():
|
||||
assert skills.next_n(None) == 1
|
||||
assert skills.next_n(4) == 5
|
||||
|
||||
|
||||
def test_frontmatter_columns_win_over_metadata():
|
||||
head = skills.frontmatter("nda", "Opis", "MIT", {"name": "x", "license": "y", "metadata": {"a": 1}})
|
||||
assert head == {"name": "nda", "description": "Opis", "license": "MIT", "metadata": {"a": 1}}
|
||||
|
||||
|
||||
def test_checked_hashes_what_an_export_would_carry():
|
||||
files = {"resources/notes.md": b"# Notatki\n"}
|
||||
doc, stored, sha = skills.checked("nda", "Przegląd NDA", "Treść\r\n", "proprietary", {}, files)
|
||||
assert stored.files == files and doc.body == "Treść\n"
|
||||
assert sha == skill_pack.content_sha256(stored)
|
||||
pack = skill_pack.read_pack(skill_pack.build_pack([stored]))
|
||||
assert skill_pack.content_sha256(skill_pack.skill_content(pack, pack.skills[0])) == sha
|
||||
|
||||
|
||||
@pytest.mark.parametrize("slug, files, code", [
|
||||
("Not Kebab", {}, "skill_bad_name"),
|
||||
("nda", {"run.sh": b"echo"}, "pack_file_type"),
|
||||
("nda", {"../escape.md": b"x"}, "pack_bad_path"),
|
||||
("nda", {"a\\b.md": b"x"}, "pack_bad_path"),
|
||||
("nda", {"/abs.md": b"x"}, "pack_bad_path"),
|
||||
("nda", {"a//b.md": b"x"}, "pack_bad_path"),
|
||||
("nda", {"SKILL.md": b"---\nname: nda\ndescription: x\n---\n"}, "pack_duplicate_name"),
|
||||
])
|
||||
def test_checked_applies_the_import_rules(slug, files, code):
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
skills.checked(slug, "Opis", "Treść", "proprietary", {}, files)
|
||||
assert caught.value.code == code
|
||||
|
||||
|
||||
def test_every_allowed_extension_has_a_media_type():
|
||||
assert set(skills.MEDIA_TYPES) == skill_pack.ALLOWED_TYPES
|
||||
|
||||
|
||||
# ---- publication (T1) ----
|
||||
|
||||
class _PublishDb:
|
||||
def __init__(self):
|
||||
self.added = []
|
||||
|
||||
def scalar(self, _query):
|
||||
return None # no pending request for this version yet
|
||||
|
||||
def add(self, row):
|
||||
self.added.append(row)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def audited(monkeypatch):
|
||||
actions = []
|
||||
monkeypatch.setattr(skills.audit, "record", lambda _db, **kw: actions.append(kw["action"]))
|
||||
return actions
|
||||
|
||||
|
||||
def _version(n=1):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["approval", "direct"])
|
||||
def test_publication_follows_the_setting(monkeypatch, audited, mode):
|
||||
monkeypatch.setattr(skills.settings, "get", lambda _db, key: {"skills_firm_publish": mode}[key])
|
||||
skill, version, db = _skill("personal"), _version(), _PublishDb()
|
||||
out = skills._publish(db, OWNER, skills.PublishKind.skill, skill, version, ip=None)
|
||||
if mode == "direct":
|
||||
assert out["status"] == "published" and not db.added
|
||||
assert (skill.scope, skill.current_version_id) == ("firm", version.id)
|
||||
assert audited == ["skill.publish_approve"]
|
||||
else:
|
||||
assert out["status"] == "pending" and skill.scope == "personal"
|
||||
assert [(r.kind, r.version_id, r.status) for r in db.added] == [
|
||||
("skill", version.id, "pending")]
|
||||
assert audited == ["skill.publish_request"]
|
||||
|
||||
|
||||
def test_a_new_firm_version_waits_for_approval(monkeypatch, audited):
|
||||
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "approval")
|
||||
approved = uuid.uuid4()
|
||||
skill = _skill("firm", current=approved)
|
||||
skills._publish(_PublishDb(), OWNER, skills.PublishKind.skill, skill, _version(2), ip=None)
|
||||
assert skill.current_version_id == approved
|
||||
|
||||
|
||||
def test_the_published_version_is_not_published_twice(monkeypatch):
|
||||
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "direct")
|
||||
version = _version()
|
||||
skill = _skill("firm", current=version.id)
|
||||
with pytest.raises(ConflictError):
|
||||
skills._publish(_PublishDb(), OWNER, skills.PublishKind.skill, skill, version, ip=None)
|
||||
|
||||
|
||||
def test_approving_an_older_version_is_refused():
|
||||
assert skills.refuses_older(_skill("firm"), 3, _version(2))
|
||||
assert not skills.refuses_older(_skill("firm"), 2, _version(3))
|
||||
assert not skills.refuses_older(_skill("personal"), None, _version(1))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("call", [
|
||||
lambda: skills.decide_publish(None, OTHER, uuid.uuid4(), approve=True),
|
||||
lambda: skills.pending_publish_requests(None, OTHER),
|
||||
])
|
||||
def test_only_an_administrator_decides(call):
|
||||
with pytest.raises(AuthorizationError):
|
||||
call()
|
||||
|
||||
|
||||
def test_an_imported_slug_takes_the_first_free_number():
|
||||
assert skills.free_slug(set(), "x") == "x"
|
||||
assert skills.free_slug({"x"}, "x") == "x-2"
|
||||
assert skills.free_slug({"x", "x-2"}, "x") == "x-3"
|
||||
long = "a" * 64
|
||||
assert skills.free_slug({long}, long) == "a" * 62 + "-2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("user, firm_export, allowed", [
|
||||
(OWNER, "administrator", True), # one's own: always
|
||||
(OTHER, "administrator", False),
|
||||
(ADMIN, "administrator", True),
|
||||
(OTHER, "everyone", True),
|
||||
])
|
||||
def test_t2_decides_who_exports_a_firm_skill(user, firm_export, allowed):
|
||||
assert skills.may_export(user, _skill("firm"), firm_export) is allowed
|
||||
|
||||
|
||||
def test_an_agent_pack_or_a_pack_without_skill_md_is_not_a_skill_import():
|
||||
agent = skill_pack.build_pack([], skill_pack.AgentDoc(
|
||||
name="a", description="d", body="b", frontmatter={"name": "a", "description": "d"}))
|
||||
with pytest.raises(PackRejected) as err:
|
||||
skills.import_skills(None, OWNER, agent, ip=None)
|
||||
assert err.value.code == "pack_is_agent"
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as zf:
|
||||
zf.writestr("notes.md", "hi")
|
||||
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",
|
||||
"en": "A firm agent pins only the firm's published skill versions.",
|
||||
"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"
|
||||
+74
-74
@@ -1,74 +1,74 @@
|
||||
# Przegląd QA platformy Atrium - 2026-10-07 (noc)
|
||||
|
||||
Zakres: Compass (gałąź `rejestr/fundament`, przed PR), Atrium, Galena, Sygna, Counsel Scorecard + wspólne logowanie platformy. Infrastruktura: skill `atrium-qa-kontrakt`, agenci auditor / test-runner / e2e, kopia `C:/Users/badur/projects/atrium-qa`. Zero zmian i pushy w repo rodziny. Szczegóły i dowody per moduł: [2026-10-07/](2026-10-07/). Zrzuty ekranu, skrypty sond i specy Playwright (`platform-sso.spec.ts`, `rejestr-e2e.spec.ts`) zostały w kopii QA u Tobiasza - na prośbę dołożymy.
|
||||
|
||||
| moduł | SHA | stan |
|
||||
|---|---|---|
|
||||
| atrium | 0b09f50 | origin/main |
|
||||
| galena | 40f78a8 | pin == HEAD |
|
||||
| sygna | 41ab5f9 | pin == HEAD |
|
||||
| counsel | 5ad8476 | pin == HEAD |
|
||||
| dredd-core | v0.12.0 | pin z atrium/backend/requirements.txt (w kontenerach potwierdzone przez e2e) |
|
||||
| compass | 1d7593d | gałąź rejestr/fundament (poza platformą - raport gotowości) |
|
||||
|
||||
## 1. Wady w stronę ZGODY (wpuszczają za dużo) - od najpoważniejszej
|
||||
|
||||
1. **Galena - użytkownik z samym odczytem może obciąć albo nadpisać dowolny plik na serwerze.** Parametry `ref`, `a`, `b` w trasach historii (`app/routers/history.py:30, :48`) idą prosto do gita, więc `--output=<ścieżka>` jest opcją, nie nazwą wersji. Potwierdzone wywołaniem funkcji (pliki obcięte do 0 B); żądania HTTP nikt nie wysłał, dojście wynika z kodu. **Galena działa na żywym Contabo.** Poprawka: odrzucać ref zaczynający się od `-` (albo `--end-of-options`) w `changes.resolve_ref`, `git_facade.log`, `changed_files`, `blame`. → [2026-10-07/galena-audyt.md](2026-10-07/galena-audyt.md)
|
||||
2. **Sygna - prawnik, który założył sprawę, może zdjąć chiński mur postawiony przez partnera nadzorującego.** Przenosi sprawę do swojej przestrzeni osobistej (albo na najwyższy poziom drzewa), staje się administratorem murów, zdejmuje mur i wpuszcza osobę z konfliktem; partner traci wgląd. `routers/nodes.py:98-110` nie sprawdza uprawnień na starym rodzicu. Potwierdzone dwa razy na prawdziwej bazie. Poprawka: kilka linii (diff w raporcie modułu). → [2026-10-07/sygna-audyt.md](2026-10-07/sygna-audyt.md)
|
||||
3. **Atrium - wyciekły token aplikacji wybija sobie kolejne tokeny, które działają po odwołaniu pierwszego.** `routers/users.py:308-352` bez bramki „tylko z sesji”; Compass taką ma. Poprawka: przenieść `require_session_credential` z Compassu. → [2026-10-07/atrium-audyt.md](2026-10-07/atrium-audyt.md)
|
||||
4. **Atrium - przywrócenie konta oddaje dostęp do modułów, który w międzyczasie odebrano** (usunięcie z jednostki albo wyłączenie modułu). Poprawka sprawdzona sondą: `sync_members` w `reactivate`.
|
||||
5. **Atrium - kierownik jednostki (nie admin, nie moderator) wpuszcza ludzi do modułów** przez dodanie ich do folderu. Wada albo nieopisana decyzja; łamie obietnicę z ONBOARDING-compass §3. Do rozstrzygnięcia Roman/Tobiasz.
|
||||
6. **Compass (rejestr) - „Przyjmij z karty” przy walucie robi z ręcznych „5 EUR” kwotę „5 PLN” oznaczoną jako „z karty”.** Poprawka: kwota i waluta przyjmowane razem. → [2026-10-07/compass-audyt.md](2026-10-07/compass-audyt.md)
|
||||
7. **Compass (rejestr) - dziennik zmian zapisuje „z karty”, ale nie z której analizy** (spec R3).
|
||||
8. **Atrium - logowanie w hubie zwraca sekret sesji także w treści odpowiedzi** (poza ciasteczkiem HttpOnly), więc kod w stronie może go odczytać. Do potwierdzenia z autorem (klient desktopowy?). (e2e platformy)
|
||||
9. **Galena, Sygna, Counsel, Atrium - domyślna instalacja z `init.sh` stawia moduły jako osobne aplikacje z własnymi kontami** (znana luka #6, potwierdzona na wszystkich): bez dopisania dwóch linii do env każdy z kontem w module wchodzi bez zgody z Atrium. Komentarze w env („until its cutover revision lands”) są nieaktualne.
|
||||
10. **Strażnik „jedno konto” (`assert_identity_schema`) bez testu we wszystkich czterech modułach platformy** - działa na żywej bazie, ale usunięcie nie czerwieni niczego. W Atrium bez testu zachowania są też: awans na administratora, odwołanie sesji przy dezaktywacji, sprawdzenie kierownika przy zakładaniu folderu (mutacje przechodzą na zielono).
|
||||
11. Drobniejsze: Compass - `CLEARABLE_FIELDS` nikt nie czyta; ochrona przed wstrzyknięciem w nowych miejscach konsoli bez testu (kod dziś poprawny); waluta „ZZZ” przyjmowana; wyczyszczenie kwoty zostawia walutę. Atrium - dwa testy kitu zawsze pomijają Compass (zła ścieżka). OpenAPI i `/docs` publiczne bez sesji we wszystkich modułach.
|
||||
|
||||
## 2. Wady w stronę ODMOWY
|
||||
- **Świeże `init.sh` + `push.sh` pada w kroku 1/5** (`provision.sql` platformowy vs zakomentowane `PLATFORM_IDENTITY_SCHEMA`) - instalacja „z pudełka” opisana w README nie działa bez ręcznych zmian z RUNBOOK §4. `push.sh` woła compose bez `-p`.
|
||||
- Counsel (i najpewniej Sygna) przyjmuje połowiczną konfigurację tożsamości: moduł martwy albo wylogowuje ludzi z Atrium.
|
||||
- Sygna, Counsel: zalogowany bez uprawnienia widzi „Zaloguj się w Atrium” zamiast „nie masz dostępu” (pętla); login w module 409 zamiast 404.
|
||||
- Compass (rejestr): pusty tekst z API blokuje wypełnienie z karty; na telefonie lista szersza niż ekran; komunikaty serwera po angielsku; kwoty w wersji EN w formacie polskim.
|
||||
|
||||
## 3. Kontrakt K1-K7
|
||||
|
||||
| | Atrium | Galena | Sygna | Counsel | Compass (gałąź) |
|
||||
|---|---|---|---|---|---|
|
||||
| K1 jedno konto | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak |
|
||||
| K2 `dredd_session` | kod tak, wdrożenie `atrium_session` | trzyma | kod tak, wdrożenie nie | kod tak, wdrożenie nie | kod tak |
|
||||
| K3 `assert_may_use` | nie dotyczy | trzyma | trzyma | trzyma (test tekstowy) | trzyma |
|
||||
| K4 schemat + role | trzyma (managed check) | trzyma (managed check) | częściowo | statycznie | managed-db OK |
|
||||
| K5 prefiks | trzyma (e2e S7) | trzyma (e2e) | trzyma (e2e) | trzyma (e2e) | nieznane |
|
||||
| K6 licencje | trzyma | backend tak | trzyma | trzyma | trzyma |
|
||||
| K7 dwa obrazy | trzyma | trzyma | trzyma | trzyma | nieznane |
|
||||
| K-A strażnik | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak |
|
||||
| K-B v0.12.0 | tak (kontener) | tak (kontener) | tak (kontener) | tak (kontener) | tak |
|
||||
|
||||
Referencja skilla (`references/kontrakt.md`) podaje v0.11.0 - nieaktualna. `CLAUDE.md` Atrium podaje v0.9.0.
|
||||
|
||||
## 4. Testy (pominięte = NIEZNANE)
|
||||
|
||||
| moduł | standalone z integracją | tryb platformy | bramki |
|
||||
|---|---|---|---|
|
||||
| Compass 1d7593d | 4939 / 70 / 82 - **64 porażki to artefakt** (kopię QA przełączył w trakcie inny agent); powtórka 8 plików: 206 / 0 / 7; wcześniejsza bramka pętli na tym SHA: 5009 / 0 | managed-db: migracje 0001-0010 OK; job platform NIEZNANY (14 pominiętych) | license OK, deploy_check OK, node OK |
|
||||
| Atrium | 364 / 0 / 2 (2 = martwe testy Compassu) | managed check OK, odmowa migracji jako superuser OK; pytest managed-db przerwany = NIEZNANY | license OK, deploy_check OK |
|
||||
| Galena | 288 / 0 / 14 | provisioning + managed check OK; `test_platform_live` (13) NIEZNANY | - |
|
||||
| Sygna | 569 / 0 / 17 | NIEZNANY (seed platformy padł na granty - kolejność kroków) | license OK, deploy_check OK |
|
||||
| Counsel | 178 / 0 / 11 | NIEZNANY (11 pominiętych) | license OK |
|
||||
|
||||
ruff we wszystkich modułach zgłasza I001/B008 - do sprawdzenia, czy CI w ogóle go odpala. Python 3.13 lokalnie, CI 3.12.
|
||||
|
||||
## 5. E2E
|
||||
- **Platforma (S1-S9), cały stos:** 50 testów, 45 zielonych, 5 czerwonych (każdy to znalezisko wyżej). Wspólne logowanie, wylogowanie we wszystkich modułach, odmowa bez uprawnienia, 403 dla zwykłej roli, prefiksy, odporność na podrobione nagłówki i powtórkę ciasteczka - OK. Dwa testy zweryfikowane mutacją. Spec: `2026-10-07-platforma-e2e/platform-sso.spec.ts`. Compass poza zakresem (na platformie stoi `main`).
|
||||
- **Compass, ekrany rejestru:** wszystko z §5 specu działa; wstrzyknięcie skryptu renderuje się jako tekst; viewer bez edycji (403). Rozjazd z prawdziwą kartą NIE URUCHOMIONY (brak modelu). Spec: `2026-10-07-rejestr-e2e/rejestr-e2e.spec.ts`.
|
||||
|
||||
## 6. Hipotezy niepotwierdzone
|
||||
- Counsel: `GET /users` pokazuje moderatorowi cały katalog kont platformy.
|
||||
- Sygna: rola aplikacji ma UPDATE na `conflict_check` i `aml_assessment` (niezmienność trzyma tylko kod).
|
||||
- Galena: `blame` i `git diff --output` z treścią - do dobicia.
|
||||
- Compass: źródło „karta” liczone od dzisiejszej nazwy firmy; rejestr a maskowanie PESEL w nazwie strony.
|
||||
- `deploy/README.md:1193` vs ONBOARDING §2.1 - jeden z dokumentów nieaktualny.
|
||||
|
||||
## 7. Czego nie uruchomiono
|
||||
Joby platformowe pytest w Galenie, Sygnie, Counselu i Compassie; PG17 w backendach; obrazów pojedynczych modułów poza e2e; compose-smoke; regresji option injection przez HTTP w Galenie; rozjazdu rejestru z prawdziwą kartą; Compassu na platformie.
|
||||
# Przegląd QA platformy Atrium - 2026-10-07 (noc)
|
||||
|
||||
Zakres: Compass (gałąź `rejestr/fundament`, przed PR), Atrium, Galena, Sygna, Counsel Scorecard + wspólne logowanie platformy. Infrastruktura: skill `atrium-qa-kontrakt`, agenci auditor / test-runner / e2e, kopia `C:/Users/badur/projects/atrium-qa`. Zero zmian i pushy w repo rodziny. Szczegóły i dowody per moduł: [2026-10-07/](2026-10-07/). Zrzuty ekranu, skrypty sond i specy Playwright (`platform-sso.spec.ts`, `rejestr-e2e.spec.ts`) zostały w kopii QA u Tobiasza - na prośbę dołożymy.
|
||||
|
||||
| moduł | SHA | stan |
|
||||
|---|---|---|
|
||||
| atrium | 0b09f50 | origin/main |
|
||||
| galena | 40f78a8 | pin == HEAD |
|
||||
| sygna | 41ab5f9 | pin == HEAD |
|
||||
| counsel | 5ad8476 | pin == HEAD |
|
||||
| dredd-core | v0.12.0 | pin z atrium/backend/requirements.txt (w kontenerach potwierdzone przez e2e) |
|
||||
| compass | 1d7593d | gałąź rejestr/fundament (poza platformą - raport gotowości) |
|
||||
|
||||
## 1. Wady w stronę ZGODY (wpuszczają za dużo) - od najpoważniejszej
|
||||
|
||||
1. **Galena - użytkownik z samym odczytem może obciąć albo nadpisać dowolny plik na serwerze.** Parametry `ref`, `a`, `b` w trasach historii (`app/routers/history.py:30, :48`) idą prosto do gita, więc `--output=<ścieżka>` jest opcją, nie nazwą wersji. Potwierdzone wywołaniem funkcji (pliki obcięte do 0 B); żądania HTTP nikt nie wysłał, dojście wynika z kodu. **Galena działa na żywym Contabo.** Poprawka: odrzucać ref zaczynający się od `-` (albo `--end-of-options`) w `changes.resolve_ref`, `git_facade.log`, `changed_files`, `blame`. → [2026-10-07/galena-audyt.md](2026-10-07/galena-audyt.md)
|
||||
2. **Sygna - prawnik, który założył sprawę, może zdjąć chiński mur postawiony przez partnera nadzorującego.** Przenosi sprawę do swojej przestrzeni osobistej (albo na najwyższy poziom drzewa), staje się administratorem murów, zdejmuje mur i wpuszcza osobę z konfliktem; partner traci wgląd. `routers/nodes.py:98-110` nie sprawdza uprawnień na starym rodzicu. Potwierdzone dwa razy na prawdziwej bazie. Poprawka: kilka linii (diff w raporcie modułu). → [2026-10-07/sygna-audyt.md](2026-10-07/sygna-audyt.md)
|
||||
3. **Atrium - wyciekły token aplikacji wybija sobie kolejne tokeny, które działają po odwołaniu pierwszego.** `routers/users.py:308-352` bez bramki „tylko z sesji”; Compass taką ma. Poprawka: przenieść `require_session_credential` z Compassu. → [2026-10-07/atrium-audyt.md](2026-10-07/atrium-audyt.md)
|
||||
4. **Atrium - przywrócenie konta oddaje dostęp do modułów, który w międzyczasie odebrano** (usunięcie z jednostki albo wyłączenie modułu). Poprawka sprawdzona sondą: `sync_members` w `reactivate`.
|
||||
5. **Atrium - kierownik jednostki (nie admin, nie moderator) wpuszcza ludzi do modułów** przez dodanie ich do folderu. Wada albo nieopisana decyzja; łamie obietnicę z ONBOARDING-compass §3. Do rozstrzygnięcia Roman/Tobiasz.
|
||||
6. **Compass (rejestr) - „Przyjmij z karty” przy walucie robi z ręcznych „5 EUR” kwotę „5 PLN” oznaczoną jako „z karty”.** Poprawka: kwota i waluta przyjmowane razem. → [2026-10-07/compass-audyt.md](2026-10-07/compass-audyt.md)
|
||||
7. **Compass (rejestr) - dziennik zmian zapisuje „z karty”, ale nie z której analizy** (spec R3).
|
||||
8. **Atrium - logowanie w hubie zwraca sekret sesji także w treści odpowiedzi** (poza ciasteczkiem HttpOnly), więc kod w stronie może go odczytać. Do potwierdzenia z autorem (klient desktopowy?). (e2e platformy)
|
||||
9. **Galena, Sygna, Counsel, Atrium - domyślna instalacja z `init.sh` stawia moduły jako osobne aplikacje z własnymi kontami** (znana luka #6, potwierdzona na wszystkich): bez dopisania dwóch linii do env każdy z kontem w module wchodzi bez zgody z Atrium. Komentarze w env („until its cutover revision lands”) są nieaktualne.
|
||||
10. **Strażnik „jedno konto” (`assert_identity_schema`) bez testu we wszystkich czterech modułach platformy** - działa na żywej bazie, ale usunięcie nie czerwieni niczego. W Atrium bez testu zachowania są też: awans na administratora, odwołanie sesji przy dezaktywacji, sprawdzenie kierownika przy zakładaniu folderu (mutacje przechodzą na zielono).
|
||||
11. Drobniejsze: Compass - `CLEARABLE_FIELDS` nikt nie czyta; ochrona przed wstrzyknięciem w nowych miejscach konsoli bez testu (kod dziś poprawny); waluta „ZZZ” przyjmowana; wyczyszczenie kwoty zostawia walutę. Atrium - dwa testy kitu zawsze pomijają Compass (zła ścieżka). OpenAPI i `/docs` publiczne bez sesji we wszystkich modułach.
|
||||
|
||||
## 2. Wady w stronę ODMOWY
|
||||
- **Świeże `init.sh` + `push.sh` pada w kroku 1/5** (`provision.sql` platformowy vs zakomentowane `PLATFORM_IDENTITY_SCHEMA`) - instalacja „z pudełka” opisana w README nie działa bez ręcznych zmian z RUNBOOK §4. `push.sh` woła compose bez `-p`.
|
||||
- Counsel (i najpewniej Sygna) przyjmuje połowiczną konfigurację tożsamości: moduł martwy albo wylogowuje ludzi z Atrium.
|
||||
- Sygna, Counsel: zalogowany bez uprawnienia widzi „Zaloguj się w Atrium” zamiast „nie masz dostępu” (pętla); login w module 409 zamiast 404.
|
||||
- Compass (rejestr): pusty tekst z API blokuje wypełnienie z karty; na telefonie lista szersza niż ekran; komunikaty serwera po angielsku; kwoty w wersji EN w formacie polskim.
|
||||
|
||||
## 3. Kontrakt K1-K7
|
||||
|
||||
| | Atrium | Galena | Sygna | Counsel | Compass (gałąź) |
|
||||
|---|---|---|---|---|---|
|
||||
| K1 jedno konto | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak |
|
||||
| K2 `dredd_session` | kod tak, wdrożenie `atrium_session` | trzyma | kod tak, wdrożenie nie | kod tak, wdrożenie nie | kod tak |
|
||||
| K3 `assert_may_use` | nie dotyczy | trzyma | trzyma | trzyma (test tekstowy) | trzyma |
|
||||
| K4 schemat + role | trzyma (managed check) | trzyma (managed check) | częściowo | statycznie | managed-db OK |
|
||||
| K5 prefiks | trzyma (e2e S7) | trzyma (e2e) | trzyma (e2e) | trzyma (e2e) | nieznane |
|
||||
| K6 licencje | trzyma | backend tak | trzyma | trzyma | trzyma |
|
||||
| K7 dwa obrazy | trzyma | trzyma | trzyma | trzyma | nieznane |
|
||||
| K-A strażnik | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak |
|
||||
| K-B v0.12.0 | tak (kontener) | tak (kontener) | tak (kontener) | tak (kontener) | tak |
|
||||
|
||||
Referencja skilla (`references/kontrakt.md`) podaje v0.11.0 - nieaktualna. `CLAUDE.md` Atrium podaje v0.9.0.
|
||||
|
||||
## 4. Testy (pominięte = NIEZNANE)
|
||||
|
||||
| moduł | standalone z integracją | tryb platformy | bramki |
|
||||
|---|---|---|---|
|
||||
| Compass 1d7593d | 4939 / 70 / 82 - **64 porażki to artefakt** (kopię QA przełączył w trakcie inny agent); powtórka 8 plików: 206 / 0 / 7; wcześniejsza bramka pętli na tym SHA: 5009 / 0 | managed-db: migracje 0001-0010 OK; job platform NIEZNANY (14 pominiętych) | license OK, deploy_check OK, node OK |
|
||||
| Atrium | 364 / 0 / 2 (2 = martwe testy Compassu) | managed check OK, odmowa migracji jako superuser OK; pytest managed-db przerwany = NIEZNANY | license OK, deploy_check OK |
|
||||
| Galena | 288 / 0 / 14 | provisioning + managed check OK; `test_platform_live` (13) NIEZNANY | - |
|
||||
| Sygna | 569 / 0 / 17 | NIEZNANY (seed platformy padł na granty - kolejność kroków) | license OK, deploy_check OK |
|
||||
| Counsel | 178 / 0 / 11 | NIEZNANY (11 pominiętych) | license OK |
|
||||
|
||||
ruff we wszystkich modułach zgłasza I001/B008 - do sprawdzenia, czy CI w ogóle go odpala. Python 3.13 lokalnie, CI 3.12.
|
||||
|
||||
## 5. E2E
|
||||
- **Platforma (S1-S9), cały stos:** 50 testów, 45 zielonych, 5 czerwonych (każdy to znalezisko wyżej). Wspólne logowanie, wylogowanie we wszystkich modułach, odmowa bez uprawnienia, 403 dla zwykłej roli, prefiksy, odporność na podrobione nagłówki i powtórkę ciasteczka - OK. Dwa testy zweryfikowane mutacją. Spec: `2026-10-07-platforma-e2e/platform-sso.spec.ts`. Compass poza zakresem (na platformie stoi `main`).
|
||||
- **Compass, ekrany rejestru:** wszystko z §5 specu działa; wstrzyknięcie skryptu renderuje się jako tekst; viewer bez edycji (403). Rozjazd z prawdziwą kartą NIE URUCHOMIONY (brak modelu). Spec: `2026-10-07-rejestr-e2e/rejestr-e2e.spec.ts`.
|
||||
|
||||
## 6. Hipotezy niepotwierdzone
|
||||
- Counsel: `GET /users` pokazuje moderatorowi cały katalog kont platformy.
|
||||
- Sygna: rola aplikacji ma UPDATE na `conflict_check` i `aml_assessment` (niezmienność trzyma tylko kod).
|
||||
- Galena: `blame` i `git diff --output` z treścią - do dobicia.
|
||||
- Compass: źródło „karta” liczone od dzisiejszej nazwy firmy; rejestr a maskowanie PESEL w nazwie strony.
|
||||
- `deploy/README.md:1193` vs ONBOARDING §2.1 - jeden z dokumentów nieaktualny.
|
||||
|
||||
## 7. Czego nie uruchomiono
|
||||
Joby platformowe pytest w Galenie, Sygnie, Counselu i Compassie; PG17 w backendach; obrazów pojedynczych modułów poza e2e; compose-smoke; regresji option injection przez HTTP w Galenie; rozjazdu rejestru z prawdziwą kartą; Compassu na platformie.
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
# Skille i agenci użytkownika — infrastruktura
|
||||
|
||||
Status: SZKIC v2 po recenzji (2026-11-05). Do akceptacji: Tobiasz (C1), Roman (R1-R3). Bez commita.
|
||||
Rozpoznanie: sejf `AI Kancelaria/AI Kancelaria - Skille i agenci użytkownika (rozpoznanie).md`.
|
||||
|
||||
## Sedno
|
||||
|
||||
Każda osoba na platformie może napisać skill (instrukcja + pliki referencyjne) i agenta (instrukcja + przypięte skille + model + narzędzia), wyeksportować je do ZIP-a i zaimportować cudzy ZIP. Format pliku to SKILL.md (standard Agent Skills), więc wchodzą też skille z Claude Code, legalwork i mike-workflows. Katalog zapisuje tylko Atrium.
|
||||
|
||||
## Decyzje podjęte
|
||||
|
||||
- **D1 (1a):** skill w v1 to tekst + pliki referencyjne. Kod wykonywalny w paczce = odrzucenie całej paczki.
|
||||
- **D2 (2a):** agenci Compassu trafiają do wspólnego katalogu. **Sposób — patrz C1, do ponownego potwierdzenia po recenzji.**
|
||||
- **D3:** uprawnienia nadaje platforma. `allowed-tools`, `model`, `hooks`, `mcpServers`, `permissionMode` z pliku są zapisywane jako informacja, nigdy nie nadają niczego.
|
||||
- **T1:** publikacja do firmy domyślnie wymaga zgody administratora — **każdej wersji**, nie tylko pierwszej; administrator może przełączyć (`skills.firm_publish` = `approval` | `direct`).
|
||||
- **T2:** skille i agentów firmy domyślnie eksportuje tylko administrator; administrator może przełączyć (`skills.firm_export` = `administrator` | `everyone`).
|
||||
- **T3:** polski pakiet z mike-workflows w paczce startowej, po przeglądzie jakości.
|
||||
- „Administrator”, nie „moderator”: Atrium nie ma własnych moderatorów. Ustawienia T1/T2 wchodzą do zamkniętego `services/settings.SPECS`, zmiana idzie do dziennika.
|
||||
- Hermes i oszczędzanie tokenów: PAUZA.
|
||||
|
||||
## C1 — Compass: ODŁOŻONE (Tobiasz, 2026-11-05)
|
||||
|
||||
Compass jest przebudowywany przez Romana i Piotra, więc v1 go pomija: bez E5, bez typów `compass.*`. Kiedy przebudowa się skończy, wracamy do wyboru niżej (dwa typy agentów Compassu: czerwone linie i karta umowy, oba to ustrukturyzowane listy kontrolne, nie wolny tekst). Tabele v1 i tak idą do schematu Atrium, bo żaden moduł ich nie czyta.
|
||||
|
||||
### Zapis z recenzji (do powrotu)
|
||||
|
||||
Recenzja (sprawdzona w kodzie Compassu) pokazała, że przeniesienie tabel `agent`/`agent_version` do Atrium jest dużo cięższe, niż zakładałem:
|
||||
- podpisane analizy wskazują wersję reguł kluczem obcym, którego nie wolno ruszyć (`models/analysis.py:93`), więc przeniesienie wymaga przepięcia klucza między schematami przy zachowaniu UUID;
|
||||
- edycję i aktywację reguł w Compassie dają role z drzewa Compassu (`editor`, `approver`), których Atrium nie widzi; zapis „przez API Atrium” oznacza albo odebranie edycji dzisiejszym edytorom, albo moduł zapisujący w imieniu dowolnej osoby (zakazane w CLAUDE.md);
|
||||
- próba (trial) blokuje wiersz agenta do zapisu (`services/agents.py:833`), czego rola tylko do odczytu nie zrobi;
|
||||
- jest drugi typ agenta, `facts` (`agents.py:64`), a reguły czytają też worker, runner i program na laptopie w ściśle ustalonym kształcie;
|
||||
- furtka importu z dredd-core odmawia, gdy wspólna tabela nie jest pusta (`model_providers.py:888-900`), więc nie da się jej użyć po E2-E4.
|
||||
|
||||
Dwie drogi:
|
||||
- **C1-a „wspólny format i jeden widok” (rekomendacja):** agenci Compassu zostają w tabelach Compassu (podpisy, role, próba bez zmian). Dostają ten sam ZIP (eksport/import) i pojawiają się w ekranie „Skille i agenci” Atrium jako pozycje z Compassu (link do edycji w Compassie). Agent Compassu może przypinać skille z katalogu Atrium. Koszt: kilka dni po stronie Compassu. Prawnik widzi jeden katalog; dwa magazyny są ukryte.
|
||||
- **C1-b „pełne przeniesienie”:** jedna tabela agentów dla całej platformy. Wymaga od Romana nowej funkcji migracji w core, modelu uprawnień „kto edytuje agenta modułu” i przepięcia kluczy pod podpisanymi analizami. Koszt (zgaduję): 2-3 tygodnie, ryzyko w jedynej kontroli, dla której Compass istnieje (podpis).
|
||||
|
||||
Wybór C1-a zmienia też R1: skoro żaden moduł nie czyta katalogu z bazy, tabele idą do schematu Atrium, a nie do wspólnego — co przy okazji zamyka znalezisko recenzji, że wspólny schemat czyta każdy moduł (Galena, Sygna, Insider), więc każdy moduł widziałby każdy osobisty skill.
|
||||
|
||||
## Model danych (schemat Atrium przy C1-a)
|
||||
|
||||
Stała tożsamość + zamrożone wersje, jak `agent`/`agent_version` w Compassie. Zmiana treści = nowa wersja.
|
||||
|
||||
```
|
||||
skill
|
||||
id, slug (kebab ≤64, unikalny per właściciel), name, owner_id → app_user (RESTRICT)
|
||||
scope: personal | firm -- zmienne: zmiana przez publikację (prośba lub direct)
|
||||
status: active | archived -- bez „draft”: szkic to po prostu skill osobisty
|
||||
current_version_id → skill_version -- dla firm: tylko wersja zatwierdzona
|
||||
origin: authored | imported | bundled
|
||||
|
||||
skill_version -- REVOKE UPDATE, DELETE
|
||||
id, skill_id, n (unikalne per skill)
|
||||
description (≤1024), body_md (≤30 000 znaków — limit wyniku narzędzia czatu)
|
||||
license (domyślnie "proprietary"; z importu nienadpisywalna)
|
||||
metadata JSONB (≤8 KB, frontmatter spoza schematu)
|
||||
content_sha256, provenance JSONB NULL, created_at, created_by
|
||||
|
||||
skill_file -- REVOKE UPDATE, DELETE
|
||||
id, skill_version_id, path, media_type, size, sha256
|
||||
content BYTEA -- oryginał, do eksportu
|
||||
|
||||
agent
|
||||
id, name, owner_id, scope, status (active | archived), kind ("assistant" w v1)
|
||||
current_version_id → agent_version
|
||||
|
||||
agent_version -- REVOKE UPDATE, DELETE
|
||||
id, agent_id, n, instructions_md, model_policy JSONB (podpowiedź), tools_requested TEXT[]
|
||||
created_at, created_by
|
||||
|
||||
agent_version_skill -- REVOKE UPDATE, DELETE; zamiast tablicy UUID
|
||||
agent_version_id → agent_version (RESTRICT), skill_version_id → skill_version (RESTRICT), position
|
||||
|
||||
publish_request -- AccessRequest jest związany z modułem, więc osobna tabela
|
||||
id, kind (skill|agent), version_id, requested_by, status (pending|approved|declined), decided_by, decided_at, note
|
||||
```
|
||||
|
||||
Reguły:
|
||||
- **Agent firmowy przypina tylko skille firmowe.** Agent osobisty może przypinać osobiste i firmowe.
|
||||
- **Archiwizacja skilla** nie rusza przypiętych wersji (FK RESTRICT); agent działa dalej na przypiętej wersji, ekran pokazuje „skill zarchiwizowany”.
|
||||
- **Administrator nie widzi cudzych osobistych skilli w liście** (to robocze notatki prawnika); widzi je tylko w prośbie o publikację. Do potwierdzenia, jeśli kancelaria wymaga wglądu.
|
||||
- Cudzy osobisty skill/agent → 404, nie 403.
|
||||
- **Skille i agenci nie są węzłami drzewa organizacji** (drzewo trzyma tylko jednostki, CLAUDE.md), więc dostęp nie idzie przez `authz.assert_can_read`: liczy go jedna funkcja `skills.visible_to(db, user)` (właściciel ∪ `scope=firm` ∪ administrator dla próśb), wołana przez każdą ścieżkę odczytu i zapisu. To świadome odstępstwo od „authz jedynym autorytetem”, do opisania w docstringu serwisu i w CLAUDE.md przy PR.
|
||||
|
||||
**`content_sha256`** = SHA-256 z: znormalizowanego SKILL.md (UTF-8, NFC, końce linii LF, frontmatter po kanonicznym zrzucie YAML z kluczami w kolejności alfabetycznej) + posortowanej listy `ścieżka\0sha256` plików. Eksport→import musi dać tę samą sumę (test).
|
||||
|
||||
## Format wymiany (ZIP)
|
||||
|
||||
```
|
||||
nda-przeglad/
|
||||
SKILL.md
|
||||
resources/playbook-nda.docx
|
||||
atrium-pack.json wersja formatu, typ (skill|agent), lista plików z sha256
|
||||
```
|
||||
|
||||
SKILL.md: frontmatter `name`, `description`, `license`, `metadata: {version, author, language}`, potem treść.
|
||||
Agent: `agent.md` (frontmatter `name`, `description`, `kind`, `tools`, `model` jako podpowiedź) + foldery skilli obok + manifest. Agent Compassu (C1-a): ten sam układ + `config.json` z regułami; import idzie przez Compass.
|
||||
|
||||
Suma w manifeście chroni przed zmianą po drodze, nie potwierdza autora. Podpisy poza v1.
|
||||
|
||||
## Import — reguły
|
||||
|
||||
Tylko upload. Atrium nie pobiera paczek z adresu (SSRF, jak przy dostawcach).
|
||||
|
||||
Odrzucenie całej paczki z komunikatem, gdy:
|
||||
- ZIP > 10 MB, > 200 plików, suma po rozpakowaniu > 50 MB, stopień kompresji pliku > 100:1, ZIP64;
|
||||
- ścieżka z `..`, absolutna, z `\`, dowiązanie, duplikat nazwy, dwie nazwy różniące się tylko wielkością liter;
|
||||
- plik spoza listy `.md .txt .docx .pdf .xlsx .csv .json .yaml .yml`, albo treść niezgodna z rozszerzeniem (sprawdzenie sygnatury; `.docx` z makrami, czyli z `vbaProject.bin`, = odrzucenie);
|
||||
- ZIP wewnątrz paczki, który nie jest DOCX/XLSX (wnętrze DOCX/XLSX sprawdzane biblioteką standardową `zipfile`: te same limity rozmiaru i kompresji, brak `vbaProject.bin`);
|
||||
- frontmatter > 8 KB, z aliasami/kotwicami YAML, nie jest mapą, brak `name`/`description`, `name` nie kebab ≤64, `description` > 1024, treść > 30 000 znaków;
|
||||
- kod wykonywalny (D1) — także w wtyczce Claude Code: z `.claude-plugin/` bierzemy `skills/*/SKILL.md`; jeśli wtyczka zawiera skrypty, hooki albo serwery MCP, **odrzucenie** z listą tych plików (spójnie z D1), nie ciche pominięcie.
|
||||
|
||||
Import tworzy niezależną kopię osobistą (`origin=imported`, `provenance`, wersja 1). Kolizja sluga → `-2`. Ta sama paczka (ten sam sha256) → pytanie, czy dodać jako nową wersję. Nic nie aktualizuje się samo. Ekran po imporcie pokazuje, co z paczki zostało zapisane tylko jako informacja (np. „prosiła o narzędzia: Bash, WebFetch”).
|
||||
|
||||
## Ekstrakcja tekstu z plików referencyjnych
|
||||
|
||||
**Decyzja Tobiasza (2026-11-05, wariant b): w E1-E3 Word, Excel i PDF są PRZYJMOWANE i przechowywane do pobrania, ale NIE czytane.** Nic w tym przebiegu nie czyta tekstu (czytelnikiem będzie czat, E4). Bez nowych bibliotek do parsowania, bez procesu ekstrakcji, bez kolumny `text`. Sprawdzenie pliku przy imporcie: sygnatura (`%PDF-` dla PDF, ZIP z `[Content_Types].xml` dla DOCX/XLSX) i reguły archiwum wyżej, wszystko biblioteką standardową. Ekran przy takim pliku: „plik do pobrania, model go jeszcze nie czyta”.
|
||||
|
||||
Na E4 (do zrobienia razem z czatem, nie teraz): ekstrakcja raz przy zapisie, nowa kolumna `skill_file.text` w osobnej rewizji, osobny proces z limitem czasu i pamięci:
|
||||
- DOCX: `python-docx` (MIT) + `defusedxml`; XLSX: `openpyxl` (MIT); PDF: `pypdf` (BSD) — **nie PyMuPDF** (AGPL, bramka licencji).
|
||||
- W osobnym procesie z limitem czasu i pamięci, nie w procesie bramy wejściowej platformy.
|
||||
- Brak tekstu (skan) = plik przechodzi, `text` puste. OCR poza v1.
|
||||
|
||||
## Eksport — reguły
|
||||
|
||||
Własne skille i agenci: zawsze. Firmowe: wg T2. Eksport agenta zawiera jego przypięte skille, więc eksport agenta z firmowymi skillami podlega T2 tak samo. Licencja wymagana (domyślnie `proprietary`). Każdy eksport i import → dziennik zdarzeń (kto, co, sha256 paczki).
|
||||
|
||||
## Udostępnianie
|
||||
|
||||
`personal` i `firm`. Publikacja = `publish_request` na konkretną wersję (przy `approval`); przy `direct` od razu. Nowa wersja skilla firmowego przy `approval` wymaga ponownej zgody; do tego czasu `current_version_id` wskazuje ostatnią zatwierdzoną. Opublikowane widzą wszyscy, edytuje właściciel i administrator, inni robią kopię osobistą. Publiczny katalog między firmami: poza v1; katalog v1 = paczki dołączone do instalacji.
|
||||
|
||||
## Gdzie się tego używa (v1)
|
||||
|
||||
**Czat na Home** (gałąź `home-chat`, jeszcze nie na `main` — E4 zależy od jej scalenia):
|
||||
- wybór agenta obok wyboru modelu; prompt systemowy = instrukcja agenta + `description` przypiętych skilli;
|
||||
- treść skilla i tekst plików model doczytuje narzędziem `czytaj_skill(skill_version_id, plik?)`;
|
||||
- narzędzia czatu definiuje i wykonuje przeglądarka (`routers/models.py:110` na `home-chat`), więc „przecięcie narzędzi” liczy **backend przy wydawaniu listy narzędzi i przy każdym wywołaniu**: `czytaj_skill` sprawdza po stronie serwera, że wersja jest przypięta do wybranego agenta i widoczna dla osoby; narzędzia modułów i tak sprawdza każdy moduł swoją sesją.
|
||||
|
||||
**Compass** — wg C1.
|
||||
|
||||
## Bezpieczeństwo
|
||||
|
||||
- Ukryte polecenie w skillu firmowym: obrona poufności jak w czacie (brak kanału na zewnątrz, brak zapisu). Obrona **rzetelności** (np. ukryte „zawsze oceniaj NDA jako zgodne”) to zgoda administratora na każdą wersję (T1) i widoczna różnica wersji przy zatwierdzaniu — nie technika.
|
||||
- Test ukrytego polecenia, kryteria zaliczenia: w odpowiedzi brak adresu spoza wyników rozmowy, brak wywołania narzędzia spoza listy agenta, a odpowiedź na pytanie kontrolne zgodna z odpowiedzią bez wstrzykniętego zdania.
|
||||
- Agent nigdy nie ma więcej niż osoba, która go uruchamia.
|
||||
|
||||
## Etapy
|
||||
|
||||
| Etap | Co | Kto |
|
||||
|---|---|---|
|
||||
| E1 | Tabele w schemacie Atrium + rewizja migracji z `runtime_grants_sql`, REVOKE na wszystkich tabelach wersji | my (przy C1-a); przegląd Roman |
|
||||
| E2 | API: CRUD, wersje, archiwizacja, import, eksport, prośby o publikację, ustawienia T1/T2 | my |
|
||||
| E3 | Ekran „Skille i agenci”: lista, edytor, pliki, różnice wersji, import/eksport, kolejka próśb dla administratora | my |
|
||||
| E4 | Czat Home: wybór agenta, `czytaj_skill`, pomiar na Qwenie 9B (po scaleniu `home-chat`) | my |
|
||||
| E5 | ODŁOŻONE: Compass wg C1, po przebudowie Romana i Piotra | — |
|
||||
| E6 | Paczka startowa: przegląd `polish-law-pack` (MIT, zachować informację o licencji) | my |
|
||||
|
||||
Testy obowiązkowe: złośliwe ZIP-y (każda reguła z sekcji Import osobno), eksport→import = ta sama suma, macierz widoczności (osobisty/firmowy/obcy/administrator), agent firmowy z osobistym skillem odrzucony, nowa wersja firmowa niewidoczna przed zgodą, obniżenie uprawnień agenta, ukryte polecenie z kryteriami wyżej.
|
||||
|
||||
Koszt (zgaduję): E1-E4 około 2 tygodni, E5 przy C1-a kilka dni, przy C1-b 2-3 tygodnie.
|
||||
|
||||
## Rozstrzygnięcia backendu (Tobiasz, 2026-11-05: bez uzgadniania z Romanem, trafi do niego jako PR)
|
||||
|
||||
- **R1:** tabele w schemacie Atrium, nie we wspólnym.
|
||||
- **R2:** jedyna nowa zależność w E1-E3 to `PyYAML` (MIT) do frontmattera; ekstrakcja przesunięta do E4.
|
||||
- **R3:** pliki referencyjne jako BYTEA, limit 10 MB na paczkę.
|
||||
|
||||
# Plan wykonania (dla Meduzy)
|
||||
|
||||
Zakres tego przebiegu: **E1-E3**. E4 (czat) czeka na scalenie PR #27 `home-chat`; E5 odłożone; E6 (przegląd polskiego pakietu) robi człowiek po E3.
|
||||
|
||||
Repo: worktree `C:\Users\badur\projects\lw-atrium-skille`, gałąź `skille-agenci` od `origin/main` (37d29b3, 2026-11-03). Przed każdym etapem przeczytaj `CLAUDE.md` repo — jego inwarianty mają pierwszeństwo przed tym specem; sprzeczność = pytanie w QUESTIONS.md, nie obejście.
|
||||
|
||||
## Bramka testów (każde zadanie)
|
||||
|
||||
```
|
||||
cd backend && pytest -q # unit, bez bazy
|
||||
node --check frontend/app.js
|
||||
python scripts/license_gate.py
|
||||
```
|
||||
Testy integracyjne (`ATRIUM_RUN_INTEGRATION=1`, Postgres) pisze się w E2, a uruchamia przed PR (osobny krok poza pętlą). Test integracyjny pominięty z braku bazy NIE jest zielony — raport końcowy ma podać, ile pominięto.
|
||||
|
||||
## Etap 0 — środowisko (człowiek, przed pętlą)
|
||||
|
||||
- venv dla worktree z `dredd-core@v0.16.0` (prywatne repo, poświadczenia GitHub) + `requirements-dev.txt`; lokalny `lw-venv` ma core 0.13 i się nie nadaje.
|
||||
- Bramka zielona na czystym `origin/main` przed pierwszym zadaniem.
|
||||
|
||||
## E1 — modele i migracja
|
||||
|
||||
1. `backend/app/models/skills.py`: `Skill`, `SkillVersion`, `SkillFile`, `Agent`, `AgentVersion`, `AgentVersionSkill`, `PublishRequest` wg „Model danych”. Słowniki (`scope`, `status`, `origin`, `kind`, `publish_request.status`/`kind`) jako `Text` + CHECK, nie natywne enumy (jak `models/marketplace.py`, pilnuje `test_marketplace_vocabularies_are_check_constraints_not_enum_types` — rozszerz go o nowe tabele). Klucze obce do `app_user` z `ondelete="RESTRICT"`. `UniqueConstraint(owner_id, slug)` dla skilla, `(skill_id, n)` i `(agent_id, n)` dla wersji.
|
||||
2. Import w `models/__init__.py`; nazwy tabel dopisane do `test_the_apps_own_tables_are_registered`.
|
||||
3. `backend/alembic/versions/0010_skills.py`: idempotentnie (`checkfirst`), potem `runtime_grants_sql` jak w `0008` (te same tabele-dowody, `read_only` jawnie), potem **osobno** `REVOKE UPDATE, DELETE` od roli runtime na `skill_version`, `skill_file`, `agent_version`, `agent_version_skill` (nie przez `read_only`, bo ten zabiera też INSERT). Rewizja weryfikuje wynik i rzuca błąd, jeśli rola runtime nadal ma UPDATE/DELETE. Downgrade: drop tabel w odwrotnej kolejności.
|
||||
- **Zrobione gdy:** bramka zielona; `alembic upgrade head --sql` pokazuje 7 tabel i REVOKE; test jednostkowy na wygenerowanym SQL rewizji sprawdza REVOKE na czterech tabelach.
|
||||
|
||||
## E2 — serwisy i API
|
||||
|
||||
Kolejność zadań: paczka (czyste funkcje) → serwis domenowy → ustawienia → router → integracja.
|
||||
|
||||
1. `services/skill_pack.py` — czyste funkcje, bez bazy: `read_pack(data: bytes) -> Pack | odrzucenie`, `build_pack(...) -> bytes`, `content_sha256(...)`. Każda reguła z sekcji „Import — reguły” to osobny test jednostkowy na ZIP-ie budowanym w pamięci (`zipfile`), także: wtyczka Claude Code ze skryptem = odrzucenie, DOCX z `vbaProject.bin` = odrzucenie, kotwica YAML = odrzucenie. Test: `build_pack(read_pack(x))` daje tę samą sumę. Komunikaty odrzucenia PL/EN z kodem (`code`) jak `module_admission_refused`.
|
||||
2. `PyYAML` w `requirements.txt` z komentarzem licencji (jedyna nowa zależność); `license_gate` zielony. Bez ekstrakcji tekstu (wariant b).
|
||||
3. `services/skills.py` — cała logika domenowa (routery bez SQL): widoczność (własne + firmowe; cudze osobiste → `NotFoundError`), tworzenie, nowa wersja (zamrożenie, `n+1`, `content_sha256`), archiwizacja, import (kopia osobista, `provenance`, kolizja sluga → `-2`, ta sama suma → odpowiedź „już masz, dodać jako wersję?”), eksport (T2), publikacja (T1: `approval` → `publish_request` na wersję, `current_version_id` firmowego skilla rusza dopiero po zgodzie; `direct` → od razu), agent (przypina tylko widoczne wersje; agent firmowy tylko wersje skilli firmowych). Każdy zapis → `audit.record` (akcje `skill.create`, `skill.version`, `skill.archive`, `skill.import`, `skill.export`, `skill.publish_request`, `skill.publish_approve`, `skill.publish_decline`, analogicznie `agent.*`), eksport/import z sumą paczki, bez treści.
|
||||
4. `services/settings.py`: `skills_firm_publish` (CHOICE `approval`|`direct`, domyślnie `approval`), `skills_firm_export` (CHOICE `administrator`|`everyone`, domyślnie `administrator`).
|
||||
5. `routers/skills.py` (rejestracja w `main.py` jak pozostałe):
|
||||
- `GET/POST /skills`, `GET /skills/{id}`, `POST /skills/{id}/versions`, `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`** z nazwą w `?filename=` (bez nowej zależności `python-multipart`), twardy limit 10 MB czytany strumieniowo;
|
||||
- to samo dla `/agents` (`/agents/{id}/versions` przyjmuje listę `skill_version_id`);
|
||||
- administrator: `GET /admin/publish-requests`, `POST /admin/publish-requests/{id}/approve|decline` (`require_administrator`).
|
||||
- Pliki referencyjne w wersji: `POST /skills/{id}/versions` przyjmuje JSON z treścią i plikami jako base64 (limit łączny 10 MB) — jedna droga zamiast dwóch.
|
||||
6. Testy integracyjne (`tests/test_skills_integration.py`, wzorzec `test_providers_integration.py`): macierz widoczności (właściciel / inna osoba / administrator, osobisty / firmowy), nowa wersja firmowa niewidoczna przed zgodą, agent firmowy z osobistym skillem odrzucony, T2 dla eksportu skilla i agenta, przełączenie ustawień przez administratora, wiersze audytu, rola runtime nie robi UPDATE na `skill_version` (błąd z bazy).
|
||||
- **Zrobione gdy:** bramka zielona; testy integracyjne napisane i zbierane przez pytest (uruchomienie przed PR).
|
||||
|
||||
## E3 — konsola
|
||||
|
||||
1. `frontend/app.js`: pozycja „Skille i agenci” w głównym menu (obok „Połączone aplikacje”, bo każdy ma swoje). Widoki: lista z zakładkami Moje / Firmy (skille i agenci), edytor skilla (nazwa, opis, treść, pliki z informacją „bez tekstu, model go nie przeczyta” przy pustym `text`), lista wersji z różnicą linii względem poprzedniej (prosty diff w JS, bez biblioteki), import (wybór pliku → `fetch` z surowym ciałem), eksport (link), publikacja, edytor agenta (instrukcja + wybór przypiętych wersji skilli + podpowiedź modelu). Ekran po imporcie pokazuje odrzucenie z powodem albo listę rzeczy zapisanych tylko jako informacja.
|
||||
2. Administracja: „Prośby o publikację” z różnicą wersji przed zatwierdzeniem; dwa nowe ustawienia w istniejącym ekranie ustawień.
|
||||
3. Wszystko przez `esc()` i `mutate()`, teksty PL/EN, bez kroku budowania, bez CDN, ścieżki względne (API z `document.baseURI`).
|
||||
4. `tests/test_skills_console.py` wzorem `test_providers_console.py`: ekran jest w routerze, woła tylko istniejące trasy, wartości dynamiczne przez `esc()`, ekran administracyjny tylko dla administratora.
|
||||
- **Zrobione gdy:** bramka zielona (w tym `node --check`).
|
||||
|
||||
## Poza pętlą, przed PR (człowiek + agenci QA)
|
||||
|
||||
- Testy integracyjne na Postgresie (`atrium-test-runner`), z liczbą pominiętych.
|
||||
- Przegląd świeżym recenzentem na zamrożonym SHA.
|
||||
- Klik w przeglądarce na lokalnej platformie: import ZIP-a z `polish-law-pack`, eksport, ponowny import (ta sama suma), publikacja ze zgodą.
|
||||
- PR do `Alpaq92/Atrium` dopiero po „wysyłaj”.
|
||||
+24
-7
@@ -73,11 +73,18 @@
|
||||
.mi.h-gray { --mi-bg: #495057; --mi-fg: #f8f9fa; }
|
||||
|
||||
/* ── launcher: Home ────────────────────────────────────────────────────── */
|
||||
.home { max-width: 760px; margin: 24px auto 0; }
|
||||
/* Home takes the workspace's whole column, like every other page: the greeting and the search box stay
|
||||
one readable 800px column in the middle, the numbers and the admin overview below use the full width.
|
||||
:where() keeps this at one class, so the chatting rules (three classes) still win. */
|
||||
.home { margin-top: 24px; }
|
||||
.home > :where(.home-mark, .home-title, .home-sub, .banner, .home-answer, .home-box, .home-results, #homeKeys) {
|
||||
max-width: 800px; margin-inline: auto;
|
||||
}
|
||||
.home-title, .home-sub { text-align: center; }
|
||||
.home-mark { width: 48px; height: 48px; padding: 9px; border-radius: var(--at-radius-xl);
|
||||
border: 1px solid var(--at-border); background: var(--at-surface); box-shadow: var(--at-shadow-xs); }
|
||||
.home-mark .logo { width: 100%; height: 100%; display: block; }
|
||||
.home-title { margin: 28px 0 0; font-size: 40px; line-height: 1.1; font-weight: 600; letter-spacing: -0.04em; }
|
||||
.home-title { margin: 28px auto 0; font-size: 40px; line-height: 1.1; font-weight: 600; letter-spacing: -0.04em; }
|
||||
.home-q { color: var(--at-text-muted); }
|
||||
.home-sub { margin-top: 14px; color: var(--at-text-secondary); font-size: 15px; }
|
||||
.home-label { display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
@@ -108,16 +115,23 @@
|
||||
}
|
||||
.home-send:hover { background: var(--at-primary-hover); }
|
||||
.home-send.stop { background: var(--at-text); color: var(--at-canvas); }
|
||||
/* The scope, the model and the send button: the composer's bottom row, inside the card. */
|
||||
/* The model and the send button: the composer's bottom row, inside the card. */
|
||||
.home-scope {
|
||||
display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; margin-top: 8px;
|
||||
font-size: 12px; color: var(--at-text-secondary);
|
||||
}
|
||||
.home-tools { margin-left: auto; display: inline-flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: 8px; min-width: 0; }
|
||||
.home-scope-mod { display: inline-flex; align-items: center; gap: 6px; color: var(--at-text); }
|
||||
/* Attached files: chips above the question; the whole composer outlines while a file is dragged over the page. */
|
||||
.home-files { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 8px -6px; font-size: 12px; }
|
||||
.home-file { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; padding: 2px 4px 2px 8px; }
|
||||
.home-file > span[data-no-i18n] { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 260px; }
|
||||
.home-file-x { display: grid; place-items: center; width: 20px; height: 20px; border: 0; border-radius: 50%; background: none; color: inherit; cursor: pointer; }
|
||||
.home-file-x:hover { background: var(--at-hover); }
|
||||
.home-box.drop .home-input { border-color: var(--at-primary); border-style: dashed; }
|
||||
/* The model picker sits at the end of the scope bar; the answer is a quiet card, plain text only. */
|
||||
.home-model { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.home-model select { min-height: 32px; padding: 2px 8px; font-size: 12px; max-width: 260px; }
|
||||
.home-model > span:empty { display: none; }
|
||||
.home-answer {
|
||||
margin-top: 20px; padding: 14px 16px; border: 1px solid var(--at-border); border-radius: var(--at-radius-2xl);
|
||||
background: var(--at-surface);
|
||||
@@ -251,6 +265,10 @@ pre.diff {
|
||||
margin: 6px 0 0; padding: 8px; border-radius: var(--radius-sm); background: var(--surface-2);
|
||||
font: 11.5px/1.4 var(--mono); white-space: pre-wrap; word-break: break-word; max-width: 46ch;
|
||||
}
|
||||
/* A skill's body and the line diff between its versions: as wide as the card, + and − tinted. */
|
||||
pre.diff.lines { max-width: none; }
|
||||
pre.diff .add { color: var(--ok); background: var(--ok-bg); }
|
||||
pre.diff .del { color: var(--err); background: var(--err-bg); }
|
||||
/* The one field that ever holds a secret: a freshly minted app token, shown once and never again.
|
||||
Monospace so it can be proof-read character by character, because where the clipboard API is
|
||||
unavailable — plain HTTP is not a secure context — copying it by hand is the fallback. */
|
||||
@@ -276,7 +294,6 @@ pre.diff {
|
||||
.home-label { margin-top: 28px; }
|
||||
.home-box { margin-top: 22px; }
|
||||
.home-input { border-radius: 20px; padding-left: 14px; }
|
||||
.home-scope > span:first-child { display: none; }
|
||||
.home-tools { width: 100%; flex-wrap: nowrap; }
|
||||
.home-model { flex: 1; min-width: 0; }
|
||||
.home-model > span:first-child { display: none; }
|
||||
@@ -364,7 +381,7 @@ button.nav-sep.fold[aria-expanded="false"] svg { transform: rotate(-90deg); }
|
||||
|
||||
/* ── home: "W skrócie" — stat tiles and 14-day column charts (inline SVG, no library) ── */
|
||||
.home-stats:empty { display: none; }
|
||||
.stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
|
||||
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
|
||||
.stat {
|
||||
display: flex; flex-direction: column; gap: 2px; padding: 14px 16px; border: 1px solid var(--border);
|
||||
border-radius: var(--at-radius-xl); background: var(--surface); color: var(--text);
|
||||
@@ -373,7 +390,7 @@ a.stat:hover { text-decoration: none; background: var(--at-surface-hover); }
|
||||
.stat-v { font-size: 24px; font-weight: 650; font-variant-numeric: tabular-nums; letter-spacing: -.01em; }
|
||||
.stat-l { font-size: 12px; color: var(--at-text-muted); }
|
||||
.stat.warn .stat-v { color: var(--at-warning-text); }
|
||||
.charts { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 10px; margin-top: 10px; }
|
||||
.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 10px; margin-top: 10px; }
|
||||
.card.chart { padding: 14px 16px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.chart-h { display: flex; flex-direction: column; gap: 1px; }
|
||||
.chart-h b { font-size: 13px; }
|
||||
|
||||
+830
-99
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user