Add tabbed video ref picker, stricter agent HITL, and item attach.

Playground creates a new misc. item instead of overwriting one; item generate jobs persist the image path. Notes in docs/changelogs/2026-08-23.md.
This commit is contained in:
Benjiyaya
2026-08-24 04:29:49 +08:00
parent e87a7d3180
commit 71bed77095
30 changed files with 1584 additions and 350 deletions
@@ -9,9 +9,13 @@ individual plugins.
from __future__ import annotations
import logging
import re
from calliope.agent.harness.plugins import load_all as _load_plugins
from calliope.agent.harness.policy import (
is_confirmation,
is_render_request,
user_allows_render,
)
from calliope.agent.harness.prompts import (
SystemPromptService,
register_builtin_sections,
@@ -27,38 +31,9 @@ from calliope.agent.harness.registry import (
logger = logging.getLogger("calliope.harness")
# Affirmation / destructive-intent cues used to recognise an explicit user
# "yes" (or "replace it" / "start over" request) for the destructive guard.
_CONFIRM_RE = re.compile(
r"\b(yes|yeah|yep|yup|sure|ok|okay|k|confirm(?:ed)?|proceed|"
r"go\s+ahead|do\s+it|please\s+do|overwrite|replace|regenerate|"
r"redo|re-?do|start\s+over|restart|delete|wipe|reset|from\s+scratch|"
r"go\s+for\s+it|fine|sounds\s+good|that'?s\s+fine)\b",
re.IGNORECASE,
)
_NEGATE_RE = re.compile(
r"\b(no|not|don'?t|do\s+not|cancel|stop|never|abort|skip|hold\s+on|wait)\b",
re.IGNORECASE,
)
# Image/video *generation* intent cues, used by the render-approval guard. We
# deliberately avoid a bare "generate" (which would also match "generate the
# story") — only unambiguous render words unlock generation.
_RENDER_REQUEST_RE = re.compile(
r"\b(render\w*|image\w*|video\w*|portrait\w*|sheet\w*|artwork\w*|visual\w*|thumbnail\w*)\b",
re.IGNORECASE,
)
def _is_confirmation(text: str) -> bool:
"""A terse, non-negated message carrying an explicit affirmative cue."""
t = (text or "").strip()
if not t or len(t) > 200:
return False
if _NEGATE_RE.search(t):
return False
return bool(_CONFIRM_RE.search(t))
# Re-exports for tests / older imports.
_is_confirmation = is_confirmation
_is_render_request = is_render_request
def _user_confirmed_replacement(ctx: ToolContext) -> bool:
@@ -66,15 +41,7 @@ def _user_confirmed_replacement(ctx: ToolContext) -> bool:
destructive replace (derived from the event log — no separate state)."""
from calliope.agent.harness import log as session_log
return _is_confirmation(session_log.latest_user_message(ctx.session_id) or "")
def _is_render_request(text: str) -> bool:
"""True when the message explicitly asks for image/video generation."""
t = (text or "").strip()
if not t or _NEGATE_RE.search(t):
return False
return bool(_RENDER_REQUEST_RE.search(t))
return is_confirmation(session_log.latest_user_message(ctx.session_id) or "")
def _render_approval_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> PreExecuteDecision:
@@ -90,10 +57,7 @@ def _render_approval_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> P
"""
if not t.requires_approval:
return allow()
from calliope.agent.harness import log as session_log
latest = session_log.latest_user_message(ctx.session_id) or ""
if _is_render_request(latest) or _is_confirmation(latest):
if user_allows_render(ctx):
return allow()
return deny(
"Image/video generation is human-in-the-loop and needs explicit user approval. "
@@ -146,7 +146,11 @@ def latest_user_message(session_id: int) -> str | None:
except (json.JSONDecodeError, TypeError):
return None
content = data.get("content")
return content.strip() if isinstance(content, str) else None
if not isinstance(content, str):
return None
# Never treat the machine appendix as user intent (kind=image, etc.).
prose = content.split("[Calliope context]", 1)[0].strip()
return prose or None
finally:
conn.close()
@@ -60,6 +60,7 @@ ROLE_TOOLS: dict[str, list[str]] = {
"list_workflows",
"run_workflow",
"enqueue_video_jobs",
"attach_asset",
"list_jobs",
"get_job_status",
"wait_for_jobs",
@@ -84,7 +85,8 @@ Respond with ONLY a JSON object:
Rules:
- The standard EDIT pipeline (story → script → add/update assets text) is swarm work: one task per role, in that order.
- Image/video GENERATION is human-in-the-loop: only include assets/video RENDER tasks (enqueue_asset_jobs / enqueue_video_jobs / run_workflow) when the user explicitly asked to generate. For text-only edits (add/update characters, locations, items, scenes, story, script), schedule the edit task and DO NOT schedule render tasks.
- A tagged-workflow generate ([Calliope context] with workflow_id=) is a SIMPLE request — reply {"mode": "single"} so the main loop can call run_workflow.
- Film clips: video sub-agent must enqueue_video_jobs with orders (#N on Video) or scene_ids from list_scenes — ONLY the clips the user named. Never dump every scene_id. Never add_scene to attach a generated mp4. Orphan jobs (scene_id null) do not show on the Video timeline.
- A tagged workflow ([Calliope context] with workflow_id=) is a SIMPLE request — reply {"mode": "single"}. The main loop may call run_workflow only if the user asked to generate; tagging alone is not permission. Linked-film video still needs scene_id.
- Tasks run in the order you list them. Later tasks can use earlier results.
- Keep task goals concrete and self-contained; each sub-agent sees the project state fresh.
- 2-4 tasks typical. Never more than 6.
@@ -96,11 +98,7 @@ def _scoped_payload(ctx: ToolContext, allowed: list[str]) -> list[dict[str, Any]
out: list[dict[str, Any]] = []
for n in allowed:
t = registry.get(n)
if t is None:
continue
if t.requires_project and ctx.project_id is None:
continue
if t.blind_only and ctx.project_id is not None:
if t is None or not registry._visible(t, ctx):
continue
out.append(
{
@@ -382,8 +380,12 @@ async def _run_sub_agent(
"summary when done — no tool call.\n"
"Image/video generation (enqueue_asset_jobs / enqueue_video_jobs / "
"run_workflow) is human-in-the-loop: only call it when the user "
"explicitly asked to generate. For a [Calliope context] workflow_id=, "
"call run_workflow. For text-only edits, do the edit and stop."
"explicitly asked to generate. A workflow_id= appendix is not "
"permission. There is no MCP run_workflow. Film clips: "
"enqueue_video_jobs with orders (Video #N) or scene_ids from "
"list_scenes — only the clips they named, never the whole timeline. "
"Never add_scene to attach an mp4. For text-only edits, "
"do the edit and stop."
)
hardening = hardening_text()
if hardening:
@@ -57,20 +57,33 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="enqueue_video_jobs",
description=(
"Queue video clip generation for scenes (ComfyUI video jobs with "
"reference images wired automatically). Reference-based "
"workflows need character sheets / location images to EXIST "
"first — check get_workspace (✓img marks) and "
"enqueue_asset_jobs + wait_for_jobs before this. Omit scene_ids "
"to render all scenes."
"Queue video clip generation for SPECIFIC scenes. Users say "
"'#25' / 'scene 25' meaning Video-page order — pass those as "
"orders, or list_scenes.scene_id as scene_ids. NEVER dump every "
"scene_id. NEVER omit the target list (that used to mean 'all' "
"and flooded the queue). Set all_scenes=true ONLY when the user "
"explicitly asked for every clip. More than 3 clips is blocked "
"unless they said all/every/entire."
),
parameters={
"type": "object",
"properties": {
"orders": {
"type": "array",
"items": {"type": "integer"},
"description": (
"Video page clip numbers (#1, #25). Preferred when "
"the user names scenes by #."
),
},
"scene_ids": {
"type": "array",
"items": {"type": "integer"},
"description": "Real scene ids from list_scenes; omit for all",
"description": "Database ids from list_scenes.scene_id — not #N",
},
"all_scenes": {
"type": "boolean",
"description": "True only if the user asked to render every clip",
},
"workflow_id": {
"type": "integer",
@@ -87,13 +100,15 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="run_workflow",
description=(
"Queue a Calliope ComfyUI workflow. Works in sandbox AND linked "
"sessions. Sandbox jobs go to the hidden Playground scratch — "
"do NOT create_project just to generate. Use this when the user "
"message has a [Calliope context] appendix with workflow_id= "
"(from an @workflow mention). Do NOT call list_workflows to "
"guess the id. Call comfy_server_info first. prompt lands on "
"(Input:prompt). "
"Queue a Calliope ComfyUI workflow. Sandbox jobs go to Playground "
"scratch. Linked-film VIDEO clips MUST pass scene_id (from "
"list_scenes) — the worker then writes scenes.video_path. Prefer "
"enqueue_video_jobs for one or more scenes. A video job without "
"scene_id will NOT appear on the Video timeline. "
"Use this when the user message has a [Calliope context] "
"appendix with workflow_id= (from an @workflow mention). Do NOT "
"call list_workflows to guess the id. Call comfy_server_info "
"first. prompt lands on (Input:prompt). "
"width/height fill (Input:width)/(Input:height) by role. "
"attachments are ordered local paths for (Input:image) / "
"(Input:character) slots. Aspect ratio in the user's prose "
@@ -108,6 +123,13 @@ def register(registry: ToolRegistry) -> None:
"type": "integer",
"description": "Calliope workflow id from [Calliope context]",
},
"scene_id": {
"type": "integer",
"description": (
"Required for video on a linked film — real scene id "
"from list_scenes. Omit in sandbox / image generates."
),
},
"prompt": {
"type": "string",
"description": "Text for the (Input:prompt) node",
@@ -211,13 +233,13 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="attach_asset",
description=(
"Add a generated image (from a job_id or a local path) to a "
"project as a character sheet, environment, or misc. item. "
"Works in sandbox — do not create_project just to file an "
"image. Call list_projects first if the user named a film. "
"Pass an existing character_id / location_id / item_id, or "
"a name (matches an existing entity case-insensitively, "
"otherwise creates one). job_id should be the "
"Add a generated file to a project: image as character sheet / "
"environment / misc. item, or a video clip onto an existing "
"scene (target=scene). Works in sandbox — do not create_project "
"just to file a generate. Call list_projects first if the user "
"named a film. For images: character_id / location_id / item_id "
"or a name. For scene clips: scene_id from list_scenes (never "
"add_scene to 'fix' a missing clip). job_id should be the "
"run_workflow / Playground job that produced the file."
),
parameters={
@@ -237,12 +259,16 @@ def register(registry: ToolRegistry) -> None:
},
"target": {
"type": "string",
"enum": ["character_sheet", "location", "item"],
"description": "Where to file the image",
"enum": ["character_sheet", "location", "item", "scene"],
"description": "Where to file the generate",
},
"character_id": {"type": "integer"},
"location_id": {"type": "integer"},
"item_id": {"type": "integer"},
"scene_id": {
"type": "integer",
"description": "Existing scene id when target=scene",
},
"name": {
"type": "string",
"description": "Entity name — updates a match, or creates if none",
@@ -301,18 +327,94 @@ async def t_enqueue_asset_jobs(ctx: ToolContext, args: dict[str, Any]) -> dict[s
return {"jobs": jobs, "count": len(jobs)}
def _int_list(raw: Any) -> list[int]:
out: list[int] = []
for x in raw or []:
try:
out.append(int(x))
except (TypeError, ValueError):
continue
return out
async def t_enqueue_video_jobs(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
from calliope.agent.harness import log as session_log
from calliope.agent.harness.plugins.script import resolve_scene_ref
from calliope.agent.harness.policy import allows_bulk_video_enqueue
from calliope.agent.video_agent import enqueue_video_jobs as _enqueue
scene_ids = _int_list(args.get("scene_ids"))
orders = _int_list(args.get("orders"))
all_scenes = bool(args.get("all_scenes"))
latest = session_log.latest_user_message(ctx.session_id) or ""
resolved: list[int] = []
if orders or scene_ids:
conn = _db()
try:
for sid in scene_ids:
found, err = resolve_scene_ref(conn, ctx.project_id, scene_id=sid)
if err:
return {"ok": False, "error": err}
resolved.append(found)
for order in orders:
found, err = resolve_scene_ref(conn, ctx.project_id, order=order)
if err:
return {"ok": False, "error": err}
resolved.append(found)
finally:
conn.close()
# Preserve order, drop dupes.
seen: set[int] = set()
unique: list[int] = []
for sid in resolved:
if sid not in seen:
seen.add(sid)
unique.append(sid)
resolved = unique
elif all_scenes:
conn = _db()
try:
rows = conn.execute(
"SELECT id FROM scenes WHERE project_id = ? ORDER BY order_index",
(ctx.project_id,),
).fetchall()
resolved = [int(r["id"]) for r in rows]
finally:
conn.close()
else:
return {
"ok": False,
"error": (
"Say which clips: pass orders (Video page #N) or scene_ids "
"from list_scenes. Do not enqueue the whole timeline. "
"all_scenes=true only when the user asked for every clip."
),
}
if not resolved:
return {"ok": False, "error": "No matching scenes to enqueue"}
allowed_bulk = allows_bulk_video_enqueue(latest, len(resolved))
if not allowed_bulk:
return {
"ok": False,
"error": (
f"Blocked: {len(resolved)} clips is a bulk render. Users usually "
"mean the #N they named (2–3 clips). Pass only those orders, or "
"wait until they say all scenes / every clip / the entire film."
),
}
try:
jobs = await _enqueue(
ctx.project_id,
scene_ids=args.get("scene_ids"),
scene_ids=resolved,
workflow_id=args.get("workflow_id"),
)
except ValueError as exc:
return {"ok": False, "error": str(exc)}
return {"jobs": jobs, "count": len(jobs)}
return {"jobs": jobs, "count": len(jobs), "scene_ids": resolved}
_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}
@@ -385,6 +487,55 @@ async def t_run_workflow(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
finally:
conn.close()
scene_id: int | None = None
raw_scene = args.get("scene_id")
if raw_scene is not None and str(raw_scene).strip() != "":
try:
scene_id = int(raw_scene)
except (TypeError, ValueError):
return {"ok": False, "error": "scene_id must be an integer from list_scenes"}
# Linked-film video must be a scene job. Orphans (scene_id NULL) finish in
# the queue but never write scenes.video_path — the clip is preview-only.
if kind == "video" and ctx.project_id is not None:
if scene_id is None:
return {
"ok": False,
"error": (
"Linked-film video requires scene_id from list_scenes. "
"Prefer enqueue_video_jobs. Do not add_scene to attach a clip."
),
}
conn = _db()
try:
scene = conn.execute(
"SELECT id FROM scenes WHERE id = ? AND project_id = ?",
(scene_id, int(ctx.project_id)),
).fetchone()
finally:
conn.close()
if not scene:
return {"ok": False, "error": f"Scene {scene_id} not found in this project"}
from calliope.agent.video_agent import enqueue_video_jobs as _enqueue
try:
jobs = await _enqueue(
int(ctx.project_id),
scene_ids=[scene_id],
workflow_id=workflow_id,
)
except ValueError as exc:
return {"ok": False, "error": str(exc)}
return {
"jobs": [_sc_job_dict_lite(j) for j in jobs],
"count": len(jobs),
"workflow_id": workflow_id,
"workflow_name": wf_name,
"sandbox": False,
"wired_to_scene": True,
"scene_id": scene_id,
}
raw_paths = [str(p) for p in (args.get("attachments") or []) if p]
safe_paths, path_err = _sandbox_attachment_paths(raw_paths)
if path_err:
@@ -440,6 +591,7 @@ async def t_run_workflow(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
"workflow_id": workflow_id,
"workflow_name": wf_name,
"sandbox": sandbox,
"wired_to_scene": False,
}
@@ -473,8 +625,8 @@ async def t_attach_asset(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
from calliope.routers.playground import PLAYGROUND_STATUS
target = str(args.get("target") or "")
if target not in ("character_sheet", "location", "item"):
return {"ok": False, "error": "target must be character_sheet, location, or item"}
if target not in ("character_sheet", "location", "item", "scene"):
return {"ok": False, "error": "target must be character_sheet, location, item, or scene"}
project_id = args.get("project_id")
if project_id is None:
@@ -571,7 +723,7 @@ async def t_attach_asset(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
row = conn.execute("SELECT * FROM locations WHERE id = ?", (cur.lastrowid,)).fetchone()
entity = row_to_dict(row)
entity["reference_image_path"] = path
else:
elif target == "item":
iid = args.get("item_id")
row = None
if iid is not None:
@@ -599,6 +751,30 @@ async def t_attach_asset(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
row = conn.execute("SELECT * FROM items WHERE id = ?", (cur.lastrowid,)).fetchone()
entity = row_to_dict(row)
entity["reference_image_path"] = path
else:
sid = args.get("scene_id")
if sid is None:
return {"ok": False, "error": "scene_id is required for target=scene — list_scenes, never add_scene"}
row = conn.execute(
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
(int(sid), project_id),
).fetchone()
if not row:
return {"ok": False, "error": f"Scene {sid} not found in this project"}
conn.execute(
"UPDATE scenes SET video_path = ? WHERE id = ?",
(path, int(sid)),
)
job_id = args.get("job_id")
if job_id is not None:
conn.execute(
"UPDATE jobs SET scene_id = ? WHERE id = ? AND scene_id IS NULL",
(int(sid), int(job_id)),
)
created = False
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (int(sid),)).fetchone()
entity = row_to_dict(row)
entity["video_path"] = path
conn.execute(
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
@@ -642,6 +818,7 @@ def _sc_job_dict_lite(job: dict[str, Any]) -> dict[str, Any]:
"kind": job["kind"],
"status": job["status"],
"scene_id": job.get("scene_id"),
"wired_to_scene": bool(job.get("scene_id")),
"error": job.get("error"),
"output_paths": paths or [],
}
@@ -12,6 +12,58 @@ from calliope.agent.harness.registry import (
from calliope.db import row_to_dict
def annotate_scene_row(s: dict[str, Any]) -> dict[str, Any]:
"""Label user-facing clip # vs database scene_id. #N on Video is order."""
oid = int(s["id"])
order = int(s.get("order_index") or 0)
s["scene_id"] = oid
s["order"] = order
s["clip"] = f"#{order}"
return s
def resolve_scene_ref(
conn,
project_id: int,
*,
scene_id: Any = None,
order: Any = None,
) -> tuple[int | None, str | None]:
"""Resolve one scene. `order` is the Video page #N; `scene_id` is the DB id."""
if scene_id is not None and str(scene_id).strip() != "":
try:
sid = int(scene_id)
except (TypeError, ValueError):
return None, "scene_id must be an integer from list_scenes"
row = conn.execute(
"SELECT id FROM scenes WHERE id = ? AND project_id = ?",
(sid, project_id),
).fetchone()
if not row:
return None, (
f"Scene {sid} not found in this project. "
"That number is not the #N on the Video page — list_scenes "
"and use scene_id or order."
)
return int(row["id"]), None
if order is not None and str(order).strip() != "":
try:
num = int(order)
except (TypeError, ValueError):
return None, "order must be the clip number from the Video page (#1, #25)"
row = conn.execute(
"SELECT id FROM scenes WHERE project_id = ? AND order_index = ?",
(project_id, num),
).fetchone()
if not row:
return None, (
f"No clip #{num} in this project. "
"Users say #N for order (list_scenes.order / clip), not scene_id."
)
return int(row["id"]), None
return None, "Pass scene_id (database id) or order (Video page #N)"
def register(registry: ToolRegistry) -> None:
registry.register(
ToolDefinition(
@@ -41,10 +93,26 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="list_scenes",
description=(
"List the linked project's scenes in order with their real ids, "
"cast, and location — the source of truth for scene_id arguments."
"List or search scenes. EACH row has scene_id (database id) AND "
"order / clip (#N on the Video page). Users say '#25' or "
"'scene 25' meaning order=25 — NEVER treat that as scene_id. "
"Optional query (heading/action text) or orders (clip numbers) "
"to search without dumping the whole timeline."
),
parameters={"type": "object", "properties": {}},
parameters={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Optional heading/action search (user words)",
},
"orders": {
"type": "array",
"items": {"type": "integer"},
"description": "Video page clip numbers (#1, #25) — not scene_id",
},
},
},
executor=t_list_scenes,
category="script",
)
@@ -53,15 +121,20 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="update_scene",
description=(
"Update one existing scene. scene_id must come from list_scenes "
"or get_workspace — never guess it. Pass only the fields to change."
"Update one existing scene. Identify it with scene_id "
"(list_scenes.scene_id) OR order (Video page #N). Never guess. "
"Pass only the fields to change."
),
parameters={
"type": "object",
"properties": {
"scene_id": {
"type": "integer",
"description": "Real id from list_scenes/get_workspace",
"description": "Database id from list_scenes — not the #N on Video",
},
"order": {
"type": "integer",
"description": "Clip number from the Video page (#25 → 25)",
},
"heading": {"type": "string"},
"action": {"type": "string"},
@@ -74,7 +147,6 @@ def register(registry: ToolRegistry) -> None:
"description": "Replace the scene's character cast",
},
},
"required": ["scene_id"],
},
executor=t_update_scene,
category="script",
@@ -115,14 +187,21 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="delete_scene",
description=(
"Delete a scene permanently. scene_id must come from list_scenes. "
"Prefer update_scene for content changes; use this only when the "
"user wants the scene gone."
"Delete a scene permanently. Identify with scene_id or order "
"(Video page #N). Prefer update_scene for content changes."
),
parameters={
"type": "object",
"properties": {"scene_id": {"type": "integer"}},
"required": ["scene_id"],
"properties": {
"scene_id": {
"type": "integer",
"description": "Database id from list_scenes",
},
"order": {
"type": "integer",
"description": "Clip number from the Video page (#N)",
},
},
},
executor=t_delete_scene,
category="script",
@@ -170,7 +249,25 @@ async def t_list_scenes(ctx: ToolContext, args: dict[str, Any]) -> list[dict[str
rows = conn.execute(
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index", (ctx.project_id,)
).fetchall()
scenes = [row_to_dict(r) for r in rows]
scenes = [annotate_scene_row(row_to_dict(r)) for r in rows]
raw_orders = args.get("orders") or []
if raw_orders:
want = set()
for x in raw_orders:
try:
want.add(int(x))
except (TypeError, ValueError):
continue
scenes = [s for s in scenes if int(s.get("order") or 0) in want]
query = str(args.get("query") or "").strip().lower()
if query:
scenes = [
s
for s in scenes
if query in (s.get("heading") or "").lower()
or query in (s.get("action") or "").lower()
or query in (s.get("dialog") or "").lower()
]
for s in scenes:
chars = conn.execute(
"""
@@ -189,7 +286,14 @@ async def t_list_scenes(ctx: ToolContext, args: dict[str, Any]) -> list[dict[str
async def t_update_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
conn = _db()
try:
scene_id = int(args["scene_id"])
scene_id, err = resolve_scene_ref(
conn,
ctx.project_id,
scene_id=args.get("scene_id"),
order=args.get("order"),
)
if err:
return {"ok": False, "error": err}
existing = conn.execute(
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
(scene_id, ctx.project_id),
@@ -248,7 +352,7 @@ async def t_update_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
(scene_id, ctx.project_id),
).fetchone()
return {"scene": row_to_dict(row)}
return {"scene": annotate_scene_row(row_to_dict(row))}
finally:
conn.close()
@@ -319,7 +423,7 @@ async def t_add_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
)
conn.commit()
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
return {"scene": row_to_dict(row)}
return {"scene": annotate_scene_row(row_to_dict(row))}
finally:
conn.close()
@@ -327,7 +431,14 @@ async def t_add_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
async def t_delete_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
conn = _db()
try:
scene_id = int(args["scene_id"])
scene_id, err = resolve_scene_ref(
conn,
ctx.project_id,
scene_id=args.get("scene_id"),
order=args.get("order"),
)
if err:
return {"ok": False, "error": err}
cur = conn.execute(
"DELETE FROM scenes WHERE id = ? AND project_id = ?", (scene_id, ctx.project_id)
)
@@ -356,6 +467,6 @@ async def t_reorder_scenes(ctx: ToolContext, args: dict[str, Any]) -> dict[str,
"SELECT id, order_index, heading FROM scenes WHERE project_id = ? ORDER BY order_index",
(ctx.project_id,),
).fetchall()
return {"scenes": [row_to_dict(r) for r in rows]}
return {"scenes": [annotate_scene_row(row_to_dict(r)) for r in rows]}
finally:
conn.close()
@@ -0,0 +1,91 @@
"""HITL / confirmation policy — used by guards and tool-payload filtering.
Kept out of ``__init__`` / ``registry`` so those modules can import this
without a cycle. Intent is always derived from the latest user prose, never
from the machine ``[Calliope context]`` appendix.
"""
from __future__ import annotations
import re
from calliope.agent.harness.registry import ToolContext
# Affirmation / destructive-intent cues for an explicit user "yes"
# (or "replace it" / "start over") for the destructive guard.
_CONFIRM_RE = re.compile(
r"\b(yes|yeah|yep|yup|sure|ok|okay|k|confirm(?:ed)?|proceed|"
r"go\s+ahead|do\s+it|please\s+do|overwrite|replace|regenerate|"
r"redo|re-?do|start\s+over|restart|delete|wipe|reset|from\s+scratch|"
r"go\s+for\s+it|fine|sounds\s+good|that'?s\s+fine)\b",
re.IGNORECASE,
)
_NEGATE_RE = re.compile(
r"\b(no|not|don'?t|do\s+not|cancel|stop|never|abort|skip|hold\s+on|wait)\b",
re.IGNORECASE,
)
# Image/video *generation* intent. A bare "generate" is skipped on purpose
# (it would also match "generate the story").
_RENDER_REQUEST_RE = re.compile(
r"\b(render\w*|image\w*|video\w*|portrait\w*|sheet\w*|artwork\w*|visual\w*|thumbnail\w*)\b",
re.IGNORECASE,
)
_APPENDIX_MARK = "[Calliope context]"
def user_prose(text: str) -> str:
"""Visible user words only — drop a trailing Calliope context appendix."""
raw = text or ""
if _APPENDIX_MARK in raw:
raw = raw.split(_APPENDIX_MARK, 1)[0]
return raw.strip()
def is_confirmation(text: str) -> bool:
"""A terse, non-negated message carrying an explicit affirmative cue."""
t = user_prose(text)
if not t or len(t) > 200:
return False
if _NEGATE_RE.search(t):
return False
return bool(_CONFIRM_RE.search(t))
def is_render_request(text: str) -> bool:
"""True when the message explicitly asks for image/video generation."""
t = user_prose(text)
if not t or _NEGATE_RE.search(t):
return False
return bool(_RENDER_REQUEST_RE.search(t))
# More than this many clips needs an explicit "all scenes / every clip" in
# the latest user prose. A bare "yes" after a 2-clip offer must not enqueue
# the whole timeline (the model has dumped every scene_id before).
BULK_ENQUEUE_LIMIT = 3
_BULK_VIDEO_RE = re.compile(
r"\b("
r"all(\s+the)?\s+(scenes?|clips?|videos?|shots?)"
r"|every\s+(scene|clip|shot)"
r"|entire\s+(film|project|script|timeline)"
r"|whole\s+(film|project|script)"
r"|all\s+remaining"
r")\b",
re.IGNORECASE,
)
def allows_bulk_video_enqueue(text: str, count: int) -> bool:
"""True when `count` clips is a small targeted batch, or the user asked for all."""
if count <= BULK_ENQUEUE_LIMIT:
return True
return bool(_BULK_VIDEO_RE.search(user_prose(text)))
def user_allows_render(ctx: ToolContext) -> bool:
"""Latest user prose asks to generate, or tersely confirms an offer."""
from calliope.agent.harness import log as session_log
latest = session_log.latest_user_message(ctx.session_id) or ""
return is_render_request(latest) or is_confirmation(latest)
@@ -83,9 +83,10 @@ def _mode_text(ctx: ToolContext) -> str:
return (
"SESSION MODE: SANDBOX — no project is linked yet.\n"
"- You can brainstorm and discuss ideas freely.\n"
"- Tagged @workflow generates: call run_workflow directly. Do NOT "
"create_project or link_project for an image/video generate. The "
"session stays sandbox; jobs land on the hidden Playground scratch.\n"
"- Tagged @workflow + the user asked to generate/render: call "
"run_workflow (Playground scratch). Do NOT create_project or "
"link_project just for an image. If they only tagged a workflow "
"while drafting text, do NOT call run_workflow — offer and wait.\n"
"- To file a generated image onto an existing film: list_projects, "
"then attach_asset with that project_id + job_id (or path) and a "
"target (character_sheet / location / item). Do not create_project "
@@ -104,8 +105,17 @@ def _mode_text(ctx: ToolContext) -> str:
"project id.\n"
"- scene_id / character_id / location_id / job_id / workflow_id are "
"REAL numeric ids from tool results — never invent them.\n"
"- Video page #N is order (clip number), NOT scene_id. list_scenes "
"returns clip=#N, order, and scene_id. Users say 'scene 25' / '#25' "
"meaning order=25 — pass enqueue_video_jobs.orders=[25] or "
"update_scene.order=25. Never treat a # as a database id.\n"
"- To file a generated image onto a character, environment, or item: "
"attach_asset with job_id (or path) and a name or entity id."
"attach_asset with job_id (or path) and a name or entity id.\n"
"- Film clips: enqueue_video_jobs with orders or scene_ids for ONLY "
"the clips they named. Never dump every scene_id. Never omit the "
"list (that is not 'all'). all_scenes=true only if they said all/"
"every clip. Orphan video jobs (wired_to_scene=false) use "
"attach_asset target=scene + scene_id."
)
@@ -177,7 +187,8 @@ def _render_digest(p, stats, beats, chars, locs, scenes, pending) -> str:
lines.append(f"locations: {ready}")
if scenes:
s = " ".join(
f"#{sc['id']}:'{sc['heading']}'{'✓vid' if sc['video_path'] else '✗vid'}"
f"#{sc['order_index']} id={sc['id']}:'{sc['heading']}'"
f"{'✓vid' if sc['video_path'] else '✗vid'}"
for sc in scenes[:15]
)
lines.append(f"scenes: {s}" + (" …" if len(scenes) > 15 else ""))
@@ -206,15 +217,29 @@ async def _tool_discipline_section(ctx: ToolContext) -> str | None:
"Text edits — add_item, add_character, add_location, update_scene, "
"generate_story, generate_script, etc. — are NOT permission to render. "
"After text edits, if images/videos are missing, tell the user and ASK "
"whether to generate; wait for their yes. Also call comfy_server_info "
"first; if ComfyUI is unreachable or dry_run is on, say so and stop.\n"
"4b. NO COMFY MCP. There are no comfy_run_workflow / comfy_run_template / "
"comfy_search_templates / comfy_list_saved_workflows tools. The only "
"comfy_* tool is comfy_server_info (health). Generate with run_workflow "
"(tagged @workflow) or enqueue_asset_jobs / enqueue_video_jobs.\n"
"whether to generate; wait for their yes — do not call run_workflow in "
"the same turn as the question. Render tools are hidden until they ask. "
"Also call comfy_server_info first; if ComfyUI is unreachable or dry_run "
"is on, say so and stop.\n"
"4b. NO COMFY MCP. There is no MCP run_workflow / comfy_run_workflow / "
"comfy_run_template / comfy_search_templates. The only comfy_* tool is "
"comfy_server_info (health). Calliope run_workflow is the HTTP queue "
"(tagged @workflow), not MCP. Use enqueue_asset_jobs / enqueue_video_jobs "
"for project assets and clips.\n"
"5. ASSETS BEFORE VIDEO: reference-based video needs character sheets "
"and location images to exist. After enqueue_asset_jobs, wait_for_jobs "
"and only enqueue_video_jobs once images are ready.\n"
"5b. SCENE CLIPS ARE WIRED IN CODE. On a linked film, video generate "
"must be enqueue_video_jobs (orders=#N or scene_ids) or run_workflow "
"with scene_id from list_scenes. The worker writes scenes.video_path "
"from job.scene_id. Do not add_scene to 'fix' a missing clip. If "
"wait_for_jobs returns wired_to_scene=false, call attach_asset "
"target=scene with that job_id and the existing scene_id.\n"
"5c. #N IS ORDER. The Video page shows #1, #2… as order_index. "
"scene_id is a different, larger database id. list_scenes / "
"update_scene / delete_scene / enqueue_video_jobs accept order so "
"you can follow the user. Search with list_scenes query= or "
"orders=[25,26]. Never enqueue more clips than they named.\n"
"6. Standard EDIT pipeline (text only, no renders): create_project → "
"generate_story → generate_script → add/update assets (characters, "
"locations, items) as needed. Rendering is a SEPARATE step that only "
@@ -227,15 +252,14 @@ async def _tool_discipline_section(ctx: ToolContext) -> str | None:
async def _mentions_section(ctx: ToolContext) -> str | None:
return (
"Tagged workflows: when the user message includes a [Calliope context] "
"appendix with workflow_id=, call run_workflow with that id (plus the "
"user's prompt, width/height from any stated aspect ratio, and attached "
"paths). There is at most ONE tagged workflow per user message — if "
"several workflow_id= lines appear, use the first and ignore the rest. "
"Do not guess the workflow from list_workflows. In a sandbox session "
"call run_workflow immediately — do not create_project just to "
"generate. Video file attachments are context only (the worker "
"uploads image + audio refs)."
"Tagged workflows: a [Calliope context] appendix with workflow_id= "
"names the Calliope graph. It is NOT render permission and there is "
"no MCP run_workflow. Only call Calliope run_workflow when the user's "
"own words ask to generate (or they confirm an offer). Then use that "
"id plus prompt / aspect / attachments — do not list_workflows guess. "
"One tagged workflow per message (first id wins). Sandbox: do not "
"create_project just to generate. Video file attachments are context "
"only (the worker uploads image + audio refs)."
)
@@ -120,6 +120,14 @@ class ToolRegistry:
return False
if t.blind_only and ctx.project_id is not None:
return False
# Hide render tools until the user asks — the model still "knows"
# run_workflow from earlier turns, but a missing tool is harder to
# call than one that only fails in pre-execute (HITL cards).
if t.requires_approval:
from calliope.agent.harness.policy import user_allows_render
if not user_allows_render(ctx):
return False
return True
def openai_payload(self, ctx: ToolContext) -> list[dict[str, Any]]:
@@ -367,6 +367,12 @@ class QueueWorker:
).fetchone()
name = row["name"] if row else f"#{payload['location_id']}"
return f"{name} · environment"
if payload.get("item_id"):
row = conn.execute(
"SELECT name FROM items WHERE id = ?", (payload["item_id"],)
).fetchone()
name = row["name"] if row else f"#{payload['item_id']}"
return f"{name} · item"
if job.get("scene_id"):
row = conn.execute(
"SELECT heading, order_index FROM scenes WHERE id = ?", (job["scene_id"],)
@@ -387,6 +393,7 @@ class QueueWorker:
primary = paths[0]
character_id = payload.get("character_id")
location_id = payload.get("location_id")
item_id = payload.get("item_id")
scene_id = job.get("scene_id")
conn = get_db(config.settings.db_path)
try:
@@ -408,6 +415,11 @@ class QueueWorker:
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
(primary, location_id),
)
if item_id:
conn.execute(
"UPDATE items SET reference_image_path = ? WHERE id = ?",
(primary, item_id),
)
if scene_id and job["kind"] == "video":
conn.execute(
"UPDATE scenes SET video_path = ? WHERE id = ?",
@@ -12,6 +12,7 @@ from fastapi import APIRouter, File, HTTPException, UploadFile
from pydantic import BaseModel, Field
from calliope import config
from calliope.agent.prompts import item_reference_prompt
from calliope.db import get_db, row_to_dict
from calliope.events.bus import event_bus
from calliope.queue.manager import queue_manager
@@ -30,10 +31,12 @@ class PlaygroundGenerate(BaseModel):
class PlaygroundAttach(BaseModel):
path: str
project_id: int
target: Literal["character_sheet", "location", "scene"]
target: Literal["character_sheet", "location", "item", "scene"]
character_id: int | None = None
location_id: int | None = None
item_id: int | None = None # ignored: items always insert a new row
scene_id: int | None = None
name: str | None = None
def _job_public(job: dict[str, Any]) -> dict[str, Any]:
@@ -147,6 +150,10 @@ def _clear_entity_refs(conn, paths: list[str]) -> None:
"UPDATE locations SET reference_image_path = NULL WHERE reference_image_path = ?",
(path,),
)
conn.execute(
"UPDATE items SET reference_image_path = NULL WHERE reference_image_path = ?",
(path,),
)
conn.execute("UPDATE scenes SET video_path = NULL WHERE video_path = ?", (path,))
@@ -360,6 +367,27 @@ async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]:
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
(path, payload.location_id),
)
elif payload.target == "item":
# Always insert a new misc. item — Playground attach must not
# overwrite an existing project item (item_id is ignored).
raw_name = (payload.name or "").strip()
if not raw_name:
stem = Path(path).stem
raw_name = stem.split("-", 1)[-1] if len(stem) > 9 and stem[8:9] == "-" else stem
name = raw_name or "Playground item"
consistency = item_reference_prompt(
{"name": name, "description": "Added from Playground"}
)
cur = conn.execute(
"""
INSERT INTO items (
project_id, name, description, consistency_prompt, reference_image_path
)
VALUES (?, ?, ?, ?, ?)
""",
(payload.project_id, name, "Added from Playground", consistency, path),
)
created_item_id = int(cur.lastrowid)
elif payload.target == "scene":
if not payload.scene_id:
raise HTTPException(status_code=400, detail="scene_id required")
@@ -390,6 +418,14 @@ async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]:
"source": "playground_attach",
},
)
return {"ok": True, "path": path, "target": payload.target, "project_id": payload.project_id}
out: dict[str, Any] = {
"ok": True,
"path": path,
"target": payload.target,
"project_id": payload.project_id,
}
if payload.target == "item":
out["item_id"] = created_item_id
return out
finally:
conn.close()