Merge PR 25 locally for testing

This commit is contained in:
Benjiyaya
2026-08-27 11:50:18 +08:00
13 changed files with 636 additions and 38 deletions
@@ -85,10 +85,11 @@ def _destructive_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> PreEx
if not has_replace_param:
return allow()
replace = bool(args.get("replace", True))
if not replace:
return allow()
# Destructive path: only allow when the project is effectively empty, or
# the user explicitly confirmed.
# BOTH modes are gated on a non-empty project: replace=true deletes the
# existing content, and replace=false APPENDS a second full set alongside
# it (observed live 2026-08-25: an unconfirmed replace=false generate_story
# silently doubled a project's beats, 25 -> 50). Only allow when the
# project is effectively empty, or the user explicitly confirmed.
from calliope.agent.harness.registry import _db
if ctx.project_id is None:
@@ -117,11 +118,25 @@ def _destructive_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> PreEx
return allow()
if _user_confirmed_replacement(ctx):
return allow()
return deny(
counts = (
f"Project #{ctx.project_id} already has content ({scenes} scenes, {beats} beats, "
f"{chars} characters, {locs} locations, {items} items). Ask the user to confirm before replacing; "
"once they confirm (e.g. 'yes, replace'), call this tool again. "
"To append instead, pass replace=false."
f"{chars} characters, {locs} locations, {items} items)."
)
if replace:
return deny(
counts + " replace=true DELETES all of it first. Ask the user to "
"confirm before replacing; once they confirm (e.g. 'yes, replace'), "
"call this tool again. For targeted changes use the granular tools "
"instead (add/update/delete for beats, characters, locations, "
"items, scenes)."
)
return deny(
counts + " replace=false would APPEND a second full set alongside the "
"existing content (e.g. doubling the beat list) — usually wrong. Ask "
"the user to confirm before appending; once they confirm (e.g. 'yes, "
"append'), call this tool again. For targeted changes use the granular "
"tools instead (add/update/delete for beats, characters, locations, "
"items, scenes)."
)
@@ -37,6 +37,16 @@ TASK_START = "task/start"
TASK_END = "task/end"
TOOL_RESULT_TRUNCATE = 4000
# Appended wherever a tool result is cut for the LLM. Must TEACH the way out —
# a bare "[truncated]" sends agents into retry loops hoping for a different
# cut (observed live 2026-08-24: an assets sub-agent re-called get_workspace
# repeatedly, blind to characters/locations below the cut).
TRUNCATE_NOTE = (
"…[truncated — the full result is too large for one reply. Fetch a "
"smaller slice instead of retrying: get_workspace accepts "
"sections=[\"characters\",\"locations\",\"items\",\"beats\",\"scenes\"], "
"and scoped tools (get_story, list_scenes) return less.]"
)
# Cap for ANY single event payload at append time: keeps the append-only log
# faithful in shape but bounded in size (a 500 KB tool result would otherwise
@@ -311,7 +321,7 @@ def derive_llm_history(
def _truncate_result(result: Any) -> str:
text = json.dumps(result, ensure_ascii=False, default=str)
if len(text) > TOOL_RESULT_TRUNCATE:
return text[:TOOL_RESULT_TRUNCATE] + "…[truncated]"
return text[:TOOL_RESULT_TRUNCATE] + TRUNCATE_NOTE
return text
@@ -242,7 +242,7 @@ async def run_turn(
)
result_text = json.dumps(result, ensure_ascii=False, default=str)
if len(result_text) > session_log.TOOL_RESULT_TRUNCATE:
result_text = result_text[: session_log.TOOL_RESULT_TRUNCATE] + "…[truncated]"
result_text = result_text[: session_log.TOOL_RESULT_TRUNCATE] + session_log.TRUNCATE_NOTE
messages.append(
{
"role": "tool",
@@ -32,7 +32,15 @@ MAX_HISTORY_USER_TURNS = 40
# Tool subsets per sub-agent role. Scoped tighter than the full registry so a
# sub-agent cannot wander into another role's tools.
ROLE_TOOLS: dict[str, list[str]] = {
"story": ["get_workspace", "get_story", "generate_story", "list_workflows"],
"story": [
"get_workspace",
"get_story",
"generate_story",
"add_beat",
"update_beat",
"delete_beat",
"list_workflows",
],
"script": [
"get_workspace",
"list_scenes",
@@ -44,6 +52,9 @@ ROLE_TOOLS: dict[str, list[str]] = {
],
"assets": [
"get_workspace",
"update_character",
"update_location",
"update_item",
"list_workflows",
"comfy_server_info",
"run_workflow",
@@ -285,7 +296,14 @@ async def orchestrate(
}
)
except Exception as exc: # noqa: BLE001
results.append(f"[{role}] FAILED: {exc}")
# Some exceptions stringify EMPTY (httpx.ReadTimeout/ReadError,
# TimeoutError) — always name the type, and keep the traceback
# (observed live 2026-08-25: "Sub-agent failed: " with nothing
# after the colon, because a deploy restart killed the in-flight
# stream and the ReadError carried no message).
logger.exception("Sub-agent %s failed", role)
detail = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__
results.append(f"[{role}] FAILED: {detail}")
session_log.append_event(
session_id,
session_log.TASK_END,
@@ -298,7 +316,7 @@ async def orchestrate(
session_id,
session_log.ASSISTANT_MESSAGE,
{
"content": f"Sub-agent failed: {exc}",
"content": f"Sub-agent failed: {detail}",
"agent_name": f"{role}-agent",
"status": "error",
},
@@ -307,7 +325,7 @@ async def orchestrate(
{
"role": "assistant",
"agent_name": f"{role}-agent",
"content": f"Sub-agent failed: {exc}",
"content": f"Sub-agent failed: {detail}",
"status": "error",
}
)
@@ -471,7 +489,7 @@ async def _run_sub_agent(
)
result_text = json.dumps(result, ensure_ascii=False, default=str)
if len(result_text) > session_log.TOOL_RESULT_TRUNCATE:
result_text = result_text[: session_log.TOOL_RESULT_TRUNCATE] + "…[truncated]"
result_text = result_text[: session_log.TOOL_RESULT_TRUNCATE] + session_log.TRUNCATE_NOTE
messages.append(
{"role": "tool", "tool_call_id": call_id, "content": result_text}
)
@@ -52,6 +52,182 @@ def register(registry: ToolRegistry) -> None:
)
)
_register_asset_crud(registry)
_register_beat_crud(registry)
def _register_beat_crud(registry: ToolRegistry) -> None:
"""Register add/update/delete tools for story beats.
Before these existed, beats could ONLY be changed via generate_story —
a bulk regenerate — so "align the beats to this story" left an agent no
non-destructive path (observed live 2026-08-25: a story sub-agent, boxed
in, appended a duplicate 25-beat set and then hit the destructive guard).
"""
registry.register(
ToolDefinition(
name="add_beat",
description=(
"Insert one story beat. title is required. order_index is the "
"1-based timeline position — later beats shift down to make "
"room; omit it to append at the end."
),
parameters={
"type": "object",
"properties": {
"title": {"type": "string"},
"description": {"type": "string"},
"order_index": {
"type": "integer",
"description": "1-based position; omit to append at the end",
},
},
"required": ["title"],
},
executor=t_add_beat,
category="story",
)
)
registry.register(
ToolDefinition(
name="update_beat",
description=(
"Update one existing story beat. beat_id must come from "
"get_story/get_workspace — never guess it. Pass only the fields "
"to change (title, description, order_index)."
),
parameters={
"type": "object",
"properties": {
"beat_id": {"type": "integer"},
"title": {"type": "string"},
"description": {"type": "string"},
"order_index": {"type": "integer"},
},
"required": ["beat_id"],
},
executor=t_update_beat,
category="story",
)
)
registry.register(
ToolDefinition(
name="delete_beat",
description=(
"Delete one story beat permanently; later beats renumber to "
"close the gap. beat_id must come from get_story/get_workspace. "
"Prefer update_beat for content changes."
),
parameters={
"type": "object",
"properties": {"beat_id": {"type": "integer"}},
"required": ["beat_id"],
},
executor=t_delete_beat,
category="story",
destructive=True,
)
)
async def t_add_beat(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
title = args.get("title")
if not isinstance(title, str) or not title.strip():
return {"ok": False, "error": "title is required (non-empty string)"}
conn = _db()
try:
max_idx = conn.execute(
"SELECT COALESCE(MAX(order_index), 0) AS m FROM story_beats WHERE project_id = ?",
(ctx.project_id,),
).fetchone()["m"]
idx = args.get("order_index")
idx = int(idx) if idx is not None else max_idx + 1
idx = max(1, min(idx, max_idx + 1))
conn.execute(
"UPDATE story_beats SET order_index = order_index + 1 "
"WHERE project_id = ? AND order_index >= ?",
(ctx.project_id, idx),
)
cur = conn.execute(
"INSERT INTO story_beats (project_id, order_index, title, description) "
"VALUES (?, ?, ?, ?)",
(ctx.project_id, idx, title.strip(), args.get("description")),
)
conn.execute(
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
(ctx.project_id,),
)
conn.commit()
beat = conn.execute(
"SELECT * FROM story_beats WHERE id = ?", (cur.lastrowid,)
).fetchone()
return {"ok": True, "beat": row_to_dict(beat)}
finally:
conn.close()
async def t_update_beat(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
bid = int(args["beat_id"])
data = {
k: v
for k, v in args.items()
if k in ("title", "description", "order_index") and v is not None
}
if "title" in data and not str(data["title"]).strip():
data.pop("title")
conn = _db()
try:
existing = conn.execute(
"SELECT id FROM story_beats WHERE id = ? AND project_id = ?",
(bid, ctx.project_id),
).fetchone()
if not existing:
return {"ok": False, "error": f"Beat {bid} not found in this project"}
if data:
fields = ", ".join(f"{k} = :{k}" for k in data)
conn.execute(
f"UPDATE story_beats SET {fields} WHERE id = :id AND project_id = :project_id",
{**data, "id": bid, "project_id": ctx.project_id},
)
conn.execute(
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
(ctx.project_id,),
)
conn.commit()
beat = conn.execute(
"SELECT * FROM story_beats WHERE id = ?", (bid,)
).fetchone()
return {"ok": True, "beat": row_to_dict(beat)}
finally:
conn.close()
async def t_delete_beat(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
bid = int(args["beat_id"])
conn = _db()
try:
row = conn.execute(
"SELECT order_index FROM story_beats WHERE id = ? AND project_id = ?",
(bid, ctx.project_id),
).fetchone()
if not row:
return {"ok": False, "error": f"Beat {bid} not found in this project"}
conn.execute(
"DELETE FROM story_beats WHERE id = ? AND project_id = ?",
(bid, ctx.project_id),
)
conn.execute(
"UPDATE story_beats SET order_index = order_index - 1 "
"WHERE project_id = ? AND order_index > ?",
(ctx.project_id, row["order_index"]),
)
conn.execute(
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
(ctx.project_id,),
)
conn.commit()
return {"ok": True, "deleted_beat_id": bid}
finally:
conn.close()
def _register_asset_crud(registry: ToolRegistry) -> None:
@@ -21,11 +21,35 @@ def register(registry: ToolRegistry) -> None:
name="get_workspace",
description=(
"Get the current workspace: session linkage and, when linked, "
"the project with story beats, characters, locations, scenes, "
"and stats. ALWAYS call this before editing anything or when "
"you need current ids/counts."
"the project with story beats, characters, locations, items, "
"scenes, and stats. ALWAYS call this before editing anything or "
"when you need current ids/counts. On a LARGE project the full "
"result gets truncated — pass sections (e.g. "
"[\"characters\",\"locations\",\"items\"]) to fetch only what "
"you need; project + stats are always included."
),
parameters={"type": "object", "properties": {}},
parameters={
"type": "object",
"properties": {
"sections": {
"type": "array",
"items": {
"type": "string",
"enum": [
"beats",
"characters",
"locations",
"items",
"scenes",
],
},
"description": (
"Which sections to include. Omit for all — but on "
"large projects prefer only the sections you need."
),
}
},
},
executor=t_get_workspace,
requires_project=False,
category="workspace",
@@ -37,7 +61,8 @@ def register(registry: ToolRegistry) -> None:
description=(
"Link this sandbox session to an EXISTING project (call "
"list_projects first to get valid ids). Only possible while the "
"session is not yet linked — do NOT create a duplicate project "
"session is not yet linked — to switch projects, call "
"unlink_project first. Do NOT create a duplicate project "
"when one already matches."
),
parameters={
@@ -56,6 +81,21 @@ def register(registry: ToolRegistry) -> None:
category="workspace",
)
)
registry.register(
ToolDefinition(
name="unlink_project",
description=(
"Detach this session from its linked project and return to "
"sandbox mode. The project and all its content are untouched — "
"only the session binding is cleared. Use this when the user "
"wants a NEW project (then create_project) or a DIFFERENT "
"existing one (then link_project). Not available in sandbox."
),
parameters={"type": "object", "properties": {}},
executor=t_unlink_project,
category="workspace",
)
)
registry.register(
ToolDefinition(
name="create_project",
@@ -127,6 +167,9 @@ def register(registry: ToolRegistry) -> None:
)
_WS_SECTIONS = ("beats", "characters", "locations", "items", "scenes")
# ── executors ───────────────────────────────────────────────────
@@ -154,6 +197,16 @@ async def t_get_workspace(ctx: ToolContext, args: dict[str, Any]) -> dict[str, A
out["mode"] = "sandbox"
out["hint"] = "Linked project no longer exists."
return out
requested = args.get("sections")
if requested:
wanted = {sec for sec in requested if sec in _WS_SECTIONS}
if not wanted:
return {
"ok": False,
"error": f"No valid sections in {requested!r}; valid: {sorted(_WS_SECTIONS)}",
}
else:
wanted = set(_WS_SECTIONS)
beats = [
row_to_dict(r)
for r in conn.execute(
@@ -161,7 +214,7 @@ async def t_get_workspace(ctx: ToolContext, args: dict[str, Any]) -> dict[str, A
"WHERE project_id = ? ORDER BY order_index",
(ctx.project_id,),
).fetchall()
]
] if "beats" in wanted else None
characters = [
row_to_dict(r)
for r in conn.execute(
@@ -169,7 +222,7 @@ async def t_get_workspace(ctx: ToolContext, args: dict[str, Any]) -> dict[str, A
"sheet_path, consistency_prompt FROM characters WHERE project_id = ?",
(ctx.project_id,),
).fetchall()
]
] if "characters" in wanted else None
locations = [
row_to_dict(r)
for r in conn.execute(
@@ -177,7 +230,7 @@ async def t_get_workspace(ctx: ToolContext, args: dict[str, Any]) -> dict[str, A
"FROM locations WHERE project_id = ?",
(ctx.project_id,),
).fetchall()
]
] if "locations" in wanted else None
items = [
row_to_dict(r)
for r in conn.execute(
@@ -185,7 +238,7 @@ async def t_get_workspace(ctx: ToolContext, args: dict[str, Any]) -> dict[str, A
"FROM items WHERE project_id = ?",
(ctx.project_id,),
).fetchall()
]
] if "items" in wanted else None
scenes = [
row_to_dict(r)
for r in conn.execute(
@@ -193,15 +246,21 @@ async def t_get_workspace(ctx: ToolContext, args: dict[str, Any]) -> dict[str, A
"location_id, video_path FROM scenes WHERE project_id = ? ORDER BY order_index",
(ctx.project_id,),
).fetchall()
]
] if "scenes" in wanted else None
out["mode"] = "linked"
out["project"] = project
out["stats"] = _project_stats(ctx.project_id, conn)
out["beats"] = beats
out["characters"] = characters
out["locations"] = locations
out["items"] = items
out["scenes"] = scenes
for key, value in (
("beats", beats),
("characters", characters),
("locations", locations),
("items", items),
("scenes", scenes),
):
if value is not None:
out[key] = value
if len(wanted) < len(_WS_SECTIONS):
out["sections_omitted"] = sorted(set(_WS_SECTIONS) - wanted)
return out
finally:
conn.close()
@@ -228,6 +287,29 @@ async def t_link_project(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
return {"ok": True, "project_id": pid, "title": project["title"]}
async def t_unlink_project(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
released_id = ctx.project_id
conn = _db()
try:
project = _project_or_error(conn, released_id)
conn.execute(
"UPDATE agent_sessions SET project_id = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
(ctx.session_id,),
)
conn.commit()
finally:
conn.close()
ctx.project_id = None
await publish_session_updated(ctx.session_id)
return {
"ok": True,
"released_project_id": released_id,
"released_title": (project or {}).get("title"),
"mode": "sandbox",
"hint": "Session is back in sandbox — create_project and link_project are available again.",
}
_TITLE_MAX = 200 # mirrors ProjectCreate/ProjectUpdate schema bounds
@@ -14,7 +14,7 @@ from calliope.agent.harness.registry import ToolContext
# (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"go\s+ahead|do\s+it|please\s+do|overwrite|replace|append|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,
@@ -161,7 +161,13 @@ class ToolRegistry:
"error": "This tool requires a linked project. Create one with create_project first.",
}
if t.blind_only and ctx.project_id is not None:
return {"ok": False, "error": "This tool is only available in a sandbox (unlinked) session."}
return {
"ok": False,
"error": (
"This tool is only available in a sandbox (unlinked) session. "
"Call unlink_project first to return this session to sandbox."
),
}
decision = ALLOW
for hook in self.pre_execute: