feat: five named agents independent chat + custom skill management (HEL-613)

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>
This commit is contained in:
shigongyuan-agent
2026-09-28 11:28:26 +08:00
co-authored by multica-agent
parent df84c22143
commit cdd6eba8ba
21 changed files with 3571 additions and 60 deletions
@@ -0,0 +1,165 @@
"""Named-agent registry (HEL-613): the five AIGC roles that back both the
「智能体」page's independent chat sessions and (in a later card) the five-stage
creation flow.
An `agent_key` stamps a session at creation time and never changes; the
runner copies it into ToolContext so prompt assembly (persona + mode) and
LLM selection (role → agent_llm_assignments) follow it.
LLM roles reuse the five roles already exposed on the models page's
「智能体默认模型」panel (story/style/script/assets/video), so a model bound
there drives the same agent here — one source of truth, per spec §9.4.
"""
from __future__ import annotations
from typing import Any
AgentDef = dict[str, Any]
# Order matters: it is the display order in the left column (spec §4.3).
AGENTS: dict[str, AgentDef] = {
"script": {
"key": "script",
"name": "剧本创作",
"char": "剧",
"avatar": 1,
"avatar_dark": True,
"llm_role": "story",
"tagline": "从创意或既有素材发展大纲、分场与台词",
"persona": (
"你是「剧本创作」智能体——一位资深短视频/音乐短片编剧,负责把用户的创意打磨成可拍摄的剧本。\n"
"- 职责:产出故事大纲、分场结构(场次/场景/时间)、人物小传、台词与动作描述;"
"用户提供现成剧本时,先读懂再帮用户修改、补全或提炼。\n"
"- 产出要求:结构清晰(大纲→分场→台词逐层展开),台词口语化、有情绪;"
"关键设定(人物、场景、时代、基调)显式列出,方便后续环节复用。\n"
"- 你是创作顾问:有取舍分歧时给出方案与理由,请用户拍板,不自作主张定稿。\n"
"- 默认用简体中文回复。这是独立会话,不参与五段创作流程;需要视觉/分镜/素材建议时,"
"建议用户去对应智能体会话继续。"
),
},
"style": {
"key": "style",
"name": "视觉设计",
"char": "视",
"avatar": 2,
"avatar_dark": False,
"llm_role": "style",
"tagline": "为剧本给出多套风格方向与生图风格提示词",
"persona": (
"你是「视觉设计」智能体——一位 AIGC 视觉导演,负责为剧本或创意确定整体视觉风格。\n"
"- 职责:基于剧本/创意给出 2–4 套差异化风格方向(如写实电影感、动漫赛璐璐、水墨、"
"三维卡通等),每套包含:风格说明、色调与光影、材质与线条特征、适用的生图关键词组"
"(正向提示词,英文逗号分隔,可直接用于生图模型),必要时附负面提示词建议。\n"
"- 产出要求:风格方向用清晰的分段呈现;提示词词组完整可复制;说明每套风格适合的"
"题材与镜头类型。\n"
"- 你是顾问:推荐倾向可以给,最终风格由用户选择。\n"
"- 默认用简体中文回复;提示词词组本身用英文(生图模型惯例),并附中文说明。"
"这是独立会话,不参与五段创作流程。"
),
},
"storyboard": {
"key": "storyboard",
"name": "分镜设计",
"char": "分",
"avatar": 3,
"avatar_dark": False,
"llm_role": "script",
"tagline": "把剧本拆成逐镜分镜表与镜头语言",
"persona": (
"你是「分镜设计」智能体——一位分镜师,负责把剧本拆解成可执行的分镜表。\n"
"- 职责:按场次产出逐镜清单,每镜包含:镜号、景别(远/全/中/近/特写)、"
"机位与运镜(推/拉/摇/移/跟/固定)、画面内容描述、台词/音效起点、时长建议。\n"
"- 产出要求:表格或逐镜列表,信息完整可直接交给素材与视频环节;"
"运镜术语规范,节奏有起伏,重要情绪点给特写。\n"
"- 有多种可行拆法时,先给一版主推方案,再简述备选思路,请用户确认。\n"
"- 默认用简体中文回复。这是独立会话,不参与五段创作流程。"
),
},
"assets": {
"key": "assets",
"name": "素材资产",
"char": "素",
"avatar": 4,
"avatar_dark": False,
"llm_role": "assets",
"tagline": "为角色、场景、道具产出完整生图提示词",
"persona": (
"你是「素材资产」智能体——一位 AIGC 美术资产师,负责产出角色立绘、场景图、道具图的"
"完整生图提示词。\n"
"- 职责:根据剧本/分镜/风格整理资产清单(角色/场景/道具),为每项资产写出可直接"
"复制使用的生图提示词:主体与外观细节、风格关键词(沿用视觉设计确定的方向)、"
"构图与视角、画质词;必要时附负面提示词与一致性要点(同一角色多视角如何保持一致)。\n"
"- 产出要求:按资产逐条给出,提示词完整、自成一体、可复制;英文提示词附中文说明。\n"
"- 资产数量多时先给清单让用户确认优先级。\n"
"- 默认用简体中文回复。这是独立会话,不参与五段创作流程。"
),
},
"shot": {
"key": "shot",
"name": "镜头脚本",
"char": "镜",
"avatar": 5,
"avatar_dark": False,
"llm_role": "video",
"tagline": "产出视频模型可用的逐镜脚本与提示词",
"persona": (
"你是「镜头脚本」智能体——一位 AIGC 视频导演,负责把分镜转化为视频生成模型"
"(如 MiniMax H3)可用的逐镜脚本。\n"
"- 职责:为每镜产出视频提示词,包含:画面主体与动作、运镜指令、"
"镜头语言与构图、光影氛围、时长与节奏;图生视频镜头写清首帧画面来源与运动走向,"
"首尾帧镜头分别描述首帧与尾帧画面。\n"
"- 产出要求:逐镜编号、结构统一、提示词完整可复制;同一项目的运镜与风格保持一致。\n"
"- 涉及参考视频/遮罩等输入时,说明每镜需要准备的素材。\n"
"- 默认用简体中文回复;视频提示词主体用英文(视频模型惯例),并附中文说明。"
"这是独立会话,不参与五段创作流程。"
),
},
}
AGENT_KEYS: tuple[str, ...] = tuple(AGENTS.keys())
# Prompt-section text for named-agent sessions (replaces the generic SANDBOX
# mode text — these chats have no canvas/project surface of their own).
def mode_text(agent_key: str) -> str:
agent = AGENTS.get(agent_key)
name = agent["name"] if agent else agent_key
return (
f"SESSION MODE: AGENT CHAT — you are 「{name}」, talking to the user in an "
"independent chat. This session is NOT part of the five-stage creation "
"flow and has no project workspace of its own.\n"
"- Stay in your professional role; do the thinking and writing yourself.\n"
"- Skills assigned to you (and enabled) are listed in the Skills section "
"below — load them with read_skill(name) before applying them.\n"
"- Deliverables (outlines, style directions, storyboards, prompts) go "
"directly into your reply as well-structured text the user can copy.\n"
"- If the user wants media generation or the five-stage flow, say the "
"independent image/video windows and the creation workbench are the "
"right surfaces."
)
def persona_text(agent_key: str) -> str | None:
agent = AGENTS.get(agent_key)
return agent["persona"] if agent else None
def llm_role_for(agent_key: str | None) -> str:
"""LLM role for a session's agent_key; 'main' for plain sessions."""
agent = AGENTS.get(agent_key or "")
return agent["llm_role"] if agent else "main"
def public_list() -> list[dict[str, Any]]:
"""Registry view for the API (no personas — those are server-side)."""
return [
{
"key": a["key"],
"name": a["name"],
"char": a["char"],
"avatar": a["avatar"],
"avatar_dark": bool(a.get("avatar_dark")),
"llm_role": a["llm_role"],
"tagline": a["tagline"],
}
for a in AGENTS.values()
]
@@ -480,7 +480,11 @@ async def run_turn(
}
)
client = _llm_for_role("main")
# Named-agent sessions (HEL-613) use the agent's bound LLM role; plain
# sessions keep 'main' (Active LLM unless a role assignment says otherwise).
from calliope.agent.agents_registry import llm_role_for
client = _llm_for_role(llm_role_for(getattr(ctx, "agent_key", None)))
final_text = ""
turn_status = "completed"
synthetic_idx: list[int] = [] # positions of budget-nudge messages (stripped after)
@@ -11,6 +11,7 @@ from typing import Any
from calliope.agent.harness.registry import ToolContext, ToolDefinition, ToolRegistry
from calliope.agent.skills_store import (
effective_skill_dirs,
ensure_builtin_skills,
list_skills as store_list_skills,
read_skill_file,
@@ -23,7 +24,12 @@ _PROMPT_CAP = 24
async def t_list_skills(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
skills = store_list_skills()
agent_key = getattr(ctx, "agent_key", None)
if agent_key:
effective = effective_skill_dirs(agent_key)
skills = [s for s in store_list_skills(cap=None) if s["dir"] in effective]
else:
skills = store_list_skills()
return {"ok": True, "skills": skills, "count": len(skills)}
@@ -31,13 +37,28 @@ async def t_read_skill(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]
ensure_builtin_skills()
name = str(args.get("name") or "").strip()
rel = str(args.get("path") or "SKILL.md").strip()
agent_key = getattr(ctx, "agent_key", None)
if agent_key:
# Named-agent sessions may only load skills assigned to them AND
# enabled (HEL-613 gating — the discovery list matches this rule).
effective = effective_skill_dirs(agent_key)
known = {
d for d in effective
} | {s["name"] for s in store_list_skills(cap=None) if s["dir"] in effective}
if name not in known:
return {
"ok": False,
"error": (
f"skill '{name}' is not assigned to this agent or is disabled"
),
}
return read_skill_file(name, rel)
def skills_prompt_text(ctx: ToolContext) -> str | None:
"""Discovery section: names + descriptions only (cheap; bodies load via
read_skill). None when there are no skills."""
lines = skills_prompt_lines()
lines = skills_prompt_lines(agent_key=getattr(ctx, "agent_key", None))
if not lines:
return None
return (
@@ -71,6 +71,11 @@ class SystemPromptService:
async def _persona_section(ctx: ToolContext) -> str | None:
from calliope.agent.agents_registry import persona_text
named = persona_text(getattr(ctx, "agent_key", None) or "")
if named:
return named
return _persona_text()
@@ -86,6 +91,13 @@ async def _mode_section(ctx: ToolContext) -> str | None:
def _mode_text(ctx: ToolContext) -> str:
agent_key = getattr(ctx, "agent_key", None)
if agent_key:
# Named-agent independent chat (HEL-613): not a canvas sandbox —
# replace the sandbox/project mode text with the agent-chat contract.
from calliope.agent.agents_registry import mode_text
return mode_text(agent_key)
if getattr(ctx, "origin", "chat") == "scene":
return (
"SESSION MODE: BUILD SCENE — this chat drives the 3D composition.\n"
@@ -284,6 +296,10 @@ async def _tool_discipline_section(ctx: ToolContext) -> str | None:
async def _mentions_section(ctx: ToolContext) -> str | None:
if getattr(ctx, "agent_key", None):
# Named-agent chat (HEL-613): the independent agents page has no
# workflow mention affordance; skills arrive via the Skills section.
return None
if getattr(ctx, "origin", "chat") == "scene":
return (
"Build Scene sessions ignore workflow tags for generation. "
@@ -75,11 +75,15 @@ class ToolContext:
None means a blind/sandbox session (only project-creating tools allowed).
`origin` stamps WHERE the session was born ('chat' | 'scene') — scene
sessions are Build Scene's blockout surface and get the shot-tool-only
payload; it says nothing about project linking."""
payload; it says nothing about project linking.
`agent_key` names WHICH of the five AIGC agents (剧本创作 etc.) owns the
session (HEL-613) — drives per-agent persona/mode prompt sections and the
LLM role. None = a plain harness session."""
session_id: int
project_id: int | None = None
origin: str = "chat"
agent_key: str | None = None
@dataclass
@@ -140,7 +140,7 @@ class AgentRunner:
finally:
conn.close()
def _make_message_sink(self, session_id: int):
def _make_message_sink(self, session_id: int, default_agent_name: str | None = None):
"""Persistence + broadcast sink for harness messages (planner notes,
sub-agent reports). Tool calls/results are already logged by the loop
via the event log — the sink only mirrors them into agent_messages."""
@@ -157,11 +157,16 @@ class AgentRunner:
"truncated": True,
"preview": text[: session_log.EVENT_DATA_TRUNCATE] + "…[truncated]",
}
agent_name = message.get("agent_name")
if not agent_name and default_agent_name and message.get("role") == "assistant":
# Named-agent sessions (HEL-613): main-loop replies carry no
# agent_name — stamp the owning agent so bubbles/labels match.
agent_name = default_agent_name
persisted = self._persist_message(
session_id,
role=message.get("role") or "assistant",
content=message.get("content") or "",
agent_name=message.get("agent_name"),
agent_name=agent_name,
tool_name=message.get("tool_name"),
tool_args=message.get("tool_args")
if isinstance(message.get("tool_args"), dict)
@@ -366,10 +371,12 @@ class AgentRunner:
conn = self._db()
try:
row = conn.execute(
"SELECT project_id, origin FROM agent_sessions WHERE id = ?", (session_id,)
"SELECT project_id, origin, agent_key FROM agent_sessions WHERE id = ?",
(session_id,),
).fetchone()
project_id = row["project_id"] if row else None
origin = (row["origin"] if row else None) or "chat"
agent_key = (row["agent_key"] if row else None) or None
finally:
conn.close()
@@ -377,13 +384,19 @@ class AgentRunner:
session_id=session_id,
project_id=project_id,
origin=origin,
agent_key=agent_key,
)
from calliope.agent.agents_registry import AGENTS
default_agent_name = (
AGENTS.get(agent_key or "", {}).get("name") if agent_key else None
)
try:
final = await orchestrate(
ctx,
[], # history derived inside from the event log
session_id=session_id,
on_message=self._make_message_sink(session_id),
on_message=self._make_message_sink(session_id, default_agent_name),
)
# Final answer is persisted + broadcast by the loop's emit() call
# (which goes through the message sink). Only set status here.
@@ -21,7 +21,24 @@ from calliope.config import settings
READ_CHAR_CAP = 8000
_LIST_CAP = 24
VERSIONS_PER_SKILL_CAP = 20
_FRONTMATTER_RE = re.compile(r"\A---\s*\n(.*?)\n---\s*\n?", re.DOTALL)
_NAME_MAX = 64
# Skill types offered by the editor (spec §4.3): 提示词模板 / 参考知识 / 流程规则
SKILL_TYPES = ("template", "knowledge", "rules")
def _valid_dir_name(name: str) -> bool:
return bool(
name
and name not in (".", "..")
and "/" not in name
and "\\" not in name
and not name.startswith(".")
and len(name) <= _NAME_MAX
and all(ch not in name for ch in "\x00\r\n\t")
and name == name.strip()
)
def skills_root() -> Path:
@@ -110,36 +127,334 @@ def skill_summary(skill_dir: Path) -> dict[str, Any] | None:
if not meta:
return None
metadata = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
try:
updated = skill_file.stat().st_mtime
except OSError:
updated = None
skill_type = str(metadata.get("type") or "") if metadata else ""
return {
"name": str(meta.get("name") or skill_dir.name),
"description": str(meta.get("description") or "").strip(),
"version": str(meta.get("version") or ""),
"tags": metadata.get("tags") or [],
"dir": skill_dir.name,
"type": skill_type if skill_type in SKILL_TYPES else "",
"updated_at": updated,
}
def list_skills() -> list[dict[str, Any]]:
"""Frontmatter summaries for every `*/SKILL.md`, sorted by name."""
def list_skills(cap: int | None = _LIST_CAP) -> list[dict[str, Any]]:
"""Frontmatter summaries for every `*/SKILL.md`, sorted by name.
`cap=None` lists everything (the management surface); the default keeps
the historical 24-item ceiling for the discovery prompt/tool.
"""
ensure_builtin_skills()
root = skills_root()
if not root.is_dir():
return []
out: list[dict[str, Any]] = []
limit = cap # _LIST_CAP by default; explicit None = unlimited
for skill_dir in sorted(root.iterdir()):
if not skill_dir.is_dir():
continue
summary = skill_summary(skill_dir)
if summary:
out.append(summary)
if len(out) >= _LIST_CAP:
if limit is not None and len(out) >= limit:
break
return out
def skills_prompt_lines() -> list[str]:
"""`- name: description` lines for the agent's discovery section."""
return [f"- {s['name']}: {s['description']}" for s in list_skills()]
# ─────────────────────────────────────────────────────────────────────────
# Admin state (HEL-613): enable flags + per-agent assignment live in the DB;
# file content stays the single truth for what a skill IS.
# ─────────────────────────────────────────────────────────────────────────
def _admin_db():
from calliope.db import get_db
return get_db(settings.db_path)
def skill_enable_states() -> dict[str, bool]:
"""skill dir name → global enable (absent row = enabled)."""
conn = _admin_db()
try:
rows = conn.execute("SELECT skill_name, is_enabled FROM skill_overrides").fetchall()
return {r["skill_name"]: bool(r["is_enabled"]) for r in rows}
finally:
conn.close()
def skill_binding_map() -> dict[str, dict[str, bool]]:
"""skill dir name → {agent_key: enabled}."""
conn = _admin_db()
try:
rows = conn.execute(
"SELECT agent_key, skill_name, is_enabled FROM skill_bindings"
).fetchall()
out: dict[str, dict[str, bool]] = {}
for r in rows:
out.setdefault(r["skill_name"], {})[r["agent_key"]] = bool(r["is_enabled"])
return out
finally:
conn.close()
def set_skill_enabled(name: str, enabled: bool) -> None:
conn = _admin_db()
try:
conn.execute(
"INSERT INTO skill_overrides(skill_name, is_enabled) VALUES (?, ?) "
"ON CONFLICT(skill_name) DO UPDATE SET is_enabled = excluded.is_enabled",
(name, 1 if enabled else 0),
)
conn.commit()
finally:
conn.close()
def set_skill_bindings(name: str, bindings: dict[str, bool]) -> None:
"""Replace the assignment matrix for one skill (agent_key → enabled)."""
conn = _admin_db()
try:
from calliope.agent.agents_registry import AGENT_KEYS
conn.execute("DELETE FROM skill_bindings WHERE skill_name = ?", (name,))
for key in AGENT_KEYS:
if key in bindings:
conn.execute(
"INSERT INTO skill_bindings(agent_key, skill_name, is_enabled) "
"VALUES (?, ?, ?)",
(key, name, 1 if bindings[key] else 0),
)
conn.commit()
finally:
conn.close()
def effective_skill_dirs(agent_key: str | None) -> set[str]:
"""Dir names visible to a session: global enable ∩ enabled binding for
the agent. Plain sessions (agent_key None) see all globally-enabled
skills — the pre-HEL-613 behavior."""
enabled = skill_enable_states()
dirs = {s["dir"] for s in list_skills(cap=None) if enabled.get(s["dir"], True)}
if not agent_key:
return dirs
bindings = skill_binding_map()
out: set[str] = set()
for skill_dir in dirs:
if bindings.get(skill_dir, {}).get(agent_key) is True:
out.add(skill_dir)
return out
def skills_prompt_lines(agent_key: str | None = None) -> list[str]:
"""`- name: description` lines for the agent's discovery section,
filtered to the skills effective for that session's agent."""
effective = effective_skill_dirs(agent_key)
return [
f"- {s['name']}: {s['description']}"
for s in list_skills(cap=None)
if s["dir"] in effective
]
# ─────────────────────────────────────────────────────────────────────────
# Write / delete / versions
# ─────────────────────────────────────────────────────────────────────────
def _bump_version(prev: str) -> str:
prev = (prev or "").strip()
if not prev:
return "1.0.0"
m = re.match(r"(\d+)\.(\d+)\.(\d+)$", prev)
if m:
return f"{m.group(1)}.{m.group(2)}.{int(m.group(3)) + 1}"
return "1.0.1"
def render_skill_md(
name: str,
*,
description: str,
version: str,
tags: list[str] | None,
skill_type: str,
body: str,
) -> str:
desc = " ".join(description.split())[:500]
tag_line = ", ".join(str(t).strip() for t in (tags or []) if str(t).strip())
lines = ["---", f"name: {name}"]
lines.append(f'description: "{desc.replace(chr(34), chr(39))}"')
lines.append(f"version: {version or '1.0.0'}")
lines.append("metadata:")
lines.append(" author: user")
if tag_line:
lines.append(f" tags: [{tag_line}]")
if skill_type in SKILL_TYPES:
lines.append(f" type: {skill_type}")
lines.append("---")
text = "\n".join(lines) + "\n\n" + (body if body.endswith("\n") or not body else body + "\n")
return text
def snapshot_version(name: str, content: str) -> None:
"""File the current SKILL.md full text as an edit snapshot (cap 20)."""
conn = _admin_db()
try:
conn.execute(
"INSERT INTO skill_versions(skill_name, content) VALUES (?, ?)",
(name, content),
)
stale = conn.execute(
"SELECT id FROM skill_versions WHERE skill_name = ? ORDER BY id DESC "
"LIMIT -1 OFFSET ?",
(name, VERSIONS_PER_SKILL_CAP),
).fetchall()
for row in stale:
conn.execute("DELETE FROM skill_versions WHERE id = ?", (row["id"],))
conn.commit()
finally:
conn.close()
def list_versions(name: str) -> list[dict[str, Any]]:
conn = _admin_db()
try:
rows = conn.execute(
"SELECT id, skill_name, content, created_at FROM skill_versions "
"WHERE skill_name = ? ORDER BY id DESC",
(name,),
).fetchall()
return [
{
"id": r["id"],
"skill": r["skill_name"],
"created_at": r["created_at"],
"length": len(r["content"]),
"preview": r["content"][:160],
}
for r in rows
]
finally:
conn.close()
def version_content(name: str, version_id: int) -> str | None:
conn = _admin_db()
try:
row = conn.execute(
"SELECT content FROM skill_versions WHERE id = ? AND skill_name = ?",
(version_id, name),
).fetchone()
return row["content"] if row else None
finally:
conn.close()
def write_skill(
name: str,
*,
description: str,
version: str = "",
tags: list[str] | None = None,
skill_type: str = "",
body: str = "",
) -> dict[str, Any]:
"""Create/overwrite `<skills>/<name>/SKILL.md`. Snapshots the previous
file first (version history). Returns the new summary."""
if not _valid_dir_name(name):
raise ValueError(f"invalid skill name '{name}'")
ensure_builtin_skills()
skill_dir = skills_root() / name
skill_file = skill_dir / "SKILL.md"
prev_version = ""
if skill_file.is_file():
try:
old = skill_file.read_text(encoding="utf-8")
except OSError as exc:
raise ValueError(f"unreadable existing skill: {exc}") from exc
prev_meta = _parse_frontmatter(old)
prev_version = str(prev_meta.get("version") or "")
snapshot_version(name, old)
skill_dir.mkdir(parents=True, exist_ok=True)
new_version = (version or "").strip() or _bump_version(prev_version)
text = render_skill_md(
name,
description=description,
version=new_version,
tags=tags,
skill_type=skill_type,
body=body,
)
skill_file.write_text(text, encoding="utf-8")
summary = skill_summary(skill_dir)
return summary or {
"name": name,
"dir": name,
"description": description,
"version": new_version,
"tags": tags or [],
"type": skill_type,
"updated_at": None,
}
def restore_skill_file(name: str, content: str) -> dict[str, Any]:
"""Write a snapshot back verbatim (snapshotting the current file first,
so a restore is itself undoable). The snapshot carries its own
frontmatter — no re-render."""
if not _valid_dir_name(name):
raise ValueError(f"invalid skill name '{name}'")
skill_dir = skills_root() / name
skill_file = skill_dir / "SKILL.md"
if skill_file.is_file():
try:
old = skill_file.read_text(encoding="utf-8")
snapshot_version(name, old)
except OSError as exc:
raise ValueError(f"unreadable existing skill: {exc}") from exc
skill_dir.mkdir(parents=True, exist_ok=True)
skill_file.write_text(content, encoding="utf-8")
summary = skill_summary(skill_dir)
return summary or {
"name": name,
"dir": name,
"description": "",
"version": "",
"tags": [],
"type": "",
"updated_at": None,
}
def delete_skill(name: str) -> None:
"""Remove a skill dir (realpath-contained) + its DB state."""
if not _valid_dir_name(name):
raise ValueError(f"invalid skill name '{name}'")
skill_dir = skills_root() / name
if skill_dir.is_dir():
root_real = os.path.realpath(skills_root())
dir_real = os.path.realpath(skill_dir)
try:
contained = Path(dir_real).is_relative_to(Path(root_real))
except (OSError, ValueError):
contained = False
if not contained:
raise ValueError(f"invalid skill path '{name}'")
shutil.rmtree(dir_real)
conn = _admin_db()
try:
conn.execute("DELETE FROM skill_bindings WHERE skill_name = ?", (name,))
conn.execute("DELETE FROM skill_overrides WHERE skill_name = ?", (name,))
conn.execute("DELETE FROM skill_versions WHERE skill_name = ?", (name,))
conn.commit()
finally:
conn.close()
def skill_files(name: str) -> list[str] | None:
+43
View File
@@ -147,11 +147,33 @@ CREATE TABLE IF NOT EXISTS agent_sessions (
title TEXT NOT NULL DEFAULT 'New chat',
status TEXT NOT NULL DEFAULT 'idle' CHECK(status IN ('idle', 'running', 'error')),
origin TEXT NOT NULL DEFAULT 'chat' CHECK(origin IN ('chat', 'scene')),
agent_key TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_agent_sessions_project ON agent_sessions(project_id);
-- Named-agent skill state (HEL-613): file content stays the truth in
-- <data_dir>/skills/<name>/SKILL.md; these tables only carry enable flags,
-- per-agent assignment, and edit snapshots for version/rollback.
CREATE TABLE IF NOT EXISTS skill_overrides (
skill_name TEXT PRIMARY KEY,
is_enabled INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS skill_bindings (
agent_key TEXT NOT NULL,
skill_name TEXT NOT NULL,
is_enabled INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY(agent_key, skill_name)
);
CREATE TABLE IF NOT EXISTS skill_versions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
skill_name TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_skill_versions_name ON skill_versions(skill_name);
CREATE TABLE IF NOT EXISTS agent_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id INTEGER NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE,
@@ -372,6 +394,27 @@ async def migrate_db(db_path: Path) -> None:
conn.execute("ALTER TABLE agent_sessions ADD COLUMN origin TEXT NOT NULL DEFAULT 'chat'")
# Backfill: existing Scene · N sessions were born in Build Scene.
conn.execute("UPDATE agent_sessions SET origin = 'scene' WHERE title LIKE 'Scene · %'")
if "agent_key" not in session_cols:
# HEL-613: named-agent sessions (five AIGC roles). NULL = a plain
# chat/scene session (every session created before this column).
conn.execute("ALTER TABLE agent_sessions ADD COLUMN agent_key TEXT")
# Seed per-agent bindings once, when the skill_bindings table is fresh:
# every skill that exists at upgrade time (the builtins) becomes visible
# to all five agents, so agent chats keep the current out-of-the-box
# behavior; new user skills opt in via the editor's 分配给 row.
binding_count = conn.execute("SELECT COUNT(*) FROM skill_bindings").fetchone()[0]
if binding_count == 0:
from calliope.agent.agents_registry import AGENT_KEYS
from calliope.agent.skills_store import ensure_builtin_skills, skills_root
ensure_builtin_skills()
for skill_dir in sorted(skills_root().glob("*/SKILL.md")):
name = skill_dir.parent.name
conn.executemany(
"INSERT OR IGNORE INTO skill_bindings(agent_key, skill_name, is_enabled) "
"VALUES (?, ?, 1)",
[(key, name) for key in AGENT_KEYS],
)
project_cols = {r[1] for r in conn.execute("PRAGMA table_info(projects)").fetchall()}
if "cover_path" not in project_cols:
conn.execute("ALTER TABLE projects ADD COLUMN cover_path TEXT")
+198 -10
View File
@@ -21,6 +21,9 @@ class SessionCreate(BaseModel):
# (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
@@ -36,6 +39,17 @@ class SessionCreate(BaseModel):
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
@@ -171,14 +185,22 @@ 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."""
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)
@@ -214,9 +236,10 @@ async def create_session(payload: SessionCreate) -> dict[str, Any]:
"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) VALUES (?, ?, ?)",
(payload.title, payload.project_id, payload.origin),
"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()
@@ -259,7 +282,19 @@ async def get_session(session_id: int) -> dict[str, Any]:
session_log.backfill_from_messages(session_id)
events = session_log.read_events(session_id)
session["messages"] = _rows_to_messages(session_log.derive_chat_rows(events))
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
@@ -505,13 +540,166 @@ async def delete_memory(memory_id: int) -> dict[str, Any]:
return {"ok": True}
@router.get("/skills")
async def list_skills() -> 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)."""
from calliope.agent.skills_store import list_skills as store_list_skills
@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,
)
return store_list_skills()
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")