Backend:
- agents_registry: five AIGC roles (剧本创作/视觉设计/分镜设计/素材资产/镜头脚本)
with zh personas, agent-chat mode text, and llm_role mapping onto the
models-page five-role binding surface (story/style/script/assets/video)
- agent_sessions.agent_key column + migration; sessions filter/exclusion;
named replies stamped with the owner agent's display name
- prompt assembly: per-agent persona + AGENT CHAT mode section replace the
generic sandbox text; mentions section suppressed for agent chats
- main loop routes the LLM through the agent's bound role
- skill admin surface: skill_overrides/skill_bindings/skill_versions tables,
PUT/PATCH/DELETE /api/agent/skills/{name} + bindings + versions/restore;
effective rule = global enable ∩ enabled per-agent binding; builtin skills
seeded to all five agents at upgrade; read_skill/list_skills gated for
named-agent sessions
Frontend:
- /agents is now the three-column A-darkroom page (agent list + skill library
/ chat with reused AgentChat / skill manager with editor, assignment
capsules, version history + rollback); per-agent model select synced with
the models page; narrow breakpoint turns the manager into a drawer
- legacy ?project=&task= deep links still route into the canvas flow
- i18n keys added to all 7 locales
Tests: tests/test_agent_roles.py + tests/test_skill_admin.py (27 cases)
Co-authored-by: multica-agent <github@multica.ai>
731 lines
27 KiB
Python
731 lines
27 KiB
Python
"""Agent session chat API."""
|
|
from __future__ import annotations
|
|
|
|
from typing import Any, Literal
|
|
|
|
from fastapi import APIRouter, HTTPException, Query
|
|
from pydantic import BaseModel, Field, field_validator, model_validator
|
|
|
|
from calliope.agent.harness.runner import runner
|
|
from calliope.config import settings
|
|
from calliope.db import get_db, row_to_dict
|
|
from calliope.events.bus import event_bus
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class SessionCreate(BaseModel):
|
|
title: str = "New chat"
|
|
project_id: int | None = None
|
|
# WHERE the session was born: 'chat' (AI Canvas etc., default) or 'scene'
|
|
# (Build Scene's per-scene sessions). Scene-origin sessions are excluded
|
|
# from the generic session list so they never appear in the AI Canvas rail.
|
|
origin: str = "chat"
|
|
# WHICH named agent (剧本创作 etc., HEL-613) owns the session; None = a
|
|
# plain harness chat. Locked at creation; drives persona + LLM role.
|
|
agent_key: str | None = None
|
|
|
|
@field_validator("title")
|
|
@classmethod
|
|
def _bound_title(cls, v: str) -> str:
|
|
if len(v) > 300:
|
|
raise ValueError("Title too long (max 300 characters)")
|
|
return v
|
|
|
|
@field_validator("origin")
|
|
@classmethod
|
|
def _bounded_origin(cls, v: str) -> str:
|
|
if v not in ("chat", "scene"):
|
|
raise ValueError("origin must be 'chat' or 'scene'")
|
|
return v
|
|
|
|
@field_validator("agent_key")
|
|
@classmethod
|
|
def _bounded_agent_key(cls, v: str | None) -> str | None:
|
|
if v is None or v == "":
|
|
return None
|
|
from calliope.agent.agents_registry import AGENT_KEYS
|
|
|
|
if v not in AGENT_KEYS:
|
|
raise ValueError(f"agent_key must be one of {list(AGENT_KEYS)}")
|
|
return v
|
|
|
|
|
|
class SessionPatch(BaseModel):
|
|
title: str | None = None
|
|
project_id: int | None = None
|
|
unlink: bool = False
|
|
|
|
@field_validator("title")
|
|
@classmethod
|
|
def _bound_title(cls, v: str | None) -> str | None:
|
|
if v is not None and len(v) > 300:
|
|
raise ValueError("Title too long (max 300 characters)")
|
|
return v
|
|
|
|
|
|
class MessageMention(BaseModel):
|
|
type: Literal["workflow", "skill"] = "workflow"
|
|
id: int | None = None
|
|
name: str = Field(default="", max_length=200)
|
|
kind: Literal["image", "video"] = "image"
|
|
# skill mentions
|
|
description: str = Field(default="", max_length=500)
|
|
|
|
@model_validator(mode="after")
|
|
def _check_shape(self) -> "MessageMention":
|
|
if self.type == "workflow" and self.id is None:
|
|
raise ValueError("workflow mention requires id")
|
|
if self.type == "skill" and not self.name:
|
|
raise ValueError("skill mention requires name")
|
|
return self
|
|
|
|
|
|
class MessageAttachment(BaseModel):
|
|
path: str = Field(min_length=1, max_length=2000)
|
|
name: str = Field(default="", max_length=500)
|
|
kind: Literal["image", "video", "audio", "document"] = "image"
|
|
|
|
|
|
class MemoryCreate(BaseModel):
|
|
content: str = Field(min_length=1, max_length=500)
|
|
scope: Literal["global", "project"] = "global"
|
|
project_id: int | None = None
|
|
kind: Literal["preference", "convention", "correction"] = "preference"
|
|
session_id: int | None = None
|
|
|
|
|
|
class MessageCreate(BaseModel):
|
|
content: str = ""
|
|
mentions: list[MessageMention] = Field(default_factory=list, max_length=1)
|
|
attachments: list[MessageAttachment] = Field(default_factory=list, max_length=8)
|
|
answer_to: int | None = None # question/asked seq this message answers (card click)
|
|
|
|
@field_validator("content")
|
|
@classmethod
|
|
def _bound_content(cls, v: str) -> str:
|
|
# Bound the user message: a multi-MB paste would otherwise be stored,
|
|
# echoed to every SSE subscriber, and sent to the LLM verbatim.
|
|
if len(v) > 100_000: # ~100 KB of text
|
|
raise ValueError("Message too long (max 100,000 characters)")
|
|
return v
|
|
|
|
@field_validator("mentions")
|
|
@classmethod
|
|
def _one_workflow(cls, v: list[MessageMention]) -> list[MessageMention]:
|
|
if len(v) > 1:
|
|
raise ValueError("Only one @workflow mention per message")
|
|
return v
|
|
|
|
|
|
def _session_out(conn, row) -> dict[str, Any]:
|
|
session = row_to_dict(row)
|
|
if session.get("project_id"):
|
|
proj = conn.execute(
|
|
"SELECT id, title, status FROM projects WHERE id = ?", (session["project_id"],)
|
|
).fetchone()
|
|
session["project"] = row_to_dict(proj) if proj else None
|
|
else:
|
|
session["project"] = None
|
|
return session
|
|
|
|
|
|
async def session_event_payload(session_id: int) -> dict[str, Any] | None:
|
|
"""Enriched session dict for events: project info + live running flag.
|
|
Used by the harness (link/create_project) and the router so every
|
|
`agent.session.updated` event carries the same shape as GET /sessions."""
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
row = conn.execute(
|
|
"SELECT * FROM agent_sessions WHERE id = ?", (session_id,)
|
|
).fetchone()
|
|
if not row:
|
|
return None
|
|
session = _session_out(conn, row)
|
|
finally:
|
|
conn.close()
|
|
session["running"] = runner.is_running(session_id)
|
|
return session
|
|
|
|
|
|
async def _publish_session(session_id: int) -> dict[str, Any] | None:
|
|
session = await session_event_payload(session_id)
|
|
if session:
|
|
await event_bus.publish("agent.session.updated", {"session": session})
|
|
return session
|
|
|
|
|
|
def _rows_to_messages(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
"""Give derived chat rows the agent_messages response shape (id/role/
|
|
content/agent_name/tool_name/tool_args/tool_result/status/created_at)."""
|
|
out: list[dict[str, Any]] = []
|
|
for i, r in enumerate(rows, start=1):
|
|
out.append(
|
|
{
|
|
"id": -i, # derived rows have no DB id; negative keeps ordering unique
|
|
"session_id": None,
|
|
"role": r["role"],
|
|
"content": r.get("content") or "",
|
|
"agent_name": r.get("agent_name"),
|
|
"tool_name": r.get("tool_name"),
|
|
"tool_args": r.get("tool_args"),
|
|
"tool_result": r.get("tool_result"),
|
|
"status": r.get("status"),
|
|
"reasoning": r.get("reasoning"),
|
|
"mentions": r.get("mentions") or [],
|
|
"attachments": r.get("attachments") or [],
|
|
"created_at": None,
|
|
}
|
|
)
|
|
return out
|
|
|
|
|
|
@router.get("/sessions")
|
|
async def list_sessions(
|
|
project_id: int | None = None,
|
|
origin: str | None = None,
|
|
include_scene: bool = False,
|
|
agent_key: str | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
"""Sessions for the sidebars. Scene-origin sessions (Build Scene's
|
|
per-scene chats) are excluded unless asked for by origin or flag — they
|
|
are Build Scene's rail entries, not AI Canvas chats. Named-agent
|
|
sessions (HEL-613) follow the same rule: hidden from the generic list
|
|
unless the caller filters by agent_key (the 智能体 page does)."""
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
where: list[str] = []
|
|
params: list[Any] = []
|
|
if agent_key is not None and agent_key != "":
|
|
where.append("agent_key = ?")
|
|
params.append(agent_key)
|
|
else:
|
|
where.append("agent_key IS NULL")
|
|
if project_id is not None:
|
|
where.append("project_id = ?")
|
|
params.append(project_id)
|
|
if not include_scene:
|
|
# origin=scene is compatible with include_scene for clarity; a
|
|
# direct origin filter wins (Build Scene asks by origin).
|
|
if origin is not None:
|
|
where.append("origin = ?")
|
|
params.append(origin)
|
|
else:
|
|
where.append("origin != 'scene'")
|
|
sql = "SELECT * FROM agent_sessions"
|
|
if where:
|
|
sql += " WHERE " + " AND ".join(where)
|
|
sql += " ORDER BY updated_at DESC"
|
|
rows = conn.execute(sql, params).fetchall()
|
|
out = []
|
|
for r in rows:
|
|
s = _session_out(conn, r)
|
|
s["running"] = runner.is_running(s["id"])
|
|
out.append(s)
|
|
return out
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
@router.post("/sessions")
|
|
async def create_session(payload: SessionCreate) -> dict[str, Any]:
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
if payload.project_id is not None:
|
|
if not conn.execute(
|
|
"SELECT id FROM projects WHERE id = ?", (payload.project_id,)
|
|
).fetchone():
|
|
raise HTTPException(status_code=404, detail="Project not found")
|
|
origin = "chat" if payload.agent_key else payload.origin
|
|
cur = conn.execute(
|
|
"INSERT INTO agent_sessions (title, project_id, origin, agent_key) VALUES (?, ?, ?, ?)",
|
|
(payload.title, payload.project_id, origin, payload.agent_key),
|
|
)
|
|
conn.commit()
|
|
row = conn.execute("SELECT * FROM agent_sessions WHERE id = ?", (cur.lastrowid,)).fetchone()
|
|
session = _session_out(conn, row)
|
|
finally:
|
|
conn.close()
|
|
session["running"] = False
|
|
await event_bus.publish("agent.session.updated", {"session": session})
|
|
return session
|
|
|
|
|
|
@router.get("/projects")
|
|
async def list_projects_for_link() -> list[dict[str, Any]]:
|
|
"""Projects available for linking (id/title/status only) — powers the
|
|
sandbox session's link picker."""
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
rows = conn.execute(
|
|
"SELECT id, title, status FROM projects WHERE status != 'system' ORDER BY updated_at DESC"
|
|
).fetchall()
|
|
return [row_to_dict(r) for r in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
@router.get("/sessions/{session_id}")
|
|
async def get_session(session_id: int) -> dict[str, Any]:
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
row = conn.execute(
|
|
"SELECT * FROM agent_sessions WHERE id = ?", (session_id,)
|
|
).fetchone()
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Session not found")
|
|
session = _session_out(conn, row)
|
|
session["running"] = runner.is_running(session_id)
|
|
finally:
|
|
conn.close()
|
|
from calliope.agent.harness import log as session_log
|
|
|
|
session_log.backfill_from_messages(session_id)
|
|
events = session_log.read_events(session_id)
|
|
rows = _rows_to_messages(session_log.derive_chat_rows(events))
|
|
if session.get("agent_key"):
|
|
# Named-agent session (HEL-613): the loop logs main replies without
|
|
# agent_name — stamp the owning agent so bubbles/labels match. (The
|
|
# live SSE mirror in the runner applies the same stamp.)
|
|
from calliope.agent.agents_registry import AGENTS
|
|
|
|
owner = AGENTS.get(session["agent_key"], {}).get("name")
|
|
if owner:
|
|
for row in rows:
|
|
if row.get("role") == "assistant" and not row.get("agent_name"):
|
|
row["agent_name"] = owner
|
|
session["messages"] = rows
|
|
session["plan"] = session_log.derive_plan(events)
|
|
return session
|
|
|
|
|
|
@router.patch("/sessions/{session_id}")
|
|
async def patch_session(session_id: int, payload: SessionPatch) -> dict[str, Any]:
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
row = conn.execute(
|
|
"SELECT * FROM agent_sessions WHERE id = ?", (session_id,)
|
|
).fetchone()
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Session not found")
|
|
if runner.is_running(session_id):
|
|
raise HTTPException(status_code=409, detail="Session is running")
|
|
if payload.unlink:
|
|
conn.execute(
|
|
"UPDATE agent_sessions SET project_id = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
(session_id,),
|
|
)
|
|
elif payload.project_id is not None:
|
|
if not conn.execute(
|
|
"SELECT id FROM projects WHERE id = ?", (payload.project_id,)
|
|
).fetchone():
|
|
raise HTTPException(status_code=404, detail="Project not found")
|
|
conn.execute(
|
|
"UPDATE agent_sessions SET project_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
(payload.project_id, session_id),
|
|
)
|
|
if payload.title is not None:
|
|
# Renaming must never change WHERE the session is listed: origin is
|
|
# fixed at creation (the old title-prefix check made a rename break
|
|
# Build Scene's rail; origin cannot drift, titles can).
|
|
conn.execute(
|
|
"UPDATE agent_sessions SET title = ? WHERE id = ?",
|
|
(payload.title, session_id),
|
|
)
|
|
if payload.unlink:
|
|
conn.execute(
|
|
"UPDATE agent_sessions SET project_id = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
(session_id,),
|
|
)
|
|
elif payload.project_id is not None:
|
|
if not conn.execute(
|
|
"SELECT id FROM projects WHERE id = ?", (payload.project_id,)
|
|
).fetchone():
|
|
raise HTTPException(status_code=404, detail="Project not found")
|
|
conn.execute(
|
|
"UPDATE agent_sessions SET project_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
(payload.project_id, session_id),
|
|
)
|
|
conn.commit()
|
|
row = conn.execute(
|
|
"SELECT * FROM agent_sessions WHERE id = ?", (session_id,)
|
|
).fetchone()
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Session not found")
|
|
finally:
|
|
conn.close()
|
|
session = await _publish_session(session_id)
|
|
return session
|
|
|
|
|
|
@router.delete("/sessions/{session_id}")
|
|
async def delete_session(session_id: int) -> dict[str, bool]:
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
row = conn.execute(
|
|
"SELECT id FROM agent_sessions WHERE id = ?", (session_id,)
|
|
).fetchone()
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Session not found")
|
|
if runner.is_running(session_id):
|
|
raise HTTPException(status_code=409, detail="Session is running")
|
|
conn.execute("DELETE FROM agent_messages WHERE session_id = ?", (session_id,))
|
|
conn.execute("DELETE FROM agent_sessions WHERE id = ?", (session_id,))
|
|
conn.commit()
|
|
return {"ok": True}
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
@router.post("/sessions/{session_id}/messages")
|
|
async def post_message(session_id: int, payload: MessageCreate) -> dict[str, Any]:
|
|
content = payload.content.strip()
|
|
if not content and not payload.mentions and not payload.attachments:
|
|
raise HTTPException(status_code=422, detail="Message content is empty")
|
|
from calliope.routers.playground import _assert_path_in_assets
|
|
|
|
attachments: list[dict[str, Any]] = []
|
|
for att in payload.attachments:
|
|
resolved = _assert_path_in_assets(att.path)
|
|
attachments.append(
|
|
{
|
|
"path": str(resolved),
|
|
"name": att.name or resolved.name,
|
|
"kind": att.kind,
|
|
}
|
|
)
|
|
mentions = [m.model_dump() for m in payload.mentions]
|
|
try:
|
|
user_msg = await runner.start_turn(
|
|
session_id,
|
|
content,
|
|
mentions=mentions or None,
|
|
attachments=attachments or None,
|
|
answer_to=payload.answer_to,
|
|
)
|
|
except RuntimeError as exc:
|
|
# Session mid-turn: the message becomes steering, not a rejection.
|
|
# The running loop drains steering/message events between steps and
|
|
# injects them into its request history — the user course-corrects
|
|
# without killing the run (Stop stays available for a hard stop).
|
|
# Answering a question card while running stays a 409: the answer
|
|
# belongs to the NEXT turn, which starts when this one ends.
|
|
if payload.answer_to is not None:
|
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
|
steered = await runner.steer(
|
|
session_id,
|
|
content,
|
|
mentions=mentions or None,
|
|
attachments=attachments or None,
|
|
)
|
|
if steered is None:
|
|
# Lost the running race (turn ended between the two checks) —
|
|
# fall through to a normal turn so the message is never lost.
|
|
try:
|
|
user_msg = await runner.start_turn(
|
|
session_id,
|
|
content,
|
|
mentions=mentions or None,
|
|
attachments=attachments or None,
|
|
)
|
|
except RuntimeError as re_exc:
|
|
raise HTTPException(status_code=409, detail=str(re_exc)) from re_exc
|
|
except ValueError as ve:
|
|
raise HTTPException(status_code=404, detail=str(ve)) from ve
|
|
return {"ok": True, "message": user_msg}
|
|
return {"ok": True, "steered": True, "message": steered}
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=404, detail="Session not found") from exc
|
|
return {"ok": True, "message": user_msg}
|
|
|
|
|
|
@router.post("/sessions/{session_id}/cancel")
|
|
async def cancel_session(session_id: int) -> dict[str, Any]:
|
|
"""Stop = stop everything this session started: the LLM turn AND the GPU
|
|
jobs it enqueued. Agent jobs stamp session_id into their payload, so the
|
|
queue can find and cancel them; the worker's poll loop sees the flipped
|
|
row and interrupts the running ComfyUI prompt."""
|
|
from calliope.queue.manager import queue_manager
|
|
|
|
cancelled = await runner.cancel(session_id)
|
|
job_ids = queue_manager.cancel_by_session(session_id)
|
|
return {"ok": cancelled or bool(job_ids), "cancelled_jobs": job_ids}
|
|
|
|
|
|
@router.get("/memories")
|
|
async def list_memories_admin() -> list[dict[str, Any]]:
|
|
"""All memories across scopes/projects for the Settings → Agent page."""
|
|
from calliope.db import get_db, row_to_dict
|
|
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT m.*, p.title AS project_title FROM agent_memory m
|
|
LEFT JOIN projects p ON p.id = m.project_id
|
|
ORDER BY m.scope, m.project_id, m.id DESC
|
|
"""
|
|
).fetchall()
|
|
finally:
|
|
conn.close()
|
|
out = []
|
|
for r in rows:
|
|
d = row_to_dict(r)
|
|
out.append(
|
|
{
|
|
"id": d["id"],
|
|
"scope": d["scope"],
|
|
"project_id": d["project_id"],
|
|
"project_title": d.get("project_title"),
|
|
"content": d["content"],
|
|
"kind": d["kind"],
|
|
"source": d["source"],
|
|
"use_count": d["use_count"],
|
|
"created_at": d["created_at"],
|
|
}
|
|
)
|
|
return out
|
|
|
|
|
|
@router.post("/memories")
|
|
async def add_memory(payload: MemoryCreate) -> dict[str, Any]:
|
|
"""User-authored memory (source='user') from the Settings page."""
|
|
from calliope.agent.harness import log as session_log
|
|
from calliope.db import get_db
|
|
|
|
content = payload.content.strip()
|
|
if not content or len(content) > 500:
|
|
raise HTTPException(status_code=422, detail="content must be 1-500 chars")
|
|
if payload.scope not in ("global", "project"):
|
|
raise HTTPException(status_code=422, detail="scope must be global or project")
|
|
if payload.kind not in ("preference", "convention", "correction"):
|
|
raise HTTPException(status_code=422, detail="invalid kind")
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
if payload.scope == "project" and payload.project_id is not None:
|
|
if not conn.execute(
|
|
"SELECT id FROM projects WHERE id = ?", (payload.project_id,)
|
|
).fetchone():
|
|
raise HTTPException(status_code=404, detail="Project not found")
|
|
cur = conn.execute(
|
|
"INSERT INTO agent_memory (scope, project_id, content, kind, source) "
|
|
"VALUES (?, ?, ?, ?, 'user')",
|
|
(payload.scope, payload.project_id, content, payload.kind),
|
|
)
|
|
conn.commit()
|
|
mem_id = int(cur.lastrowid)
|
|
finally:
|
|
conn.close()
|
|
if payload.session_id:
|
|
session_log.append_event(
|
|
payload.session_id,
|
|
session_log.MEMORY_SAVED,
|
|
{"memory_id": mem_id, "scope": payload.scope, "kind": payload.kind, "content": content},
|
|
)
|
|
return {"ok": True, "id": mem_id}
|
|
|
|
|
|
@router.delete("/memories/{memory_id}")
|
|
async def delete_memory(memory_id: int) -> dict[str, Any]:
|
|
from calliope.db import get_db
|
|
|
|
conn = get_db(settings.db_path)
|
|
try:
|
|
cur = conn.execute("DELETE FROM agent_memory WHERE id = ?", (memory_id,))
|
|
conn.commit()
|
|
if cur.rowcount == 0:
|
|
raise HTTPException(status_code=404, detail="Memory not found")
|
|
finally:
|
|
conn.close()
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/agents")
|
|
async def list_named_agents() -> list[dict[str, Any]]:
|
|
"""The five named agents (HEL-613) with their enabled-skill counts —
|
|
powers the 智能体 page's left column. Names/personas are server-side."""
|
|
from calliope.agent.agents_registry import AGENTS, public_list
|
|
from calliope.agent.skills_store import (
|
|
skill_binding_map,
|
|
skill_enable_states,
|
|
)
|
|
|
|
bindings = skill_binding_map()
|
|
enabled = skill_enable_states()
|
|
out: list[dict[str, Any]] = []
|
|
for info in public_list():
|
|
count = sum(
|
|
1
|
|
for skill, per_agent in bindings.items()
|
|
if per_agent.get(info["key"]) is True and enabled.get(skill, True)
|
|
)
|
|
info = {**info, "skill_count": count}
|
|
info["model_profile_id"] = (settings.agent_llm_assignments or {}).get(
|
|
AGENTS[info["key"]]["llm_role"]
|
|
)
|
|
out.append(info)
|
|
return out
|
|
|
|
|
|
@router.get("/skills")
|
|
async def list_skills(all: bool = False) -> list[dict[str, Any]]:
|
|
"""Frontmatter-only skill list for the composer's `/` typeahead (same
|
|
view the agent's list_skills tool sees; no file bodies). `all=true` is
|
|
the management view (HEL-613): every skill, unlimited, with enable
|
|
flags and per-agent assignment."""
|
|
from calliope.agent.skills_store import (
|
|
list_skills as store_list_skills,
|
|
)
|
|
from calliope.agent.skills_store import (
|
|
skill_binding_map,
|
|
skill_enable_states,
|
|
)
|
|
|
|
skills = store_list_skills(cap=None) if all else store_list_skills()
|
|
if not all:
|
|
return skills
|
|
enabled = skill_enable_states()
|
|
bindings = skill_binding_map()
|
|
for s in skills:
|
|
s["is_enabled"] = enabled.get(s["dir"], True)
|
|
s["bindings"] = bindings.get(s["dir"], {})
|
|
s["assigned_count"] = sum(1 for v in s["bindings"].values() if v)
|
|
return skills
|
|
|
|
|
|
class SkillUpsert(BaseModel):
|
|
description: str = Field(default="", max_length=500)
|
|
version: str = Field(default="", max_length=40)
|
|
tags: list[str] = Field(default_factory=list, max_length=12)
|
|
skill_type: str = ""
|
|
content: str = Field(default="", max_length=200_000)
|
|
bindings: dict[str, bool] | None = None
|
|
|
|
|
|
class SkillEnablePatch(BaseModel):
|
|
is_enabled: bool
|
|
|
|
|
|
class SkillBindingsPut(BaseModel):
|
|
bindings: dict[str, bool]
|
|
|
|
|
|
@router.put("/skills/{name}")
|
|
async def upsert_skill(name: str, payload: SkillUpsert) -> dict[str, Any]:
|
|
"""Create or edit a user skill: snapshot old → write SKILL.md → apply
|
|
the assignment matrix in one shot (HEL-613)."""
|
|
from calliope.agent.agents_registry import AGENT_KEYS
|
|
from calliope.agent.skills_store import (
|
|
set_skill_bindings,
|
|
write_skill,
|
|
)
|
|
|
|
if payload.skill_type and payload.skill_type not in ("template", "knowledge", "rules"):
|
|
raise HTTPException(status_code=422, detail="skill_type must be template|knowledge|rules")
|
|
if payload.bindings is not None:
|
|
unknown = [k for k in payload.bindings if k not in AGENT_KEYS]
|
|
if unknown:
|
|
raise HTTPException(
|
|
status_code=422, detail=f"unknown agent_key(s): {unknown}"
|
|
)
|
|
try:
|
|
summary = write_skill(
|
|
name,
|
|
description=payload.description,
|
|
version=payload.version,
|
|
tags=payload.tags,
|
|
skill_type=payload.skill_type,
|
|
body=payload.content,
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
if payload.bindings is not None:
|
|
set_skill_bindings(name, payload.bindings)
|
|
return {"ok": True, "skill": summary}
|
|
|
|
|
|
@router.patch("/skills/{name}")
|
|
async def patch_skill(name: str, payload: SkillEnablePatch) -> dict[str, Any]:
|
|
"""Global enable/disable — an disabled skill disappears from every
|
|
session's discovery list immediately."""
|
|
from calliope.agent.skills_store import set_skill_enabled
|
|
|
|
set_skill_enabled(name, payload.is_enabled)
|
|
return {"ok": True, "skill": name, "is_enabled": payload.is_enabled}
|
|
|
|
|
|
@router.put("/skills/{name}/bindings")
|
|
async def put_skill_bindings(name: str, payload: SkillBindingsPut) -> dict[str, Any]:
|
|
"""Replace the skill's assignment matrix ({agent_key: enabled})."""
|
|
from calliope.agent.agents_registry import AGENT_KEYS
|
|
from calliope.agent.skills_store import set_skill_bindings
|
|
|
|
unknown = [k for k in payload.bindings if k not in AGENT_KEYS]
|
|
if unknown:
|
|
raise HTTPException(status_code=422, detail=f"unknown agent_key(s): {unknown}")
|
|
set_skill_bindings(name, payload.bindings)
|
|
return {"ok": True, "skill": name, "bindings": payload.bindings}
|
|
|
|
|
|
@router.delete("/skills/{name}")
|
|
async def delete_skill(name: str) -> dict[str, Any]:
|
|
"""Delete a skill: dir + bindings + overrides + version history."""
|
|
from calliope.agent.skills_store import delete_skill as store_delete
|
|
|
|
try:
|
|
store_delete(name)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
return {"ok": True, "skill": name}
|
|
|
|
|
|
@router.get("/skills/{name}/versions")
|
|
async def get_skill_versions(name: str) -> list[dict[str, Any]]:
|
|
from calliope.agent.skills_store import list_versions
|
|
|
|
return list_versions(name)
|
|
|
|
|
|
@router.post("/skills/{name}/versions/{version_id}/restore")
|
|
async def restore_skill_version(name: str, version_id: int) -> dict[str, Any]:
|
|
"""Restore a snapshot: the current file is snapshotted first, then the
|
|
old content is written back verbatim (its frontmatter comes with it)."""
|
|
from calliope.agent.skills_store import restore_skill_file, version_content
|
|
|
|
content = version_content(name, version_id)
|
|
if content is None:
|
|
raise HTTPException(status_code=404, detail="Version not found")
|
|
try:
|
|
summary = restore_skill_file(name, content)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
return {"ok": True, "skill": summary}
|
|
|
|
|
|
@router.get("/skills/path")
|
|
async def skills_path() -> dict[str, Any]:
|
|
"""On-disk skills folder for the Settings → Skills page."""
|
|
from calliope.agent.skills_store import skills_root
|
|
|
|
return {"path": str(skills_root())}
|
|
|
|
|
|
@router.get("/skills/{name}/files")
|
|
async def skill_files(name: str) -> dict[str, Any]:
|
|
from calliope.agent.skills_store import skill_files as store_skill_files
|
|
|
|
files = store_skill_files(name)
|
|
if files is None:
|
|
raise HTTPException(status_code=404, detail=f"Unknown skill: {name}")
|
|
return {"skill": name, "files": files}
|
|
|
|
|
|
@router.get("/skills/{name}/file")
|
|
async def read_skill_file(name: str, path: str = Query(default="SKILL.md")) -> dict[str, Any]:
|
|
from calliope.agent.skills_store import read_skill_file as store_read
|
|
|
|
result = store_read(name, path)
|
|
if not result.get("ok"):
|
|
raise HTTPException(status_code=404, detail=result.get("error") or "Not found")
|
|
return result
|