Coverage for app / router / app / skills / router.py: 90%
224 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1import logging
2from typing import Any, Optional
3from uuid import UUID
5from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
6from fastapi.responses import Response
7from pydantic import BaseModel
8from sqlalchemy.orm import Session
10from app.common.settings import AppEnv, get_settings
11from app.db.postgres.crud_schemas import Schema
12from app.db.postgres.enums import HistoryEnum
13from app.db.postgres.models import Skill, SkillRun, User
14from app.dependency.base import get_db
15from app.dependency.workspace import owner_for
16from app.dependency.resource_access import (
17 annotated,
18 scoped,
19 verify_owner_scope,
20 verify_resource_access,
21 verify_resource_read,
22)
23from app.dependency.user.context import get_current_user
24from app.router.app.history.router import register_history_routes
25from app.services import history as history_service
26from app.services import documents as documents_service
27from app.services import skill_graph
28from app.services import workspace as workspace_service
29from app.services.ai_client import (
30 AIServiceError,
31 list_agent_definitions,
32 list_skills,
33)
34from app.services.skill_runs import runner as skill_run_service
35from app.util import document_images
37logger = logging.getLogger(__name__)
40def _admin_env_only() -> None:
41 """Restrict skill endpoints to LOCAL/DEV environments (admin panel only)."""
42 if get_settings().APP_ENV not in (AppEnv.LOCAL, AppEnv.DEV):
43 raise HTTPException(status_code=403, detail="Skill management is admin-only.")
46skill_router = APIRouter(
47 prefix="/skills",
48 tags=["App - Skills"],
49 # dependencies=[Depends(_admin_env_only)],
50)
53# ---------------------------------------------------------------------------
54# Discovery — proxy to svc-ai registry
55# ---------------------------------------------------------------------------
58class NodeSlotInfo(BaseModel):
59 node_id: str
60 description: str
61 default_agent_name: str
62 default_agent_display_name: str
63 default_agent_role: str
64 default_agent_description: str
65 config_overrides: dict[str, Any] = {}
68class AvailableSkillInfo(BaseModel):
69 name: str
70 display_name: str
71 description: str
72 use_case: str
73 tags: list[str]
74 nodes: list[NodeSlotInfo]
75 edges: list[list[str]]
76 start_node: str
77 end_nodes: list[str]
78 graph_definition: dict[str, Any]
81class AvailableSkillsResponse(BaseModel):
82 skills: list[AvailableSkillInfo]
85@skill_router.get("/available", response_model=AvailableSkillsResponse)
86def get_available_skills():
87 """Return built-in skill templates available in svc-ai for selection."""
88 try:
89 raw = list_skills()
90 except AIServiceError as exc:
91 logger.error("Could not fetch skills from svc-ai: %s", exc)
92 raise HTTPException(
93 status_code=status.HTTP_502_BAD_GATEWAY,
94 detail="Could not reach svc-ai to list available skills.",
95 )
96 return AvailableSkillsResponse(skills=[AvailableSkillInfo(**s) for s in raw])
99# ---------------------------------------------------------------------------
100# Agent definitions discovery — proxy to svc-ai
101# ---------------------------------------------------------------------------
104class AgentDefinitionInfo(BaseModel):
105 name: str
106 display_name: str
107 description: str
108 role: str
109 tags: list[str] = []
110 default_tools: list[dict[str, Any]] = []
111 tools_enabled: bool = True
112 # Typed interface (schema v3) — surfaced so the graph builder can show
113 # input/output ports and offer field-level bindings and conditions.
114 input_schema: list[dict[str, Any]] = []
115 output_schema: list[dict[str, Any]] = []
118class AgentDefinitionsResponse(BaseModel):
119 definitions: list[AgentDefinitionInfo]
122@skill_router.get("/agents", response_model=AgentDefinitionsResponse)
123def get_agent_definitions(
124 role: str | None = None,
125 tag: str | None = None,
126):
127 """Return built-in worker agent definitions available for skill graphs.
129 Deliberately restricted to builtins: svc-ai's registry is global, so
130 listing custom definitions here would expose other tenants' worker names
131 (cw_*) — enough to reference their workers, and any MCP credentials baked
132 into them, from a foreign skill graph. A user's own custom workers are
133 listed via /app/workers, which returns their ``definition_name``.
134 """
135 try:
136 raw = list_agent_definitions(role=role, tag=tag, is_builtin=True)
137 except AIServiceError as exc:
138 logger.error("Could not fetch agent definitions from svc-ai: %s", exc)
139 raise HTTPException(
140 status_code=status.HTTP_502_BAD_GATEWAY,
141 detail="Could not reach svc-ai to list agent definitions.",
142 )
143 return AgentDefinitionsResponse(definitions=[AgentDefinitionInfo(**d) for d in raw])
146# ---------------------------------------------------------------------------
147# Skill CRUD
148# ---------------------------------------------------------------------------
151@skill_router.get("", response_model=list[Schema.Skill.Read])
152def list_skills_endpoint(
153 workspace: Optional[str] = None,
154 owner_organisation_id: Optional[UUID] = None,
155 owner_project_id: Optional[UUID] = None,
156 include_system: bool = False,
157 db: Session = Depends(get_db),
158 current_user: User = Depends(get_current_user),
159):
160 """The caller's skills, or an organisation's or project's.
162 ``include_system`` adds the skills bundled in the built-in skillsets, so
163 they can be opened, run on their own and bundled into a skillset of the
164 user's. Opt-in for the same reason as ``GET /skillsets``.
165 """
166 where, ws = scoped(
167 Skill,
168 current_user,
169 db,
170 workspace=workspace,
171 owner_organisation_id=owner_organisation_id,
172 owner_project_id=owner_project_id,
173 include_system=include_system,
174 )
175 query = db.query(Skill).filter(where)
176 return annotated(query.all(), ws)
179@skill_router.get("/{skill_id}", response_model=Schema.Skill.Read)
180def get_skill(
181 skill_id: UUID,
182 db: Session = Depends(get_db),
183 current_user: User = Depends(get_current_user),
184):
185 skill = db.get(Skill, skill_id)
186 if not skill:
187 raise HTTPException(
188 status_code=status.HTTP_404_NOT_FOUND, detail="Skill not found"
189 )
190 verify_resource_read(skill, current_user, db)
191 return skill
194@skill_router.post(
195 "", response_model=Schema.Skill.Read, status_code=status.HTTP_201_CREATED
196)
197def create_skill(
198 body: Schema.Skill.Create,
199 db: Session = Depends(get_db),
200 current_user: User = Depends(get_current_user),
201):
202 data = body.model_dump()
203 if not data.get("owner_organisation_id") and not data.get("owner_project_id"):
204 # The workspace the request was made in (app/dependency/workspace.py).
205 data.update(owner_for(db, current_user, model=Skill))
206 verify_owner_scope(data, current_user, db, model=Skill)
208 skill = Skill(**data)
209 # Checked before the insert so a bad model pin or an MCP server the user may
210 # not embed cannot leave a half-valid skill behind.
211 skill_graph.validate_node_overrides(
212 data.get("graph_definition") or {},
213 db,
214 current_user,
215 owner_organisation_id=data.get("owner_organisation_id"),
216 owner_project_id=data.get("owner_project_id"),
217 workspace=workspace_service.home_of(db, skill),
218 )
219 try:
220 db.add(skill)
221 db.commit()
222 db.refresh(skill)
223 history_service.record_version(
224 db,
225 resource_type=HistoryEnum.ResourceType.skill,
226 model=Skill,
227 resource=skill,
228 action=HistoryEnum.Action.created,
229 actor=current_user,
230 )
231 db.commit()
232 return skill
233 except Exception:
234 db.rollback()
235 logger.exception("Failed to create skill")
236 raise
239@skill_router.patch("/{skill_id}", response_model=Schema.Skill.Read)
240def update_skill(
241 skill_id: UUID,
242 body: Schema.Skill.Update,
243 db: Session = Depends(get_db),
244 current_user: User = Depends(get_current_user),
245):
246 skill = db.get(Skill, skill_id)
247 if not skill:
248 raise HTTPException(
249 status_code=status.HTTP_404_NOT_FOUND, detail="Skill not found"
250 )
251 verify_resource_access(skill, current_user, db)
252 updates = body.model_dump(exclude_none=True)
253 if "graph_definition" in updates:
254 skill_graph.validate_node_overrides(
255 updates["graph_definition"] or {},
256 db,
257 current_user,
258 owner_organisation_id=skill.owner_organisation_id,
259 owner_project_id=skill.owner_project_id,
260 workspace=workspace_service.home_of(db, skill),
261 )
262 for field, value in updates.items():
263 setattr(skill, field, value)
264 history_service.record_version(
265 db,
266 resource_type=HistoryEnum.ResourceType.skill,
267 model=Skill,
268 resource=skill,
269 action=HistoryEnum.Action.updated,
270 actor=current_user,
271 )
272 db.commit()
273 db.refresh(skill)
274 return skill
277@skill_router.delete("/{skill_id}", status_code=status.HTTP_204_NO_CONTENT)
278def delete_skill(
279 skill_id: UUID,
280 db: Session = Depends(get_db),
281 current_user: User = Depends(get_current_user),
282):
283 skill = db.get(Skill, skill_id)
284 if not skill:
285 raise HTTPException(
286 status_code=status.HTTP_404_NOT_FOUND, detail="Skill not found"
287 )
288 verify_resource_access(skill, current_user, db)
289 history_service.record_version(
290 db,
291 resource_type=HistoryEnum.ResourceType.skill,
292 model=Skill,
293 resource=skill,
294 action=HistoryEnum.Action.deleted,
295 actor=current_user,
296 )
297 db.delete(skill)
298 db.commit()
301# ---------------------------------------------------------------------------
302# Runs — a skill used as structured inference (services/skill_runs)
303# ---------------------------------------------------------------------------
306class RunFieldInfo(BaseModel):
307 name: str
308 type: str
309 description: str = ""
310 required: bool = False
311 default: Any = None
312 values: list[str] = []
313 items: str = "string"
314 #: interface | state | node | template — why the form asks for it.
315 source: str
316 #: Nodes that read it.
317 consumers: list[str] = []
320class RunSchemaResponse(BaseModel):
321 fields: list[RunFieldInfo]
322 #: True when the skill takes no inputs, so the task text is all it has.
323 requires_prompt: bool
324 #: False when a worker's interface could not be looked up.
325 complete: bool = True
328def _runnable_skill(skill_id: UUID, current_user: User, db: Session) -> Skill:
329 """The skill, or 404 / 403. Running a skill is using it, as prompting an
330 agent is, so it is a read."""
331 skill = db.get(Skill, skill_id)
332 if not skill:
333 raise HTTPException(
334 status_code=status.HTTP_404_NOT_FOUND, detail="Skill not found"
335 )
336 verify_resource_read(skill, current_user, db)
337 return skill
340@skill_router.get("/{skill_id}/run-schema", response_model=RunSchemaResponse)
341def get_run_schema(
342 skill_id: UUID,
343 db: Session = Depends(get_db),
344 current_user: User = Depends(get_current_user),
345):
346 """The inputs a run of this skill takes: its declared ``interface.inputs``
347 plus whatever its nodes read that nothing in the graph supplies."""
348 skill = _runnable_skill(skill_id, current_user, db)
349 return skill_run_service.run_schema(db, skill).as_dict()
352@skill_router.post(
353 "/{skill_id}/runs",
354 response_model=Schema.SkillRun.Read,
355 status_code=status.HTTP_202_ACCEPTED,
356)
357def start_skill_run(
358 skill_id: UUID,
359 body: Schema.SkillRun.Create,
360 workspace: Optional[str] = None,
361 db: Session = Depends(get_db),
362 current_user: User = Depends(get_current_user),
363):
364 """Start a run. It carries on in the background; poll the run for its
365 outcome. Inputs are validated first — a bad one is a 422 naming it.
367 ``workspace`` is the one the caller is working in, which must hold the
368 skill; its rules govern the run and its ledger counts it."""
369 skill = _runnable_skill(skill_id, current_user, db)
370 ws = None
371 if workspace:
372 from app.services import inheritance
373 from app.services import workspace as workspace_service
375 ws = workspace_service.resolve(db, workspace, current_user)
376 if skill.is_system is not True and not inheritance.visible(db, skill, ws):
377 raise HTTPException(
378 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
379 detail="This skill isn't in that workspace.",
380 )
381 try:
382 return skill_run_service.start(
383 db, skill, current_user.id, body.prompt, body.inputs, workspace=ws
384 )
385 except skill_run_service.RunRefused as exc:
386 raise HTTPException(
387 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
388 detail={"message": exc.message, "fields": exc.fields},
389 ) from exc
392@skill_router.get("/{skill_id}/runs", response_model=list[Schema.SkillRun.Summary])
393def list_skill_runs(
394 skill_id: UUID,
395 limit: int = Query(default=25, ge=1, le=100),
396 db: Session = Depends(get_db),
397 current_user: User = Depends(get_current_user),
398):
399 """The caller's own runs of this skill in the request's workspace,
400 newest first — a built-in skill run in an organisation is not listed in
401 Personal, nor the other way round."""
402 from app.dependency.workspace import request_workspace
404 _runnable_skill(skill_id, current_user, db)
405 skill_run_service.expire_abandoned(db, skill_id, current_user.id)
406 return (
407 db.query(SkillRun)
408 .filter(
409 SkillRun.skill_id == skill_id,
410 SkillRun.user_id == current_user.id,
411 request_workspace(db, current_user).made_here(SkillRun),
412 )
413 .order_by(SkillRun.started_at.desc())
414 .limit(limit)
415 .all()
416 )
419@skill_router.get("/{skill_id}/runs/{run_id}", response_model=Schema.SkillRun.Read)
420def get_skill_run(
421 skill_id: UUID,
422 run_id: UUID,
423 db: Session = Depends(get_db),
424 current_user: User = Depends(get_current_user),
425):
426 """One run in full. Only its owner can read it: the skill may be shared,
427 the inputs somebody gave it are not."""
428 run = db.get(SkillRun, run_id)
429 if not run or run.skill_id != skill_id or run.user_id != current_user.id:
430 raise HTTPException(
431 status_code=status.HTTP_404_NOT_FOUND, detail="Run not found"
432 )
433 skill_run_service.expire_abandoned(db, skill_id, current_user.id)
434 return run
437def _own_run(
438 skill_id: UUID, run_id: UUID, current_user: User, db: Session
439) -> tuple[Skill, SkillRun]:
440 """The caller's run of a skill they can still use, or 404 / 403."""
441 skill = _runnable_skill(skill_id, current_user, db)
442 run = db.get(SkillRun, run_id)
443 if not run or run.skill_id != skill_id or run.user_id != current_user.id:
444 raise HTTPException(
445 status_code=status.HTTP_404_NOT_FOUND, detail="Run not found"
446 )
447 return skill, run
450@skill_router.get(
451 "/{skill_id}/runs/{run_id}/document.pdf",
452 response_class=Response,
453 responses={200: {"content": {"application/pdf": {}}}},
454)
455def download_skill_run_document(
456 skill_id: UUID,
457 run_id: UUID,
458 index: int = Query(default=0, ge=0, le=100),
459 db: Session = Depends(get_db),
460 current_user: User = Depends(get_current_user),
461):
462 """The run's result as a PDF — rendered from what the run stored, never
463 from anything sent with the request. Only a completed run has one.
464 ``index`` picks among several documents in its answer."""
465 _, run = _own_run(skill_id, run_id, current_user, db)
466 if run.status != skill_run_service.Status.completed.value:
467 raise HTTPException(
468 status_code=status.HTTP_409_CONFLICT,
469 detail="Only a completed run can be downloaded.",
470 )
471 document = documents_service.for_skill_run(run, index)
472 if document is None:
473 raise HTTPException(
474 status_code=status.HTTP_404_NOT_FOUND,
475 detail="This run produced nothing to download.",
476 )
477 return documents_service.pdf_response(
478 document,
479 footer=documents_service.skill_run_footer(run),
480 when=run.finished_at or run.started_at,
481 )
484@skill_router.get(
485 "/{skill_id}/runs/{run_id}/images/{asset}",
486 response_class=Response,
487 responses={200: {"content": {"image/png": {}, "image/jpeg": {}}}},
488)
489def skill_run_document_image(
490 skill_id: UUID,
491 run_id: UUID,
492 asset: str = Path(pattern=document_images.ASSET_ID.pattern),
493 db: Session = Depends(get_db),
494 current_user: User = Depends(get_current_user),
495):
496 """An image a document in the run's answer shows — the copy svc-ai stored
497 when it made the document. Only an image a document in that answer names,
498 for the run's owner, once the run has completed."""
499 _, run = _own_run(skill_id, run_id, current_user, db)
500 if run.status != skill_run_service.Status.completed.value:
501 raise HTTPException(
502 status_code=status.HTTP_409_CONFLICT,
503 detail="Only a completed run's images can be shown.",
504 )
505 return documents_service.image_response(
506 documents_service.document_fences(run.output), asset
507 )
510def _refused(exc: skill_run_service.RunRefused, code: int) -> HTTPException:
511 return HTTPException(
512 status_code=code, detail={"message": exc.message, "fields": exc.fields}
513 )
516@skill_router.post(
517 "/{skill_id}/runs/{run_id}/respond",
518 response_model=Schema.SkillRun.Read,
519 status_code=status.HTTP_202_ACCEPTED,
520)
521def respond_to_skill_run(
522 skill_id: UUID,
523 run_id: UUID,
524 body: Schema.SkillRun.Respond,
525 db: Session = Depends(get_db),
526 current_user: User = Depends(get_current_user),
527):
528 """Answer a paused run — approve or reject a gate, or answer its
529 questions — and carry it on in the background. 409 when the run is not
530 waiting or the skill changed while it waited; 422 for an answer that does
531 not fit the question."""
532 skill, run = _own_run(skill_id, run_id, current_user, db)
533 if run.status != skill_run_service.Status.awaiting_input.value:
534 raise HTTPException(
535 status_code=status.HTTP_409_CONFLICT,
536 detail={"message": "This run is not waiting for input.", "fields": {}},
537 )
538 try:
539 return skill_run_service.respond(
540 db, run, skill, body.model_dump(), current_user.id
541 )
542 except skill_run_service.RunRefused as exc:
543 code = (
544 status.HTTP_422_UNPROCESSABLE_ENTITY
545 if exc.fields
546 else status.HTTP_409_CONFLICT
547 )
548 raise _refused(exc, code) from exc
551@skill_router.post(
552 "/{skill_id}/runs/{run_id}/cancel", response_model=Schema.SkillRun.Read
553)
554def cancel_skill_run(
555 skill_id: UUID,
556 run_id: UUID,
557 db: Session = Depends(get_db),
558 current_user: User = Depends(get_current_user),
559):
560 """Abandon a run that is waiting for input."""
561 _, run = _own_run(skill_id, run_id, current_user, db)
562 try:
563 return skill_run_service.cancel(db, run, "Cancelled while waiting for input.")
564 except skill_run_service.RunRefused as exc:
565 raise _refused(exc, status.HTTP_409_CONFLICT) from exc
568# ---------------------------------------------------------------------------
569# Edit history (audit trail)
570# ---------------------------------------------------------------------------
572register_history_routes(
573 skill_router,
574 resource_type=HistoryEnum.ResourceType.skill,
575 model=Skill,
576 not_found_detail="Skill not found",
577 access_check=verify_resource_read,
578)