From cdd6eba8bae81bb6c3cf7dc6e3b6d8f6d8fddef1 Mon Sep 17 00:00:00 2001 From: shigongyuan-agent <4846a27a-ba87-49c9-939d-7275f63efcc7@multica.agent> Date: Mon, 28 Sep 2026 11:28:26 +0800 Subject: [PATCH] feat: five named agents independent chat + custom skill management (HEL-613) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../src/calliope/agent/agents_registry.py | 165 ++ .../src/calliope/agent/harness/loop.py | 6 +- .../calliope/agent/harness/plugins/skills.py | 25 +- .../src/calliope/agent/harness/prompts.py | 16 + .../src/calliope/agent/harness/registry.py | 6 +- .../src/calliope/agent/harness/runner.py | 21 +- .../src/calliope/agent/skills_store.py | 327 +++- calliope-backend/src/calliope/db.py | 43 + .../src/calliope/routers/agent.py | 208 +- calliope-backend/tests/test_agent_roles.py | 202 ++ calliope-backend/tests/test_skill_admin.py | 220 +++ calliope-web/src/lib/api.ts | 82 +- .../src/lib/components/agent/agentPalette.ts | 7 + calliope-web/src/lib/i18n/de.ts | 80 + calliope-web/src/lib/i18n/en.ts | 80 + calliope-web/src/lib/i18n/es.ts | 80 + calliope-web/src/lib/i18n/fr.ts | 80 + calliope-web/src/lib/i18n/ja.ts | 80 + calliope-web/src/lib/i18n/ko.ts | 80 + calliope-web/src/lib/i18n/zh.ts | 80 + calliope-web/src/routes/agents/+page.svelte | 1743 ++++++++++++++++- 21 files changed, 3571 insertions(+), 60 deletions(-) create mode 100644 calliope-backend/src/calliope/agent/agents_registry.py create mode 100644 calliope-backend/tests/test_agent_roles.py create mode 100644 calliope-backend/tests/test_skill_admin.py diff --git a/calliope-backend/src/calliope/agent/agents_registry.py b/calliope-backend/src/calliope/agent/agents_registry.py new file mode 100644 index 00000000..1078ce94 --- /dev/null +++ b/calliope-backend/src/calliope/agent/agents_registry.py @@ -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() + ] diff --git a/calliope-backend/src/calliope/agent/harness/loop.py b/calliope-backend/src/calliope/agent/harness/loop.py index 3c12404c..28e6c1f6 100644 --- a/calliope-backend/src/calliope/agent/harness/loop.py +++ b/calliope-backend/src/calliope/agent/harness/loop.py @@ -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) diff --git a/calliope-backend/src/calliope/agent/harness/plugins/skills.py b/calliope-backend/src/calliope/agent/harness/plugins/skills.py index ab79f9d9..1c3672b0 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/skills.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/skills.py @@ -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 ( diff --git a/calliope-backend/src/calliope/agent/harness/prompts.py b/calliope-backend/src/calliope/agent/harness/prompts.py index ad66115f..d649255e 100644 --- a/calliope-backend/src/calliope/agent/harness/prompts.py +++ b/calliope-backend/src/calliope/agent/harness/prompts.py @@ -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. " diff --git a/calliope-backend/src/calliope/agent/harness/registry.py b/calliope-backend/src/calliope/agent/harness/registry.py index c0202075..ca67fbe4 100644 --- a/calliope-backend/src/calliope/agent/harness/registry.py +++ b/calliope-backend/src/calliope/agent/harness/registry.py @@ -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 diff --git a/calliope-backend/src/calliope/agent/harness/runner.py b/calliope-backend/src/calliope/agent/harness/runner.py index 41fc3a1c..e4e86580 100644 --- a/calliope-backend/src/calliope/agent/harness/runner.py +++ b/calliope-backend/src/calliope/agent/harness/runner.py @@ -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. diff --git a/calliope-backend/src/calliope/agent/skills_store.py b/calliope-backend/src/calliope/agent/skills_store.py index c4666afb..c4a7b347 100644 --- a/calliope-backend/src/calliope/agent/skills_store.py +++ b/calliope-backend/src/calliope/agent/skills_store.py @@ -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 `//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: diff --git a/calliope-backend/src/calliope/db.py b/calliope-backend/src/calliope/db.py index 56dbe8ec..d42cdd48 100644 --- a/calliope-backend/src/calliope/db.py +++ b/calliope-backend/src/calliope/db.py @@ -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 +-- /skills//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") diff --git a/calliope-backend/src/calliope/routers/agent.py b/calliope-backend/src/calliope/routers/agent.py index eae3ea90..1246296e 100644 --- a/calliope-backend/src/calliope/routers/agent.py +++ b/calliope-backend/src/calliope/routers/agent.py @@ -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") diff --git a/calliope-backend/tests/test_agent_roles.py b/calliope-backend/tests/test_agent_roles.py new file mode 100644 index 00000000..c315f0ce --- /dev/null +++ b/calliope-backend/tests/test_agent_roles.py @@ -0,0 +1,202 @@ +"""Named-agent sessions (HEL-613): the five AIGC roles. agent_key is stamped +at creation, filters the session list, injects a per-agent persona + agent-chat +mode section into the assembled system prompt, and routes the main loop's LLM +through the agent's bound role (models page 智能体默认模型 panel).""" +from __future__ import annotations + +import asyncio + +from calliope.agent.harness.registry import ToolContext + +# ───────────────────────────────────────────────────────────────────────── +# Registry +# ───────────────────────────────────────────────────────────────────────── + + +def test_agents_endpoint_lists_five_roles(client): + agents = client.get("/api/agent/agents").json() + assert [a["key"] for a in agents] == [ + "script", + "style", + "storyboard", + "assets", + "shot", + ] + names = {a["name"] for a in agents} + assert names == {"剧本创作", "视觉设计", "分镜设计", "素材资产", "镜头脚本"} + # LLM roles reuse the models-page five-role binding surface. + assert {a["llm_role"] for a in agents} == {"story", "style", "script", "assets", "video"} + # Personas are server-side — never shipped to the browser. + assert all("persona" not in a for a in agents) + assert all(isinstance(a.get("skill_count"), int) for a in agents) + + +# ───────────────────────────────────────────────────────────────────────── +# Session create / list semantics +# ───────────────────────────────────────────────────────────────────────── + + +def test_create_session_with_agent_key(client): + s = client.post("/api/agent/sessions", json={"agent_key": "style"}).json() + assert s["agent_key"] == "style" + assert s["origin"] == "chat" + + +def test_agent_key_rejects_unknown_value(client): + r = client.post("/api/agent/sessions", json={"agent_key": "director"}) + assert r.status_code == 422 + + +def test_agent_sessions_hidden_from_generic_list(client): + plain = client.post("/api/agent/sessions", json={"title": "canvas chat"}).json() + named = client.post("/api/agent/sessions", json={"agent_key": "script"}).json() + listed = client.get("/api/agent/sessions").json() + ids = {s["id"] for s in listed} + assert plain["id"] in ids + assert named["id"] not in ids + + +def test_agent_key_filter_returns_only_that_agent(client): + a = client.post("/api/agent/sessions", json={"agent_key": "script"}).json() + client.post("/api/agent/sessions", json={"agent_key": "style"}) + client.post("/api/agent/sessions", json={"title": "plain"}) + listed = client.get("/api/agent/sessions?agent_key=script").json() + assert {s["id"] for s in listed} == {a["id"]} + assert all(s["agent_key"] == "script" for s in listed) + + +def test_plain_session_has_no_agent_key(client): + s = client.post("/api/agent/sessions", json={}).json() + assert s["agent_key"] is None + + +# ───────────────────────────────────────────────────────────────────────── +# Prompt assembly: persona + mode per agent_key +# ───────────────────────────────────────────────────────────────────────── + + +def _assemble(agent_key: str | None) -> str: + from calliope.agent.harness import get_prompts + + ctx = ToolContext(session_id=1, project_id=None, origin="chat", agent_key=agent_key) + return asyncio.run(get_prompts().assemble(ctx)) + + +def test_persona_section_injected_per_agent(client): + prompt = _assemble("script") + assert "「剧本创作」" in prompt + assert "编剧" in prompt + assert "SESSION MODE: AGENT CHAT" in prompt + # The generic sandbox mode text must be replaced for named agents. + assert "GENERATING IN SANDBOX" not in prompt + + +def test_each_agent_gets_its_own_persona(client): + for key, marker in ( + ("style", "视觉"), + ("storyboard", "分镜"), + ("assets", "资产"), + ("shot", "镜头脚本"), + ): + assert marker in _assemble(key), key + + +def test_plain_prompt_unchanged(client): + prompt = _assemble(None) + assert "Calliope's production agent" in prompt + assert "SESSION MODE: SANDBOX" in prompt + assert "AGENT CHAT" not in prompt + + +def test_agent_chat_mentions_section_suppressed(client): + assert "Tagged workflows" not in _assemble("assets") + assert "Tagged workflows" in _assemble(None) + + +# ───────────────────────────────────────────────────────────────────────── +# LLM routing: the main loop uses the agent's bound role +# ───────────────────────────────────────────────────────────────────────── + + +class _RoleSpyClient: + instances: list["_RoleSpyClient"] = [] + + def __init__(self, role: str | None = None) -> None: + self.role = role + self.requests: list[list[dict]] = [] + _RoleSpyClient.instances.append(self) + + @classmethod + def for_role(cls, role: str, *, timeout: float = 120.0) -> "_RoleSpyClient": + return cls(role=role) + + def chat_stream(self, messages, temperature=0.4, tools=None): + self.requests.append(list(messages)) + return self + + def __aiter__(self): + return self + + async def __anext__(self): + raise StopAsyncIteration + + async def close(self): + pass + + +def test_run_turn_uses_agent_llm_role_and_prompt(client): + """End-to-end through run_turn with a scripted LLM: the client must be + built for the agent's role (story ← 剧本创作) and receive the per-agent + persona in the system message.""" + import calliope.agent.harness.loop as loop_mod + + session = client.post( + "/api/agent/sessions", json={"agent_key": "script", "title": "剧本会话"} + ).json() + + from calliope.agent.harness import log as session_log + + session_log.append_event( + session["id"], session_log.USER_MESSAGE, {"content": "写个三幕式大纲"} + ) + + orig = loop_mod.LLMClient + _RoleSpyClient.instances = [] + loop_mod.LLMClient = _RoleSpyClient + try: + ctx = ToolContext( + session_id=session["id"], project_id=None, origin="chat", agent_key="script" + ) + asyncio.run(loop_mod.run_turn(ctx, [])) + finally: + loop_mod.LLMClient = orig + + assert _RoleSpyClient.instances, "no LLM client was built" + spy = _RoleSpyClient.instances[0] + assert spy.role == "story" + system = next( + (m for m in spy.requests[0] if m.get("role") == "system"), None + ) + assert system is not None + assert "「剧本创作」" in system["content"] + assert "SESSION MODE: AGENT CHAT" in system["content"] + + +def test_plain_run_turn_keeps_main_role(client): + import calliope.agent.harness.loop as loop_mod + + session = client.post("/api/agent/sessions", json={}).json() + from calliope.agent.harness import log as session_log + + session_log.append_event(session["id"], session_log.USER_MESSAGE, {"content": "hi"}) + + orig = loop_mod.LLMClient + _RoleSpyClient.instances = [] + loop_mod.LLMClient = _RoleSpyClient + try: + ctx = ToolContext(session_id=session["id"], project_id=None, origin="chat") + asyncio.run(loop_mod.run_turn(ctx, [])) + finally: + loop_mod.LLMClient = orig + + assert _RoleSpyClient.instances[0].role == "main" diff --git a/calliope-backend/tests/test_skill_admin.py b/calliope-backend/tests/test_skill_admin.py new file mode 100644 index 00000000..c143cd4a --- /dev/null +++ b/calliope-backend/tests/test_skill_admin.py @@ -0,0 +1,220 @@ +"""Skill management surface (HEL-613): create/edit/enable/assign/delete user +skills, version snapshots with restore, and the effective-skill rule — +a named-agent session sees exactly: globally enabled ∩ enabled binding for +its agent_key. Plain sessions keep the legacy behavior (global enable only).""" +from __future__ import annotations + +from calliope.agent.skills_store import ( + effective_skill_dirs, + skills_prompt_lines, +) + + +def _mk(client, name: str, bindings: dict | None = None, body: str = "正文 v1") -> dict: + payload = { + "description": f"{name} 描述", + "skill_type": "template", + "content": body, + "tags": ["a", "b"], + } + if bindings is not None: + payload["bindings"] = bindings + r = client.put(f"/api/agent/skills/{name}", json=payload) + assert r.status_code == 200, r.text + return r.json() + + +# ───────────────────────────────────────────────────────────────────────── +# Create / list +# ───────────────────────────────────────────────────────────────────────── + + +def test_create_skill_and_admin_list(client): + _mk(client, "my-style-kit", bindings={"style": True, "script": False}) + skills = client.get("/api/agent/skills?all=true").json() + mine = next(s for s in skills if s["dir"] == "my-style-kit") + assert mine["name"] == "my-style-kit" + assert mine["is_enabled"] is True + assert mine["bindings"] == {"style": True, "script": False} + assert mine["assigned_count"] == 1 + assert mine["type"] == "template" + assert mine["version"] == "1.0.0" + # Non-admin list stays capped + without admin fields (composer contract). + plain = client.get("/api/agent/skills").json() + mine_plain = next(s for s in plain if s["dir"] == "my-style-kit") + assert "bindings" not in mine_plain + + +def test_migration_seeded_builtin_bindings_for_all_agents(client): + """At upgrade, every pre-existing skill (the builtins) is bound to all + five agents so agent chats keep the out-of-the-box experience.""" + skills = client.get("/api/agent/skills?all=true").json() + builtin = next(s for s in skills if s["dir"] == "h3-video-prompt-enhancer") + assert set(builtin["bindings"].keys()) == { + "script", + "style", + "storyboard", + "assets", + "shot", + } + assert builtin["assigned_count"] == 5 + + +def test_invalid_names_rejected(client): + for bad in ("../escape", "a/b", "", " ", ".hidden", "x" * 65): + r = client.put(f"/api/agent/skills/{bad}", json={"content": "x"}) + assert r.status_code in (404, 422), bad + + +def test_invalid_type_rejected(client): + r = client.put("/api/agent/skills/ok-name", json={"content": "x", "skill_type": "wild"}) + assert r.status_code == 422 + + +# ───────────────────────────────────────────────────────────────────────── +# Effective rule: global enable ∩ per-agent binding +# ───────────────────────────────────────────────────────────────────────── + + +def test_effective_rule_for_agent_sessions(client): + _mk(client, "gated-skill", bindings={"style": True, "script": True}) + assert "gated-skill" in effective_skill_dirs("style") + assert "gated-skill" in effective_skill_dirs("script") + assert "gated-skill" not in effective_skill_dirs("assets") + lines = skills_prompt_lines(agent_key="assets") + assert not any("gated-skill" in ln for ln in lines) + lines = skills_prompt_lines(agent_key="style") + assert any("gated-skill" in ln for ln in lines) + + +def test_unassigned_skill_invisible_everywhere(client): + _mk(client, "orphan-skill", bindings={}) + for key in ("script", "style", "storyboard", "assets", "shot"): + assert "orphan-skill" not in effective_skill_dirs(key) + # Plain sessions still see it (legacy behavior). + assert "orphan-skill" in effective_skill_dirs(None) + + +def test_global_disable_hides_from_all_sessions(client): + _mk(client, "kill-switch", bindings={"style": True}) + r = client.patch("/api/agent/skills/kill-switch", json={"is_enabled": False}) + assert r.status_code == 200 + assert "kill-switch" not in effective_skill_dirs("style") + assert "kill-switch" not in effective_skill_dirs(None) + r = client.patch("/api/agent/skills/kill-switch", json={"is_enabled": True}) + assert "kill-switch" in effective_skill_dirs("style") + + +def test_binding_matrix_replace(client): + _mk(client, "matrix-skill", bindings={"style": True}) + r = client.put( + "/api/agent/skills/matrix-skill/bindings", + json={"bindings": {"shot": True, "style": False}}, + ) + assert r.status_code == 200 + assert "matrix-skill" in effective_skill_dirs("shot") + assert "matrix-skill" not in effective_skill_dirs("style") + + +def test_unknown_agent_key_in_bindings_rejected(client): + r = client.put( + "/api/agent/skills/some-skill/bindings", + json={"bindings": {"director": True}}, + ) + assert r.status_code == 422 + + +def test_read_skill_tool_gates_by_assignment(client): + """The read_skill tool denies skills not effective for the agent.""" + from calliope.agent.harness.plugins.skills import t_read_skill + from calliope.agent.harness.registry import ToolContext + + _mk(client, "gated-read", bindings={"style": True}) + style_ctx = ToolContext(session_id=1, agent_key="style") + shot_ctx = ToolContext(session_id=2, agent_key="shot") + ok = asyncio_run(t_read_skill(style_ctx, {"name": "gated-read"})) + assert ok["ok"] is True + denied = asyncio_run(t_read_skill(shot_ctx, {"name": "gated-read"})) + assert denied["ok"] is False + assert "not assigned" in denied["error"] + + +def asyncio_run(coro): + import asyncio + + return asyncio.run(coro) + + +# ───────────────────────────────────────────────────────────────────────── +# Versions: snapshot on save, list, restore +# ───────────────────────────────────────────────────────────────────────── + + +def test_edit_creates_snapshot_and_version_bumps(client): + first = _mk(client, "versioned", bindings={"script": True}, body="# v1 正文") + v1 = first["skill"]["version"] + second = _mk(client, "versioned", bindings={"script": True}, body="# v2 正文改了") + v2 = second["skill"]["version"] + assert v2 != v1 # auto-bumped when the editor leaves version empty + versions = client.get("/api/agent/skills/versioned/versions").json() + assert len(versions) == 1 # the pre-edit snapshot + assert "# v1 正文" in versions[0]["preview"] + # File now holds v2 content. + body = client.get( + "/api/agent/skills/versioned/file?path=SKILL.md" + ).json()["content"] + assert "# v2 正文改了" in body + + +def test_restore_writes_snapshot_back(client): + _mk(client, "rollback", bindings={"script": True}, body="第一版") + _mk(client, "rollback", bindings={"script": True}, body="第二版") + versions = client.get("/api/agent/skills/rollback/versions").json() + old_id = versions[0]["id"] # newest first: snapshot of 第一版 + r = client.post(f"/api/agent/skills/rollback/versions/{old_id}/restore") + assert r.status_code == 200 + body = client.get("/api/agent/skills/rollback/file?path=SKILL.md").json()["content"] + assert "第一版" in body + # The restore itself snapshotted 第二版 — undoable. + versions = client.get("/api/agent/skills/rollback/versions").json() + assert any("第二版" in v["preview"] for v in versions) + + +def test_restore_unknown_version_404(client): + _mk(client, "nope-skill", bindings={"script": True}) + r = client.post("/api/agent/skills/nope-skill/versions/99999/restore") + assert r.status_code == 404 + + +# ───────────────────────────────────────────────────────────────────────── +# Delete +# ───────────────────────────────────────────────────────────────────────── + + +def test_delete_removes_everything(client): + _mk(client, "doomed", bindings={"script": True}, body="拜拜") + r = client.delete("/api/agent/skills/doomed") + assert r.status_code == 200 + skills = client.get("/api/agent/skills?all=true").json() + assert all(s["dir"] != "doomed" for s in skills) + assert client.get("/api/agent/skills/doomed/versions").json() == [] + assert "doomed" not in effective_skill_dirs("script") + + +# ───────────────────────────────────────────────────────────────────────── +# Agents endpoint skill counts +# ───────────────────────────────────────────────────────────────────────── + + +def test_agents_endpoint_counts_effective_skills(client): + _mk(client, "count-me", bindings={"style": True, "shot": True}) + _mk(client, "count-me-disabled", bindings={"style": True}) + client.patch("/api/agent/skills/count-me-disabled", json={"is_enabled": False}) + agents = {a["key"]: a for a in client.get("/api/agent/agents").json()} + style_count = agents["style"]["skill_count"] + shot_count = agents["shot"]["skill_count"] + assert style_count >= 1 and shot_count >= 1 + # A globally disabled skill never counts. + skills = client.get("/api/agent/skills?all=true").json() + disabled_dirs = {s["dir"] for s in skills if not s["is_enabled"]} + assert "count-me-disabled" in disabled_dirs diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index 9d4588cd..24d6d958 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -524,12 +524,47 @@ export interface AgentSession { status: 'idle' | 'running' | 'error'; /** WHERE the session was born: 'chat' (AI Canvas) or 'scene' (Build Scene rail). */ origin: 'chat' | 'scene'; + /** WHICH named agent owns the session (HEL-613); null = plain harness chat. */ + agent_key?: string | null; created_at: string; updated_at: string; running?: boolean; project?: { id: number; title: string; status: string } | null; } +export interface NamedAgent { + key: string; + name: string; + char: string; + avatar: number; + avatar_dark: boolean; + llm_role: string; + tagline: string; + skill_count: number; + model_profile_id?: string | null; +} + +export interface SkillAdminEntry { + name: string; + description: string; + version: string; + tags: string[]; + dir: string; + type: string; + updated_at: number | null; + is_enabled: boolean; + bindings: Record; + assigned_count: number; +} + +export interface SkillVersion { + id: number; + skill: string; + created_at: string; + length: number; + preview: string; +} + export interface AgentMessage { id: number; session_id: number; @@ -564,9 +599,17 @@ export const agentApi = { `/api/agent/sessions${projectId != null ? `?project_id=${projectId}` : ''}`, ), listSceneSessions: () => api('/api/agent/sessions?origin=scene'), + listAgentSessions: (agentKey: string) => + api(`/api/agent/sessions?agent_key=${encodeURIComponent(agentKey)}`), + listNamedAgents: () => api('/api/agent/agents'), listLinkableProjects: () => api<{ id: number; title: string; status: string }[]>('/api/agent/projects'), - createSession: (payload: { title?: string; project_id?: number | null; origin?: 'chat' | 'scene' }) => + createSession: (payload: { + title?: string; + project_id?: number | null; + origin?: 'chat' | 'scene'; + agent_key?: string | null; + }) => api('/api/agent/sessions', { method: 'POST', body: JSON.stringify(payload), @@ -601,6 +644,43 @@ export const agentApi = { api<{ name: string; description: string; version: string; tags: string[]; dir: string }[]>( '/api/agent/skills', ), + listSkillsAdmin: () => api('/api/agent/skills?all=true'), + upsertSkill: ( + dir: string, + payload: { + description: string; + version?: string; + tags?: string[]; + skill_type?: string; + content: string; + bindings?: Record; + }, + ) => + api<{ ok: boolean; skill: SkillAdminEntry }>( + `/api/agent/skills/${encodeURIComponent(dir)}`, + { method: 'PUT', body: JSON.stringify(payload) }, + ), + patchSkill: (dir: string, isEnabled: boolean) => + api<{ ok: boolean }>(`/api/agent/skills/${encodeURIComponent(dir)}`, { + method: 'PATCH', + body: JSON.stringify({ is_enabled: isEnabled }), + }), + putSkillBindings: (dir: string, bindings: Record) => + api<{ ok: boolean }>(`/api/agent/skills/${encodeURIComponent(dir)}/bindings`, { + method: 'PUT', + body: JSON.stringify({ bindings }), + }), + deleteSkill: (dir: string) => + api<{ ok: boolean }>(`/api/agent/skills/${encodeURIComponent(dir)}`, { + method: 'DELETE', + }), + listSkillVersions: (dir: string) => + api(`/api/agent/skills/${encodeURIComponent(dir)}/versions`), + restoreSkillVersion: (dir: string, versionId: number) => + api<{ ok: boolean; skill: SkillAdminEntry }>( + `/api/agent/skills/${encodeURIComponent(dir)}/versions/${versionId}/restore`, + { method: 'POST' }, + ), listMemories: () => api< { diff --git a/calliope-web/src/lib/components/agent/agentPalette.ts b/calliope-web/src/lib/components/agent/agentPalette.ts index 72e1eac8..ad18ce36 100644 --- a/calliope-web/src/lib/components/agent/agentPalette.ts +++ b/calliope-web/src/lib/components/agent/agentPalette.ts @@ -17,6 +17,13 @@ const IDENTITIES: Record = { 'assets-agent': { label: 'Assets Agent', color: '#ec4899' }, // pink 'video-agent': { label: 'Video Agent', color: '#fb923c' }, // orange 'research-agent': { label: 'Research Agent', color: '#a78bfa' }, // violet + // The five named agents (HEL-613) — the runner stamps their zh names on + // named-session replies; colors mirror the spec §2.1 avatar five-set. + 剧本创作: { label: '剧本创作', color: '#e8a33d' }, + 视觉设计: { label: '视觉设计', color: '#5b8def' }, + 分镜设计: { label: '分镜设计', color: '#3fb97f' }, + 素材资产: { label: '素材资产', color: '#b98be0' }, + 镜头脚本: { label: '镜头脚本', color: '#d98e6a' }, }; // Fallback palette for unknown names (stable hash → deterministic color). diff --git a/calliope-web/src/lib/i18n/de.ts b/calliope-web/src/lib/i18n/de.ts index e2a399b1..4892f576 100644 --- a/calliope-web/src/lib/i18n/de.ts +++ b/calliope-web/src/lib/i18n/de.ts @@ -1489,5 +1489,85 @@ export const de: Dict = { 'tasks.delConfirm': 'Die Ergebnisdateien werden mitgelöscht. Löschen?', 'tasks.outputs': '{n} Ergebnisse', + 'agentsPage.title': 'Agenten', + 'agentsPage.subtitle': 'Chatte unabhängig mit den fünf Kreativ-Agenten; Skills definieren und zuweisen', + 'agentsPage.statusChip': '{n} Skills · {m} aktiv', + 'agentsPage.agentsTitle': 'Agent', + 'agentsPage.skillLib': 'Skill-Bibliothek', + 'agentsPage.newSkill': 'Neuer Skill', + 'agentsPage.skillLibEmpty': 'Noch keine Skills — lege einen über „Neuer Skill“ an.', + 'agentsPage.skillsCount': '{n} Skills', + 'agentsPage.replying': 'Antwortet…', + 'agentsPage.idle': 'Inaktiv', + 'agentsPage.assigned': 'zugewiesen {n}', + 'agentsPage.edit': 'Bearbeiten', + 'agentsPage.toggleSkill': 'Skill ein- oder ausschalten', + 'agentsPage.independentNote': 'Eigenständiger Chat · außerhalb des Kreativ-Workflows', + 'agentsPage.model': 'Modell', + 'agentsPage.modelDefault': 'Agent-Standard', + 'agentsPage.newSessionLabel': 'Neuer Chat', + 'agentsPage.newSession': 'Neuer Chat', + 'agentsPage.clear': 'Leeren', + 'agentsPage.export': 'Exportieren', + 'agentsPage.skillManage': 'Skill-Verwaltung', + 'agentsPage.composerPlaceholder': 'Weiterschreiben oder SkriptFragment einfügen… (Enter senden, Shift+Enter Zeilenumbruch)', + 'agentsPage.send': 'Senden', + 'agentsPage.clearTitle': 'Chat leeren', + 'agentsPage.clearConfirm': 'Der Verlauf ist danach unwiederbringlich weg. Chat mit Agent {name} leeren?', + 'agentsPage.skillErrName': 'Gib dem Skill einen Namen', + 'agentsPage.skillErrAssign': 'Mindestens einem Agent zuweisen, sonst wirkt er nie', + 'agentsPage.skillLoadFailed': 'Skill-Inhalt konnte nicht gelesen werden', + 'agentsPage.skillSaved': 'Skill gespeichert', + 'agentsPage.skillSaveFailed': 'Speichern fehlgeschlagen: {detail}', + 'agentsPage.skillEnabled': 'Skill aktiviert', + 'agentsPage.skillDisabled': 'Skill deaktiviert — neue Antworten nutzen ihn nicht mehr', + 'agentsPage.skillDeleted': 'Skill gelöscht', + 'agentsPage.skillRestored': 'Auf frühere Version zurückgesetzt', + 'agentsPage.skillTypeTemplate': 'Prompt-Vorlage', + 'agentsPage.skillTypeKnowledge': 'Referenzwissen', + 'agentsPage.skillTypeRules': 'Prozessregeln', + 'agentsPage.versions': 'Versionsverlauf', + 'agentsPage.versionsEmpty': 'Noch keine Versionen — jedes Speichern archiviert die alte.', + 'agentsPage.restore': 'Zurücksetzen', + 'agentsPage.close': 'Schließen', + 'agentsPage.editSkill': 'Skill bearbeiten', + 'agentsPage.skillName': 'Name', + 'agentsPage.skillNamePh': 'z. B. cyberpunk-style-kit', + 'agentsPage.skillType': 'Typ', + 'agentsPage.skillDesc': 'Beschreibung', + 'agentsPage.skillDescPh': 'Wann der Agent ihn nutzen soll (erscheint in seiner Skill-Liste)', + 'agentsPage.skillContent': 'Inhalt', + 'agentsPage.skillContentPh': 'Markdown möglich: Vorlagen, Referenzen oder Regeln…', + 'agentsPage.skillContentHint': 'Markdown möglich; beim Speichern wird die Version erhöht und die alte archiviert.', + 'agentsPage.assignTo': 'Zuweisen an', + 'agentsPage.saveNext': 'v{v}+1 speichern', + 'agentsPage.save': 'Speichern', + 'agentsPage.disable': 'Deaktivieren', + 'agentsPage.enable': 'Aktivieren', + 'agentsPage.delete': 'Löschen', + 'agentsPage.delSkillTitle': 'Skill löschen', + 'agentsPage.delSkillConfirm': 'Unwiderruflich; die {n} zugewiesenen Agenten verlieren ihn ebenfalls. Löschen?', + 'agentsPage.skillIdleHint': 'Wähle „Bearbeiten“ in der Bibliothek oder klicke „Neuer Skill“', + 'agentsPage.sugScript1': 'Idee zu einem Drei-Akt-Plan', + 'agentsPage.sugScript1P': 'Idee: Ein Ladenmitarbeiter bemerkt jede Nacht zur selben Minute denselben Kunden. Schreibe einen Drei-Akt-Plan.', + 'agentsPage.sugScript2': 'Bestehendes Skript überarbeiten', + 'agentsPage.sugScript2P': 'Ich füge ein Skript ein — lies es zuerst und nenne drei Verbesserungen zu Dialog und Rhythmus.', + 'agentsPage.sugStyle1': 'Stilrichtungen vorschlagen', + 'agentsPage.sugStyle1P': 'Urbaner Liebes-Kurzfilm im Neonregen: drei unterschiedliche Stilrichtungen mit englischen Prompt-Schlüsselwörtern.', + 'agentsPage.sugStyle2': 'Realistische Film-Lookkeywords', + 'agentsPage.sugStyle2P': 'Erstelle nutzbare Prompts für realistischen Filmlook (positiv + negativ), Englisch mit chinesischen Notizen.', + 'agentsPage.sugBoard1': 'Skript in Storyboard zerlegen', + 'agentsPage.sugBoard1P': 'Zerlege dieses Skript in Einstellungen: Nummer, Größe, Bewegung, Inhalt, Dialog, Dauer.', + 'agentsPage.sugBoard2': 'Höhepunkt-Storyboard', + 'agentsPage.sugBoard2P': '30-sekündige Verfolgungs-Szene: eine Version mit klarem Rhythmus.', + 'agentsPage.sugAssets1': 'Charakterbogen-Prompts', + 'agentsPage.sugAssets1P': 'Die Protagonistin ist eine 17-jährige Nacht-Detektivin: konsistente Prompts (front / Seite / Ganzkörper).', + 'agentsPage.sugAssets2': 'Asset-Liste', + 'agentsPage.sugAssets2P': 'Erstelle für den Convenience-Store im Regen Prompt-Listen für Sets und Requisiten.', + 'agentsPage.sugShot1': 'Ein Video-Prompt', + 'agentsPage.sugShot1P': 'Heranfahrende Einstellung vom Neonschild zur Glastür: ein sofort nutzbarer Video-Prompt.', + 'agentsPage.sugShot2': 'Erst-/Letztbild-Einstellungen', + 'agentsPage.sugShot2P': 'Zeige, wie man einen Erst-/Letztbild-Prompt schreibt: Beschreibung, Bewegung und Dauer.', + }; diff --git a/calliope-web/src/lib/i18n/en.ts b/calliope-web/src/lib/i18n/en.ts index b1d1f78e..dad3191d 100644 --- a/calliope-web/src/lib/i18n/en.ts +++ b/calliope-web/src/lib/i18n/en.ts @@ -1488,6 +1488,86 @@ export const en = { 'tasks.delConfirm': 'The result files will be removed together with the task. Delete it?', 'tasks.outputs': '{n} outputs', + 'agentsPage.title': 'Agents', + 'agentsPage.subtitle': 'Chat independently with the five creation agents; define and assign Skills', + 'agentsPage.statusChip': '{n} Skills · {m} enabled', + 'agentsPage.agentsTitle': 'Agent', + 'agentsPage.skillLib': 'Skill library', + 'agentsPage.newSkill': 'New Skill', + 'agentsPage.skillLibEmpty': 'No Skills yet — create one with “New Skill” above.', + 'agentsPage.skillsCount': '{n} Skills', + 'agentsPage.replying': 'Replying…', + 'agentsPage.idle': 'Idle', + 'agentsPage.assigned': 'assigned {n}', + 'agentsPage.edit': 'Edit', + 'agentsPage.toggleSkill': 'Enable or disable Skill', + 'agentsPage.independentNote': 'Independent chat · not part of the creation flow', + 'agentsPage.model': 'Model', + 'agentsPage.modelDefault': 'Agent default', + 'agentsPage.newSessionLabel': 'New chat', + 'agentsPage.newSession': 'New chat', + 'agentsPage.clear': 'Clear', + 'agentsPage.export': 'Export', + 'agentsPage.skillManage': 'Skill manager', + 'agentsPage.composerPlaceholder': 'Keep chatting, or paste a script fragment… (Enter to send, Shift+Enter for newline)', + 'agentsPage.send': 'Send', + 'agentsPage.clearTitle': 'Clear chat', + 'agentsPage.clearConfirm': 'History cannot be recovered after clearing. Clear the chat with the {name} agent?', + 'agentsPage.skillErrName': 'Please give the Skill a name', + 'agentsPage.skillErrAssign': 'Assign it to at least one Agent, otherwise it never takes effect', + 'agentsPage.skillLoadFailed': 'Failed to read Skill content', + 'agentsPage.skillSaved': 'Skill saved', + 'agentsPage.skillSaveFailed': 'Save failed: {detail}', + 'agentsPage.skillEnabled': 'Skill enabled', + 'agentsPage.skillDisabled': 'Skill disabled — new replies will not use it', + 'agentsPage.skillDeleted': 'Skill deleted', + 'agentsPage.skillRestored': 'Rolled back to a previous version', + 'agentsPage.skillTypeTemplate': 'Prompt template', + 'agentsPage.skillTypeKnowledge': 'Reference knowledge', + 'agentsPage.skillTypeRules': 'Process rules', + 'agentsPage.versions': 'Version history', + 'agentsPage.versionsEmpty': 'No versions yet — every save snapshots the old one.', + 'agentsPage.restore': 'Restore', + 'agentsPage.close': 'Close', + 'agentsPage.editSkill': 'Edit Skill', + 'agentsPage.skillName': 'Name', + 'agentsPage.skillNamePh': 'e.g. cyberpunk-style-kit', + 'agentsPage.skillType': 'Type', + 'agentsPage.skillDesc': 'Description', + 'agentsPage.skillDescPh': 'When should the agent use this Skill (shown in its skill list)', + 'agentsPage.skillContent': 'Content', + 'agentsPage.skillContentPh': 'Markdown supported: prompt templates, references, or process rules…', + 'agentsPage.skillContentHint': 'Markdown supported; saving auto-bumps the version and archives the old one.', + 'agentsPage.assignTo': 'Assign to', + 'agentsPage.saveNext': 'Save v{v}+1', + 'agentsPage.save': 'Save', + 'agentsPage.disable': 'Disable', + 'agentsPage.enable': 'Enable', + 'agentsPage.delete': 'Delete', + 'agentsPage.delSkillTitle': 'Delete Skill', + 'agentsPage.delSkillConfirm': 'Deletion is irreversible; the {n} assigned agents lose it too. Delete it?', + 'agentsPage.skillIdleHint': 'Pick “Edit” from the Skill library, or click “New Skill”', + 'agentsPage.sugScript1': 'Turn an idea into a three-act outline', + 'agentsPage.sugScript1P': 'I have an idea: a convenience-store clerk notices the same customer at the same minute every night. Please write a three-act short-film outline.', + 'agentsPage.sugScript2': 'Polish an existing script', + 'agentsPage.sugScript2P': 'I will paste an existing script — read it first, then point out three improvements to dialogue and pacing.', + 'agentsPage.sugStyle1': 'Propose style directions', + 'agentsPage.sugStyle1P': 'A neon-lit rainy urban romance short — give me three distinct visual style directions, each with English image-prompt keyword sets.', + 'agentsPage.sugStyle2': 'Cinematic-realism keywords', + 'agentsPage.sugStyle2P': 'Compile a ready-to-use set of cinematic-realism style prompts (positive + negative), English with Chinese notes.', + 'agentsPage.sugBoard1': 'Break the script into a storyboard', + 'agentsPage.sugBoard1P': 'Break this script into a shot list: shot number, size, camera move, frame content, dialogue cue, suggested duration.', + 'agentsPage.sugBoard2': 'Storyboard a climax', + 'agentsPage.sugBoard2P': 'A thirty-second chase climax — give one storyboard pass with clear rhythm changes.', + 'agentsPage.sugAssets1': 'Character sheet prompts', + 'agentsPage.sugAssets1P': 'The protagonist is a 17-year-old night-owl girl detective — write a consistent character-sheet prompt set (front / side / full body).', + 'agentsPage.sugAssets2': 'Asset checklist', + 'agentsPage.sugAssets2P': 'Based on the rainy convenience-store scene, list scene and prop asset prompts.', + 'agentsPage.sugShot1': 'One video prompt', + 'agentsPage.sugShot1P': 'A push-in shot at the store entrance, neon sign to glass door — write one directly usable video-model prompt.', + 'agentsPage.sugShot2': 'First/last-frame shots', + 'agentsPage.sugShot2P': 'Show how to write a first/last-frame video prompt: how to describe first frame, last frame, camera move, and duration.', + }; diff --git a/calliope-web/src/lib/i18n/es.ts b/calliope-web/src/lib/i18n/es.ts index 72441a91..7bf0862c 100644 --- a/calliope-web/src/lib/i18n/es.ts +++ b/calliope-web/src/lib/i18n/es.ts @@ -1489,5 +1489,85 @@ export const es: Dict = { 'tasks.delConfirm': 'Los archivos de resultados se eliminarán junto con la tarea. ¿Eliminar?', 'tasks.outputs': '{n} resultados', + 'agentsPage.title': 'Agentes', + 'agentsPage.subtitle': 'Habla de forma independiente con los cinco agentes de creación; define y asigna Skills', + 'agentsPage.statusChip': '{n} Skills · {m} activos', + 'agentsPage.agentsTitle': 'Agent', + 'agentsPage.skillLib': 'Biblioteca de Skills', + 'agentsPage.newSkill': 'Nuevo Skill', + 'agentsPage.skillLibEmpty': 'Aún no hay Skills; crea uno con «Nuevo Skill».', + 'agentsPage.skillsCount': '{n} Skills', + 'agentsPage.replying': 'Respondiendo…', + 'agentsPage.idle': 'Inactivo', + 'agentsPage.assigned': 'asignado {n}', + 'agentsPage.edit': 'Editar', + 'agentsPage.toggleSkill': 'Activar o desactivar Skill', + 'agentsPage.independentNote': 'Chat independiente · fuera del flujo de creación', + 'agentsPage.model': 'Modelo', + 'agentsPage.modelDefault': 'Predeterminado del agente', + 'agentsPage.newSessionLabel': 'Nueva conversación', + 'agentsPage.newSession': 'Nueva conversación', + 'agentsPage.clear': 'Vaciar', + 'agentsPage.export': 'Exportar', + 'agentsPage.skillManage': 'Gestión de Skills', + 'agentsPage.composerPlaceholder': 'Sigue charlando o pega un fragmento de guion… (Enter envía, Shift+Enter salto de línea)', + 'agentsPage.send': 'Enviar', + 'agentsPage.clearTitle': 'Vaciar conversación', + 'agentsPage.clearConfirm': 'El historial no se puede recuperar. ¿Vaciar la conversación con el agente {name}?', + 'agentsPage.skillErrName': 'Ponle un nombre al Skill', + 'agentsPage.skillErrAssign': 'Asígnalo al menos a un Agent, o no surtirá efecto', + 'agentsPage.skillLoadFailed': 'No se pudo leer el contenido del Skill', + 'agentsPage.skillSaved': 'Skill guardado', + 'agentsPage.skillSaveFailed': 'Error al guardar: {detail}', + 'agentsPage.skillEnabled': 'Skill activado', + 'agentsPage.skillDisabled': 'Skill desactivado; las nuevas respuestas no lo usarán', + 'agentsPage.skillDeleted': 'Skill eliminado', + 'agentsPage.skillRestored': 'Se restauró una versión anterior', + 'agentsPage.skillTypeTemplate': 'Plantilla de prompts', + 'agentsPage.skillTypeKnowledge': 'Conocimiento de referencia', + 'agentsPage.skillTypeRules': 'Reglas de proceso', + 'agentsPage.versions': 'Historial de versiones', + 'agentsPage.versionsEmpty': 'Aún no hay versiones; cada guardado archiva la anterior.', + 'agentsPage.restore': 'Restaurar', + 'agentsPage.close': 'Cerrar', + 'agentsPage.editSkill': 'Editar Skill', + 'agentsPage.skillName': 'Nombre', + 'agentsPage.skillNamePh': 'p. ej. cyberpunk-style-kit', + 'agentsPage.skillType': 'Tipo', + 'agentsPage.skillDesc': 'Descripción', + 'agentsPage.skillDescPh': 'Cuándo debe usarlo el agente (aparece en su lista de Skills)', + 'agentsPage.skillContent': 'Contenido', + 'agentsPage.skillContentPh': 'Admite Markdown: plantillas, referencias o reglas…', + 'agentsPage.skillContentHint': 'Admite Markdown; al guardar se incrementa la versión y se archiva la anterior.', + 'agentsPage.assignTo': 'Asignar a', + 'agentsPage.saveNext': 'Guardar v{v}+1', + 'agentsPage.save': 'Guardar', + 'agentsPage.disable': 'Desactivar', + 'agentsPage.enable': 'Activar', + 'agentsPage.delete': 'Eliminar', + 'agentsPage.delSkillTitle': 'Eliminar Skill', + 'agentsPage.delSkillConfirm': 'No se puede deshacer; los {n} agentes asignados lo perderán. ¿Eliminar?', + 'agentsPage.skillIdleHint': 'Elige «Editar» en la biblioteca o pulsa «Nuevo Skill»', + 'agentsPage.sugScript1': 'Convierte una idea en un esquema de tres actos', + 'agentsPage.sugScript1P': 'Tengo una idea: un dependiente nota al mismo cliente al mismo minuto cada noche. Escribe un esquema de tres actos.', + 'agentsPage.sugScript2': 'Pulir un guion existente', + 'agentsPage.sugScript2P': 'Pegaré un guion; léelo primero y señala tres mejoras de diálogo y ritmo.', + 'agentsPage.sugStyle1': 'Proponer direcciones de estilo', + 'agentsPage.sugStyle1P': 'Corto romántico urbano bajo lluvia y neón: dame tres direcciones visuales distintas con palabras clave en inglés.', + 'agentsPage.sugStyle2': 'Palabras clave cinematográficas', + 'agentsPage.sugStyle2P': 'Compila prompts de estilo cinematográfico realista (positivo + negativo), inglés con notas en chino.', + 'agentsPage.sugBoard1': 'Desglosar el guion en un storyboard', + 'agentsPage.sugBoard1P': 'Desglosa este guion por planos: número, tamaño, movimiento, contenido, diálogo y duración.', + 'agentsPage.sugBoard2': 'Storyboard del clímax', + 'agentsPage.sugBoard2P': 'Clímax de persecución de 30 segundos: da una versión con ritmo marcado.', + 'agentsPage.sugAssets1': 'Prompts de hoja de personaje', + 'agentsPage.sugAssets1P': 'La protagonista es una detective de 17 años: escribe prompts coherentes (frente / perfil / cuerpo entero).', + 'agentsPage.sugAssets2': 'Lista de assets', + 'agentsPage.sugAssets2P': 'Basándote en la escena de la tienda nocturna, lista prompts de escenarios y atrezzo.', + 'agentsPage.sugShot1': 'Un prompt de vídeo', + 'agentsPage.sugShot1P': 'Travelling de entrada al neón hacia la puerta de cristal: escribe un prompt de vídeo listo para usar.', + 'agentsPage.sugShot2': 'Planos primer/último fotograma', + 'agentsPage.sugShot2P': 'Muestra cómo escribir un prompt con primer y último fotograma: descripción, movimiento y duración.', + }; diff --git a/calliope-web/src/lib/i18n/fr.ts b/calliope-web/src/lib/i18n/fr.ts index cbdbbe83..ded0c5f7 100644 --- a/calliope-web/src/lib/i18n/fr.ts +++ b/calliope-web/src/lib/i18n/fr.ts @@ -1489,5 +1489,85 @@ export const fr: Dict = { 'tasks.delConfirm': 'Les fichiers de résultats seront supprimés avec la tâche. Supprimer ?', 'tasks.outputs': '{n} résultats', + 'agentsPage.title': 'Agents', + 'agentsPage.subtitle': 'Discutez séparément avec les cinq agents de création ; définissez et attribuez des Skills', + 'agentsPage.statusChip': '{n} Skills · {m} activés', + 'agentsPage.agentsTitle': 'Agent', + 'agentsPage.skillLib': 'Bibliothèque de Skills', + 'agentsPage.newSkill': 'Nouveau Skill', + 'agentsPage.skillLibEmpty': 'Aucun Skill pour l’instant — créez-en un avec « Nouveau Skill ».', + 'agentsPage.skillsCount': '{n} Skills', + 'agentsPage.replying': 'Réponse…', + 'agentsPage.idle': 'Inactif', + 'agentsPage.assigned': 'attribué {n}', + 'agentsPage.edit': 'Modifier', + 'agentsPage.toggleSkill': 'Activer ou désactiver le Skill', + 'agentsPage.independentNote': 'Chat indépendant · hors du flux de création', + 'agentsPage.model': 'Modèle', + 'agentsPage.modelDefault': 'Défaut de l’agent', + 'agentsPage.newSessionLabel': 'Nouvelle discussion', + 'agentsPage.newSession': 'Nouvelle discussion', + 'agentsPage.clear': 'Vider', + 'agentsPage.export': 'Exporter', + 'agentsPage.skillManage': 'Gestion des Skills', + 'agentsPage.composerPlaceholder': 'Continuez la discussion ou collez un fragment de scénario… (Entrée pour envoyer, Maj+Entrée pour un saut de ligne)', + 'agentsPage.send': 'Envoyer', + 'agentsPage.clearTitle': 'Vider la discussion', + 'agentsPage.clearConfirm': 'L’historique sera perdu définitivement. Vider la discussion avec l’agent {name} ?', + 'agentsPage.skillErrName': 'Donnez un nom au Skill', + 'agentsPage.skillErrAssign': 'Attribuez-le à au moins un Agent, sinon il ne prendra jamais effet', + 'agentsPage.skillLoadFailed': 'Échec de lecture du contenu du Skill', + 'agentsPage.skillSaved': 'Skill enregistré', + 'agentsPage.skillSaveFailed': 'Échec de l’enregistrement : {detail}', + 'agentsPage.skillEnabled': 'Skill activé', + 'agentsPage.skillDisabled': 'Skill désactivé — les nouvelles réponses ne l’utiliseront plus', + 'agentsPage.skillDeleted': 'Skill supprimé', + 'agentsPage.skillRestored': 'Version précédente restaurée', + 'agentsPage.skillTypeTemplate': 'Modèle de prompt', + 'agentsPage.skillTypeKnowledge': 'Connaissance de référence', + 'agentsPage.skillTypeRules': 'Règles de processus', + 'agentsPage.versions': 'Historique des versions', + 'agentsPage.versionsEmpty': 'Aucune version — chaque enregistrement archive la précédente.', + 'agentsPage.restore': 'Restaurer', + 'agentsPage.close': 'Fermer', + 'agentsPage.editSkill': 'Modifier le Skill', + 'agentsPage.skillName': 'Nom', + 'agentsPage.skillNamePh': 'ex. cyberpunk-style-kit', + 'agentsPage.skillType': 'Type', + 'agentsPage.skillDesc': 'Description', + 'agentsPage.skillDescPh': 'Quand l’agent doit l’utiliser (affiché dans sa liste de Skills)', + 'agentsPage.skillContent': 'Contenu', + 'agentsPage.skillContentPh': 'Markdown pris en charge : modèles, références ou règles…', + 'agentsPage.skillContentHint': 'Markdown pris en charge ; l’enregistrement incrémente la version et archive l’ancienne.', + 'agentsPage.assignTo': 'Attribuer à', + 'agentsPage.saveNext': 'Enregistrer v{v}+1', + 'agentsPage.save': 'Enregistrer', + 'agentsPage.disable': 'Désactiver', + 'agentsPage.enable': 'Activer', + 'agentsPage.delete': 'Supprimer', + 'agentsPage.delSkillTitle': 'Supprimer le Skill', + 'agentsPage.delSkillConfirm': 'Irréversible ; les {n} agents assignés le perdront aussi. Supprimer ?', + 'agentsPage.skillIdleHint': 'Choisissez « Modifier » dans la bibliothèque ou cliquez « Nouveau Skill »', + 'agentsPage.sugScript1': 'Transformer une idée en plan trois actes', + 'agentsPage.sugScript1P': 'Idée : un vendeur de supérette remarque le même client à la même minute chaque nuit. Écrivez un plan en trois actes.', + 'agentsPage.sugScript2': 'Peaufiner un scénario existant', + 'agentsPage.sugScript2P': 'Je collerai un scénario ; lisez-le puis proposez trois améliorations de dialogue et de rythme.', + 'agentsPage.sugStyle1': 'Proposer des directions visuelles', + 'agentsPage.sugStyle1P': 'Court-métrage romantique urbain sous la pluie néon : trois directions visuelles distinctes avec mots-clés anglais.', + 'agentsPage.sugStyle2': 'Mots-clés cinéma réaliste', + 'agentsPage.sugStyle2P': 'Compilez des prompts de style cinéma réaliste (positif + négatif), anglais annoté en chinois.', + 'agentsPage.sugBoard1': 'Découper le scénario en storyboard', + 'agentsPage.sugBoard1P': 'Découpez ce scénario plan par plan : numéro, échelle, mouvement, contenu, réplique, durée.', + 'agentsPage.sugBoard2': 'Storyboard du climax', + 'agentsPage.sugBoard2P': 'Climax de poursuite de 30 secondes : une version au rythme marqué.', + 'agentsPage.sugAssets1': 'Prompts de fiche personnage', + 'agentsPage.sugAssets1P': 'L’héroïne est une détective de 17 ans : des prompts cohérents (face / profil / plein pied).', + 'agentsPage.sugAssets2': 'Liste d’assets', + 'agentsPage.sugAssets2P': 'À partir de la supérette sous la pluie, listez des prompts de décors et accessoires.', + 'agentsPage.sugShot1': 'Un prompt vidéo', + 'agentsPage.sugShot1P': 'Travelling avant de l’enseigne néon vers la porte vitrée : un prompt vidéo prêt à l’emploi.', + 'agentsPage.sugShot2': 'Plans premier/dernier cadre', + 'agentsPage.sugShot2P': 'Montrez comment écrire un prompt premier/dernier cadre : description, mouvement et durée.', + }; diff --git a/calliope-web/src/lib/i18n/ja.ts b/calliope-web/src/lib/i18n/ja.ts index 3f2220ea..7042167e 100644 --- a/calliope-web/src/lib/i18n/ja.ts +++ b/calliope-web/src/lib/i18n/ja.ts @@ -1489,5 +1489,85 @@ export const ja: Dict = { 'tasks.delConfirm': '結果ファイルも一緒に削除されます。削除しますか?', 'tasks.outputs': '結果 {n} 件', + 'agentsPage.title': 'エージェント', + 'agentsPage.subtitle': '5つの制作エージェントと個別に会話し、Skill を定義・割り当て', + 'agentsPage.statusChip': 'Skill {n} 件 · 有効 {m} 件', + 'agentsPage.agentsTitle': 'Agent', + 'agentsPage.skillLib': 'Skill ライブラリ', + 'agentsPage.newSkill': 'Skill を追加', + 'agentsPage.skillLibEmpty': 'Skill がありません。上の「Skill を追加」から作成してください。', + 'agentsPage.skillsCount': 'Skill {n} 件', + 'agentsPage.replying': '返信中…', + 'agentsPage.idle': '待機中', + 'agentsPage.assigned': '割り当て {n}', + 'agentsPage.edit': '編集', + 'agentsPage.toggleSkill': 'Skill の有効/無効を切り替え', + 'agentsPage.independentNote': '独立セッション · 制作フローには参加しません', + 'agentsPage.model': 'モデル', + 'agentsPage.modelDefault': 'エージェント既定', + 'agentsPage.newSessionLabel': '新しい会話', + 'agentsPage.newSession': '新しい会話', + 'agentsPage.clear': 'クリア', + 'agentsPage.export': 'エクスポート', + 'agentsPage.skillManage': 'Skill 管理', + 'agentsPage.composerPlaceholder': '会話を続けるか、台本の断片を貼り付けて…(Enter で送信、Shift+Enter で改行)', + 'agentsPage.send': '送信', + 'agentsPage.clearTitle': '会話をクリア', + 'agentsPage.clearConfirm': 'クリアすると履歴は復元できません。{name}エージェントとの会話をクリアしますか?', + 'agentsPage.skillErrName': 'Skill に名前を付けてください', + 'agentsPage.skillErrAssign': '少なくとも1つの Agent に割り当てないと有効になりません', + 'agentsPage.skillLoadFailed': 'Skill の内容を読み込めませんでした', + 'agentsPage.skillSaved': 'Skill を保存しました', + 'agentsPage.skillSaveFailed': '保存に失敗:{detail}', + 'agentsPage.skillEnabled': 'Skill を有効にしました', + 'agentsPage.skillDisabled': 'Skill を無効にしました。以後の返信では使用されません', + 'agentsPage.skillDeleted': 'Skill を削除しました', + 'agentsPage.skillRestored': '過去のバージョンに戻しました', + 'agentsPage.skillTypeTemplate': 'プロンプトテンプレート', + 'agentsPage.skillTypeKnowledge': '参考知識', + 'agentsPage.skillTypeRules': 'プロセスルール', + 'agentsPage.versions': 'バージョン履歴', + 'agentsPage.versionsEmpty': '履歴はまだありません。保存のたびに旧版をアーカイブします。', + 'agentsPage.restore': '戻す', + 'agentsPage.close': '閉じる', + 'agentsPage.editSkill': 'Skill を編集', + 'agentsPage.skillName': '名前', + 'agentsPage.skillNamePh': '例:cyberpunk-style-kit', + 'agentsPage.skillType': 'タイプ', + 'agentsPage.skillDesc': '説明', + 'agentsPage.skillDescPh': 'エージェントがいつ使うか(Skill 一覧に表示されます)', + 'agentsPage.skillContent': '内容', + 'agentsPage.skillContentPh': 'Markdown 対応:テンプレート・参考資料・ルールなどを書けます…', + 'agentsPage.skillContentHint': 'Markdown 対応。保存時にバージョンが上がり、旧版はアーカイブされます。', + 'agentsPage.assignTo': '割り当て先', + 'agentsPage.saveNext': 'v{v}+1 を保存', + 'agentsPage.save': '保存', + 'agentsPage.disable': '無効化', + 'agentsPage.enable': '有効化', + 'agentsPage.delete': '削除', + 'agentsPage.delSkillTitle': 'Skill を削除', + 'agentsPage.delSkillConfirm': '元に戻せません。割り当て中の {n} 個の Agent からも外れます。削除しますか?', + 'agentsPage.skillIdleHint': 'ライブラリの「編集」を選ぶか「Skill を追加」を押してください', + 'agentsPage.sugScript1': 'アイデアを三幕構成に', + 'agentsPage.sugScript1P': 'アイデア:コンビニ店員が毎晩同じ時刻に同じ客が来ることに気づく。三幕構成のアウトラインを書いて。', + 'agentsPage.sugScript2': '既存の台本を推敲', + 'agentsPage.sugScript2P': '台本を貼るので、まず読んで、台詞とテンポ改善点を3つ挙げて。', + 'agentsPage.sugStyle1': 'スタイル方向を提案', + 'agentsPage.sugStyle1P': '雨のネオン街の都市型ラブショート:英語の画像プロンプト付きで3方向のビジュアルを提案して。', + 'agentsPage.sugStyle2': '映像実写風キーワード', + 'agentsPage.sugStyle2P': 'シネマティック・リアリズムのスタイルプロンプト(ポジ+ネガ)を中国語注記付きで整理して。', + 'agentsPage.sugBoard1': '台本を絵コンテに分解', + 'agentsPage.sugBoard1P': 'この台本をカット表に分解して:カット番号、サイズ、カメラワーク、内容、台詞、秒数。', + 'agentsPage.sugBoard2': 'クライマックスの絵コンテ', + 'agentsPage.sugBoard2P': '30秒の追跡シーンクライマックスに、メリハリある絵コンテを一版。', + 'agentsPage.sugAssets1': 'キャラシートプロンプト', + 'agentsPage.sugAssets1P': '主人公は17歳の夜行性少女探偵。一貫性のあるキャラシートプロンプト(正面向き/横向き/全身)を書いて。', + 'agentsPage.sugAssets2': 'アセットリスト', + 'agentsPage.sugAssets2P': '雨のコンビニのシーンから、セットと小道具のプロンプト一覧を作って。', + 'agentsPage.sugShot1': '動画プロンプトを1つ', + 'agentsPage.sugShot1P': 'ネオン看板からガラス扉へのプッシュイン。そのまま使える動画モデルプロンプトを書いて。', + 'agentsPage.sugShot2': '最初・最終フレームの書き方', + 'agentsPage.sugShot2P': '最初/最終フレームの動画プロンプトの書き方を実演して:描写・カメラワーク・秒数。', + }; diff --git a/calliope-web/src/lib/i18n/ko.ts b/calliope-web/src/lib/i18n/ko.ts index ed5999c4..3b3dade1 100644 --- a/calliope-web/src/lib/i18n/ko.ts +++ b/calliope-web/src/lib/i18n/ko.ts @@ -1489,5 +1489,85 @@ export const ko: Dict = { 'tasks.delConfirm': '결과 파일도 함께 삭제됩니다. 삭제할까요?', 'tasks.outputs': '결과 {n}개', + 'agentsPage.title': '에이전트', + 'agentsPage.subtitle': '다섯 제작 에이전트와 개별 대화하며 Skill을 정의·할당', + 'agentsPage.statusChip': 'Skill {n}개 · 활성 {m}개', + 'agentsPage.agentsTitle': 'Agent', + 'agentsPage.skillLib': 'Skill 라이브러리', + 'agentsPage.newSkill': 'Skill 추가', + 'agentsPage.skillLibEmpty': 'Skill이 없습니다. 위의「Skill 추가」로 만들어 보세요.', + 'agentsPage.skillsCount': 'Skill {n}개', + 'agentsPage.replying': '응답 중…', + 'agentsPage.idle': '대기 중', + 'agentsPage.assigned': '할당 {n}', + 'agentsPage.edit': '편집', + 'agentsPage.toggleSkill': 'Skill 켜기/끄기', + 'agentsPage.independentNote': '독립 세션 · 제작 흐름에 참여하지 않음', + 'agentsPage.model': '모델', + 'agentsPage.modelDefault': '에이전트 기본', + 'agentsPage.newSessionLabel': '새 대화', + 'agentsPage.newSession': '새 대화', + 'agentsPage.clear': '비우기', + 'agentsPage.export': '내보내기', + 'agentsPage.skillManage': 'Skill 관리', + 'agentsPage.composerPlaceholder': '계속 대화하거나 대본 조각을 붙여넣으세요… (Enter 전송, Shift+Enter 줄바꿈)', + 'agentsPage.send': '전송', + 'agentsPage.clearTitle': '대화 비우기', + 'agentsPage.clearConfirm': '비우면 기록을 복구할 수 없습니다. {name} 에이전트와의 대화를 비울까요?', + 'agentsPage.skillErrName': 'Skill 이름을 지어주세요', + 'agentsPage.skillErrAssign': '최소 한 개 Agent에 할당해야 적용됩니다', + 'agentsPage.skillLoadFailed': 'Skill 내용을 읽지 못했습니다', + 'agentsPage.skillSaved': 'Skill 저장됨', + 'agentsPage.skillSaveFailed': '저장 실패: {detail}', + 'agentsPage.skillEnabled': 'Skill 활성화됨', + 'agentsPage.skillDisabled': 'Skill 비활성화됨 — 이후 응답에서는 사용되지 않습니다', + 'agentsPage.skillDeleted': 'Skill 삭제됨', + 'agentsPage.skillRestored': '이전 버전으로 복원됨', + 'agentsPage.skillTypeTemplate': '프롬프트 템플릿', + 'agentsPage.skillTypeKnowledge': '참고 지식', + 'agentsPage.skillTypeRules': '프로세스 규칙', + 'agentsPage.versions': '버전 기록', + 'agentsPage.versionsEmpty': '버전이 아직 없습니다. 저장할 때마다 이전 버전이 보관됩니다.', + 'agentsPage.restore': '복원', + 'agentsPage.close': '닫기', + 'agentsPage.editSkill': 'Skill 편집', + 'agentsPage.skillName': '이름', + 'agentsPage.skillNamePh': '예: cyberpunk-style-kit', + 'agentsPage.skillType': '유형', + 'agentsPage.skillDesc': '설명', + 'agentsPage.skillDescPh': '에이전트가 언제 사용할지(스킬 목록에 표시됨)', + 'agentsPage.skillContent': '내용', + 'agentsPage.skillContentPh': '마크다운 지원: 템플릿, 참고 자료, 규칙 등…', + 'agentsPage.skillContentHint': '마크다운 지원. 저장 시 버전이 올라가고 이전 버전이 보관됩니다.', + 'agentsPage.assignTo': '할당 대상', + 'agentsPage.saveNext': 'v{v}+1 저장', + 'agentsPage.save': '저장', + 'agentsPage.disable': '비활성화', + 'agentsPage.enable': '활성화', + 'agentsPage.delete': '삭제', + 'agentsPage.delSkillTitle': 'Skill 삭제', + 'agentsPage.delSkillConfirm': '되돌릴 수 없습니다. 할당된 {n}개 Agent에서도 제거됩니다. 삭제할까요?', + 'agentsPage.skillIdleHint': '라이브러리에서「편집」을 고르거나「Skill 추가」를 누르세요', + 'agentsPage.sugScript1': '아이디어를 3막 개요로', + 'agentsPage.sugScript1P': '아이디어: 편의점 직원이 매일 같은 시각 같은 손님을 알아챈다. 3막 단편 개요를 써 줘.', + 'agentsPage.sugScript2': '기존 대본 다듬기', + 'agentsPage.sugScript2P': '대본을 붙여 넣을게. 먼저 읽고 대사와 리듬 개선점 세 가지를 알려 줘.', + 'agentsPage.sugStyle1': '스타일 방향 제안', + 'agentsPage.sugStyle1P': '비 내리는 네온 도시의 러브 숏폼. 영어 이미지 프롬프트 키워드와 함께 서로 다른 세 방향을 제안해 줘.', + 'agentsPage.sugStyle2': '영화적 리얼리즘 키워드', + 'agentsPage.sugStyle2P': '시네마틱 리얼리즘 스타일 프롬프트(긍정+부정) 세트를 중국어 주석과 함께 정리해 줘.', + 'agentsPage.sugBoard1': '대본을 스토리보드로', + 'agentsPage.sugBoard1P': '이 대본을 컷 단위로 나눠 줘: 컷 번호, 크기, 카메라 무브, 내용, 대사, 길이.', + 'agentsPage.sugBoard2': '클라이맥스 스토리보드', + 'agentsPage.sugBoard2P': '30초 추격전 클라이맥스에 리듬이 살아있는 스토리보드 한 판을 줘.', + 'agentsPage.sugAssets1': '캐릭터 시트 프롬프트', + 'agentsPage.sugAssets1P': '주인공은 17세 야행성 소녀 탐정. 일관된 캐릭터 시트 프롬프트(정면/측면/전신)를 써 줘.', + 'agentsPage.sugAssets2': '에셋 목록', + 'agentsPage.sugAssets2P': '비 오는 밤 편의점 장면을 바탕으로 세트와 소품 프롬프트 목록을 만들어 줘.', + 'agentsPage.sugShot1': '영상 프롬프트 하나', + 'agentsPage.sugShot1P': '네간 간판에서 유리문으로 밀어 들어가는 푸시인 샷. 바로 쓸 수 있는 영상 모델 프롬프트를 써 줘.', + 'agentsPage.sugShot2': '첫/끝 프레임 샷 쓰기', + 'agentsPage.sugShot2P': '첫/끝 프레임 영상 프롬프트 작성법을 보여 줘: 묘사, 카메라 무브, 길이.', + }; diff --git a/calliope-web/src/lib/i18n/zh.ts b/calliope-web/src/lib/i18n/zh.ts index 9d695f27..0e2df85e 100644 --- a/calliope-web/src/lib/i18n/zh.ts +++ b/calliope-web/src/lib/i18n/zh.ts @@ -1488,5 +1488,85 @@ export const zh: Dict = { 'tasks.delConfirm': '删除后该任务的结果文件会一并移除。确定删除?', 'tasks.outputs': '{n} 个结果', + 'agentsPage.title': '智能体', + 'agentsPage.subtitle': '与五个创作智能体独立对话,自定义并分配 Skill', + 'agentsPage.statusChip': '{n} 个 Skill · {m} 个启用', + 'agentsPage.agentsTitle': 'Agent', + 'agentsPage.skillLib': 'Skill 库', + 'agentsPage.newSkill': '新增 Skill', + 'agentsPage.skillLibEmpty': '还没有 Skill,点上方「新增 Skill」创建一个。', + 'agentsPage.skillsCount': '{n} 个 Skill', + 'agentsPage.replying': '回复中…', + 'agentsPage.idle': '空闲', + 'agentsPage.assigned': '分配 {n}', + 'agentsPage.edit': '编辑', + 'agentsPage.toggleSkill': '启用或停用 Skill', + 'agentsPage.independentNote': '独立会话 · 不参与创作流程', + 'agentsPage.model': '模型', + 'agentsPage.modelDefault': '智能体默认', + 'agentsPage.newSessionLabel': '新会话', + 'agentsPage.newSession': '新会话', + 'agentsPage.clear': '清空', + 'agentsPage.export': '导出', + 'agentsPage.skillManage': 'Skill 管理', + 'agentsPage.composerPlaceholder': '继续聊,或贴入新剧本片段…(Enter 发送,Shift+Enter 换行)', + 'agentsPage.send': '发送', + 'agentsPage.clearTitle': '清空会话', + 'agentsPage.clearConfirm': '清空后历史不可恢复。确定清空与{name}智能体的会话?', + 'agentsPage.skillErrName': '请给 Skill 起个名字', + 'agentsPage.skillErrAssign': '至少分配给一个 Agent,否则不会生效', + 'agentsPage.skillLoadFailed': '读取 Skill 内容失败', + 'agentsPage.skillSaved': 'Skill 已保存', + 'agentsPage.skillSaveFailed': '保存失败:{detail}', + 'agentsPage.skillEnabled': 'Skill 已启用', + 'agentsPage.skillDisabled': 'Skill 已停用,新回复不再使用它', + 'agentsPage.skillDeleted': 'Skill 已删除', + 'agentsPage.skillRestored': '已回退到历史版本', + 'agentsPage.skillTypeTemplate': '提示词模板', + 'agentsPage.skillTypeKnowledge': '参考知识', + 'agentsPage.skillTypeRules': '流程规则', + 'agentsPage.versions': '版本历史', + 'agentsPage.versionsEmpty': '还没有历史版本;每次保存会自动留档。', + 'agentsPage.restore': '回退', + 'agentsPage.close': '关闭', + 'agentsPage.editSkill': '编辑 Skill', + 'agentsPage.skillName': '名称', + 'agentsPage.skillNamePh': '例如:cyberpunk-style-kit', + 'agentsPage.skillType': '类型', + 'agentsPage.skillDesc': '描述', + 'agentsPage.skillDescPh': '什么时候用这个 Skill(展示在智能体的技能列表里)', + 'agentsPage.skillContent': '内容', + 'agentsPage.skillContentPh': '支持 Markdown:写提示词模板、参考资料或流程规则…', + 'agentsPage.skillContentHint': '内容支持 Markdown;保存后自动升版并留档旧版本。', + 'agentsPage.assignTo': '分配给', + 'agentsPage.saveNext': '保存 v{v} → v{v}+1', + 'agentsPage.save': '保存', + 'agentsPage.disable': '停用', + 'agentsPage.enable': '启用', + 'agentsPage.delete': '删除', + 'agentsPage.delSkillTitle': '删除 Skill', + 'agentsPage.delSkillConfirm': '删除后不可恢复,已分配的 {n} 个 Agent 将同时移除。确定删除?', + 'agentsPage.skillIdleHint': '从左侧 Skill 库选择「编辑」,或点「新增 Skill」', + 'agentsPage.sugScript1': '把一个创意写成三幕式短片大纲', + 'agentsPage.sugScript1P': '我有一个创意:凌晨的便利店,店员发现每天同一时刻都有同一位顾客光顾。请帮我写成三幕式短片大纲。', + 'agentsPage.sugScript2': '帮我修改现成剧本', + 'agentsPage.sugScript2P': '我会贴一段现成剧本,请你先读懂,再指出对白和节奏上可以改进的三处。', + 'agentsPage.sugStyle1': '给剧本出几套风格方向', + 'agentsPage.sugStyle1P': '这是一个雨夜霓虹灯下的都市爱情短片,请给出三套差异化视觉风格方向,每套附英文生图关键词组。', + 'agentsPage.sugStyle2': '写实电影感风格关键词', + 'agentsPage.sugStyle2P': '请为「写实电影感」整理一组可直接使用的生图风格提示词(正向+负面),中英对照。', + 'agentsPage.sugBoard1': '把剧本拆成分镜表', + 'agentsPage.sugBoard1P': '请把这段剧本拆成逐镜分镜表:镜号、景别、运镜、画面内容、台词起点、时长建议。', + 'agentsPage.sugBoard2': '高潮段落怎么分镜', + 'agentsPage.sugBoard2P': '追逐戏的高潮段落,三十秒,请给一版有节奏起伏的分镜方案。', + 'agentsPage.sugAssets1': '整理角色生图提示词', + 'agentsPage.sugAssets1P': '主角是 17 岁的夜行少女侦探,请写一套角色立绘生图提示词(正面/侧面/全身),保持一致性。', + 'agentsPage.sugAssets2': '场景资产清单', + 'agentsPage.sugAssets2P': '请根据雨夜便利店场景,列一份场景与道具资产生图提示词清单。', + 'agentsPage.sugShot1': '写一镜视频提示词', + 'agentsPage.sugShot1P': '雨夜便利店门口的推镜,从霓虹招牌推向玻璃门内,请写一条可直接使用的视频模型提示词。', + 'agentsPage.sugShot2': '首尾帧镜头怎么写', + 'agentsPage.sugShot2P': '请演示一个首尾帧生视频镜头的提示词写法:首帧画面、尾帧画面、运镜与时长分别怎么描述。', + }; diff --git a/calliope-web/src/routes/agents/+page.svelte b/calliope-web/src/routes/agents/+page.svelte index 71723e02..25f7a213 100644 --- a/calliope-web/src/routes/agents/+page.svelte +++ b/calliope-web/src/routes/agents/+page.svelte @@ -2,66 +2,1739 @@ import { onMount } from 'svelte'; import { goto } from '$app/navigation'; import { page } from '$app/state'; - import { agentApi, canvasApi } from '$lib/api'; + import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query'; + import { fade } from 'svelte/transition'; + import AppShell from '$lib/components/shell/AppShell.svelte'; + import Button from '$lib/components/ui/Button.svelte'; + import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte'; + import Icon from '$lib/components/ui/Icon.svelte'; + import AgentChat from '$lib/components/agent/AgentChat.svelte'; + import { + agentApi, + settings, + type AgentMessage, + type AgentSession, + type NamedAgent, + type SkillAdminEntry, + type SkillVersion, + type Settings, + canvasApi, + } from '$lib/api'; import { AGENT_TASK_PROMPTS, AGENT_TASK_TITLE_KEYS, isAgentTaskKind } from '$lib/agentTasks'; + import { connectEvents } from '$lib/events'; + import { toStore } from 'svelte/store'; import { t } from '$lib/i18n.svelte'; + import { toast } from '$lib/toast'; - let failed = $state(''); + const client = useQueryClient(); + + // ───────────────────────────────────────────────────────────────────── + // Legacy deep-link contract (Project stages): /agents?project=&task= + // story|script still routes into the canvas flow, not this page. + // ───────────────────────────────────────────────────────────────────── + let legacyRedirect = $state<'pending' | 'off' | 'failed'>('pending'); + let legacyError = $state(''); onMount(async () => { + const projectParam = page.url.searchParams.get('project'); + const taskParam = page.url.searchParams.get('task'); + if (projectParam == null && taskParam == null) { + legacyRedirect = 'off'; + return; + } try { - const projectParam = page.url.searchParams.get('project'); - const taskParam = page.url.searchParams.get('task'); - let sessionId: number; - let prefill = ''; - - if (projectParam != null || taskParam != null) { - // Deep-link contract from the Project stages: /agents?project=&task= - const pid = projectParam != null && projectParam !== '' ? Number(projectParam) : null; - const task = isAgentTaskKind(taskParam) ? taskParam : null; - const s = await agentApi.createSession({ - ...(pid != null && Number.isFinite(pid) ? { project_id: pid } : {}), - ...(task ? { title: t(AGENT_TASK_TITLE_KEYS[task]) } : {}), - }); - sessionId = s.id; - prefill = task ? AGENT_TASK_PROMPTS[task] : ''; - } else { - const sessions = await agentApi.listSessions(); - const stored = Number(localStorage.getItem('calliope.agents.activeSession')); - const found = sessions.find((s) => s.id === stored) ?? sessions[0]; - sessionId = found?.id ?? (await agentApi.createSession({})).id; - } - - const session = await agentApi.getSession(sessionId); + const pid = + projectParam != null && projectParam !== '' ? Number(projectParam) : null; + const task = isAgentTaskKind(taskParam) ? taskParam : null; + const s = await agentApi.createSession({ + ...(pid != null && Number.isFinite(pid) ? { project_id: pid } : {}), + ...(task ? { title: t(AGENT_TASK_TITLE_KEYS[task]) } : {}), + }); + const session = await agentApi.getSession(s.id); const graph = session.project_id ? await canvasApi.ensureForProject(session.project_id) : await canvasApi.ensureForSession(session.id); const url = `/canvas/${graph.canvas.id}?session=${session.id}`; - if (prefill) sessionStorage.setItem('calliope.canvas.composerPrefill', prefill); + if (task) sessionStorage.setItem('calliope.canvas.composerPrefill', AGENT_TASK_PROMPTS[task]); goto(url, { replaceState: true }); } catch (err) { - failed = err instanceof Error ? err.message : t('agents.openFailed'); + legacyError = err instanceof Error ? err.message : String(err); + legacyRedirect = 'failed'; } }); + + // ───────────────────────────────────────────────────────────────────── + // Registry / sessions / skills / settings + // ───────────────────────────────────────────────────────────────────── + const agentsQuery = createQuery({ + queryKey: ['agents-registry'], + queryFn: agentApi.listNamedAgents, + }); + const settingsQuery = createQuery({ queryKey: ['settings'], queryFn: settings.get }); + + const ALL_KEYS = ['script', 'style', 'storyboard', 'assets', 'shot'] as const; + + // One query for all five agents' sessions (left-column busy flags and + // the per-agent session selector share it). + const allSessionsQuery = createQuery({ + queryKey: ['agents-page-sessions'], + queryFn: async () => { + const lists = await Promise.all(ALL_KEYS.map((k) => agentApi.listAgentSessions(k))); + return lists.flat(); + }, + }); + + let activeKey = $state( + (() => { + const stored = localStorage.getItem('calliope.agents.activeKey'); + return stored && (ALL_KEYS as readonly string[]).includes(stored) ? stored : 'script'; + })(), + ); + + const agents = $derived($agentsQuery.data ?? []); + const activeAgent: NamedAgent | null = $derived( + agents.find((a) => a.key === activeKey) ?? null, + ); + const activeSessions = $derived( + ($allSessionsQuery.data ?? []).filter((s) => s.agent_key === activeKey), + ); + const busyByAgent = $derived.by(() => { + const map: Record = {}; + for (const s of $allSessionsQuery.data ?? []) { + if (s.running) map[s.agent_key ?? ''] = true; + } + return map; + }); + + let activeId = $state(null); + const sessionQuery = createQuery( + toStore(() => ({ + queryKey: ['agent-session', activeId], + queryFn: () => agentApi.getSession(activeId!), + enabled: activeId != null, + })), + ); + + // Session selection per agent, persisted; falls back to the newest. + $effect(() => { + const list = activeSessions; + const key = activeKey; + if (!list.length) { + activeId = null; + return; + } + const stored = Number(localStorage.getItem(`calliope.agents.session.${key}`)); + const found = list.find((s) => s.id === stored) ?? list[0]; + activeId = found.id; + }); + + function rememberSession(key: string, id: number | null) { + if (id != null) localStorage.setItem(`calliope.agents.session.${key}`, String(id)); + else localStorage.removeItem(`calliope.agents.session.${key}`); + } + + function selectAgent(key: string) { + localStorage.setItem('calliope.agents.activeKey', key); + activeKey = key; + resetStreaming(); + } + + function selectSession(id: number) { + activeId = id; + rememberSession(activeKey, id); + resetStreaming(); + } + + async function newSession() { + try { + const s = await agentApi.createSession({ agent_key: activeKey }); + rememberSession(activeKey, s.id); + await client.invalidateQueries({ queryKey: ['agents-page-sessions'] }); + activeId = s.id; + resetStreaming(); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + } + + // ───────────────────────────────────────────────────────────────────── + // Chat streaming state (same SSE contract as the canvas page) + // ───────────────────────────────────────────────────────────────────── + let streaming = $state(''); + let streamingReasoning = $state(''); + let thinkingAgent = $state(null); + let liveTools = $state< + { tool: string; args?: Record | null; result?: unknown; phase: 'running' | 'done' | 'error' }[] + >([]); + + function resetStreaming() { + streaming = ''; + streamingReasoning = ''; + thinkingAgent = null; + liveTools = []; + } + + function appendMessage(sid: number, msg: AgentMessage) { + if (sid !== activeId) return; + client.setQueryData( + ['agent-session', sid], + (old) => { + if (!old || !Array.isArray(old.messages)) return old; + if (old.messages.some((m) => m.id === msg.id)) return old; + return { ...old, messages: [...old.messages, msg] }; + }, + ); + } + + onMount(() => { + const stop = connectEvents((ev) => { + if (ev.type === 'events.resync') { + client.invalidateQueries({ queryKey: ['agents-page-sessions'] }); + if (activeId != null) + client.invalidateQueries({ queryKey: ['agent-session', activeId] }); + client.invalidateQueries({ queryKey: ['agents-registry'] }); + return; + } + if (ev.type === 'agent.session.updated') { + client.invalidateQueries({ queryKey: ['agents-page-sessions'] }); + if (activeId != null) + client.invalidateQueries({ queryKey: ['agent-session', activeId] }); + return; + } + if (ev.type === 'agent.message') { + const msg = ev.data?.message as AgentMessage | undefined; + if (msg) { + appendMessage(msg.session_id, msg); + if (msg.session_id === activeId && msg.role === 'tool') liveTools = []; + if (msg.session_id === activeId && msg.role === 'assistant') resetStreaming(); + } + return; + } + if (ev.data?.session_id !== activeId) return; + if (ev.type === 'agent.token') { + if (!ev.data?.agent_name) streaming += String(ev.data?.content ?? ''); + } else if (ev.type === 'agent.thinking') { + const name = (ev.data?.agent_name as string | undefined) ?? null; + if (name !== thinkingAgent) { + streamingReasoning += `${name ? `${name}: ` : ''}`; + thinkingAgent = name; + } + streamingReasoning += String(ev.data?.content ?? ''); + } else if (ev.type === 'agent.tool') { + const name = String(ev.data?.tool ?? ''); + const phase = String(ev.data?.phase ?? ''); + if (phase === 'start') { + liveTools.push({ + tool: name, + args: (ev.data?.args as Record) ?? null, + phase: 'running', + }); + } else if (phase === 'finish') { + const idx = [...liveTools].reverse().findIndex((x) => x.tool === name && x.phase === 'running'); + if (idx >= 0) { + const real = liveTools.length - 1 - idx; + liveTools[real] = { + ...liveTools[real], + result: ev.data?.result, + phase: (ev.data?.result as { ok?: boolean } | undefined)?.ok === false ? 'error' : 'done', + }; + } + } + } + }); + return stop; + }); + + const running = $derived($sessionQuery.data?.running === true); + const messages = $derived($sessionQuery.data?.messages ?? []); + + // ───────────────────────────────────────────────────────────────────── + // Composer (spec §4.3: Enter 发送 / Shift+Enter 换行) + // ───────────────────────────────────────────────────────────────────── + let draft = $state(''); + + async function handleSend() { + const content = draft.trim(); + if (!content || running) return; + let sid = activeId; + try { + if (sid == null) { + const s = await agentApi.createSession({ agent_key: activeKey }); + sid = s.id; + rememberSession(activeKey, sid); + await client.invalidateQueries({ queryKey: ['agents-page-sessions'] }); + activeId = sid; + } + draft = ''; + await agentApi.postMessage(sid, content); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + } + + function onKeydown(e: KeyboardEvent) { + if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { + e.preventDefault(); + void handleSend(); + } + } + + function handleAnswer(option: string, _scope: string, questionSeq: number) { + if (running || activeId == null) return; + draft = option; + void (async () => { + const content = option; + draft = ''; + try { + await agentApi.postMessage(activeId!, { content, mentions: [], attachments: [], answer_to: questionSeq }); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + })(); + } + + // Per-agent opening suggestions for the empty timeline. + const SUGGESTIONS: Record = { + script: [ + { labelKey: 'agentsPage.sugScript1', promptKey: 'agentsPage.sugScript1P' }, + { labelKey: 'agentsPage.sugScript2', promptKey: 'agentsPage.sugScript2P' }, + ], + style: [ + { labelKey: 'agentsPage.sugStyle1', promptKey: 'agentsPage.sugStyle1P' }, + { labelKey: 'agentsPage.sugStyle2', promptKey: 'agentsPage.sugStyle2P' }, + ], + storyboard: [ + { labelKey: 'agentsPage.sugBoard1', promptKey: 'agentsPage.sugBoard1P' }, + { labelKey: 'agentsPage.sugBoard2', promptKey: 'agentsPage.sugBoard2P' }, + ], + assets: [ + { labelKey: 'agentsPage.sugAssets1', promptKey: 'agentsPage.sugAssets1P' }, + { labelKey: 'agentsPage.sugAssets2', promptKey: 'agentsPage.sugAssets2P' }, + ], + shot: [ + { labelKey: 'agentsPage.sugShot1', promptKey: 'agentsPage.sugShot1P' }, + { labelKey: 'agentsPage.sugShot2', promptKey: 'agentsPage.sugShot2P' }, + ], + }; + const suggestions = $derived( + (SUGGESTIONS[activeKey] ?? []).map((s) => ({ label: t(s.labelKey), prompt: t(s.promptKey) })), + ); + + // ───────────────────────────────────────────────────────────────────── + // 清空 / 导出 + // ───────────────────────────────────────────────────────────────────── + let clearOpen = $state(false); + + const clearMutation = createMutation({ + mutationFn: async () => { + if (activeId == null) return; + await agentApi.deleteSession(activeId); + rememberSession(activeKey, null); + const s = await agentApi.createSession({ agent_key: activeKey }); + rememberSession(activeKey, s.id); + return s; + }, + onSuccess: (s) => { + clearOpen = false; + resetStreaming(); + void client.invalidateQueries({ queryKey: ['agents-page-sessions'] }); + if (s) activeId = s.id; + }, + onError: (err) => toast.error(err instanceof Error ? err.message : String(err)), + }); + + function exportMarkdown() { + const s = $sessionQuery.data; + if (!s || !messages.length) return; + const name = activeAgent?.name ?? activeKey; + const lines = [`# ${name} · ${s.title}`, '']; + for (const m of messages) { + if (m.role === 'user') lines.push(`## 🧑 用户`, '', m.content, ''); + else if (m.role === 'assistant') lines.push(`## 🤖 ${m.agent_name ?? name}`, '', m.content, ''); + else if (m.role === 'tool' && m.tool_name) + lines.push(`> 工具调用 \`${m.tool_name}\``, ''); + } + const blob = new Blob([lines.join('\n')], { type: 'text/markdown;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `agents-${activeKey}-${s.id}.md`; + a.click(); + URL.revokeObjectURL(url); + } + + // ───────────────────────────────────────────────────────────────────── + // Per-agent model binding (shares data with the models page panel) + // ───────────────────────────────────────────────────────────────────── + const assignMutation = createMutation({ + mutationFn: (payload: Record) => + settings.update({ agent_llm_assignments: payload }), + onSuccess: () => client.invalidateQueries({ queryKey: ['settings'] }), + onError: (err) => { + void client.invalidateQueries({ queryKey: ['settings'] }); + toast.error(err instanceof Error ? err.message : String(err)); + }, + }); + + function setAgentModel(s: Settings, role: string, value: string) { + const merged: Record = { ...(s.agent_llm_assignments ?? {}) }; + merged[role] = value === '' ? null : value; + $assignMutation.mutate(merged); + } + + // ───────────────────────────────────────────────────────────────────── + // Skill management (right column) + // ───────────────────────────────────────────────────────────────────── + const skillsQuery = createQuery({ + queryKey: ['skills-admin'], + queryFn: agentApi.listSkillsAdmin, + }); + const skills = $derived($skillsQuery.data ?? []); + + type EditorMode = 'idle' | 'add' | 'edit'; + let editorMode = $state('idle'); + let editingDir = $state(null); + let form = $state({ name: '', type: 'template', desc: '', content: '' }); + let formBindings = $state>({}); + let showSkillErrors = $state(false); + let drawerOpen = $state(false); + let versionsOpen = $state(false); + let versions = $state([]); + + const skillErrors = $derived.by(() => { + const errs: Record = {}; + if (!form.name.trim()) errs.name = t('agentsPage.skillErrName'); + if (editorMode === 'edit' && Object.values(formBindings).every((v) => !v)) + errs.bindings = t('agentsPage.skillErrAssign'); + return errs; + }); + + function resetEditor() { + editorMode = 'idle'; + editingDir = null; + form = { name: '', type: 'template', desc: '', content: '' }; + formBindings = {}; + showSkillErrors = false; + versionsOpen = false; + versions = []; + drawerOpen = false; + } + + function startAddSkill() { + resetEditor(); + editorMode = 'add'; + // A new skill defaults to the agent being viewed. + formBindings = { [activeKey]: true }; + openDrawer(); + } + + async function startEditSkill(skill: SkillAdminEntry) { + resetEditor(); + editorMode = 'edit'; + editingDir = skill.dir; + form = { + name: skill.dir, + type: skill.type || 'template', + desc: skill.description, + content: '', + }; + formBindings = { ...skill.bindings }; + openDrawer(); + try { + const res = await agentApi.readSkillFile(skill.dir, 'SKILL.md'); + // Strip frontmatter for the editor body. + const text = res.content ?? ''; + const m = text.match(/\A---\s*\n[\s\S]*?\n---\s*\n?/); + form.content = m ? text.slice(m[0].length) : text; + } catch { + toast.error(t('agentsPage.skillLoadFailed')); + } + } + + function openDrawer() { + drawerOpen = true; + } + + const saveSkillMutation = createMutation({ + mutationFn: async () => { + const dir = editorMode === 'edit' && editingDir ? editingDir : form.name.trim(); + return agentApi.upsertSkill(dir, { + description: form.desc.trim(), + skill_type: form.type, + content: form.content, + bindings: formBindings, + }); + }, + onSuccess: () => { + toast.success(t('agentsPage.skillSaved')); + void client.invalidateQueries({ queryKey: ['skills-admin'] }); + void client.invalidateQueries({ queryKey: ['agents-registry'] }); + resetEditor(); + }, + onError: (err) => + toast.error( + t('agentsPage.skillSaveFailed', { detail: err instanceof Error ? err.message : String(err) }), + ), + }); + + function submitSkill() { + showSkillErrors = true; + if (Object.keys(skillErrors).length || $saveSkillMutation.isPending) return; + $saveSkillMutation.mutate(); + } + + const toggleSkillMutation = createMutation({ + mutationFn: ({ dir, next }: { dir: string; next: boolean }) => agentApi.patchSkill(dir, next), + onSuccess: (_d, vars) => { + toast.success(vars.next ? t('agentsPage.skillEnabled') : t('agentsPage.skillDisabled')); + void client.invalidateQueries({ queryKey: ['skills-admin'] }); + void client.invalidateQueries({ queryKey: ['agents-registry'] }); + }, + onError: (err) => { + void client.invalidateQueries({ queryKey: ['skills-admin'] }); + toast.error(err instanceof Error ? err.message : String(err)); + }, + }); + + let deleteSkillOpen = $state(false); + let deleteSkillTarget = $state(null); + + const deleteSkillMutation = createMutation({ + mutationFn: (dir: string) => agentApi.deleteSkill(dir), + onSuccess: () => { + deleteSkillOpen = false; + toast.success(t('agentsPage.skillDeleted')); + if (editingDir === deleteSkillTarget?.dir) resetEditor(); + deleteSkillTarget = null; + void client.invalidateQueries({ queryKey: ['skills-admin'] }); + void client.invalidateQueries({ queryKey: ['agents-registry'] }); + }, + onError: (err) => toast.error(err instanceof Error ? err.message : String(err)), + }); + + async function loadVersions(dir: string) { + try { + versions = await agentApi.listSkillVersions(dir); + versionsOpen = true; + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + } + + const restoreMutation = createMutation({ + mutationFn: ({ dir, id }: { dir: string; id: number }) => agentApi.restoreSkillVersion(dir, id), + onSuccess: () => { + toast.success(t('agentsPage.skillRestored')); + void client.invalidateQueries({ queryKey: ['skills-admin'] }); + if (editingDir) void loadVersions(editingDir); + // Refresh the open editor body to the restored content. + if (editingDir) { + void (async () => { + const skill = $skillsQuery.data?.find((s) => s.dir === editingDir); + if (skill) await startEditSkill(skill); + })(); + } + }, + onError: (err) => toast.error(err instanceof Error ? err.message : String(err)), + }); + + function typeLabel(type: string): string { + return type === 'knowledge' + ? t('agentsPage.skillTypeKnowledge') + : type === 'rules' + ? t('agentsPage.skillTypeRules') + : t('agentsPage.skillTypeTemplate'); + } + + function formatUpdatedAt(ts: number | null): string { + if (!ts) return ''; + return new Date(ts * 1000).toLocaleString([], { + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }); + } + + const editingVersion = $derived( + editorMode === 'edit' && editingDir + ? (skills.find((s) => s.dir === editingDir)?.version ?? '') + : '', + ); + + function avatarStyle(n: number): string { + return `var(--avatar-${Math.min(Math.max(n, 1), 5)})`; + } -{#if failed} - -{:else} +{#if legacyRedirect === 'pending'}
{t('agents.opening')}
+{:else if legacyRedirect === 'failed'} + +{:else} + + {#snippet actions()} + + {t('agentsPage.statusChip', { + n: skills.length, + m: skills.filter((s) => s.is_enabled).length, + })} + + {/snippet} + +
+
+ + + + +
+ {#if activeAgent} +
+ + {activeAgent.char} + +
+

{activeAgent.name}

+

{t('agentsPage.independentNote')}

+
+ + {#if running} + + {t('agentsPage.replying')} + {:else} + + {t('agentsPage.idle')} + {/if} + +
+ + + + + + +
+
+ +
+ (draft = p)} + onAnswer={handleAnswer} + /> +
+ +
+ + +
+ {/if} +
+ + + {#if editorMode !== 'idle' || drawerOpen} + +
(drawerOpen ? resetEditor() : undefined)} aria-hidden="true">
+ {/if} + +
+
+
+ + $clearMutation.mutate()} + oncancel={() => (clearOpen = false)} + /> + + deleteSkillTarget && $deleteSkillMutation.mutate(deleteSkillTarget.dir)} + oncancel={() => (deleteSkillTarget = null)} + /> {/if}