From a11317ae0a7ea965b17a8c6b6606755fc194b7ec Mon Sep 17 00:00:00 2001 From: Benjiyaya Date: Sun, 6 Sep 2026 05:14:24 +0800 Subject: [PATCH] feat(harness): canvas/skills/memory/interaction plugins + guard hardening Self-registering harness plugins for the merged Canvas surface: canvas tools (summarize/create/connect/link/update/run/post/delete, get-or-create sandbox canvas), SKILL.md skills library with / composer picker, durable agent memory, and ask_user question cards with structured HITL approvals. Guards emit typed reason codes; stop cancels session jobs via ComfyUI interrupt; contract vocabulary gate (contracts.json + export script) keeps web/backend names in sync. --- calliope-backend/contracts.json | 136 +++ calliope-backend/scripts/export_contracts.py | 101 ++ .../character-consistency/SKILL.md | 49 + .../h3-video-prompt-enhancer/README.md | 123 +++ .../h3-video-prompt-enhancer/SKILL.md | 251 +++++ .../references/base-multishot-format.md | 182 ++++ .../references/creative-showcase.md | 453 ++++++++ .../references/ref2va-format.md | 240 +++++ .../skills_builtin/scene-to-video/SKILL.md | 50 + .../src/calliope/agent/asset_agent.py | 4 + .../src/calliope/agent/harness/__init__.py | 37 +- .../src/calliope/agent/harness/log.py | 60 +- .../src/calliope/agent/harness/loop.py | 58 +- .../calliope/agent/harness/orchestrator.py | 7 +- .../agent/harness/plugins/__init__.py | 4 + .../calliope/agent/harness/plugins/canvas.py | 975 ++++++++++++++++++ .../agent/harness/plugins/interaction.py | 124 +++ .../calliope/agent/harness/plugins/memory.py | 249 +++++ .../calliope/agent/harness/plugins/render.py | 310 +++++- .../calliope/agent/harness/plugins/skills.py | 97 ++ .../src/calliope/agent/harness/policy.py | 141 ++- .../src/calliope/agent/harness/prompts.py | 72 +- .../src/calliope/agent/harness/registry.py | 11 +- .../src/calliope/agent/harness/runner.py | 30 +- .../src/calliope/agent/skills_store.py | 196 ++++ .../src/calliope/agent/video_agent.py | 3 + calliope-backend/src/calliope/db.py | 66 ++ calliope-backend/src/calliope/main.py | 4 +- .../src/calliope/queue/manager.py | 38 + calliope-backend/src/calliope/queue/worker.py | 51 +- .../src/calliope/routers/agent.py | 162 ++- .../src/calliope/routers/canvas.py | 513 ++++++++- .../src/calliope/routers/workflows.py | 75 ++ calliope-backend/tests/test_agent_attach.py | 94 ++ .../tests/test_agent_canvas_plugin.py | 423 ++++++++ .../tests/test_agent_interaction.py | 173 ++++ calliope-backend/tests/test_agent_memory.py | 163 +++ calliope-backend/tests/test_agent_security.py | 90 +- calliope-backend/tests/test_agent_skills.py | 133 +++ calliope-backend/tests/test_canvas_edges.py | 310 ++++++ calliope-backend/tests/test_canvas_layout.py | 144 +++ calliope-backend/tests/test_canvas_router.py | 188 ++++ .../tests/test_contract_vocabulary.py | 103 ++ calliope-backend/tests/test_render_intent.py | 45 + calliope-backend/tests/test_repeat_guard.py | 171 +++ .../tests/test_run_workflow_batch.py | 105 ++ .../tests/test_stop_kills_jobs.py | 69 ++ .../tests/test_tag_render_permission.py | 156 +++ calliope-backend/tests/test_video_continue.py | 5 +- calliope-web/src/app.html | 1 + calliope-web/src/lib/agentComposer.ts | 30 +- calliope-web/src/lib/api.ts | 102 +- .../src/lib/canvas/ArtifactNode.svelte | 213 ++++ calliope-web/src/lib/canvas/EntityNode.svelte | 82 +- calliope-web/src/lib/canvas/tokens.css | 5 + .../src/lib/components/ActivityPanel.svelte | 4 +- .../src/lib/components/AssetsStage.svelte | 40 +- .../src/lib/components/QueueStage.svelte | 27 +- .../src/lib/components/ScriptStage.svelte | 4 +- .../src/lib/components/agent/AgentChat.svelte | 102 ++ .../lib/components/agent/AgentComposer.svelte | 187 +++- .../agent/WorkflowMentionMenu.svelte | 56 +- .../components/settings/MemoryPanel.svelte | 274 +++++ .../components/settings/SettingsNav.svelte | 5 +- .../components/settings/SkillsLibrary.svelte | 518 ++++++++++ .../components/video/JobInputsDrawer.svelte | 70 +- .../video/VideoEditWorkspace.svelte | 14 +- calliope-web/src/lib/events.ts | 18 +- .../src/routes/canvas/[id]/+layout.svelte | 15 + .../src/routes/canvas/[id]/+page.svelte | 558 ++++++++-- .../src/routes/project/[id]/+page.svelte | 13 +- calliope-web/src/routes/settings/+page.svelte | 33 +- 72 files changed, 9299 insertions(+), 316 deletions(-) create mode 100644 calliope-backend/contracts.json create mode 100644 calliope-backend/scripts/export_contracts.py create mode 100644 calliope-backend/skills_builtin/character-consistency/SKILL.md create mode 100644 calliope-backend/skills_builtin/h3-video-prompt-enhancer/README.md create mode 100644 calliope-backend/skills_builtin/h3-video-prompt-enhancer/SKILL.md create mode 100644 calliope-backend/skills_builtin/h3-video-prompt-enhancer/references/base-multishot-format.md create mode 100644 calliope-backend/skills_builtin/h3-video-prompt-enhancer/references/creative-showcase.md create mode 100644 calliope-backend/skills_builtin/h3-video-prompt-enhancer/references/ref2va-format.md create mode 100644 calliope-backend/skills_builtin/scene-to-video/SKILL.md create mode 100644 calliope-backend/src/calliope/agent/harness/plugins/canvas.py create mode 100644 calliope-backend/src/calliope/agent/harness/plugins/interaction.py create mode 100644 calliope-backend/src/calliope/agent/harness/plugins/memory.py create mode 100644 calliope-backend/src/calliope/agent/harness/plugins/skills.py create mode 100644 calliope-backend/src/calliope/agent/skills_store.py create mode 100644 calliope-backend/tests/test_agent_attach.py create mode 100644 calliope-backend/tests/test_agent_canvas_plugin.py create mode 100644 calliope-backend/tests/test_agent_interaction.py create mode 100644 calliope-backend/tests/test_agent_memory.py create mode 100644 calliope-backend/tests/test_agent_skills.py create mode 100644 calliope-backend/tests/test_canvas_edges.py create mode 100644 calliope-backend/tests/test_canvas_layout.py create mode 100644 calliope-backend/tests/test_contract_vocabulary.py create mode 100644 calliope-backend/tests/test_render_intent.py create mode 100644 calliope-backend/tests/test_repeat_guard.py create mode 100644 calliope-backend/tests/test_run_workflow_batch.py create mode 100644 calliope-backend/tests/test_stop_kills_jobs.py create mode 100644 calliope-backend/tests/test_tag_render_permission.py create mode 100644 calliope-web/src/lib/canvas/ArtifactNode.svelte create mode 100644 calliope-web/src/lib/components/settings/MemoryPanel.svelte create mode 100644 calliope-web/src/lib/components/settings/SkillsLibrary.svelte create mode 100644 calliope-web/src/routes/canvas/[id]/+layout.svelte diff --git a/calliope-backend/contracts.json b/calliope-backend/contracts.json new file mode 100644 index 00000000..2b410aa7 --- /dev/null +++ b/calliope-backend/contracts.json @@ -0,0 +1,136 @@ +{ + "input_roles": [ + "positive", + "prompt", + "neg", + "negative", + "w", + "width", + "h", + "height", + "char", + "character", + "face", + "portrait", + "ref", + "sheet", + "background", + "env", + "environment", + "loc", + "location", + "scene", + "image", + "img", + "vid", + "video", + "audio", + "sfx", + "sound", + "seed", + "dur", + "duration", + "length", + "seconds" + ], + "output_roles": [ + "image", + "img", + "vid", + "video" + ], + "agent_event_types": [ + "assistant/message", + "memory/forgotten", + "memory/saved", + "plan/created", + "question/answered", + "question/asked", + "step/end", + "step/start", + "task/end", + "task/start", + "tool/call", + "tool/result", + "turn/end", + "turn/start", + "user/message" + ], + "agent_tool_names": [ + "add_beat", + "add_character", + "add_item", + "add_location", + "add_scene", + "ask_user", + "attach_asset", + "canvas_connect", + "canvas_link", + "comfy_server_info", + "create_canvas_node", + "create_project", + "delete_beat", + "delete_canvas_node", + "delete_character", + "delete_item", + "delete_location", + "delete_scene", + "enqueue_asset_jobs", + "enqueue_video_jobs", + "forget_memory", + "generate_script", + "generate_story", + "get_job_status", + "get_story", + "get_workspace", + "link_project", + "list_jobs", + "list_memories", + "list_projects", + "list_scenes", + "list_skills", + "list_workflows", + "post_artifact_to_canvas", + "read_skill", + "reorder_scenes", + "run_canvas_node", + "run_workflow", + "save_memory", + "summarize_canvas", + "unlink_project", + "update_beat", + "update_canvas_node", + "update_character", + "update_item", + "update_location", + "update_project", + "update_scene", + "wait_for_jobs" + ], + "sse_events": [ + "agent.message", + "agent.plan", + "agent.session.updated", + "agent.task", + "agent.thinking", + "agent.token", + "agent.tool", + "asset.ready", + "canvas.updated", + "job.completed", + "job.created", + "job.deleted", + "job.failed", + "job.progress", + "job.started", + "story.ready" + ], + "prompt_profiles": [ + "minimax_h3_ref", + "prose" + ], + "guard_codes": [ + "guard_destructive_replace", + "guard_render_approval" + ] +} diff --git a/calliope-backend/scripts/export_contracts.py b/calliope-backend/scripts/export_contracts.py new file mode 100644 index 00000000..068d9609 --- /dev/null +++ b/calliope-backend/scripts/export_contracts.py @@ -0,0 +1,101 @@ +"""Contract vocabulary export: single registry of names shared across layers. + +Calliope's backend and frontend communicate through stringly-typed contracts +(agent tool names, harness event types, SSE bus events, ComfyUI roles, +prompt profiles, guard codes). Nothing type-checks across that boundary, so +a rename ships silently until a user clicks. This script emits the positive +allowlist — `contracts.json` — consumed by tests/test_contract_vocabulary.py, +which fails when the web bundle references a name that no longer exists. + +Regenerate after ANY change to: roles.py alias tables, log.py event types, +harness tool registrations, event_bus.publish("…"), prompt profiles, guard codes: + + python scripts/export_contracts.py +""" +from __future__ import annotations + +import json +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SRC = ROOT / "src" / "calliope" +OUT = ROOT / "contracts.json" + +# ── roles (from comfyui/roles.py — parsed, not imported, so this script +# never needs the venv) ──────────────────────────────────────────────── +_ROLE_BLOCK = re.compile( + r"(INPUT|OUTPUT)_ROLE_ALIASES[^=]*=\s*\{(.*?)\n\}", re.DOTALL +) + + +def _extract_roles() -> dict[str, list[str]]: + text = (SRC / "comfyui" / "roles.py").read_text(encoding="utf-8") + roles: dict[str, list[str]] = {"input": [], "output": []} + for kind, block in _ROLE_BLOCK.findall(text): + key = kind.lower() + for canon, aliases in re.findall(r'"([a-z0-9_-]+)"\s*:\s*frozenset\(\{(.*?)\}\)', block, re.DOTALL): + names = [canon] + re.findall(r'"([a-z0-9_-]+)"', aliases) + roles[key].extend(sorted(set(names))) + return roles + + +def _extract_event_types() -> list[str]: + text = (SRC / "agent" / "harness" / "log.py").read_text(encoding="utf-8") + return sorted(set(re.findall(r'^[A-Z_]+ = "([a-z/]+)"', text, re.MULTILINE))) + + +def _extract_tool_names() -> list[str]: + names: set[str] = set() + for plugin in (SRC / "agent" / "harness" / "plugins").glob("*.py"): + text = plugin.read_text(encoding="utf-8") + names.update(re.findall(r'name="([a-z_]+)"', text)) + return sorted(names) + + +def _extract_sse_events() -> list[str]: + """Every literal published on the SSE bus, across the whole backend.""" + events: set[str] = set() + pattern = re.compile(r'(?:event_bus\.publish|publish_user_event)\(\s*\n?\s*"([a-z_.]+)"') + for py in SRC.rglob("*.py"): + text = py.read_text(encoding="utf-8") + events.update(pattern.findall(text)) + return sorted(events) + + +def _extract_prompt_profiles() -> list[str]: + text = (SRC / "comfyui" / "profiles.py").read_text(encoding="utf-8") if (SRC / "comfyui" / "profiles.py").exists() else "" + if not text: + # profiles may live elsewhere; fall back to the canonical two from AGENTS.md + return ["prose", "minimax_h3_ref"] + return sorted(set(re.findall(r'"(prose|minimax_h3_ref)"', text)) or {"prose", "minimax_h3_ref"}) + + +def _extract_guard_codes() -> list[str]: + text = (SRC / "agent" / "harness" / "__init__.py").read_text(encoding="utf-8") + return sorted(set(re.findall(r'GUARD_[A-Z_]+ = "([a-z_]+)"', text))) + + +def build_registry() -> dict[str, list[str]]: + return { + "input_roles": _extract_roles()["input"], + "output_roles": _extract_roles()["output"], + "agent_event_types": _extract_event_types(), + "agent_tool_names": _extract_tool_names(), + "sse_events": _extract_sse_events(), + "prompt_profiles": _extract_prompt_profiles(), + "guard_codes": _extract_guard_codes(), + } + + +def main() -> int: + registry = build_registry() + OUT.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + total = sum(len(v) for v in registry.values()) + print(f"wrote {OUT.relative_to(ROOT)} ({total} names)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/calliope-backend/skills_builtin/character-consistency/SKILL.md b/calliope-backend/skills_builtin/character-consistency/SKILL.md new file mode 100644 index 00000000..5e779de2 --- /dev/null +++ b/calliope-backend/skills_builtin/character-consistency/SKILL.md @@ -0,0 +1,49 @@ +--- +name: character-consistency +description: "Use when writing or improving character image prompts — sheets, portraits, and reference images that stay consistent across scenes." +version: 1.0.0 +license: MIT +metadata: + author: Calliope + tags: [characters, image, prompts, consistency] +--- + +# Character Consistency + +## Overview + +Pattern guide for the character **Image prompt** field (Assets) — the prompt +that generates the reference sheet all scene videos will reuse. Consistency is +decided here, not at video time. + +## When to Use + +- Creating a character whose look must hold across many scenes +- A generated sheet drifted (hair/clothing changes between generations) +- The user describes a character loosely and needs the prompt firmed up + +## Prompt Patterns + +1. **Anchor identity with stable traits first**: age range, build, hair color + and style, eye color, skin tone. These go early — image models weight + leading tokens heavily. +2. **One signature detail** that disambiguates this character from every other + in the project ("a faded scar across the left eyebrow", "always wears a + broken wristwatch"). Reuse the exact wording in every scene prompt. +3. **Clothing described as a set, not a list** — "a charcoal utility jacket + over a bone-white shirt, sleeves pushed to the forearm" beats five + comma-separated adjectives. +4. **Sheet intent in the prompt**: for the reference image say "character + reference sheet, front and side view, neutral pose, plain background" — + scenes want the identity, not the dramatic lighting. +5. **Negative prompt discipline**: put *contradictions* there (e.g. "multiple + people, text, watermark"), not style preferences you haven't stated + positively. + +## When Drift Happens + +- Compare the drifted artifact with the sheet: if the *sheet* is ambiguous + ("long hair" → curly vs straight), fix the sheet prompt and regenerate the + reference — scene prompts inherit the fix. +- If only one scene drifted, edit that scene's prompt instead (usually a + paraphrased identity phrase). diff --git a/calliope-backend/skills_builtin/h3-video-prompt-enhancer/README.md b/calliope-backend/skills_builtin/h3-video-prompt-enhancer/README.md new file mode 100644 index 00000000..27f1e0bf --- /dev/null +++ b/calliope-backend/skills_builtin/h3-video-prompt-enhancer/README.md @@ -0,0 +1,123 @@ +# 🎬 MiniMax H3 Video Prompt Agent Skill + +An agent skill (DSH / harness / file-based agents) that transforms rough video ideas + reference images/audio into production-grade **MiniMax H3** video generation prompts. + +## What It Does + +When you attach images, video, or audio and describe a video concept, this skill: + +1. **Detects the H3 mode** automatically (Ref2VA, T2VA, I2VA, FL2VA, L2VA) +2. **Creatively enhances** your idea across 7 cinematic dimensions +3. **Outputs the exact H3 format** — ready to paste into ComfyUI + +## H3 Modes Supported + +| Mode | Use Case | Output Format | +|---|---|---| +| **Ref2VA** | Character/style/voice reference assets | 6-section structured prompt | +| **T2VA** | Text-to-video (no images) | Timed multi-shot timeline | +| **I2VA** | 1 image as first frame | Instruction line + timeline | +| **FL2VA** | 2 images (first + last frame) | Instruction line + timeline | +| **L2VA** | 1 image as last frame | Instruction line + timeline | + +## Creative Enhancement Dimensions + +Every prompt is enriched across: + +- 🎥 **Camera Identity** — Physical camera type, imperfections, format aesthetic +- 🎨 **Visual Texture** — Grain, color palette, lighting design, exposure behavior +- ⚡ **Pacing Arc** — Energy progression, cut rhythm, build patterns +- 👤 **Character Detail** — Physical features, wardrobe, visual signature colors +- 🧭 **Spatial Geography** — Screen directions, action vectors, environmental layout +- 🔄 **Continuity Progression** — State tracking, damage accumulation, emotional arcs +- 🔊 **Sound Design** — Ambience, SFX, diegetic/non-diegetic music mapping + +## Installation + +### For DSH / file-based agents (this skill) + +Place the `h3-video-prompt-enhancer/` folder in your agent's skills directory so it auto-loads by name. In DSH the skill is invoked by its exact name (`h3-video-prompt-enhancer`); the harness injects `SKILL.md` as instructions when the task matches, and the `references/` files are loaded on demand via the read tool. + +``` +skills/ +└── h3-video-prompt-enhancer/ + ├── SKILL.md + └── references/... +``` + +Restart / refresh the agent's skill catalog if it does not appear. The skill auto-triggers when you attach media and describe a video idea. + +### For Any File-Based Agent (Claude, Codex, Hermes, etc.) + +The `SKILL.md` and reference files are standard Markdown — load them as system context or project rules in any agent that supports file-based instructions. + +## File Structure + +``` +h3-video-prompt-enhancer/ +├── README.md # You are here +├── SKILL.md # Main skill — workflow, rules, verification +└── references/ + ├── ref2va-format.md # Full Ref2VA 6-section format spec + ├── base-multishot-format.md # T2VA / I2VA / FL2VA / L2VA format spec + └── creative-showcase.md # Advanced long-form prompt patterns & benchmarks +``` + +## Usage Examples + +### Ref2VA (Character References) + +``` +📎 Attach: character_sheet.png, voice_sample.mp3 +💬 "A woman matching this character walks through a neon-lit Tokyo street at night, + stops at a ramen stand, says hi to the cook" +``` + +→ Outputs a 6-section structured prompt with `subject_definitions`, `summary`, `retention_analysis`, `detailed_description`, `overall_soundscape`, `non_diegetic_music`. + +### I2VA (Image-to-Video) + +``` +📎 Attach: first_frame.png +💬 "A baker opening his shop before sunrise, proud of the first loaf" +``` + +→ Outputs a timed multi-shot timeline anchored to the first-frame image. + +### FL2VA (First + Last Frame) + +``` +📎 Attach: first_frame.png, last_frame.png +💬 "Day to night transition over a city skyline" +``` + +→ Outputs a continuous interpolation prompt from first to last frame. + +## Key Format Rules + +- Output is **raw structured text** — no markdown fences, no preamble +- All timestamps use `MM:SS.mmm` format, strictly increasing +- One dominant action per shot — never cram multiple actions +- Camera motion written as natural English (e.g., *"The camera pushes in with small amplitude at slow speed"*) +- Dialogue preserved verbatim inside `[Language] ...` tags +- Reference labels (``, ``, `