feat: commit the local agent shell, history budget, and loop hardening

These files were already edited on this machine. Publish that tree instead of rewriting a slice onto a GitHub checkout.
This commit is contained in:
Benjiyaya
2026-09-27 04:42:22 +08:00
parent 61db492ee2
commit b28f6eea2b
34 changed files with 4378 additions and 137 deletions
+7 -1
View File
@@ -116,6 +116,7 @@
"reset_pose",
"reset_transform",
"run_canvas_node",
"run_command",
"run_workflow",
"save_memory",
"select_object",
@@ -165,6 +166,11 @@
"guard_destructive_replace",
"guard_no_export_video_tool",
"guard_render_approval",
"guard_scene_tool_scope"
"guard_scene_tool_scope",
"guard_shell_approval",
"guard_shell_denied_command",
"guard_shell_denied_path",
"guard_shell_disabled",
"guard_shell_outside_workspace"
]
}
@@ -0,0 +1,61 @@
"""Export a recorded agent session as a deterministic replay fixture.
The golden-scenario harness (tests/test_golden_replay.py) replays a session's
event log through run_turn / orchestrate with the LLM mocked to REPLAY the
recorded assistant outputs, then asserts structural invariants (every
assistant tool_calls has matching tool results, turn/end present with a valid
status, no dangling call ids). This script dumps the raw material: the
session's user/assistant/tool events in order.
Usage:
python scripts/export_session_replay.py --db data/calliope.db --session-id 12 --out tests/fixtures/replay/my_case.json
Only ever run against a COPY of a database or a test DB — never against the
live calliope.db while the app is writing to it.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from calliope.db import get_db, migrate_db # noqa: E402
from calliope.config import settings # noqa: E402
from calliope.agent.harness import log as session_log # noqa: E402
def export_session(db_path: Path, session_id: int) -> dict:
settings.data_dir = db_path.parent
asyncio.run(migrate_db(db_path))
events = session_log.read_events(session_id)
if not events:
raise SystemExit(f"Session {session_id} has no events in {db_path}")
out = {"session_id": session_id, "events": []}
for e in events:
out["events"].append({"seq": e.seq, "type": e.type, "data": e.data})
return out
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--db", required=True, help="Path to a calliope SQLite DB (a copy)")
parser.add_argument("--session-id", type=int, required=True)
parser.add_argument("--out", required=True, help="Output fixture path (.json)")
args = parser.parse_args()
fixture = export_session(Path(args.db), args.session_id)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(
json.dumps(fixture, ensure_ascii=False, indent=2), encoding="utf-8"
)
print(f"Exported session {args.session_id} -> {out_path} ({len(fixture['events'])} events)")
if __name__ == "__main__":
main()
@@ -35,6 +35,13 @@ logger = logging.getLogger("calliope.harness")
# human guidance text stays in the deny message for the model).
GUARD_RENDER_APPROVAL = "guard_render_approval"
GUARD_DESTRUCTIVE_REPLACE = "guard_destructive_replace"
# Agent shell (run_command) denials — defined here so the contracts exporter
# (which scans this module + registry.py) picks them up.
GUARD_SHELL_DISABLED = "guard_shell_disabled"
GUARD_SHELL_APPROVAL = "guard_shell_approval"
GUARD_SHELL_OUTSIDE_WORKSPACE = "guard_shell_outside_workspace"
GUARD_SHELL_DENIED_PATH = "guard_shell_denied_path"
GUARD_SHELL_DENIED_COMMAND = "guard_shell_denied_command"
# Scene tool scope guard lives in registry.py (circular-import free); the
# contracts exporter reads guard codes from THIS module, so re-export here.
from calliope.agent.harness.registry import ( # noqa: E402
@@ -185,6 +192,7 @@ def build_harness() -> tuple[ToolRegistry, SystemPromptService]:
shot_builder,
skills,
story,
system,
workspace,
)
@@ -197,6 +205,7 @@ def build_harness() -> tuple[ToolRegistry, SystemPromptService]:
memory.register(registry)
skills.register(registry)
shot_builder.register(registry)
system.register(registry)
registry.on_pre_execute(_destructive_guard)
registry.on_pre_execute(_render_approval_guard)
register_builtin_sections(prompts)
@@ -143,6 +143,153 @@ def apply_fail_streak(result: dict[str, Any], streak: int) -> str:
return fail_directive_text(streak)
return ""
# ── Legacy JSON-action bridge (finding 6) ───────────────────────────────
# Some OpenAI-compatible endpoints (and older models) answer a tools payload
# with a prose/JSON action instead of a native tool_call. The bridge parses a
# {"tool": ..., "arguments": {...}} object out of the reply and executes it
# through the exact same guarded path — a parse loop can't spin forever, so
# bridged calls are capped per turn.
_BRIDGE_CAP_PER_TURN = 8
NO_FUNCTION_CALLING_NOTE = (
"[This model answered with raw JSON instead of a tool call — its endpoint "
"does not support function calling. Switch to a tool-calling model for "
"agentic work.]"
)
def _extract_json_action(text: str) -> tuple[str, dict[str, Any]] | None:
"""Extract a ``{"tool": name, "arguments": {...}}`` action from model text.
Prefers a fenced ```json block, then a bare/leading JSON object. Returns
None when the text carries no parseable action — plain prose stays a final
answer, never a bridge.
"""
if not text or "{" not in text:
return None
def _action_from(candidate: str) -> tuple[str, dict[str, Any]] | None:
try:
parsed = json.loads(candidate)
except json.JSONDecodeError:
return None
if not isinstance(parsed, dict):
return None
name = parsed.get("tool") or parsed.get("name") or parsed.get("action")
if not isinstance(name, str) or not name.strip():
return None
args = parsed.get("arguments", parsed.get("args", {}))
if args is None:
args = {}
if not isinstance(args, dict):
return None
return name.strip(), args
# 1) fenced blocks first (```json ... ``` / ``` ... ```)
if "```" in text:
lines = text.splitlines()
inside = False
chunks: list[str] = []
buf: list[str] = []
for line in lines:
stripped = line.strip()
if not inside and stripped.startswith("```"):
inside = True
continue
if inside and stripped.startswith("```"):
inside = False
chunks.append("\n".join(buf))
buf = []
continue
if inside:
buf.append(line)
if inside and buf:
chunks.append("\n".join(buf))
for chunk in chunks:
action = _action_from(chunk.strip())
if action is not None:
return action
# 2) first balanced {...} object anywhere in the text
decoder = json.JSONDecoder()
start = text.find("{")
while start != -1:
try:
parsed, _ = decoder.raw_decode(text[start:])
except json.JSONDecodeError:
start = text.find("{", start + 1)
continue
if isinstance(parsed, dict):
name = parsed.get("tool") or parsed.get("name") or parsed.get("action")
if isinstance(name, str) and name.strip():
args = parsed.get("arguments", parsed.get("args", {}))
if args is None:
args = {}
if isinstance(args, dict):
return name.strip(), args
start = text.find("{", start + 1)
return None
def _looks_like_json_reply(text: str) -> bool:
"""Heuristic for 'the model tried to answer in JSON but no action parsed'."""
stripped = (text or "").strip()
return stripped.startswith("{") or stripped.startswith("```")
# ── Read-only parallel dispatch (finding 8a) ────────────────────────────
# Provably read-only lookups: safe to run concurrently via asyncio.gather.
# Name-based allowlist plus a list_* prefix rule; everything NOT here (writes,
# generation, ask_user, run_command, wait_for_jobs) stays strictly sequential.
_READONLY_TOOLS = frozenset(
{
"get_workspace",
"get_story",
"get_job_status",
"get_scene",
"summarize_canvas",
"read_skill",
"list_skills",
"list_memories",
"comfy_server_info",
"list_shot_presets",
"list_poses",
"list_projects",
"list_jobs",
"list_workflows",
}
)
def _is_readonly_tool(name: str) -> bool:
return name in _READONLY_TOOLS or name.startswith("list_")
def _usage_totals(usage: dict[str, Any]) -> dict[str, int] | None:
"""Normalize a server usage dict to prompt/completion/total counts.
OpenAI-compatible servers report prompt_tokens/completion_tokens/total_tokens;
total is derived when absent. None when nothing usable is present (no
fabrication — absent means the server never reported it).
"""
def _int(value: Any) -> int | None:
try:
out = int(value)
except (TypeError, ValueError):
return None
return out if out >= 0 else None
prompt = _int(usage.get("prompt_tokens"))
completion = _int(usage.get("completion_tokens"))
total = _int(usage.get("total_tokens"))
if prompt is None and completion is None:
return None
if total is None:
total = (prompt or 0) + (completion or 0)
return {"prompt_tokens": prompt or 0, "completion_tokens": completion or 0, "total_tokens": total}
# Async callback that persists + broadcasts one harness message.
MessageSink = Callable[[dict[str, Any]], Awaitable[None]]
@@ -207,10 +354,139 @@ async def run_turn(
{"role": "user", "content": session_log.steering_user_content(s.data)}
)
def step_end_data(**extra: Any) -> dict[str, Any]:
data: dict[str, Any] = {"turn": turn_no, "step": iteration, **extra}
if step_usage is not None:
data["usage"] = dict(step_usage)
return data
async def _log_call_start(tc: dict[str, Any], name: str, args: Any) -> None:
"""Persist the tool/call event + SSE start for one call. Shared by the
sequential and parallel dispatch paths (parallel used to skip the
call-side event, leaving tool/result rows with no matching record)."""
raw_args = tc["function"].get("arguments") or "{}"
log_append(
session_log.TOOL_CALL,
{
"turn": turn_no,
"step": iteration,
"call_id": tc["id"],
"tool_name": name,
"arguments": raw_args,
"agent_name": agent_name,
},
)
await event_bus.publish(
"agent.tool",
{
"session_id": ctx.session_id,
"agent_name": agent_name,
"phase": "start",
"tool": name,
"args": args,
},
)
async def _exec_one(tc: dict[str, Any]) -> tuple[str, Any, dict[str, Any]]:
"""Execute one native tool call (parse args, guards, execute).
Returns (name, parsed_args_or_None, result) — logging/emitting and
message-append stay with the caller so ordering and control flow
(ask_user pause, fail streak) are identical on both dispatch paths.
"""
name = tc["function"]["name"]
raw_args = tc["function"].get("arguments") or "{}"
try:
args = json.loads(raw_args) if raw_args.strip() else {}
except json.JSONDecodeError:
args = None
if args is None:
return name, None, {"ok": False, "error": f"Invalid JSON arguments for {name}: {raw_args[:200]}"}
if not isinstance(args, dict):
# Valid JSON but not an object (e.g. "[1,2,3]" / "\"hi\""):
# tools call args.get(...) — reject with a self-correcting
# message instead of an AttributeError traceback string.
return (
name,
args,
{
"ok": False,
"error": (
f"Tool arguments for {name} must be a JSON object, "
f"got {type(args).__name__}: {raw_args[:200]}"
),
},
)
intercepted = repeat.intercept(name, args)
if intercepted is not None:
return name, args, intercepted
result = await registry.execute(ctx, name, args)
repeat.record(name, args, result)
return name, args, result
async def _finish_call(
tc: dict[str, Any], name: str, args: Any, result: dict[str, Any]
) -> None:
"""Log + emit one executed call and append its tool message. Shared by
the sequential and parallel dispatch paths."""
nonlocal fail_streak
log_append(
session_log.TOOL_RESULT,
{
"turn": turn_no,
"step": iteration,
"call_id": tc["id"],
"tool_name": name,
"result": result,
"agent_name": agent_name,
},
)
await event_bus.publish(
"agent.tool",
{
"session_id": ctx.session_id,
"agent_name": agent_name,
"phase": "finish",
"tool": name,
"result": result,
},
)
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] + session_log.TRUNCATE_NOTE
# Thrash killer: a run of failures (guard denials, errors)
# escalates — the appended directive forces a DIFFERENT
# action or an explicit hand-back. Never a third blind try.
if isinstance(result, dict) and result.get("ok") is False:
fail_streak += 1
elif isinstance(result, dict):
fail_streak = 0
result_text += apply_fail_streak(result, fail_streak)
messages.append(
{
"role": "tool",
"tool_call_id": tc["id"],
"content": result_text,
}
)
await emit(
{
"role": "tool",
"agent_name": agent_name,
"tool_name": name,
"tool_args": args,
"tool_result": result,
"content": "",
}
)
client = _llm_for_role("main")
final_text = ""
turn_status = "completed"
synthetic_idx: list[int] = [] # positions of budget-nudge messages (stripped after)
bridged_count = 0 # JSON-action bridge executions this turn (cap _BRIDGE_CAP_PER_TURN)
turn_usage: dict[str, int] = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
usage_seen = False # only surface usage when the server actually reported it
try:
messages = [m for m in history if m.get("role") != "system"]
for iteration in range(1, max_iterations + 1):
@@ -242,6 +518,7 @@ async def run_turn(
content_acc: list[str] = []
reasoning_acc: list[str] = []
tool_calls: list[dict[str, Any]] = []
step_usage: dict[str, int] | None = None
async for ev in stream:
if ev["type"] == "delta":
content_acc.append(ev["content"])
@@ -265,6 +542,13 @@ async def run_turn(
)
elif ev["type"] == "tool_call":
tool_calls.append(ev["tool_call"])
elif ev["type"] == "usage":
normalized = _usage_totals(ev["usage"] or {})
if normalized:
step_usage = normalized
usage_seen = True
for key, value in normalized.items():
turn_usage[key] = turn_usage.get(key, 0) + value
assistant_msg: dict[str, Any] = {
"role": "assistant",
@@ -285,13 +569,168 @@ async def run_turn(
messages.append(assistant_msg)
if not tool_calls:
# ── Legacy JSON-action bridge (finding 6) ────────────
# Zero native tool_calls but a tools payload WAS sent: the
# endpoint may have answered with a prose/JSON action. Parse
# one out and run it through the exact same guarded exec path
# (synthetic call id bridge_{n}); plain prose is untouched.
step_text = "".join(content_acc)
action = _extract_json_action(step_text) if tools else None
if action is not None and bridged_count < _BRIDGE_CAP_PER_TURN:
bridged_count += 1
bridge_name, bridge_args = action
raw_args = json.dumps(bridge_args, ensure_ascii=False)
call_id = f"bridge_{turn_no}_{bridged_count}"
# Persist the assistant message WITH its synthetic tool_calls
# so derive_llm_history replays the same valid exchange the
# live loop built (mirrors the native batch path above).
log_append(
session_log.ASSISTANT_MESSAGE,
{
"turn": turn_no,
"step": iteration,
"content": step_text.strip() or None,
"agent_name": agent_name,
"tool_calls": [
{
"id": call_id,
"type": "function",
"function": {
"name": bridge_name,
"arguments": raw_args,
},
}
],
},
)
log_append(
session_log.TOOL_CALL,
{
"turn": turn_no,
"step": iteration,
"call_id": call_id,
"tool_name": bridge_name,
"arguments": raw_args,
"agent_name": agent_name,
"bridged": True,
},
)
await event_bus.publish(
"agent.tool",
{
"session_id": ctx.session_id,
"agent_name": agent_name,
"phase": "start",
"tool": bridge_name,
"args": bridge_args,
},
)
if registry.get(bridge_name) is None:
result = {
"ok": False,
"error": f"Unknown tool: {bridge_name}",
}
else:
intercepted = repeat.intercept(bridge_name, bridge_args)
if intercepted is not None:
result = intercepted
else:
result = await registry.execute(ctx, bridge_name, bridge_args)
repeat.record(bridge_name, bridge_args, result)
log_append(
session_log.TOOL_RESULT,
{
"turn": turn_no,
"step": iteration,
"call_id": call_id,
"tool_name": bridge_name,
"result": result,
"agent_name": agent_name,
},
)
await event_bus.publish(
"agent.tool",
{
"session_id": ctx.session_id,
"agent_name": agent_name,
"phase": "finish",
"tool": bridge_name,
"result": result,
},
)
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] + session_log.TRUNCATE_NOTE
if isinstance(result, dict) and result.get("ok") is False:
fail_streak += 1
elif isinstance(result, dict):
fail_streak = 0
result_text += apply_fail_streak(result, fail_streak)
# Rewrite the assistant message into a proper tool-call
# exchange so derive_llm_history replays a valid sequence.
messages.pop()
assistant_msg = {
"role": "assistant",
"content": ("".join(content_acc) or None),
"tool_calls": [
{
"id": call_id,
"type": "function",
"function": {
"name": bridge_name,
"arguments": raw_args,
},
}
],
}
messages.append(assistant_msg)
messages.append(
{"role": "tool", "tool_call_id": call_id, "content": result_text}
)
await emit(
{
"role": "tool",
"agent_name": agent_name,
"tool_name": bridge_name,
"tool_args": bridge_args,
"tool_result": result,
"content": "",
}
)
# ask_user via the bridge pauses the turn like a native one.
if isinstance(result, dict) and result.get("awaiting_user_input"):
log_append(session_log.STEP_END, step_end_data())
turn_status = "awaiting_input"
raise _AwaitingInput()
log_append(session_log.STEP_END, step_end_data(bridged=True))
continue # next step: the model sees its tool result
if action is not None:
# Bridge cap reached: stop the parse loop deterministically.
final_text = (
"I paused: this turn executed the maximum number of "
f"bridged tool calls ({_BRIDGE_CAP_PER_TURN}). Send another "
"message to continue — or switch to a tool-calling "
"model, which does not have this limit."
)
log_append(
session_log.ASSISTANT_MESSAGE,
{"turn": turn_no, "step": iteration, "content": final_text, "agent_name": agent_name},
)
log_append(session_log.STEP_END, step_end_data())
await emit({"role": "assistant", "agent_name": agent_name, "content": final_text})
break
final_text = "".join(content_acc).strip()
if final_text and _looks_like_json_reply(final_text) and tools:
# Raw JSON that parsed as neither a native call nor a
# bridge action: the endpoint does not support function
# calling — tell the user instead of a silent no-op.
final_text = final_text + "\n\n" + NO_FUNCTION_CALLING_NOTE
reasoning_text = "".join(reasoning_acc).strip() or None
msg_data: dict[str, Any] = {"turn": turn_no, "step": iteration, "content": final_text, "agent_name": agent_name}
if reasoning_text:
msg_data["reasoning"] = reasoning_text
log_append(session_log.ASSISTANT_MESSAGE, msg_data)
log_append(session_log.STEP_END, {"turn": turn_no, "step": iteration})
log_append(session_log.STEP_END, step_end_data())
# Emit the final assistant message as an SSE event so the
# frontend can display it immediately (without waiting for
# the next poll cycle).
@@ -318,6 +757,27 @@ async def run_turn(
if reasoning_text:
tool_msg_data["reasoning"] = reasoning_text
log_append(session_log.ASSISTANT_MESSAGE, tool_msg_data)
# ── Read-only parallel dispatch (finding 8a) ────────────────
# A batch of >1 calls runs concurrently ONLY when every call's
# tool is a provably read-only lookup — no writes, no approvals,
# no shell. Everything else keeps today's exact sequential
# behavior (execute → log → emit per call, in order).
parallel = len(tool_calls) > 1 and all(
_is_readonly_tool(tc["function"]["name"]) for tc in tool_calls
)
if parallel:
# Call-side events first, in order, then gather — every
# tool/result keeps a matching tool/call record.
for tc in tool_calls:
await _log_call_start(tc, tc["function"]["name"], None)
exec_results: list[tuple[str, Any, dict[str, Any]]] = list(
await asyncio.gather(*(_exec_one(tc) for tc in tool_calls))
)
for tc, (name, args, result) in zip(tool_calls, exec_results):
await _finish_call(tc, name, args, result)
log_append(session_log.STEP_END, step_end_data(parallel=True))
continue
for tc_idx, tc in enumerate(tool_calls):
name = tc["function"]["name"]
raw_args = tc["function"].get("arguments") or "{}"
@@ -325,103 +785,13 @@ async def run_turn(
args = json.loads(raw_args) if raw_args.strip() else {}
except json.JSONDecodeError:
args = None
log_append(
session_log.TOOL_CALL,
{
"turn": turn_no,
"step": iteration,
"call_id": tc["id"],
"tool_name": name,
"arguments": raw_args,
"agent_name": agent_name,
},
)
await event_bus.publish(
"agent.tool",
{
"session_id": ctx.session_id,
"agent_name": agent_name,
"phase": "start",
"tool": name,
"args": args,
},
)
if args is None:
result = {
"ok": False,
"error": f"Invalid JSON arguments for {name}: {raw_args[:200]}",
}
elif not isinstance(args, dict):
# Valid JSON but not an object (e.g. "[1,2,3]" / "\"hi\""):
# tools call args.get(...) — reject with a self-correcting
# message instead of an AttributeError traceback string.
result = {
"ok": False,
"error": (
f"Tool arguments for {name} must be a JSON object, "
f"got {type(args).__name__}: {raw_args[:200]}"
),
}
else:
intercepted = repeat.intercept(name, args)
if intercepted is not None:
result = intercepted
else:
result = await registry.execute(ctx, name, args)
repeat.record(name, args, result)
await _log_call_start(tc, name, args)
name, args, result = await _exec_one(tc)
# Log + emit the result FIRST. The ask_user card and the
# tool-row spinner both read these; ending the turn before
# them left the UI with no question and a stuck "working…"
# (the "agent loop just stops there" bug).
log_append(
session_log.TOOL_RESULT,
{
"turn": turn_no,
"step": iteration,
"call_id": tc["id"],
"tool_name": name,
"result": result,
"agent_name": agent_name,
},
)
await event_bus.publish(
"agent.tool",
{
"session_id": ctx.session_id,
"agent_name": agent_name,
"phase": "finish",
"tool": name,
"result": result,
},
)
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] + session_log.TRUNCATE_NOTE
# Thrash killer: a run of failures (guard denials, errors)
# escalates — the appended directive forces a DIFFERENT
# action or an explicit hand-back. Never a third blind try.
if isinstance(result, dict) and result.get("ok") is False:
fail_streak += 1
elif isinstance(result, dict):
fail_streak = 0
result_text += apply_fail_streak(result, fail_streak)
messages.append(
{
"role": "tool",
"tool_call_id": tc["id"],
"content": result_text,
}
)
await emit(
{
"role": "tool",
"agent_name": agent_name,
"tool_name": name,
"tool_args": args,
"tool_result": result,
"content": "",
}
)
await _finish_call(tc, name, args, result)
# ask_user ends the turn: the agent's question waits for the
# user's answer, so the loop must not burn steps polling.
if isinstance(result, dict) and result.get("awaiting_user_input"):
@@ -485,10 +855,10 @@ async def run_turn(
"content": "",
}
)
log_append(session_log.STEP_END, {"turn": turn_no, "step": iteration})
log_append(session_log.STEP_END, step_end_data())
turn_status = "awaiting_input"
raise _AwaitingInput()
log_append(session_log.STEP_END, {"turn": turn_no, "step": iteration})
log_append(session_log.STEP_END, step_end_data())
else:
final_text = (
"I reached my step budget for this turn. Here is where things "
@@ -518,7 +888,10 @@ async def run_turn(
raise
finally:
await client.close()
log_append(session_log.TURN_END, {"turn": turn_no, "status": turn_status})
turn_end_data: dict[str, Any] = {"turn": turn_no, "status": turn_status}
if usage_seen:
turn_end_data["usage"] = dict(turn_usage)
log_append(session_log.TURN_END, turn_end_data)
# Persist the exchange into history (the runner saves it to the DB),
# minus the synthetic budget-nudge message — it belongs to THIS
# turn's context only and would pollute the next turn.
@@ -51,6 +51,29 @@ MAX_HISTORY_USER_TURNS = 40
# pauses the swarm on it (skips remaining tasks, no synthesis LLM call).
_PAUSED_PREFIX = "Paused: "
# Prior task reports carried into each sub-agent's context: the LAST N
# reports, each capped, so later tasks build on earlier results without a
# full replay (sub-agents were fully stateless — finding 3).
_PRIOR_REPORT_COUNT = 2
_PRIOR_REPORT_CHARS = 1500
def _prior_reports_digest(results: list[str]) -> str:
"""Capped digest of the most recent task reports for the next sub-agent."""
if not results:
return ""
lines = []
for r in results[-_PRIOR_REPORT_COUNT:]:
r = (r or "").strip()
if not r:
continue
if len(r) > _PRIOR_REPORT_CHARS:
r = r[:_PRIOR_REPORT_CHARS] + "…[truncated]"
lines.append(r)
if not lines:
return ""
return "Prior task reports:\n" + "\n".join(lines) + "\n"
# Trivial-goal fast-path: one-line imperative messages skip the planner
# round-trip entirely. The single loop has every tool, so a misfire just
# loses the task-list UI — routing decision, not a permission change.
@@ -130,6 +153,14 @@ ROLE_TOOLS: dict[str, list[str]] = {
"delete_scene",
"list_workflows",
"ask_user",
# Memory + skills are role-agnostic knowledge access: a sub-agent must
# be able to honor a saved user preference and load a skill body
# (escalation via ask_user is role-agnostic for the same reason).
"save_memory",
"list_memories",
"forget_memory",
"read_skill",
"list_skills",
],
"script": [
"get_workspace",
@@ -146,6 +177,11 @@ ROLE_TOOLS: dict[str, list[str]] = {
"reorder_scenes",
"refresh_continuity_plan",
"ask_user",
"save_memory",
"list_memories",
"forget_memory",
"read_skill",
"list_skills",
],
"assets": [
"get_workspace",
@@ -170,6 +206,11 @@ ROLE_TOOLS: dict[str, list[str]] = {
"post_artifact_to_canvas",
"summarize_canvas",
"ask_user",
"save_memory",
"list_memories",
"forget_memory",
"read_skill",
"list_skills",
],
"video": [
"get_workspace",
@@ -185,6 +226,11 @@ ROLE_TOOLS: dict[str, list[str]] = {
"comfy_server_info",
"ask_user",
"post_artifact_to_canvas",
"save_memory",
"list_memories",
"forget_memory",
"read_skill",
"list_skills",
],
}
@@ -368,20 +414,39 @@ async def orchestrate(
return await run_turn(ctx, history, on_message=on_message)
# ── Swarm path ──────────────────────────────────────────────
# Planner output is LLM JSON — roles can be typos or invented names
# ("asset", "renderer"). Silent fallback ran the task with the script
# toolset; clamp to story instead and RECORD the clamp so the plan event
# and the user-facing note both surface it (finding 5).
valid_roles = set(ROLE_TOOLS)
norm_tasks: list[dict[str, str]] = []
for t in plan["tasks"]:
clamped_roles: list[dict[str, str]] = []
for idx, t in enumerate(plan["tasks"]):
raw_role = str(t.get("role") or "story").strip()
role = raw_role if raw_role in valid_roles else "story"
if role != raw_role:
clamped_roles.append({"from": raw_role, "to": role, "index": idx})
norm_tasks.append(
{
"role": t.get("role") or "script",
"role": role,
"goal": (t.get("goal") or goal).strip(),
}
)
if clamped_roles:
clamp_note = "Role validation: " + ", ".join(
f"task {c['index']} role '{c['from']}' is not valid — ran as {c['to']}"
for c in clamped_roles
)
note = f"{note}\n{clamp_note}" if note else clamp_note
# Persist the plan so the UI can render a live to-do table and re-derive
# it after a reload; broadcast the full list with initial pending status.
plan_event_data: dict[str, Any] = {"tasks": norm_tasks, "note": note}
if clamped_roles:
plan_event_data["clamped_roles"] = clamped_roles
session_log.append_event(
session_id,
session_log.PLAN_CREATED,
{"tasks": norm_tasks, "note": note},
plan_event_data,
)
await event_bus.publish(
"agent.plan",
@@ -458,12 +523,15 @@ async def orchestrate(
"content": f"Starting: {goal_i}",
}
)
digest = _prior_reports_digest(results)
sub_history: list[dict[str, Any]] = [
{
"role": "user",
"content": (
f"You are the {role} sub-agent. Goal: {goal_i}\n"
f"Project: #{ctx.project_id}. Complete your goal with your "
f"Project: #{ctx.project_id}.\n"
+ (digest + "\n" if digest else "")
+ "Complete your goal with your "
"available tools, then reply with a concise summary of what "
"you did and what the next sub-agent should know."
),
@@ -628,6 +696,19 @@ async def _run_sub_agent(
"the whole timeline. Never add_scene to attach an mp4. For "
"text-only edits, do the edit and stop."
)
# Memory + skills sections, same content the main loop renders (order 35
# / 37). Rendered ONCE here: a sub-agent lives for one task, and memory
# recall doubles as use-count accounting, so per-step re-render would
# inflate ranking. Sections stay None when there is nothing to show.
from calliope.agent.harness.plugins.memory import memory_prompt_text
from calliope.agent.harness.plugins.skills import skills_prompt_text
try:
for section in (memory_prompt_text(ctx), skills_prompt_text(ctx)):
if section:
system += "\n\n" + section
except Exception: # noqa: BLE001 — prompt garnish must never kill a task
logger.exception("Sub-agent memory/skills section render failed")
hardening = hardening_text()
if hardening:
system += "\n\n" + hardening
@@ -18,6 +18,7 @@ _PLUGIN_MODULES = (
"calliope.agent.harness.plugins.memory",
"calliope.agent.harness.plugins.skills",
"calliope.agent.harness.plugins.shot_builder",
"calliope.agent.harness.plugins.system",
)
@@ -15,7 +15,7 @@ from calliope.agent.harness.registry import ToolContext, ToolDefinition, ToolReg
logger = logging.getLogger("calliope.harness.plugins.interaction")
ALLOWED_SCOPES = ("render", "destructive_replace", "info")
ALLOWED_SCOPES = ("render", "destructive_replace", "shell", "info")
_QUESTION_CAP = 500
_OPTION_CAP = 6
_OPTION_LEN_CAP = 120
@@ -94,7 +94,8 @@ def register(registry: ToolRegistry) -> None:
'question="Generate images for all 3 characters?", '
'options=["Yes, generate", "No, not yet"], scope="render"). '
"scope: 'render' for generation approval, 'destructive_replace' for "
"content replacement, 'info' for everything else. Returns "
"content replacement, 'shell' for running a command via "
"run_command, 'info' for everything else. Returns "
"awaiting_user_input — treat it as the end of your turn."
),
parameters={
@@ -0,0 +1,315 @@
"""System plugin: the agent shell (run_command).
Cursor/Hermes-class agents are flexible because the model can run commands,
not only curated tools. Calliope ships to end users with secrets on disk
(``calliope_config.json`` carries the LLM API key; ``calliope.db`` carries
every session), so the shell is sandboxed to a dedicated workspace folder:
- default OFF (``settings.agent_shell_enabled``) — explicit opt-in,
- cwd AND path-like args containment-checked against
``settings.workspace_dir`` (``data_dir / "workspace"`` unless overridden)
plus ``assets_dir`` for read-side reference inspection,
- deny-list on sensitive names (config / *.db / .env / credentials),
- shell interpreters blocked (a ``bash -c`` payload defeats argv-level
path containment),
- non-read-only commands need the user's explicit ask: a structured
``scope="shell"`` question card or the command named in their words,
- exec is always an argv list via ``create_subprocess_exec`` (never a
shell string), with a stripped environment and a wall-clock timeout.
Residual risk (accepted, documented in AGENTS.md): an approved interpreter
(``python -c …``) can compute paths dynamically — the guard chain is
defense-in-depth + full audit (tool/call + tool/result events), not a VM
boundary. Policy lives in the pre-execute hook; the executor is mechanics.
"""
from __future__ import annotations
import asyncio
import logging
import os
import shutil
import re
from pathlib import Path
from typing import Any
from calliope.agent.harness.registry import (
ToolContext,
ToolDefinition,
ToolRegistry,
allow,
deny,
)
from calliope.config import settings
logger = logging.getLogger("calliope.harness.plugins.system")
DEFAULT_TIMEOUT_SEC = 120.0
_STREAM_CAP = 2000
_ARG_CAP = 64
# Commands whose payload is a single opaque string — they defeat argv-level
# path containment, so they are refused outright.
_SHELL_INTERPRETERS = frozenset(
{"sh", "bash", "zsh", "fish", "dash", "ksh", "csh", "tcsh", "cmd", "cmd.exe",
"powershell", "powershell.exe", "pwsh", "pwsh.exe"}
)
# Names that must never appear in any argument, whatever the command.
_SENSITIVE_NAME_RE = re.compile(
r"calliope_config\.json|\.env\b|calliope\.db|credential|secret|id_rsa|"
r"\.pem\b|\.pfx\b|\.p12\b",
re.IGNORECASE,
)
# Env var names stripped from the child process (case-insensitive contains).
_ENV_STRIP_RE = re.compile(r"KEY|SECRET|TOKEN|CREDENTIAL|PASSWORD|PASSWD", re.IGNORECASE)
# A command that cannot mutate anything may auto-run without approval.
_VERSION_FLAGS = frozenset({"--version", "-version", "-V", "--help", "-h", "-?"})
def _is_read_only(command: str, args: list[str]) -> bool:
if command.lower() in {"ffprobe", "which", "where", "whoami", "hostname"}:
return True
return bool(args) and all(a in _VERSION_FLAGS for a in args)
def _looks_like_path(arg: str) -> bool:
if not arg or len(arg) > 260:
return False
if "/" in arg or "\\" in arg:
return True
p = Path(arg)
return bool(p.anchor) or p.is_file() or p.is_dir()
def _contained(path: Path, roots: list[Path]) -> bool:
try:
resolved = path.resolve()
except OSError:
return False
for root in roots:
try:
resolved.relative_to(root.resolve())
return True
except (ValueError, OSError):
continue
return False
def _child_env() -> dict[str, str]:
return {k: v for k, v in os.environ.items() if not _ENV_STRIP_RE.search(k)}
async def _shell_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> Any:
"""Pre-execute policy for run_command (everything the plan's guard chain
checks BEFORE spawning). Every hook must return a decision — allow() for
tools this guard does not own."""
if t.name != "run_command":
return allow()
import calliope.agent.harness as harness
if not settings.agent_shell_enabled:
return deny(
"The agent shell is disabled. Enable it in Settings → Agent "
"('Agent shell' toggle) — commands can then run only inside the "
"agent workspace folder (Settings → System Paths).",
code=harness.GUARD_SHELL_DISABLED,
)
command = str(args.get("command") or "").strip()
if not command or "/" in command or "\\" in command:
return deny(
"command must be a bare executable name (e.g. 'ffmpeg'), not a path "
"or a shell string.",
code=harness.GUARD_SHELL_DENIED_COMMAND,
)
if command.lower() in _SHELL_INTERPRETERS:
return deny(
f"'{command}' is a shell interpreter and is blocked — its payload "
"would bypass path containment. Call the real tool directly.",
code=harness.GUARD_SHELL_DENIED_COMMAND,
)
if shutil.which(command) is None:
return deny(
f"'{command}' is not an installed executable on this machine.",
code=harness.GUARD_SHELL_DENIED_COMMAND,
)
raw_args = args.get("args") or []
if not isinstance(raw_args, list) or len(raw_args) > _ARG_CAP:
return deny(
f"args must be a list of at most {_ARG_CAP} strings.",
code=harness.GUARD_SHELL_DENIED_COMMAND,
)
str_args = [str(a) for a in raw_args]
# 1. Approval: read-only inspection auto-runs; anything else needs the
# user's explicit ask (scope='shell' card, or the command in their words).
if not _is_read_only(command, str_args):
from calliope.agent.harness import policy as shell_policy
if not shell_policy.user_allows_shell(ctx, command):
return deny(
f"Running '{command}' is human-in-the-loop. Ask the user with "
"ask_user(question=\"Run '{command}' in the agent workspace?\", "
"options=[\"Yes, run it\", \"No\"], scope=\"shell\") and retry "
"after they answer — read-only inspection (ffprobe) does not "
"need this.".replace("{command}", command),
code=harness.GUARD_SHELL_APPROVAL,
)
# 2. cwd containment: the process is born inside the workspace or nowhere.
ws = settings.workspace_dir
roots = [ws, settings.assets_dir]
cwd_arg = args.get("cwd")
if cwd_arg is not None:
cwd_path = Path(str(cwd_arg))
if not _contained(cwd_path, [ws]):
return deny(
f"cwd '{cwd_arg}' resolves outside the agent workspace "
f"({ws}) — the shell cannot leave that folder.",
code=harness.GUARD_SHELL_OUTSIDE_WORKSPACE,
)
cwd = cwd_path.resolve()
else:
cwd = ws.resolve()
# 3. Arg path containment + sensitive-name deny-list.
for a in str_args:
if _SENSITIVE_NAME_RE.search(a):
return deny(
f"Argument '{a}' names a sensitive file (config/database/"
"credentials) — the agent shell can never touch those.",
code=harness.GUARD_SHELL_DENIED_PATH,
)
if not _looks_like_path(a):
continue
p = Path(a)
if p.anchor or "/" in a or "\\" in a:
if not _contained(p, roots):
return deny(
f"Argument '{a}' resolves outside the agent workspace "
f"({ws}) and assets folder — pass a path inside them.",
code=harness.GUARD_SHELL_OUTSIDE_WORKSPACE,
)
elif (p.is_file() or p.is_dir()) and not _contained(p, roots):
return deny(
f"Argument '{a}' resolves to an existing path outside the "
f"agent workspace ({ws}) — pass a path inside it instead.",
code=harness.GUARD_SHELL_OUTSIDE_WORKSPACE,
)
return allow() # all checks passed
async def t_run_command(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
command = str(args.get("command") or "").strip()
str_args = [str(a) for a in (args.get("args") or [])]
ws = settings.workspace_dir
cwd_arg = args.get("cwd")
cwd = Path(str(cwd_arg)).resolve() if cwd_arg else ws.resolve()
timeout_arg = args.get("timeout_sec")
try:
timeout = float(timeout_arg) if timeout_arg is not None else DEFAULT_TIMEOUT_SEC
except (TypeError, ValueError):
return {"ok": False, "error": "timeout_sec must be a number"}
cap = settings.queue_poll_timeout_sec
timeout = max(1.0, min(timeout, cap) if cap > 0 else timeout)
exe = shutil.which(command)
if exe is None:
return {"ok": False, "error": f"'{command}' is not installed"}
creationflags = getattr(os, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
try:
proc = await asyncio.create_subprocess_exec(
exe,
*str_args,
cwd=str(cwd),
env=_child_env(),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
creationflags=creationflags,
)
except OSError as exc:
return {"ok": False, "error": f"failed to start '{command}': {exc}"}
try:
stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except asyncio.TimeoutError:
proc.kill()
return {
"ok": False,
"error": (
f"'{command}' exceeded {timeout:.0f}s and was killed. Narrow the "
"task (fewer files, shorter work) or ask for a longer timeout."
),
"timed_out": True,
}
stdout = stdout_b.decode("utf-8", errors="replace")[:_STREAM_CAP]
stderr = stderr_b.decode("utf-8", errors="replace")[:_STREAM_CAP]
out: dict[str, Any] = {
"ok": proc.returncode == 0,
"exit_code": proc.returncode,
"cwd": str(cwd),
}
if stdout:
out["stdout"] = stdout
if len(stdout_b) > _STREAM_CAP:
out["stdout_truncated"] = True
if stderr:
out["stderr"] = stderr
if len(stderr_b) > _STREAM_CAP:
out["stderr_truncated"] = True
if proc.returncode != 0 and not stderr:
out["error"] = f"'{command}' exited with code {proc.returncode}"
return out
def register(registry: ToolRegistry) -> None:
registry.register(
ToolDefinition(
name="run_command",
description=(
"Run an installed command-line executable INSIDE the agent "
"workspace folder (Settings → System Paths). Use for the long "
"tail the curated tools don't cover: ffprobe inspection of "
"reference media, batch file checks, quick probes. args is an "
"argv list — never a shell string; shell interpreters (bash, "
"powershell, …) are blocked. Read-only inspection runs "
"directly; anything else needs the user's approval first "
"(ask them with a scope='shell' ask_user card). Disabled "
"unless the operator enabled the agent shell in Settings."
),
parameters={
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Bare executable name, e.g. 'ffprobe' — no paths, no shell",
},
"args": {
"type": "array",
"items": {"type": "string"},
"description": "Argv list passed verbatim; path arguments must stay inside the agent workspace (assets_dir is allowed for reference inspection)",
},
"cwd": {
"type": "string",
"description": "Optional working directory; default and only allowed root is the agent workspace",
},
"timeout_sec": {
"type": "number",
"description": "Wall-clock cap (default 120s, hard-capped by the operator's tool timeout)",
},
},
"required": ["command"],
},
executor=t_run_command,
category="system",
requires_project=False,
)
)
registry.on_pre_execute(_shell_guard)
@@ -163,6 +163,55 @@ def user_allows_render(ctx: ToolContext) -> bool:
return is_render_request(latest) or is_confirmation(latest)
# ── Shell permission (run_command) ────────────────────────────────────────
# A non-read-only command runs only when the user explicitly asked for it:
# a scope="shell" question card answered affirmatively, or the command name
# appearing in their own visible words ("run ffprobe on clip 3" — ffprobe is
# read-only anyway; "run ffmpeg to convert it" names the mutating command).
# A bare "yes" to an unrelated card must not unlock the shell.
_SHELL_REQUEST_RE = re.compile(
r"\b(run|execute|launch|invoke)\b.{0,40}?\b"
r"(command|shell|terminal|ffmpeg|ffprobe|script|python|cli)\b",
re.IGNORECASE,
)
def is_shell_request(text: str, command: str | None = None) -> bool:
"""True when the user's prose explicitly asks for shell/command use.
With `command`, the command name appearing in the visible words counts
by itself; without it, a generic run/execute-a-command cue is matched.
Clause-scoped: the cue must not be negated.
"""
t = user_prose(text)
if not t:
return False
if command and re.search(rf"(?<![A-Za-z0-9_-]){re.escape(command)}(?![A-Za-z0-9_-])", t, re.IGNORECASE):
for clause in re.split(r"[,.;!?]|\bbut\b|\bhowever\b", t, flags=re.IGNORECASE):
m = re.search(
rf"(?<![A-Za-z0-9_-]){re.escape(command)}(?![A-Za-z0-9_-])", clause, re.IGNORECASE
)
if m and not _cue_is_negated(clause[: m.start()], clause[m.end() :]):
return True
return False
for clause in re.split(r"[,.;!?]|\bbut\b|\bhowever\b", t, flags=re.IGNORECASE):
m = _SHELL_REQUEST_RE.search(clause)
if m and not _cue_is_negated(clause[: m.start()], clause[m.end() :]):
return True
return False
def user_allows_shell(ctx: ToolContext, command: str | None = None) -> bool:
"""Shell permission from explicit user acts only (mirrors user_allows_render)."""
if has_structured_approval(ctx, "shell"):
return True
from calliope.agent.harness import log as session_log
latest = session_log.latest_user_message(ctx.session_id) or ""
return is_shell_request(latest, command)
# ── Structured approvals (ask_user question cards) ────────────────────────
# An approval is an event-log fact, not parsed prose: question/asked followed
# by question/answered with an affirmative option. The card click sends the
@@ -179,6 +179,12 @@ class ToolRegistry:
return False
if t.blind_only and ctx.project_id is not None:
return False
# shot_* tools exist ONLY on the Build Scene surface (origin='scene').
# A chat-origin session (AI Canvas, main loop) should not see 23 shot
# tools it can never legitimately use — payload noise at best, wasted
# calls at worst.
if t.category == "shot" and ctx.origin != "scene":
return False
# Build Scene surface: shot tools + minimal base ONLY. A missing tool
# is harder to misuse than one that fails at execute time.
if ctx.origin == "scene" and not _scene_scoped(t):
+32 -2
View File
@@ -102,6 +102,15 @@ class Settings(BaseSettings):
data_dir: Path = DEFAULT_DATA_DIR
assets_dir: Path = DEFAULT_ASSETS_DIR
db_name: str = "calliope.db"
# Dedicated sandbox folder the agent shell (run_command) may work in.
# None → data_dir / "workspace". The shell's cwd AND its path-like args
# are containment-checked against this folder (plus assets_dir for
# read-side reference inspection) — config / DB / repo root are never
# reachable from a tool call. User-settable in Settings → System Paths.
agent_workspace_dir: Path | None = None
# Master switch for the agent shell. Default OFF (ships to end users with
# secrets on disk; the eval callout requires explicit opt-in).
agent_shell_enabled: bool = False
llm_base_url: str = "http://127.0.0.1:11434/v1"
llm_model: str = "llama3.2"
@@ -145,9 +154,17 @@ class Settings(BaseSettings):
def db_path(self) -> Path:
return self.data_dir / self.db_name
@property
def workspace_dir(self) -> Path:
"""The agent shell's sandbox root (real folder, always under a disk home)."""
if self.agent_workspace_dir is not None:
return self.agent_workspace_dir
return self.data_dir / "workspace"
def ensure_storage_dirs(self) -> None:
self.data_dir.mkdir(parents=True, exist_ok=True)
self.assets_dir.mkdir(parents=True, exist_ok=True)
self.workspace_dir.mkdir(parents=True, exist_ok=True)
def ensure_llm_profiles(self) -> bool:
"""Guarantee at least one profile and that llm_* match the active one.
@@ -313,6 +330,7 @@ class Settings(BaseSettings):
"port": self.port,
"data_dir": str(self.data_dir),
"assets_dir": str(self.assets_dir),
"agent_workspace_dir": str(self.workspace_dir),
"db_name": self.db_name,
"llm_base_url": self.llm_base_url,
"llm_model": self.llm_model,
@@ -328,6 +346,7 @@ class Settings(BaseSettings):
"agent_max_steps": self.agent_max_steps,
"agent_hardening_prompt": self.agent_hardening_prompt,
"agent_history_char_budget": self.agent_history_char_budget,
"agent_shell_enabled": bool(self.agent_shell_enabled),
"h3_rewrite_extra_body": dict(self.h3_rewrite_extra_body or {}),
"dry_run": bool(self.dry_run),
}
@@ -354,7 +373,7 @@ class Settings(BaseSettings):
return
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
path_keys = {"data_dir", "assets_dir"}
path_keys = {"data_dir", "assets_dir", "agent_workspace_dir"}
# Ignore legacy comfyui_input_dir / comfyui_output_dir if present in old configs.
skip_keys = {"comfyui_input_dir", "comfyui_output_dir"}
for key, value in data.items():
@@ -364,12 +383,17 @@ class Settings(BaseSettings):
value = normalize_path(value)
if key == "dry_run":
value = bool(value)
if hasattr(self, key) and key not in {"data_dir", "assets_dir"}:
if key == "agent_shell_enabled":
value = bool(value)
if hasattr(self, key) and key not in {"data_dir", "assets_dir", "agent_workspace_dir"}:
setattr(self, key, value)
data_dir = normalize_path(data.get("data_dir")) or DEFAULT_DATA_DIR
assets_dir = normalize_path(data.get("assets_dir")) or (data_dir / "assets")
self._apply_storage_paths(data_dir, assets_dir)
# Agent workspace: explicit + non-ephemeral wins; else the data_dir default.
ws = normalize_path(data.get("agent_workspace_dir"))
self.agent_workspace_dir = ws if ws is not None and not is_ephemeral_path(ws) else None
self.dry_run = bool(data.get("dry_run", False))
self.ensure_storage_dirs()
profiles_migrated = self.ensure_llm_profiles()
@@ -389,7 +413,11 @@ class Settings(BaseSettings):
self.data_dir = DEFAULT_DATA_DIR
if is_ephemeral_path(self.assets_dir):
self.assets_dir = self.data_dir / "assets"
# Same poison guard for the agent shell workspace
if self.agent_workspace_dir is not None and is_ephemeral_path(self.agent_workspace_dir):
self.agent_workspace_dir = None
self.dry_run = bool(self.dry_run)
self.agent_shell_enabled = bool(self.agent_shell_enabled)
self.ensure_storage_dirs()
data = {
@@ -397,6 +425,7 @@ class Settings(BaseSettings):
"port": self.port,
"data_dir": str(self.data_dir),
"assets_dir": str(self.assets_dir),
"agent_workspace_dir": str(self.workspace_dir),
"db_name": self.db_name,
"llm_base_url": self.llm_base_url,
"llm_model": self.llm_model,
@@ -412,6 +441,7 @@ class Settings(BaseSettings):
"agent_max_steps": self.agent_max_steps,
"agent_hardening_prompt": self.agent_hardening_prompt,
"agent_history_char_budget": self.agent_history_char_budget,
"agent_shell_enabled": bool(self.agent_shell_enabled),
"h3_rewrite_extra_body": dict(self.h3_rewrite_extra_body or {}),
"dry_run": bool(self.dry_run),
}
@@ -30,12 +30,15 @@ class SettingsUpdate(BaseModel):
comfyui_base_url: str | None = None
data_dir: str | None = None
assets_dir: str | None = None
agent_workspace_dir: str | None = None
agent_shell_enabled: bool | None = None
queue_concurrency: int | None = Field(None, ge=1, le=8)
queue_poll_interval_sec: float | None = Field(None, ge=0.5, le=60.0)
queue_poll_timeout_sec: float | None = Field(None, ge=0, le=86400.0)
queue_max_retries: int | None = Field(None, ge=0, le=10)
agent_max_steps: int | None = Field(None, ge=1, le=100)
agent_hardening_prompt: str | None = Field(None, max_length=20000)
agent_history_char_budget: int | None = Field(None, ge=10_000, le=2_000_000)
h3_rewrite_extra_body: dict[str, Any] | None = None
dry_run: bool | None = None
@@ -54,7 +57,7 @@ async def update_settings(payload: SettingsUpdate) -> dict[str, Any]:
legacy_llm = {k: data.pop(k) for k in list(data) if k in _LEGACY_LLM_KEYS}
for key, value in data.items():
if key in {"data_dir", "assets_dir"}:
if key in {"data_dir", "assets_dir", "agent_workspace_dir"}:
path = normalize_path(value)
if path is not None:
setattr(settings, key, path)
@@ -62,6 +65,9 @@ async def update_settings(payload: SettingsUpdate) -> dict[str, Any]:
if key == "dry_run":
setattr(settings, key, bool(value))
continue
if key == "agent_shell_enabled":
setattr(settings, key, bool(value))
continue
setattr(settings, key, value)
if profiles_in is not None:
@@ -0,0 +1,21 @@
{
"name": "ask_user_pause_mid_batch",
"description": "Synthetic: a step with two tool calls where the first is ask_user; the second call has skipped tool/call + tool/result receipts and the turn ends awaiting_input.",
"events": [
{ "seq": 1, "type": "user/message", "data": { "content": "Generate a portrait for Kira." } },
{ "seq": 2, "type": "turn/start", "data": { "turn": 1 } },
{ "seq": 3, "type": "step/start", "data": { "turn": 1, "step": 1 } },
{ "seq": 4, "type": "assistant/message", "data": { "turn": 1, "step": 1, "content": null, "agent_name": null, "tool_calls": [
{ "id": "q1", "type": "function", "function": { "name": "ask_user", "arguments": "{\"question\": \"Render a portrait of Kira now?\", \"options\": [\"Yes\", \"No\"], \"scope\": \"render\"}" } },
{ "id": "w1", "type": "function", "function": { "name": "enqueue_asset_jobs", "arguments": "{\"character_ids\": [3]}" } }
] } },
{ "seq": 5, "type": "tool/call", "data": { "turn": 1, "step": 1, "call_id": "q1", "tool_name": "ask_user", "arguments": "{\"question\": \"Render a portrait of Kira now?\", \"options\": [\"Yes\", \"No\"], \"scope\": \"render\"}", "agent_name": null } },
{ "seq": 6, "type": "tool/result", "data": { "turn": 1, "step": 1, "call_id": "q1", "tool_name": "ask_user", "result": { "ok": true, "awaiting_user_input": true, "question": "Render a portrait of Kira now?" }, "agent_name": null } },
{ "seq": 7, "type": "question/asked", "data": { "question": "Render a portrait of Kira now?", "options": ["Yes", "No"], "scope": "render" } },
{ "seq": 8, "type": "tool/call", "data": { "turn": 1, "step": 1, "call_id": "w1", "tool_name": "enqueue_asset_jobs", "arguments": "{\"character_ids\": [3]}", "agent_name": null } },
{ "seq": 9, "type": "tool/result", "data": { "turn": 1, "step": 1, "call_id": "w1", "tool_name": "enqueue_asset_jobs", "result": { "ok": false, "skipped": true, "error": "Not executed — this turn paused for the user's answer to an ask_user question in the same step. Re-issue the call after they answer if still needed." }, "agent_name": null } },
{ "seq": 10, "type": "step/end", "data": { "turn": 1, "step": 1 } },
{ "seq": 11, "type": "assistant/message", "data": { "turn": 1, "step": 1, "content": "Paused: Render a portrait of Kira now?", "agent_name": null } },
{ "seq": 12, "type": "turn/end", "data": { "turn": 1, "status": "awaiting_input" } }
]
}
@@ -0,0 +1,25 @@
{
"name": "guard_denial_recovery",
"description": "Synthetic: a render call denied by guard_render_approval, the model escalates via ask_user, and the turn ends awaiting_input.",
"events": [
{ "seq": 1, "type": "user/message", "data": { "content": "Make the film better." } },
{ "seq": 2, "type": "turn/start", "data": { "turn": 1 } },
{ "seq": 3, "type": "step/start", "data": { "turn": 1, "step": 1 } },
{ "seq": 4, "type": "assistant/message", "data": { "turn": 1, "step": 1, "content": null, "agent_name": null, "tool_calls": [
{ "id": "r1", "type": "function", "function": { "name": "enqueue_video_jobs", "arguments": "{\"scene_ids\": [1]}" } }
] } },
{ "seq": 5, "type": "tool/call", "data": { "turn": 1, "step": 1, "call_id": "r1", "tool_name": "enqueue_video_jobs", "arguments": "{\"scene_ids\": [1]}", "agent_name": null } },
{ "seq": 6, "type": "tool/result", "data": { "turn": 1, "step": 1, "call_id": "r1", "tool_name": "enqueue_video_jobs", "result": { "ok": false, "reason_code": "guard_render_approval", "error": "blocked: nothing is being generated — the user has not asked for generation. Ask with ask_user(...)." }, "agent_name": null } },
{ "seq": 7, "type": "step/end", "data": { "turn": 1, "step": 1 } },
{ "seq": 8, "type": "step/start", "data": { "turn": 1, "step": 2 } },
{ "seq": 9, "type": "assistant/message", "data": { "turn": 1, "step": 2, "content": null, "agent_name": null, "tool_calls": [
{ "id": "q1", "type": "function", "function": { "name": "ask_user", "arguments": "{\"question\": \"Render scene 1 now?\", \"options\": [\"Yes\", \"No\"], \"scope\": \"render\"}" } }
] } },
{ "seq": 10, "type": "tool/call", "data": { "turn": 1, "step": 2, "call_id": "q1", "tool_name": "ask_user", "arguments": "{\"question\": \"Render scene 1 now?\", \"options\": [\"Yes\", \"No\"], \"scope\": \"render\"}", "agent_name": null } },
{ "seq": 11, "type": "tool/result", "data": { "turn": 1, "step": 2, "call_id": "q1", "tool_name": "ask_user", "result": { "ok": true, "awaiting_user_input": true, "question": "Render scene 1 now?" }, "agent_name": null } },
{ "seq": 12, "type": "question/asked", "data": { "question": "Render scene 1 now?", "options": ["Yes", "No"], "scope": "render" } },
{ "seq": 13, "type": "step/end", "data": { "turn": 1, "step": 2 } },
{ "seq": 14, "type": "assistant/message", "data": { "turn": 1, "step": 2, "content": "Paused: Render scene 1 now?", "agent_name": null } },
{ "seq": 15, "type": "turn/end", "data": { "turn": 1, "status": "awaiting_input" } }
]
}
@@ -0,0 +1,22 @@
{
"name": "multi_tool_sequential",
"description": "Synthetic: one turn, two steps. Step 1 issues two tool calls (one write, one read) executed sequentially; step 2 answers.",
"events": [
{ "seq": 1, "type": "user/message", "data": { "content": "Summarize the project and list the workflows." } },
{ "seq": 2, "type": "turn/start", "data": { "turn": 1 } },
{ "seq": 3, "type": "step/start", "data": { "turn": 1, "step": 1 } },
{ "seq": 4, "type": "assistant/message", "data": { "turn": 1, "step": 1, "content": null, "agent_name": null, "tool_calls": [
{ "id": "c1", "type": "function", "function": { "name": "get_workspace", "arguments": "{}" } },
{ "id": "c2", "type": "function", "function": { "name": "list_workflows", "arguments": "{}" } }
] } },
{ "seq": 5, "type": "tool/call", "data": { "turn": 1, "step": 1, "call_id": "c1", "tool_name": "get_workspace", "arguments": "{}", "agent_name": null } },
{ "seq": 6, "type": "tool/result", "data": { "turn": 1, "step": 1, "call_id": "c1", "tool_name": "get_workspace", "result": { "ok": true, "characters": 2 }, "agent_name": null } },
{ "seq": 7, "type": "tool/call", "data": { "turn": 1, "step": 1, "call_id": "c2", "tool_name": "list_workflows", "arguments": "{}", "agent_name": null } },
{ "seq": 8, "type": "tool/result", "data": { "turn": 1, "step": 1, "call_id": "c2", "tool_name": "list_workflows", "result": { "ok": true, "workflows": [] }, "agent_name": null } },
{ "seq": 9, "type": "step/end", "data": { "turn": 1, "step": 1 } },
{ "seq": 10, "type": "step/start", "data": { "turn": 1, "step": 2 } },
{ "seq": 11, "type": "assistant/message", "data": { "turn": 1, "step": 2, "content": "The project has 2 characters and no workflows yet.", "agent_name": null } },
{ "seq": 12, "type": "step/end", "data": { "turn": 1, "step": 2 } },
{ "seq": 13, "type": "turn/end", "data": { "turn": 1, "status": "completed" } }
]
}
@@ -48,7 +48,7 @@ def _run(sid: int, tool: str, args: dict | None = None):
def test_gate_tools_visible_in_sandbox():
from calliope.agent.harness.tools import openai_tools_payload
ctx = ToolContext(session_id=_mk_session(), project_id=None)
ctx = ToolContext(session_id=_mk_session(), project_id=None, origin="scene")
names = {e["function"]["name"] for e in openai_tools_payload(ctx)}
assert "record_build_scene_gate" in names
assert "get_build_scene_gates" in names
@@ -0,0 +1,311 @@
"""Golden-scenario replay harness.
Replays recorded agent_events (from fixtures — synthetic, never real user
sessions) through run_turn with the LLM mocked to REPLAY the recorded
assistant outputs, then asserts structural invariants on the NEW event log:
- every assistant tool_calls message has a matching tool result (no dangling
call ids in derive_llm_history),
- turn/end exists with a valid status,
- bridged/parallel paths produce the same derived shape as sequential.
The replay LLM is driven by the fixture itself: each fixture embeds an
ordered list of assistant replies (the same shape run_turn's stream yields),
so a fixture both documents a golden scenario and deterministically
re-executes it.
"""
from __future__ import annotations
import asyncio
import json
import tempfile
from pathlib import Path
import pytest
from calliope.agent.harness import loop as loop_mod
from calliope.agent.harness import log as session_log
from calliope.agent.harness.registry import ToolContext
from calliope.config import settings
from calliope.db import get_db
FIXTURES_DIR = Path(__file__).resolve().parent / "fixtures" / "replay"
VALID_TURN_STATUSES = {"completed", "step_budget_exhausted", "cancelled", "failed", "awaiting_input"}
@pytest.fixture(autouse=True, scope="module")
def _never_touch_real_db():
prev = settings.data_dir
with tempfile.TemporaryDirectory() as tmp:
settings.data_dir = Path(tmp)
settings.assets_dir = Path(tmp) / "assets"
asyncio.run(_migrate(settings.db_path))
yield
settings.data_dir = prev
async def _migrate(db_path):
from calliope.db import migrate_db
await migrate_db(db_path)
def _mk_session(title: str) -> int:
conn = get_db(settings.db_path)
try:
cur = conn.execute(
"INSERT INTO agent_sessions (title, project_id) VALUES (?, NULL)", (title,)
)
conn.commit()
return int(cur.lastrowid)
finally:
conn.close()
def _load_fixtures() -> list[dict]:
return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(FIXTURES_DIR.glob("*.json"))]
class _ReplayClient:
"""One scripted reply per step, popped in order; records usage seen."""
def __init__(self, replies: list[dict]):
self._replies = list(replies)
self.closed = False
def chat_stream(self, messages, temperature=0.4, tools=None, tool_choice=None):
reply = self._replies.pop(0) if self._replies else {
"role": "assistant", "content": "done", "tool_calls": []
}
return self._stream(reply)
async def _stream(self, reply: dict):
if reply.get("content"):
yield {"type": "delta", "content": reply["content"]}
for tc in reply.get("tool_calls") or []:
yield {"type": "tool_call", "tool_call": tc}
if reply.get("usage"):
yield {"type": "usage", "usage": reply["usage"]}
yield {"type": "done"}
async def close(self):
self.closed = True
class _RecordingRegistry:
"""Executes only the fixture's expected tools; records (name, args)."""
def __init__(
self,
results_by_tool: dict[str, dict] | None = None,
payload_tools: list[str] | None = None,
):
self.executed: list[tuple[str, dict]] = []
self.results_by_tool = results_by_tool or {}
self.payload_tools = payload_tools or []
def openai_payload(self, ctx):
return [
{"type": "function", "function": {"name": n, "description": "", "parameters": {}}}
for n in self.payload_tools
]
def get(self, name):
if name in self.payload_tools or name in self.results_by_tool:
return {"name": name}
return None
async def execute(self, ctx, name, args):
self.executed.append((name, dict(args)))
r = self.results_by_tool.get(name)
if r is not None:
return dict(r)
if name == "ask_user":
return {
"ok": True,
"awaiting_user_input": True,
"question": "Render scene 1 now?",
}
return {"ok": True}
def _replay(fixture: dict, registry: _RecordingRegistry) -> list[dict]:
"""Load the fixture's events into a fresh session, replay its assistant
replies through run_turn, return the NEW log's derived history."""
sid = _mk_session(f"replay-{fixture['name']}")
for e in fixture["events"]:
session_log.append_event(sid, e["type"], dict(e["data"]))
# The replay replies are the fixture's assistant messages (in order).
replies = [
{"content": e["data"].get("content"), "tool_calls": e["data"].get("tool_calls") or [], "usage": e["data"].get("usage")}
for e in fixture["events"]
if e["type"] == "assistant/message"
]
client = _ReplayClient(replies)
orig_client = loop_mod.LLMClient
orig_registry = loop_mod.get_registry
loop_mod.LLMClient = lambda *a, **k: client
loop_mod.get_registry = lambda: registry
try:
ctx = ToolContext(session_id=sid, project_id=None)
history = session_log.derive_llm_history(session_log.read_events(sid))
asyncio.run(loop_mod.run_turn(ctx, history))
finally:
loop_mod.LLMClient = orig_client
loop_mod.get_registry = orig_registry
return session_log.derive_llm_history(session_log.read_events(sid))
def _assert_common_invariants(fixture: dict, derived: list[dict]) -> None:
"""Invariants shared by every golden scenario."""
# 1. Every assistant tool_calls message has matching tool results — no
# dangling call ids (derive would otherwise 400 on strict servers).
call_ids: list[str] = []
for m in derived:
for tc in m.get("tool_calls") or []:
call_ids.append(tc["id"])
result_ids = {m["tool_call_id"] for m in derived if m.get("role") == "tool"}
assert call_ids, f"{fixture['name']}: replay produced no tool calls"
for cid in call_ids:
assert cid in result_ids, f"{fixture['name']}: dangling call id {cid}"
# 2. turn/end exists with a valid status.
events = session_log.read_events(_session_id_for(fixture))
turn_ends = [e for e in events if e.type == session_log.TURN_END]
assert turn_ends, f"{fixture['name']}: no turn/end event"
status = turn_ends[-1].data.get("status")
assert status in VALID_TURN_STATUSES, f"{fixture['name']}: invalid turn status {status}"
# 3. step/end present for every step/start.
starts = sum(1 for e in events if e.type == session_log.STEP_START)
ends = sum(1 for e in events if e.type == session_log.STEP_END)
assert starts == ends, f"{fixture['name']}: {starts} step/start vs {ends} step/end"
_SESSION_IDS: dict[str, int] = {}
def _session_id_for(fixture: dict) -> int:
return _SESSION_IDS[fixture["name"]]
@pytest.mark.parametrize("fixture", _load_fixtures(), ids=lambda f: f["name"])
def test_replay_invariants(fixture: dict):
registry = _RecordingRegistry()
derived = _replay(fixture, registry)
_SESSION_IDS[fixture["name"]] = _last_session_id()
_assert_common_invariants(fixture, derived)
def _last_session_id() -> int:
conn = get_db(settings.db_path)
try:
row = conn.execute("SELECT MAX(id) AS m FROM agent_sessions").fetchone()
return int(row["m"])
finally:
conn.close()
def test_bridge_replay_matches_sequential_shape():
"""A bridged JSON-action reply must produce the SAME derived history shape
as a native tool-call reply (assistant tool_calls -> tool result), so
downstream history replay cannot tell the paths apart."""
sid = _mk_session("replay-bridge")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "get workspace"})
bridge_reply = {
"content": '```json\n{"tool": "get_workspace", "arguments": {}}\n```',
"tool_calls": [],
}
final_reply = {"content": "All done.", "tool_calls": []}
client = _ReplayClient([bridge_reply, final_reply])
registry = _RecordingRegistry(
{"get_workspace": {"ok": True, "characters": 0}}, payload_tools=["get_workspace"]
)
orig_client, orig_registry = loop_mod.LLMClient, loop_mod.get_registry
loop_mod.LLMClient = lambda *a, **k: client
loop_mod.get_registry = lambda: registry
try:
ctx = ToolContext(session_id=sid, project_id=None)
history = session_log.derive_llm_history(session_log.read_events(sid))
asyncio.run(loop_mod.run_turn(ctx, history))
finally:
loop_mod.LLMClient, loop_mod.get_registry = orig_client, orig_registry
derived = session_log.derive_llm_history(session_log.read_events(sid))
bridge_assistant = [m for m in derived if m.get("tool_calls")]
assert bridge_assistant, "bridged call did not materialize as assistant tool_calls"
assert bridge_assistant[0]["tool_calls"][0]["id"].startswith("bridge_")
result_msgs = [m for m in derived if m.get("role") == "tool"]
assert result_msgs and result_msgs[0]["tool_call_id"].startswith("bridge_")
# The registry executed exactly once through the same guarded path.
assert [n for n, _ in registry.executed] == ["get_workspace"]
def test_parallel_replay_preserves_order():
"""A read-only parallel batch (all allowlisted) keeps the batch's original
call order in the derived history — gather must not reorder results."""
sid = _mk_session("replay-parallel")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "inspect"})
batch_reply = {
"content": None,
"tool_calls": [
{"id": "p1", "type": "function", "function": {"name": "get_workspace", "arguments": "{}"}},
{"id": "p2", "type": "function", "function": {"name": "list_workflows", "arguments": "{}"}},
{"id": "p3", "type": "function", "function": {"name": "list_memories", "arguments": "{}"}},
],
}
final_reply = {"content": "done", "tool_calls": []}
client = _ReplayClient([batch_reply, final_reply])
registry = _RecordingRegistry()
orig_client, orig_registry = loop_mod.LLMClient, loop_mod.get_registry
loop_mod.LLMClient = lambda *a, **k: client
loop_mod.get_registry = lambda: registry
try:
ctx = ToolContext(session_id=sid, project_id=None)
history = session_log.derive_llm_history(session_log.read_events(sid))
asyncio.run(loop_mod.run_turn(ctx, history))
finally:
loop_mod.LLMClient, loop_mod.get_registry = orig_client, orig_registry
derived = session_log.derive_llm_history(session_log.read_events(sid))
results = [m["tool_call_id"] for m in derived if m.get("role") == "tool"]
assert results == ["p1", "p2", "p3"], f"order drifted: {results}"
events = session_log.read_events(sid)
step_ends = [e for e in events if e.type == session_log.STEP_END]
assert step_ends and step_ends[0].data.get("parallel") is True
def test_usage_recorded_when_server_reports_it():
"""step/end + turn/end carry usage only when the server reported it."""
sid = _mk_session("replay-usage")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "hi"})
usage_reply = {
"content": "quick answer",
"tool_calls": [],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
}
client = _ReplayClient([usage_reply])
orig_client, orig_registry = loop_mod.LLMClient, loop_mod.get_registry
loop_mod.LLMClient = lambda *a, **k: client
loop_mod.get_registry = lambda: _RecordingRegistry()
try:
ctx = ToolContext(session_id=sid, project_id=None)
history = session_log.derive_llm_history(session_log.read_events(sid))
asyncio.run(loop_mod.run_turn(ctx, history))
finally:
loop_mod.LLMClient, loop_mod.get_registry = orig_client, orig_registry
events = session_log.read_events(sid)
step_end = next(e for e in events if e.type == session_log.STEP_END)
assert step_end.data.get("usage") == {
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15
}
turn_end = next(e for e in events if e.type == session_log.TURN_END)
assert turn_end.data.get("usage", {}).get("total_tokens") == 15
@@ -0,0 +1,23 @@
"""History budget setting: API roundtrip + field validation (finding 7)."""
from __future__ import annotations
def test_history_budget_roundtrip(client, monkeypatch):
"""POST /api/settings persists agent_history_char_budget; GET reflects it."""
r = client.post("/api/settings", json={"agent_history_char_budget": 120_000})
assert r.status_code == 200
assert r.json()["agent_history_char_budget"] == 120_000
r2 = client.get("/api/settings")
assert r2.status_code == 200
assert r2.json()["agent_history_char_budget"] == 120_000
def test_history_budget_rejects_below_floor(client):
"""ge=10_000 — a 4999-char budget is a validation error, not a silent set."""
r = client.post("/api/settings", json={"agent_history_char_budget": 4_999})
assert r.status_code == 422
def test_history_budget_rejects_above_ceiling(client):
r = client.post("/api/settings", json={"agent_history_char_budget": 3_000_000})
assert r.status_code == 422
+389
View File
@@ -0,0 +1,389 @@
"""Legacy JSON-action bridge + read-only parallel dispatch (loop.run_turn).
Bridge: a no-function-calling model answering with a {"tool": ...} JSON
action still executes through the same guarded path, capped per turn; raw
JSON that parses as no action gets the no-function-calling note.
Parallel: a read-only batch gathers, mixed batches stay sequential, ask_user
is never parallel.
"""
from __future__ import annotations
import asyncio
import json
import tempfile
from pathlib import Path
import pytest
from calliope.agent.harness import loop as loop_mod
from calliope.agent.harness import log as session_log
from calliope.agent.harness.loop import (
NO_FUNCTION_CALLING_NOTE,
_BRIDGE_CAP_PER_TURN,
_extract_json_action,
_is_readonly_tool,
)
from calliope.agent.harness.registry import ToolContext
from calliope.config import settings
from calliope.db import get_db
@pytest.fixture(autouse=True, scope="module")
def _never_touch_real_db():
prev = settings.data_dir
with tempfile.TemporaryDirectory() as tmp:
settings.data_dir = Path(tmp)
settings.assets_dir = Path(tmp) / "assets"
asyncio.run(_migrate(settings.db_path))
yield
settings.data_dir = prev
async def _migrate(db_path):
from calliope.db import migrate_db
await migrate_db(db_path)
def _mk_session(title: str = "loop-bridge") -> int:
conn = get_db(settings.db_path)
try:
cur = conn.execute(
"INSERT INTO agent_sessions (title, project_id) VALUES (?, NULL)", (title,)
)
conn.commit()
return int(cur.lastrowid)
finally:
conn.close()
def _tc(name: str, args: str = "{}", call_id: str = "c1"):
return {
"id": call_id,
"type": "function",
"function": {"name": name, "arguments": args},
}
class _ScriptedStreamClient:
"""chat_stream replays scripted replies; each reply is a raw assistant msg."""
def __init__(self, replies):
self._replies = list(replies)
def chat_stream(self, messages, temperature=0.4, tools=None, tool_choice=None):
reply = self._replies.pop(0) if self._replies else {
"role": "assistant", "content": "done", "tool_calls": []
}
return self._stream(reply)
async def _stream(self, reply):
if reply.get("content"):
yield {"type": "delta", "content": reply["content"]}
for tc in reply.get("tool_calls") or []:
yield {"type": "tool_call", "tool_call": tc}
yield {"type": "done"}
async def close(self):
pass
class _StubRegistry:
def __init__(self, results_by_tool=None, payload_tools=None):
self.executed: list[tuple[str, dict]] = []
self.results_by_tool = results_by_tool or {}
self.payload_tools = payload_tools or []
def openai_payload(self, ctx):
return [
{"type": "function", "function": {"name": n, "description": "", "parameters": {}}}
for n in self.payload_tools
]
def get(self, name):
if name in self.payload_tools:
return {"name": name}
return None
async def execute(self, ctx, name, args):
self.executed.append((name, dict(args)))
r = self.results_by_tool.get(name)
if r is not None:
return dict(r)
if name == "ask_user":
return {"ok": True, "awaiting_user_input": True, "question": "q?"}
return {"ok": True}
def _run_turn_with(sid, client, registry, replies=None):
orig_client, orig_registry = loop_mod.LLMClient, loop_mod.get_registry
loop_mod.LLMClient = lambda *a, **k: client
loop_mod.get_registry = lambda: registry
try:
ctx = ToolContext(session_id=sid, project_id=None)
history = session_log.derive_llm_history(session_log.read_events(sid))
final = asyncio.run(loop_mod.run_turn(ctx, history))
finally:
loop_mod.LLMClient, loop_mod.get_registry = orig_client, orig_registry
return final
def _events_of(sid):
return session_log.read_events(sid)
# ── _extract_json_action ─────────────────────────────────────────────────
def test_extract_fenced_action():
text = 'I will do it.\n```json\n{"tool": "get_workspace", "arguments": {"sections": ["beats"]}}\n```'
assert _extract_json_action(text) == ("get_workspace", {"sections": ["beats"]})
def test_extract_bare_object_action():
text = '{"tool": "get_story", "arguments": {}}'
assert _extract_json_action(text) == ("get_story", {})
def test_extract_returns_none_for_prose():
assert _extract_json_action("The project has 3 characters and 2 scenes.") is None
assert _extract_json_action("") is None
def test_extract_rejects_non_dict_arguments():
text = '{"tool": "get_story", "arguments": "not-a-dict"}'
assert _extract_json_action(text) is None
# ── bridge executes through the guarded path ─────────────────────────────
def test_bridge_executes_action_and_logs_events():
sid = _mk_session()
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "go"})
client = _ScriptedStreamClient(
[
{"content": '```json\n{"tool": "get_workspace", "arguments": {}}\n```', "tool_calls": []},
{"content": "All done.", "tool_calls": []},
]
)
registry = _StubRegistry(
{"get_workspace": {"ok": True}}, payload_tools=["get_workspace"]
)
final = _run_turn_with(sid, client, registry)
assert final == "All done."
assert [n for n, _ in registry.executed] == ["get_workspace"]
events = _events_of(sid)
tool_calls = [e for e in events if e.type == session_log.TOOL_CALL]
assert tool_calls and tool_calls[0].data["call_id"].startswith("bridge_")
assert tool_calls[0].data.get("bridged") is True
# ASSISTANT_MESSAGE carries the synthetic tool_calls for history derivation.
assistant = [e for e in events if e.type == session_log.ASSISTANT_MESSAGE]
assert any(
(e.data.get("tool_calls") or []) and e.data["tool_calls"][0]["id"].startswith("bridge_")
for e in assistant
)
# step/end marks the bridged step.
step_ends = [e for e in events if e.type == session_log.STEP_END]
assert any(e.data.get("bridged") is True for e in step_ends)
def test_bridge_guard_denial_applies():
"""A bridged requires_approval call is denied like a native one — the
bridge is transport, not a permission bypass."""
sid = _mk_session()
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "render"})
denial = {"ok": False, "reason_code": "guard_render_approval", "error": "blocked"}
client = _ScriptedStreamClient(
[
{"content": '{"tool": "enqueue_video_jobs", "arguments": {"scene_ids": [1]}}', "tool_calls": []},
{"content": "gave up", "tool_calls": []},
]
)
registry = _StubRegistry({"enqueue_video_jobs": denial}, payload_tools=["enqueue_video_jobs"])
_run_turn_with(sid, client, registry)
results = [e for e in _events_of(sid) if e.type == session_log.TOOL_RESULT]
assert results[0].data["result"].get("reason_code") == "guard_render_approval"
def test_bridge_cap_stops_parse_loop():
sid = _mk_session()
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "go"})
# Distinct args per reply so the RepeatGuard stays out of the way and the
# test isolates the bridge cap itself.
replies = [
{"content": json.dumps({"tool": "get_workspace", "arguments": {"n": i}}), "tool_calls": []}
for i in range(_BRIDGE_CAP_PER_TURN + 5)
]
client = _ScriptedStreamClient(replies)
registry = _StubRegistry({"get_workspace": {"ok": True}}, payload_tools=["get_workspace"])
final = _run_turn_with(sid, client, registry)
assert len(registry.executed) == _BRIDGE_CAP_PER_TURN
assert "maximum number of bridged tool calls" in final
def test_raw_json_without_action_gets_no_fc_note():
sid = _mk_session()
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "hi"})
client = _ScriptedStreamClient(
[{"content": '{"status": "ok", "items": []}', "tool_calls": []}]
)
registry = _StubRegistry(payload_tools=["get_workspace"])
final = _run_turn_with(sid, client, registry)
assert NO_FUNCTION_CALLING_NOTE in final
def test_plain_prose_final_untouched():
sid = _mk_session()
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "hi"})
client = _ScriptedStreamClient([{"content": "The project has 2 scenes.", "tool_calls": []}])
registry = _StubRegistry(payload_tools=["get_workspace"])
final = _run_turn_with(sid, client, registry)
assert final == "The project has 2 scenes."
assert NO_FUNCTION_CALLING_NOTE not in final
# ── read-only parallel dispatch ──────────────────────────────────────────
def test_readonly_allowlist_membership():
assert _is_readonly_tool("get_workspace")
assert _is_readonly_tool("list_workflows") # list_ prefix
assert _is_readonly_tool("read_skill")
assert not _is_readonly_tool("run_command")
assert not _is_readonly_tool("enqueue_video_jobs")
assert not _is_readonly_tool("ask_user")
assert not _is_readonly_tool("save_memory") # a write
assert not _is_readonly_tool("wait_for_jobs")
def test_readonly_batch_runs_parallel_and_preserves_order():
sid = _mk_session("loop-parallel")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "inspect"})
client = _ScriptedStreamClient(
[
{
"content": None,
"tool_calls": [
_tc("get_workspace", call_id="p1"),
_tc("list_workflows", call_id="p2"),
_tc("list_memories", call_id="p3"),
],
},
{"content": "done", "tool_calls": []},
]
)
registry = _StubRegistry(
payload_tools=["get_workspace", "list_workflows", "list_memories"]
)
_run_turn_with(sid, client, registry)
events = _events_of(sid)
step_ends = [e for e in events if e.type == session_log.STEP_END]
assert any(e.data.get("parallel") is True for e in step_ends)
results = [e for e in events if e.type == session_log.TOOL_RESULT]
assert [e.data["call_id"] for e in results] == ["p1", "p2", "p3"]
def test_parallel_batch_logs_call_and_result_pairs():
"""Every parallel tool/result keeps a matching tool/call event (same
contract as the sequential path — the audit log never has orphaned
results)."""
sid = _mk_session("loop-parallel-pairs")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "inspect"})
client = _ScriptedStreamClient(
[
{
"content": None,
"tool_calls": [
_tc("get_workspace", call_id="c1"),
_tc("list_workflows", call_id="c2"),
],
},
{"content": "done", "tool_calls": []},
]
)
registry = _StubRegistry(payload_tools=["get_workspace", "list_workflows"])
_run_turn_with(sid, client, registry)
events = _events_of(sid)
calls = [e for e in events if e.type == session_log.TOOL_CALL]
results = [e for e in events if e.type == session_log.TOOL_RESULT]
assert [e.data["call_id"] for e in calls] == ["c1", "c2"]
assert [e.data["call_id"] for e in results] == ["c1", "c2"]
def test_mixed_batch_stays_sequential():
sid = _mk_session("loop-mixed")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "do"})
client = _ScriptedStreamClient(
[
{
"content": None,
"tool_calls": [
_tc("get_workspace", call_id="m1"),
_tc("save_memory", call_id="m2"),
],
},
{"content": "done", "tool_calls": []},
]
)
registry = _StubRegistry(payload_tools=["get_workspace", "save_memory"])
_run_turn_with(sid, client, registry)
step_ends = [e for e in _events_of(sid) if e.type == session_log.STEP_END]
assert not any(e.data.get("parallel") for e in step_ends), (
"a batch containing a write must stay sequential"
)
def test_single_call_batch_stays_sequential():
sid = _mk_session("loop-single")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "do"})
client = _ScriptedStreamClient(
[
{"content": None, "tool_calls": [_tc("get_workspace", call_id="s1")]},
{"content": "done", "tool_calls": []},
]
)
registry = _StubRegistry(payload_tools=["get_workspace"])
_run_turn_with(sid, client, registry)
step_ends = [e for e in _events_of(sid) if e.type == session_log.STEP_END]
assert not any(e.data.get("parallel") for e in step_ends)
def test_usage_lands_on_step_and_turn_end_when_reported():
sid = _mk_session("loop-usage")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "hi"})
class _UsageClient(_ScriptedStreamClient):
def chat_stream(self, messages, temperature=0.4, tools=None, tool_choice=None):
reply = self._replies.pop(0)
return self._stream(reply)
async def _stream(self, reply):
async for ev in super()._stream(reply):
yield ev
if reply.get("usage"):
yield {"type": "usage", "usage": reply["usage"]}
client = _UsageClient(
[{"content": "quick", "tool_calls": [], "usage": {"prompt_tokens": 12, "completion_tokens": 7}}]
)
registry = _StubRegistry(payload_tools=["get_workspace"])
_run_turn_with(sid, client, registry)
events = _events_of(sid)
step_end = next(e for e in events if e.type == session_log.STEP_END)
assert step_end.data["usage"]["total_tokens"] == 19
turn_end = next(e for e in events if e.type == session_log.TURN_END)
assert turn_end.data["usage"]["total_tokens"] == 19
def test_usage_absent_when_server_reports_none():
sid = _mk_session("loop-no-usage")
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "hi"})
client = _ScriptedStreamClient([{"content": "plain", "tool_calls": []}])
registry = _StubRegistry(payload_tools=["get_workspace"])
_run_turn_with(sid, client, registry)
events = _events_of(sid)
step_end = next(e for e in events if e.type == session_log.STEP_END)
assert "usage" not in step_end.data
turn_end = next(e for e in events if e.type == session_log.TURN_END)
assert "usage" not in turn_end.data
@@ -0,0 +1,225 @@
"""Prior task reports + memory/skills in the swarm.
Finding 3 (stateless sub-agents) + the user catch: sub-agents get (a) a
capped digest of the last prior task reports in their kickoff message and
(b) the memory + skills tools and prompt sections the main loop has.
"""
from __future__ import annotations
import asyncio
import tempfile
from pathlib import Path
import pytest
from calliope.agent.harness.registry import ToolContext
from calliope.config import settings
from calliope.db import get_db
from calliope.agent.harness.orchestrator import (
_PRIOR_REPORT_CHARS,
_prior_reports_digest,
ROLE_TOOLS,
)
MEMORY_SKILL_TOOLS = {
"save_memory",
"list_memories",
"forget_memory",
"read_skill",
"list_skills",
}
@pytest.fixture(autouse=True, scope="module")
def _never_touch_real_db():
prev = settings.data_dir
with tempfile.TemporaryDirectory() as tmp:
settings.data_dir = Path(tmp)
settings.assets_dir = Path(tmp) / "assets"
asyncio.run(_migrate(settings.db_path))
yield
settings.data_dir = prev
async def _migrate(db_path):
from calliope.db import migrate_db
await migrate_db(db_path)
def _mk_session() -> int:
conn = get_db(settings.db_path)
try:
cur = conn.execute(
"INSERT INTO agent_sessions (title, project_id) VALUES (?, NULL)",
("prior-reports-test",),
)
conn.commit()
return int(cur.lastrowid)
finally:
conn.close()
def _tc(name: str, args: str = "{}", call_id: str = "c1"):
return {
"id": call_id,
"type": "function",
"function": {"name": name, "arguments": args},
}
class _ScriptedClient:
def __init__(self, responses):
self._responses = list(responses)
self.seen_messages: list[list[dict]] = []
async def chat_with_tools(self, messages, temperature=0.7, tools=None, tool_choice=None):
self.seen_messages.append(list(messages))
if self._responses:
return self._responses.pop(0)
return {"role": "assistant", "content": "done", "tool_calls": []}
async def close(self):
pass
class _StubRegistry:
def __init__(self, results_by_tool=None):
self.executed: list[tuple[str, dict]] = []
self.results_by_tool = results_by_tool or {}
def get(self, name):
return None
async def execute(self, ctx, name, args):
self.executed.append((name, dict(args)))
r = self.results_by_tool.get(name)
return dict(r) if isinstance(r, dict) else {"ok": True}
def _install(orch, client, registry):
orch.LLMClient = lambda: client
orch.get_registry = lambda: registry
# ── _prior_reports_digest unit behavior ─────────────────────────────────
def test_digest_empty_when_no_results():
assert _prior_reports_digest([]) == ""
def test_digest_keeps_last_two_and_caps_chars():
reports = [f"[story] report {i} " + "x" * 40 for i in range(4)]
digest = _prior_reports_digest(reports)
assert "[story] report 0" not in digest
assert "[story] report 1" not in digest
assert "[story] report 2" in digest and "[story] report 3" in digest
assert digest.startswith("Prior task reports:")
def test_digest_truncates_long_reports():
long = "[story] " + "y" * (_PRIOR_REPORT_CHARS + 500)
digest = _prior_reports_digest([long])
assert "…[truncated]" in digest
assert len(digest) < _PRIOR_REPORT_CHARS + 200
def test_digest_marks_failed_reports():
digest = _prior_reports_digest(["[script] FAILED: timeout"])
assert "FAILED: timeout" in digest
# ── swarm integration: digest lands in the sub-agent's kickoff message ──
def test_swarm_second_task_sees_first_task_report():
import calliope.agent.harness.orchestrator as orch
sid = _mk_session()
client = _ScriptedClient(
[
{"role": "assistant", "content": "story work finished", "tool_calls": []},
{"role": "assistant", "content": "script work finished", "tool_calls": []},
]
)
registry = _StubRegistry()
orig_client, orig_reg = orch.LLMClient, orch.get_registry
_install(orch, client, registry)
ctx = ToolContext(session_id=sid, project_id=1)
tasks = [
{"role": "story", "goal": "write beats"},
{"role": "script", "goal": "write scenes"},
]
try:
# Directly exercise the loop body the way orchestrate does:
results: list[str] = []
from calliope.agent.harness.orchestrator import _prior_reports_digest
for task in tasks:
digest = _prior_reports_digest(results)
sub_history = [
{
"role": "user",
"content": (
f"You are the {task['role']} sub-agent. Goal: {task['goal']}\n"
f"Project: #{ctx.project_id}.\n"
+ (digest + "\n" if digest else "")
+ "Complete your goal."
),
}
]
answer = asyncio.run(
orch._run_sub_agent(
ctx, sub_history, ROLE_TOOLS[task["role"]], agent_name=f"{task['role']}-agent"
)
)
results.append(f"[{task['role']}] {answer}")
finally:
orch.LLMClient, orch.get_registry = orig_client, orig_reg
# seen_messages[1] is the second task's [system, user...] batch; the user
# kickoff message carries the digest.
second_user = next(
m for m in client.seen_messages[1] if m.get("role") == "user"
)
assert "Prior task reports:" in second_user["content"]
assert "[story] story work finished" in second_user["content"]
# ── memory + skills tools present in every role ──────────────────────────
@pytest.mark.parametrize("role", ["story", "script", "assets", "video"])
def test_memory_skill_tools_in_every_role(role):
for tool in MEMORY_SKILL_TOOLS:
assert tool in ROLE_TOOLS[role], f"{tool} missing from {role}"
# ── memory + skills sections render into the sub-agent system prompt ────
def test_sub_agent_system_prompt_includes_memory_and_skills_sections():
import calliope.agent.harness.orchestrator as orch
sid = _mk_session()
client = _ScriptedClient([{"role": "assistant", "content": "ok", "tool_calls": []}])
registry = _StubRegistry()
orig_client, orig_reg = orch.LLMClient, orch.get_registry
_install(orch, client, registry)
try:
ctx = ToolContext(session_id=sid, project_id=None)
asyncio.run(
orch._run_sub_agent(
ctx, [{"role": "user", "content": "go"}], ["get_workspace"], agent_name="story-agent"
)
)
finally:
orch.LLMClient, orch.get_registry = orig_client, orig_reg
system = client.seen_messages[0][0]["content"]
assert "## Memory" in system or "## Skills" in system, (
"sub-agent system prompt renders neither memory nor skills section"
)
@@ -143,6 +143,30 @@ def test_chat_payload_unaffected_by_scene_scope(client):
assert "run_workflow" in names or "list_workflows" in names
def test_chat_origin_payload_has_no_shot_tools(client):
"""shot_* tools exist ONLY on the Build Scene surface (origin='scene') —
a chat-origin sandbox must not carry the 23-tool shot payload (~2k tokens
of noise the model can never legitimately use)."""
from calliope.agent.harness.tools import openai_tools_payload
chat_ctx = ToolContext(session_id=1, project_id=None, origin="chat")
names = {t["function"]["name"] for t in openai_tools_payload(chat_ctx)}
shot_names = [n for n in names if n.startswith("shot_") or n.startswith("add_") and n in {
"add_object", "add_keyframe", "update_keyframe", "delete_keyframe",
"move_keyframe_time", "set_playback",
}]
assert not shot_names, f"shot tools leaked into chat payload: {shot_names}"
assert "get_scene" not in names and "set_shot" not in names
assert "list_shot_presets" not in names
def test_scene_origin_payload_still_has_shot_tools(client):
from calliope.agent.harness.tools import openai_tools_payload
names = {t["function"]["name"] for t in openai_tools_payload(_scene_ctx())}
assert "get_scene" in names and "add_keyframe" in names and "set_shot" in names
def test_scene_execute_denies_out_of_scope_tool(client):
from calliope.agent.harness.tools import execute_tool
+417
View File
@@ -0,0 +1,417 @@
"""Agent shell (run_command): containment, approvals, exec mechanics.
The shell is default-OFF; every guard branch here is a security contract:
- disabled → guard_shell_disabled
- read-only (ffprobe / --version) runs without approval, anything else
needs a scope='shell' card or the command named in the user's words
- cwd must resolve inside the agent workspace
- path-like args must resolve inside workspace/assets_dir, and sensitive
names (config, *.db, .env, credentials) are always denied
- shell interpreters are blocked outright
- exec is argv-list based with a stripped environment and a timeout
"""
from __future__ import annotations
import asyncio
import sys
from pathlib import Path
import pytest
from calliope.agent.harness import build_harness
from calliope.agent.harness import log as session_log
from calliope.agent.harness.registry import ToolContext
PYTHON = Path(sys.executable).stem # bare name ("python") — the tool refuses paths
@pytest.fixture(autouse=True, scope="module")
def _never_touch_real_db():
"""Redirect data_dir before ANY write in this module (repo test rule)."""
import tempfile
import calliope.config as config_module
from calliope.db import migrate_db
prev = {
"data_dir": config_module.settings.data_dir,
"assets_dir": config_module.settings.assets_dir,
"agent_workspace_dir": config_module.settings.agent_workspace_dir,
"agent_shell_enabled": config_module.settings.agent_shell_enabled,
"dry_run": config_module.settings.dry_run,
}
with tempfile.TemporaryDirectory() as tmp:
config_module.settings.data_dir = Path(tmp)
config_module.settings.assets_dir = Path(tmp) / "assets"
config_module.settings.agent_workspace_dir = None
config_module.settings.agent_shell_enabled = False
config_module.settings.dry_run = True
config_module.settings.ensure_storage_dirs()
asyncio.run(migrate_db(config_module.settings.db_path))
yield
for k, v in prev.items():
setattr(config_module.settings, k, v)
def _session() -> int:
from calliope.db import get_db
from calliope.config import settings
conn = get_db(settings.db_path)
try:
cur = conn.execute(
"INSERT INTO agent_sessions (title, project_id) VALUES (?, NULL)",
("shell-test",),
)
conn.commit()
return int(cur.lastrowid)
finally:
conn.close()
def _say(session_id: int, text: str) -> None:
session_log.append_event(session_id, session_log.USER_MESSAGE, {"content": text})
def _answer_card(session_id: int, answer: str) -> None:
"""A scope='shell' question card answered affirmatively (the ask_user flow)."""
session_log.append_event(
session_id, session_log.QUESTION_ASKED, {"question": "Run it?", "scope": "shell"}
)
session_log.append_event(session_id, session_log.QUESTION_ANSWERED, {"scope": "shell", "answer": answer})
session_log.append_event(session_id, session_log.USER_MESSAGE, {"content": answer})
@pytest.fixture()
def enabled():
import calliope.config as config_module
config_module.settings.agent_shell_enabled = True
yield
config_module.settings.agent_shell_enabled = False
def _ctx() -> ToolContext:
return ToolContext(session_id=_session(), project_id=None)
# ─────────────────────────────────────────────────────────────────────────
# Registration & default-off
# ─────────────────────────────────────────────────────────────────────────
def test_run_command_registered_and_sandbox_visible():
registry, _ = build_harness()
t = registry.get("run_command")
assert t is not None
assert t.requires_project is False
assert t.category == "system"
def test_disabled_by_default_denial(client):
registry, _ = build_harness()
out = asyncio.run(registry.execute(_ctx(), "run_command", {"command": "ffprobe"}))
assert out["ok"] is False
assert out["reason_code"] == "guard_shell_disabled"
# ─────────────────────────────────────────────────────────────────────────
# Command validation
# ─────────────────────────────────────────────────────────────────────────
def test_path_in_command_denied(enabled):
registry, _ = build_harness()
out = asyncio.run(
registry.execute(_ctx(), "run_command", {"command": "C:/evil/python.exe"})
)
assert out["reason_code"] == "guard_shell_denied_command"
def test_shell_interpreter_denied(enabled):
registry, _ = build_harness()
out = asyncio.run(
registry.execute(_ctx(), "run_command", {"command": "bash", "args": ["-c", "ls"]})
)
assert out["reason_code"] == "guard_shell_denied_command"
def test_unknown_binary_denied(enabled):
registry, _ = build_harness()
out = asyncio.run(
registry.execute(_ctx(), "run_command", {"command": "definitely-not-installed-xyz"})
)
assert out["reason_code"] == "guard_shell_denied_command"
# ─────────────────────────────────────────────────────────────────────────
# Approval gate
# ─────────────────────────────────────────────────────────────────────────
def test_read_only_probe_runs_without_approval(enabled):
"""A --version flag pair counts as read-only — no user ask needed."""
registry, _ = build_harness()
out = asyncio.run(
registry.execute(
_ctx(), "run_command", {"command": PYTHON, "args": ["--version"]}
)
)
assert out["ok"] is True, out
assert out["exit_code"] == 0
def test_mutating_without_approval_denied(enabled):
registry, _ = build_harness()
sid = _session()
_say(sid, "organize my workspace please") # no command named, no shell cue
out = asyncio.run(
registry.execute(
ToolContext(session_id=sid, project_id=None),
"run_command",
{"command": PYTHON, "args": ["-c", "print('hi')"]},
)
)
assert out["ok"] is False
assert out["reason_code"] == "guard_shell_approval"
def test_command_named_in_user_words_allows(enabled):
registry, _ = build_harness()
sid = _session()
_say(sid, "run python -c to check the workspace files")
out = asyncio.run(
registry.execute(
ToolContext(session_id=sid, project_id=None),
"run_command",
{"command": "python", "args": ["-c", "print('approved')"]},
)
)
assert out["ok"] is True, out
def test_structured_shell_approval_allows(enabled):
registry, _ = build_harness()
sid = _session()
_answer_card(sid, "Yes, run it")
out = asyncio.run(
registry.execute(
ToolContext(session_id=sid, project_id=None),
"run_command",
{"command": PYTHON, "args": ["-c", "print('card-approved')"]},
)
)
assert out["ok"] is True, out
# ─────────────────────────────────────────────────────────────────────────
# Containment
# ─────────────────────────────────────────────────────────────────────────
def test_cwd_outside_workspace_denied(enabled):
registry, _ = build_harness()
out = asyncio.run(
registry.execute(
_ctx(),
"run_command",
{"command": "ffprobe", "cwd": str(Path(settings_data_dir_home()))},
)
)
assert out["reason_code"] == "guard_shell_outside_workspace"
def settings_data_dir_home() -> Path:
"""The user's real home — definitively outside the test workspace."""
return Path.home()
def test_sensitive_arg_denied(enabled, tmp_path):
registry, _ = build_harness()
secret = tmp_path / "calliope_config.json"
secret.write_text("{}", encoding="utf-8")
out = asyncio.run(
registry.execute(
_ctx(),
"run_command",
{"command": "ffprobe", "args": [str(secret)]},
)
)
assert out["reason_code"] == "guard_shell_denied_path"
def test_db_arg_denied(enabled, tmp_path):
registry, _ = build_harness()
db = tmp_path / "calliope.db"
db.write_bytes(b"")
out = asyncio.run(
registry.execute(
_ctx(),
"run_command",
{"command": "ffprobe", "args": [str(db)]},
)
)
assert out["reason_code"] == "guard_shell_denied_path"
def test_env_file_arg_denied(enabled):
registry, _ = build_harness()
out = asyncio.run(
registry.execute(
_ctx(),
"run_command",
{"command": "ffprobe", "args": ["--", ".env"]},
)
)
assert out["reason_code"] == "guard_shell_denied_path"
def test_outside_absolute_arg_denied(enabled, tmp_path):
registry, _ = build_harness()
outside = tmp_path / "movie.mp4"
outside.write_bytes(b"00")
out = asyncio.run(
registry.execute(
_ctx(),
"run_command",
{"command": "ffprobe", "args": [str(outside)]},
)
)
assert out["reason_code"] == "guard_shell_outside_workspace"
def test_inside_asset_arg_allowed(enabled):
"""assets_dir is a legit read root for reference inspection."""
from calliope.config import settings
registry, _ = build_harness()
ref = settings.assets_dir / "ref.mp4"
ref.write_bytes(b"00")
out = asyncio.run(
registry.execute(
_ctx(),
"run_command",
{"command": "ffprobe", "args": ["-v", "error", str(ref)]},
)
)
# Not a real mp4 — ffprobe fails, but the GUARD must not have denied it.
assert out.get("reason_code") is None
assert out.get("exit_code") != 0 or out.get("ok") is False or out["ok"] is True
def test_workspace_relative_cwd_allowed(enabled, tmp_path):
from calliope.config import settings
registry, _ = build_harness()
sub = settings.workspace_dir / "sub"
sub.mkdir(parents=True, exist_ok=True)
sid = _session()
_say(sid, "run python to print the cwd")
out = asyncio.run(
registry.execute(
ToolContext(session_id=sid, project_id=None),
"run_command",
{"command": PYTHON, "args": ["-c", "import os; print(os.getcwd())"], "cwd": str(sub)},
)
)
assert out["ok"] is True, out
assert out["stdout"].strip().lower() == str(sub.resolve()).lower()
# ─────────────────────────────────────────────────────────────────────────
# Exec mechanics
# ─────────────────────────────────────────────────────────────────────────
def test_stdout_captured_and_env_stripped(enabled):
registry, _ = build_harness()
sid = _session()
_say(sid, "run python -c to dump env keys")
out = asyncio.run(
registry.execute(
ToolContext(session_id=sid, project_id=None),
"run_command",
{
"command": PYTHON,
"args": [
"-c",
"import os; print('KEY' + '=' + str('LLM_API_KEY' in os.environ or 'FAKE_API_KEY' in os.environ)); print('ran')",
],
},
)
)
assert out["ok"] is True, out
assert "ran" in out["stdout"]
assert "=False" in out["stdout"]
def test_timeout_kills_process(enabled):
registry, _ = build_harness()
sid = _session()
_say(sid, "run python -c sleep check")
out = asyncio.run(
registry.execute(
ToolContext(session_id=sid, project_id=None),
"run_command",
{
"command": PYTHON,
"args": ["-c", "import time; time.sleep(30)"],
"timeout_sec": 2,
},
)
)
assert out["ok"] is False
assert out.get("timed_out") is True
def test_nonzero_exit_reported(enabled):
registry, _ = build_harness()
sid = _session()
_say(sid, "run python -c failing check")
out = asyncio.run(
registry.execute(
ToolContext(session_id=sid, project_id=None),
"run_command",
{"command": PYTHON, "args": ["-c", "raise SystemExit(3)"]},
)
)
assert out["ok"] is False
assert out["exit_code"] == 3
# ─────────────────────────────────────────────────────────────────────────
# Settings roundtrip
# ─────────────────────────────────────────────────────────────────────────
def test_settings_roundtrip_for_new_keys(client, monkeypatch):
"""POST /api/settings persists agent_workspace_dir + agent_shell_enabled."""
import tempfile
with tempfile.TemporaryDirectory() as tmp:
r = client.post(
"/api/settings",
json={"agent_workspace_dir": tmp, "agent_shell_enabled": True},
)
assert r.status_code == 200, r.text
body = r.json()
assert body["agent_shell_enabled"] is True
assert Path(body["agent_workspace_dir"]).resolve() == Path(tmp).resolve()
r2 = client.post("/api/settings", json={"agent_shell_enabled": False})
assert r2.status_code == 200
assert r2.json()["agent_shell_enabled"] is False
def test_settings_rejects_ephemeral_workspace():
"""load/save poison-guard: a %TEMP% workspace resets to the data_dir default."""
import tempfile
import calliope.config as config_module
s = config_module.settings
with tempfile.TemporaryDirectory() as tmp:
s.agent_workspace_dir = Path(tmp)
s.save_config_file()
assert s.agent_workspace_dir is None
assert s.workspace_dir == s.data_dir / "workspace"
+1 -1
View File
@@ -72,7 +72,7 @@ def test_shot_tools_hidden_in_linked_sessions():
def test_shot_tools_visible_in_sandbox():
ctx = ToolContext(session_id=_mk_session(), project_id=None)
ctx = ToolContext(session_id=_mk_session(), project_id=None, origin="scene")
names = {e["function"]["name"] for e in openai_tools_payload(ctx)}
assert "get_scene" in names
assert "set_joint" in names
@@ -385,3 +385,142 @@ def test_trivial_goal_skips_planner():
assert out == "single-loop answer"
assert planner_calls["n"] == 0
# ── planner role validation (finding 5) ─────────────────────────────────
def test_unknown_planner_role_clamped_to_story_with_note():
"""A planner that invents a role ("asset" typo, "renderer") gets it clamped
to story; the clamp is recorded in the plan event and surfaced in the note
instead of silently running the script toolset."""
import json as _json
import calliope.agent.harness.orchestrator as orch
from calliope.agent.harness import log as session_log
sid = _mk_session()
session_log.append_event(
sid, session_log.USER_MESSAGE, {"content": "Build the whole film from scratch"}
)
class _PlannerClient:
async def chat(self, *a, **kw):
return _json.dumps(
{
"mode": "swarm",
"note": "Plan ready.",
"tasks": [
{"role": "story", "goal": "write beats"},
{"role": "asset", "goal": "make characters"},
{"role": "renderer", "goal": "render it"},
],
}
)
async def close(self):
return None
async def fake_run_sub(ctx, sub_history, allowed, *, agent_name=None, on_message=None):
return f"{agent_name} done"
async def fake_run_turn(ctx, history, *, on_message=None):
return "single"
orig_client = orch.LLMClient
orig_run_sub = orch._run_sub_agent
orig_run_turn = orch.run_turn
orch.LLMClient = lambda: _PlannerClient()
orch._run_sub_agent = fake_run_sub
orch.run_turn = fake_run_turn
class _NoWorkspace:
def get(self, name):
return {"ok": True}
async def execute(self, ctx, name, args):
return {"ok": True}
orig_ws = orch.get_registry
orch.get_registry = lambda: _NoWorkspace()
try:
ctx = ToolContext(session_id=sid, project_id=1)
asyncio.run(orch.orchestrate(ctx, [], session_id=sid))
finally:
orch.LLMClient = orig_client
orch._run_sub_agent = orig_run_sub
orch.run_turn = orig_run_turn
orch.get_registry = orig_ws
events = session_log.read_events(sid)
plan_event = next(e for e in events if e.type == session_log.PLAN_CREATED)
clamped = plan_event.data.get("clamped_roles")
assert clamped and len(clamped) == 2
assert {c["from"] for c in clamped} == {"asset", "renderer"}
assert all(c["to"] == "story" for c in clamped)
# The plan event roles are the CLAMPED ones.
assert {t["role"] for t in plan_event.data["tasks"]} == {"story"}
# The note surfaced the clamp.
assert "'asset' is not valid — ran as story" in plan_event.data["note"]
assert "'renderer' is not valid — ran as story" in plan_event.data["note"]
def test_valid_planner_roles_not_clamped():
"""A well-formed plan records no clamped_roles entry."""
import json as _json
import calliope.agent.harness.orchestrator as orch
from calliope.agent.harness import log as session_log
sid = _mk_session()
session_log.append_event(
sid, session_log.USER_MESSAGE, {"content": "Build the whole film from scratch"}
)
class _PlannerClient:
async def chat(self, *a, **kw):
return _json.dumps(
{
"mode": "swarm",
"note": "",
"tasks": [
{"role": "story", "goal": "a"},
{"role": "script", "goal": "b"},
{"role": "assets", "goal": "c"},
{"role": "video", "goal": "d"},
],
}
)
async def close(self):
return None
async def fake_run_sub(ctx, sub_history, allowed, *, agent_name=None, on_message=None):
return "done"
orig_client = orch.LLMClient
orig_run_sub = orch._run_sub_agent
orch.LLMClient = lambda: _PlannerClient()
orch._run_sub_agent = fake_run_sub
class _NoWorkspace:
def get(self, name):
return {"ok": True}
async def execute(self, ctx, name, args):
return {"ok": True}
orig_ws = orch.get_registry
orch.get_registry = lambda: _NoWorkspace()
try:
ctx = ToolContext(session_id=sid, project_id=1)
asyncio.run(orch.orchestrate(ctx, [], session_id=sid))
finally:
orch.LLMClient = orig_client
orch._run_sub_agent = orig_run_sub
orch.get_registry = orig_ws
plan_event = next(
e for e in session_log.read_events(sid) if e.type == session_log.PLAN_CREATED
)
assert "clamped_roles" not in plan_event.data
+1451
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -88,6 +88,7 @@ export interface Settings {
port: number;
data_dir: string;
assets_dir: string;
agent_workspace_dir: string;
db_name: string;
llm_base_url: string;
llm_model: string;
@@ -101,7 +102,9 @@ export interface Settings {
queue_max_retries: number;
agent_max_steps: number;
agent_hardening_prompt: string;
agent_history_char_budget: number;
agent_llm_assignments: Record<string, string | null>;
agent_shell_enabled: boolean;
dry_run: boolean;
}
+24 -4
View File
@@ -57,8 +57,8 @@ export const de: Dict = {
'nav.skillsBlurb': 'In diesem Projekt verfügbare Agenten-Fähigkeiten.',
'nav.queue': 'Warteschlange',
'nav.queueBlurb': 'Parallelität und Zeitlimits für Generierungsjobs.',
'nav.storage': 'Speicher',
'nav.storageBlurb': 'Wo Dateien auf der Festplatte liegen.',
'nav.storage': 'Systempfade',
'nav.storageBlurb': 'Wo Dateien liegen und wo der Agent arbeiten darf.',
// --- Toast ---
'toast.dismiss': 'Ausblenden',
@@ -1012,12 +1012,32 @@ export const de: Dict = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'Wo ComfyUI läuft.',
'settings.comfyHint': 'Muss von diesem Rechner aus erreichbar sein.',
'settings.storageSection': 'Speicher',
'settings.storageLead': 'Wo Dateien auf der Festplatte liegen.',
'settings.storageSection': 'Systempfade',
'settings.storageLead': 'Wo Dateien liegen und wo der Agent arbeiten darf.',
'settings.storageCalloutStrong': 'Datenverzeichnis ändern',
'settings.storageCalloutBody': 'verschiebt Ressourcen. Bestehende Pfade funktionieren weiter, bis sie hier gesetzt werden.',
'settings.dataDir': 'Datenverzeichnis',
'settings.assetsDir': 'Ressourcen-Verzeichnis',
'settings.workspaceDir': 'Agent-Arbeitsbereich',
'settings.workspaceDirHint':
'Isolierter Ordner, in dem die Agent-Shell (run_command) arbeiten darf. Leer = DATA_DIR/workspace. Der Agent kann nichts außerhalb anfassen.',
'settings.shellSection': 'Agent-Shell',
'settings.shellLead': 'Erlaubt dem Agenten, installierte Kommandozeilen-Tools in seinem Arbeitsbereich auszuführen.',
'settings.shellCalloutStrong': 'Nur nach Zustimmung:',
'settings.shellCalloutBody':
'Befehle laufen auf dieser Maschine, auf den Agent-Arbeitsbereich beschränkt. Sensible Dateien (Konfiguration, Datenbank, Zugangsdaten) werden immer abgelehnt; alles Nicht-Lese-Zugriff fragt vorher nach.',
'settings.shellLabel': 'Agent-Shell aktivieren (run_command)',
'settings.shellHint':
'Standardmäßig aus. Wenn aktiv, darf der Agent Inspektionsbefehle (ffprobe) frei ausführen; alles Modifizierende nur nach Freigabe über eine scope="shell"-Fragekarte.',
'settings.historyBudgetSection': 'Kontextverlaufs-Budget',
'settings.historyBudgetLead':
'Begrenzt, wie viel Konversationsverlauf jede Agentenanfrage wiedergibt, damit lange Sitzungen das Kontextfenster des Modells nie überlaufen.',
'settings.historyBudgetField': 'Verlaufsbudget (Zeichen)',
'settings.historyBudgetHint':
'≈4 Zeichen pro Token. Älteste ganze Runden fallen zuerst heraus; die Presets unten sind gute Startwerte.',
'settings.historyBudgetSmall': 'Klein · 60k',
'settings.historyBudgetMedium': 'Mittel · 120k',
'settings.historyBudgetLarge': 'Groß · 400k',
'settings.hardeningSection': 'Prompt-Härtung',
'settings.hardeningLead': 'Regeln, die Generierungs-Prompts vorangestellt werden.',
'settings.hardeningHint': 'Dienen dazu, negative Vorgaben oder Stil-Leitplanken durchzusetzen.',
+24 -4
View File
@@ -55,8 +55,8 @@ export const en = {
'nav.skillsBlurb': 'Agent skills available in this project.',
'nav.queue': 'Job queue',
'nav.queueBlurb': 'Concurrency and timeouts for generation jobs.',
'nav.storage': 'Storage',
'nav.storageBlurb': 'Where files live on disk.',
'nav.storage': 'System Paths',
'nav.storageBlurb': 'Where files live, and where the agent may work.',
// --- Toast ---
'toast.dismiss': 'Dismiss',
@@ -1012,12 +1012,32 @@ export const en = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'Where ComfyUI runs.',
'settings.comfyHint': 'Must be reachable from this machine.',
'settings.storageSection': 'Storage',
'settings.storageLead': 'Where files live on disk.',
'settings.storageSection': 'System Paths',
'settings.storageLead': 'Where files live on disk, and where the agent may work.',
'settings.storageCalloutStrong': 'Changing data directory',
'settings.storageCalloutBody': 'moves assets. Existing paths keep working until set here.',
'settings.dataDir': 'Data directory',
'settings.assetsDir': 'Assets directory',
'settings.workspaceDir': 'Agent workspace',
'settings.workspaceDirHint':
'Sandbox folder the AI agent’s shell may work in (run_command). Leave empty to use DATA_DIR/workspace. The agent cannot touch anything outside it.',
'settings.shellSection': 'Agent shell',
'settings.shellLead': 'Let the agent run installed command-line tools in its workspace.',
'settings.shellCalloutStrong': 'Opt-in only:',
'settings.shellCalloutBody':
'commands run on this machine, sandboxed to the agent workspace. Sensitive files (config, database, credentials) are always denied; anything not read-only asks you first.',
'settings.shellLabel': 'Enable agent shell (run_command)',
'settings.shellHint':
'Off by default. When on, the agent may run inspection commands (ffprobe) freely and mutating commands only after you approve a scope="shell" question card.',
'settings.historyBudgetSection': 'Context history budget',
'settings.historyBudgetLead':
'Caps how much conversation history each agent request replays, so long sessions never overflow the model’s context window.',
'settings.historyBudgetField': 'History budget (characters)',
'settings.historyBudgetHint':
'≈4 characters per token. Oldest whole turns drop first; presets below are good starting points.',
'settings.historyBudgetSmall': 'Small · 60k',
'settings.historyBudgetMedium': 'Medium · 120k',
'settings.historyBudgetLarge': 'Large · 400k',
'settings.hardeningSection': 'Prompt hardening',
'settings.hardeningLead': 'Rules prepended to generation prompts.',
'settings.hardeningHint': 'Used to enforce negative constraints or style guardrails.',
+24 -4
View File
@@ -57,8 +57,8 @@ export const es: Dict = {
'nav.skillsBlurb': 'Habilidades del agente disponibles en este proyecto.',
'nav.queue': 'Cola de tareas',
'nav.queueBlurb': 'Concurrencia y tiempos de espera de las tareas de generación.',
'nav.storage': 'Almacenamiento',
'nav.storageBlurb': 'Dónde se guardan los archivos en el disco.',
'nav.storage': 'Rutas del sistema',
'nav.storageBlurb': 'Dónde se guardan los archivos y dónde puede trabajar el agente.',
// --- Toast ---
'toast.dismiss': 'Descartar',
@@ -1012,12 +1012,32 @@ export const es: Dict = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'Dónde se ejecuta ComfyUI.',
'settings.comfyHint': 'Debe ser accesible desde este equipo.',
'settings.storageSection': 'Almacenamiento',
'settings.storageLead': 'Dónde se guardan los archivos en el disco.',
'settings.storageSection': 'Rutas del sistema',
'settings.storageLead': 'Dónde se guardan los archivos y dónde puede trabajar el agente.',
'settings.storageCalloutStrong': 'Cambiar el directorio de datos',
'settings.storageCalloutBody': 'mueve los recursos. Las rutas existentes seguirán funcionando hasta que se establezca aquí.',
'settings.dataDir': 'Directorio de datos',
'settings.assetsDir': 'Directorio de recursos',
'settings.workspaceDir': 'Espacio de trabajo del agente',
'settings.workspaceDirHint':
'Carpeta aislada donde puede trabajar el shell del agente (run_command). Si se deja vacía, se usa DATA_DIR/workspace. El agente no puede tocar nada fuera de ella.',
'settings.shellSection': 'Shell del agente',
'settings.shellLead': 'Permite al agente ejecutar herramientas de línea de comandos en su espacio de trabajo.',
'settings.shellCalloutStrong': 'Solo con consentimiento:',
'settings.shellCalloutBody':
'los comandos se ejecutan en esta máquina, aislados en el espacio de trabajo del agente. Los archivos sensibles (configuración, base de datos, credenciales) siempre se rechazan; lo que no sea de solo lectura te lo preguntará antes.',
'settings.shellLabel': 'Activar el shell del agente (run_command)',
'settings.shellHint':
'Desactivado por defecto. Al activarlo, el agente puede ejecutar comandos de inspección (ffprobe) libremente, y los comandos de modificación solo tras aprobar una tarjeta de pregunta scope="shell".',
'settings.historyBudgetSection': 'Presupuesto de historial de contexto',
'settings.historyBudgetLead':
'Limita cuánto historial de conversación repite cada solicitud del agente, para que las sesiones largas nunca desborden la ventana de contexto del modelo.',
'settings.historyBudgetField': 'Presupuesto de historial (caracteres)',
'settings.historyBudgetHint':
'≈4 caracteres por token. Los turnos más antiguos se descartan primero; los preajustes de abajo son buenos puntos de partida.',
'settings.historyBudgetSmall': 'Pequeño · 60k',
'settings.historyBudgetMedium': 'Medio · 120k',
'settings.historyBudgetLarge': 'Grande · 400k',
'settings.hardeningSection': 'Refuerzo de prompts',
'settings.hardeningLead': 'Reglas que se añaden al inicio de los prompts de generación.',
'settings.hardeningHint': 'Sirve para imponer restricciones negativas o límites de estilo.',
+24 -4
View File
@@ -57,8 +57,8 @@ export const fr: Dict = {
'nav.skillsBlurb': "Compétences de l'agent disponibles dans ce projet.",
'nav.queue': "File d'attente",
'nav.queueBlurb': 'Parallélisme et délais des tâches de génération.',
'nav.storage': 'Stockage',
'nav.storageBlurb': 'Où les fichiers sont stockés sur le disque.',
'nav.storage': 'Chemins système',
'nav.storageBlurb': "Où les fichiers sont stockés et où l'agent peut travailler.",
// --- Toast ---
'toast.dismiss': 'Ignorer',
@@ -1012,12 +1012,32 @@ export const fr: Dict = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': "Où ComfyUI s'exécute.",
'settings.comfyHint': 'Doit être accessible depuis cette machine.',
'settings.storageSection': 'Stockage',
'settings.storageLead': 'Où les fichiers sont stockés sur le disque.',
'settings.storageSection': 'Chemins système',
'settings.storageLead': "Où les fichiers sont stockés et où l'agent peut travailler.",
'settings.storageCalloutStrong': 'Changer le répertoire de données',
'settings.storageCalloutBody': "déplace les ressources. Les chemins existants continuent de fonctionner jusqu'à la définition ici.",
'settings.dataDir': 'Répertoire de données',
'settings.assetsDir': 'Répertoire des ressources',
'settings.workspaceDir': "Espace de travail de l'agent",
'settings.workspaceDirHint':
"Dossier isolé où le shell de l'agent (run_command) peut travailler. Vide = DATA_DIR/workspace. L'agent ne peut rien toucher en dehors.",
'settings.shellSection': "Shell de l'agent",
'settings.shellLead': "Permet à l'agent d'exécuter des outils en ligne de commande dans son espace de travail.",
'settings.shellCalloutStrong': 'Sur activation :',
'settings.shellCalloutBody':
"les commandes s'exécutent sur cette machine, isolées dans l'espace de travail de l'agent. Les fichiers sensibles (config, base de données, identifiants) sont toujours refusés ; tout ce qui n'est pas en lecture seule vous est demandé avant.",
'settings.shellLabel': "Activer le shell de l'agent (run_command)",
'settings.shellHint':
'Désactivé par défaut. Une fois activé, l\'agent peut lancer librement des commandes d\'inspection (ffprobe) ; les commandes modifiantes ne passent qu\'après approbation via une carte de question scope="shell".',
'settings.historyBudgetSection': 'Budget d\'historique du contexte',
'settings.historyBudgetLead':
'Limite la quantité d\'historique de conversation rejouée à chaque requête de l\'agent, afin que les longues sessions ne débordent jamais de la fenêtre de contexte du modèle.',
'settings.historyBudgetField': 'Budget d\'historique (caractères)',
'settings.historyBudgetHint':
'≈4 caractères par token. Les tours les plus anciens sont d\'abord retirés ; les préréglages ci-dessous sont de bons points de départ.',
'settings.historyBudgetSmall': 'Petit · 60k',
'settings.historyBudgetMedium': 'Moyen · 120k',
'settings.historyBudgetLarge': 'Grand · 400k',
'settings.hardeningSection': 'Renforcement du prompt',
'settings.hardeningLead': 'Règles ajoutées au début des prompts de génération.',
'settings.hardeningHint': 'Sert à imposer des contraintes négatives ou des garde-fous de style.',
+24 -4
View File
@@ -57,8 +57,8 @@ export const ja: Dict = {
'nav.skillsBlurb': 'このプロジェクトで利用できるエージェントスキル。',
'nav.queue': 'ジョブキュー',
'nav.queueBlurb': '生成ジョブの並列数とタイムアウト。',
'nav.storage': 'ストレージ',
'nav.storageBlurb': 'ファイルの保存先。',
'nav.storage': 'システムパス',
'nav.storageBlurb': 'ファイルの保存先とエージェントの作業場所。',
// --- Toast ---
'toast.dismiss': '閉じる',
@@ -1012,12 +1012,32 @@ export const ja: Dict = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'ComfyUI の実行場所。',
'settings.comfyHint': 'このマシンから到達できる必要があります。',
'settings.storageSection': 'ストレージ',
'settings.storageLead': 'ファイルの保存先。',
'settings.storageSection': 'システムパス',
'settings.storageLead': 'ファイルの保存先と、エージェントの作業場所。',
'settings.storageCalloutStrong': 'データディレクトリの変更',
'settings.storageCalloutBody': 'はアセットを移動します。既存のパスはここで設定するまで引き続き機能します。',
'settings.dataDir': 'データディレクトリ',
'settings.assetsDir': 'アセットディレクトリ',
'settings.workspaceDir': 'エージェントワークスペース',
'settings.workspaceDirHint':
'エージェントのシェル(run_command)が作業できるサンドボックスフォルダ。空欄の場合は DATA_DIR/workspace を使用します。エージェントはこのフォルダの外にはアクセスできません。',
'settings.shellSection': 'エージェントシェル',
'settings.shellLead': 'ワークスペース内でインストール済みのコマンドラインツールを実行できるようにします。',
'settings.shellCalloutStrong': 'オプトイン:',
'settings.shellCalloutBody':
'コマンドはこのマシン上で実行されますが、エージェントワークスペースにサンドボックス化されます。機密ファイル(設定・データベース・資格情報)は常に拒否され、読み取り専用以外のコマンドは事前に確認を求めます。',
'settings.shellLabel': 'エージェントシェルを有効化(run_command)',
'settings.shellHint':
'デフォルトはオフです。オンにすると、検査系コマンド(ffprobe)は自由に実行でき、変更を伴うコマンドは scope="shell" の質問カードで承認を得た後にのみ実行されます。',
'settings.historyBudgetSection': 'コンテキスト履歴バジェット',
'settings.historyBudgetLead':
'各エージェント要求が再生する会話履歴の量を制限し、長いセッションでもモデルのコンテキストウィンドウがあふれないようにします。',
'settings.historyBudgetField': '履歴バジェット(文字数)',
'settings.historyBudgetHint':
'≈1トークン4文字。最も古いターンから先に除外されます。下のプリセットが良い出発点です。',
'settings.historyBudgetSmall': '小 · 60k',
'settings.historyBudgetMedium': '中 · 120k',
'settings.historyBudgetLarge': '大 · 400k',
'settings.hardeningSection': 'プロンプトのハードニング',
'settings.hardeningLead': '生成プロンプトの先頭に付加されるルール。',
'settings.hardeningHint': 'ネガティブ制約やスタイルのガードレールの適用に使います。',
+24 -4
View File
@@ -57,8 +57,8 @@ export const ko: Dict = {
'nav.skillsBlurb': '이 프로젝트에서 사용할 수 있는 에이전트 스킬입니다.',
'nav.queue': '작업 대기열',
'nav.queueBlurb': '생성 작업의 동시 실행 수와 시간 초과를 설정합니다.',
'nav.storage': '저장소',
'nav.storageBlurb': '파일이 디스크에 저장되는 위치입니다.',
'nav.storage': '시스템 경로',
'nav.storageBlurb': '파일이 저장되는 위치와 에이전트가 작업할 수 있는 위치입니다.',
// --- Toast ---
'toast.dismiss': '닫기',
@@ -1012,12 +1012,32 @@ export const ko: Dict = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'ComfyUI가 실행되는 위치입니다.',
'settings.comfyHint': '이 컴퓨터에서 접근할 수 있어야 합니다.',
'settings.storageSection': '저장소',
'settings.storageLead': '파일이 디스크에 저장되는 위치입니다.',
'settings.storageSection': '시스템 경로',
'settings.storageLead': '파일이 저장되는 위치와 에이전트가 작업할 수 있는 위치입니다.',
'settings.storageCalloutStrong': '데이터 디렉터리를 변경하면',
'settings.storageCalloutBody': '에셋이 이동합니다. 여기에 설정하기 전까지 기존 경로는 계속 작동합니다.',
'settings.dataDir': '데이터 디렉터리',
'settings.assetsDir': '에셋 디렉터리',
'settings.workspaceDir': '에이전트 작업 공간',
'settings.workspaceDirHint':
'에이전트 셸(run_command)이 작업할 수 있는 샌드박스 폴더입니다. 비워 두면 DATA_DIR/workspace를 사용합니다. 에이전트는 이 폴더 밖의 어떤 것도 건드릴 수 없습니다.',
'settings.shellSection': '에이전트 셸',
'settings.shellLead': '에이전트가 작업 공간 안에서 설치된 명령줄 도구를 실행할 수 있게 합니다.',
'settings.shellCalloutStrong': '직접 허용 필요:',
'settings.shellCalloutBody':
'명령은 이 머신에서, 에이전트 작업 공간으로 샌드박스되어 실행됩니다. 민감한 파일(설정, 데이터베이스, 자격 증명)은 항상 거부되며, 읽기 전용이 아닌 명령은 먼저 사용자에게 묻습니다.',
'settings.shellLabel': '에이전트 셸 사용 (run_command)',
'settings.shellHint':
'기본값은 꺼짐입니다. 켜면 에이전트가 검사 명령(ffprobe)은 자유롭게 실행할 수 있고, 변경 명령은 scope="shell" 질문 카드로 승인받은 후에만 실행됩니다.',
'settings.historyBudgetSection': '컨텍스트 기록 예산',
'settings.historyBudgetLead':
'각 에이전트 요청이 재생하는 대화 기록의 양을 제한하여, 긴 세션도 모델의 컨텍스트 창을 넘치지 않도록 합니다.',
'settings.historyBudgetField': '기록 예산 (문자 수)',
'settings.historyBudgetHint':
'약 토큰당 4문자입니다. 가장 오래된 대화 턴부터 먼저 제외되며, 아래 프리셋이 좋은 시작점입니다.',
'settings.historyBudgetSmall': '소형 · 60k',
'settings.historyBudgetMedium': '중형 · 120k',
'settings.historyBudgetLarge': '대형 · 400k',
'settings.hardeningSection': '프롬프트 강화',
'settings.hardeningLead': '생성 프롬프트 앞에 추가되는 규칙입니다.',
'settings.hardeningHint': '네거티브 제약이나 스타일 가드레일을 적용할 때 사용합니다.',
+24 -4
View File
@@ -57,8 +57,8 @@ export const zh: Dict = {
'nav.skillsBlurb': '本项目可用的智能体技能。',
'nav.queue': '任务队列',
'nav.queueBlurb': '生成任务的并发数与超时设置。',
'nav.storage': '存储',
'nav.storageBlurb': '文件在磁盘上的位置。',
'nav.storage': '系统路径',
'nav.storageBlurb': '文件在磁盘上的位置,以及代理可以工作的位置。',
// --- Toast ---
'toast.dismiss': '关闭',
@@ -1012,12 +1012,32 @@ export const zh: Dict = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'ComfyUI 的运行位置。',
'settings.comfyHint': '必须能从本机访问。',
'settings.storageSection': '存储',
'settings.storageLead': '文件在磁盘上的位置。',
'settings.storageSection': '系统路径',
'settings.storageLead': '文件在磁盘上的位置,以及 AI 代理可以工作的位置。',
'settings.storageCalloutStrong': '更改数据目录',
'settings.storageCalloutBody': '会移动素材。在你于此设置之前,现有路径仍可正常使用。',
'settings.dataDir': '数据目录',
'settings.assetsDir': '素材目录',
'settings.workspaceDir': '代理工作区',
'settings.workspaceDirHint':
'AI 代理 shell(run_command)可以工作的沙盒文件夹。留空则使用 DATA_DIR/workspace。代理无法触及该文件夹之外的任何内容。',
'settings.shellSection': '代理 Shell',
'settings.shellLead': '允许代理在其工作区内运行已安装的命令行工具。',
'settings.shellCalloutStrong': '需手动开启:',
'settings.shellCalloutBody':
'命令在本机运行,且被沙盒限制在代理工作区内。敏感文件(配置、数据库、凭据)始终被拒绝;非只读操作会先询问你。',
'settings.shellLabel': '启用代理 Shell(run_command)',
'settings.shellHint':
'默认关闭。开启后,代理可以自由运行检查类命令(ffprobe),修改类命令需先通过 scope="shell" 的提问卡片征得你同意。',
'settings.historyBudgetSection': '上下文历史预算',
'settings.historyBudgetLead':
'限制每次代理请求重放的对话历史数量,避免长会话溢出模型的上下文窗口。',
'settings.historyBudgetField': '历史预算(字符数)',
'settings.historyBudgetHint':
'约每 token 4 个字符。最早的整轮对话最先被丢弃;下方预设是不错的起点。',
'settings.historyBudgetSmall': '小 · 60k',
'settings.historyBudgetMedium': '中 · 120k',
'settings.historyBudgetLarge': '大 · 400k',
'settings.hardeningSection': '提示词加固',
'settings.hardeningLead': '添加到生成提示词前面的规则。',
'settings.hardeningHint': '用于强制执行负面约束或风格护栏。',
@@ -54,9 +54,12 @@
agent_max_steps: 'queue',
agent_hardening_prompt: 'agent',
agent_llm_assignments: 'agent',
agent_history_char_budget: 'agent',
data_dir: 'storage',
assets_dir: 'storage',
agent_workspace_dir: 'storage',
db_name: 'storage',
agent_shell_enabled: 'agent',
};
// Mirrors backend Field(ge=..., le=...) limits — validated client-side so
// save never trips a raw 422.
@@ -66,6 +69,7 @@
queue_poll_timeout_sec: { min: 0, max: 86400, labelKey: 'settings.pollTimeoutField' },
queue_max_retries: { min: 0, max: 10, labelKey: 'settings.maxRetriesField' },
agent_max_steps: { min: 1, max: 100, labelKey: 'settings.agentMaxStepsField' },
agent_history_char_budget: { min: 10000, max: 2000000, labelKey: 'settings.historyBudgetField' },
};
const dirtyTabs = $derived(
new Set(dirtyKeys.map((k) => FIELD_TAB[k]).filter((t): t is string => Boolean(t))),
@@ -205,6 +209,26 @@
return s.dry_run === true;
}
function shellChecked(s: Settings): boolean {
if (draft.agent_shell_enabled !== undefined) return Boolean(draft.agent_shell_enabled);
return s.agent_shell_enabled === true;
}
// History budget presets (chars). Large matches the backend default (400k).
const HISTORY_BUDGET_PRESETS: { value: number; labelKey: string }[] = [
{ value: 60_000, labelKey: 'settings.historyBudgetSmall' },
{ value: 120_000, labelKey: 'settings.historyBudgetMedium' },
{ value: 400_000, labelKey: 'settings.historyBudgetLarge' },
];
function historyBudgetActive(s: Settings, value: number): boolean {
const current =
draft.agent_history_char_budget !== undefined
? Number(draft.agent_history_char_budget)
: Number(s.agent_history_char_budget ?? 0);
return current === value;
}
// Snap out-of-range numbers back into the valid range when the user leaves
// the field, so a typed 200 never reaches the backend.
function clampOnBlur(e: FocusEvent, key: string) {
@@ -609,6 +633,60 @@
></textarea>
<p class="field-hint">{t('settings.hardeningHint')}</p>
</label>
</section>
<section class="panel">
<h1>{t('settings.historyBudgetSection')}</h1>
<p class="lead">{t('settings.historyBudgetLead')}</p>
<label class="field">
<span class="field-label">{t('settings.historyBudgetField')}</span>
<input
class="field-input"
class:invalid={validationErrors.agent_history_char_budget}
type="number"
min="10000"
max="2000000"
step="1000"
value={String(fieldValue('agent_history_char_budget', s.agent_history_char_budget))}
oninput={(e) => (draft.agent_history_char_budget = e.currentTarget.value)}
onblur={(e) => clampOnBlur(e, 'agent_history_char_budget')}
/>
{#if validationErrors.agent_history_char_budget}
<p class="field-error">{validationErrors.agent_history_char_budget}</p>
{/if}
<div class="preset-chips">
{#each HISTORY_BUDGET_PRESETS as preset (preset.value)}
<button
type="button"
class="preset-chip"
class:active={historyBudgetActive(s, preset.value)}
onclick={() => (draft.agent_history_char_budget = String(preset.value))}
>
{t(preset.labelKey)}
</button>
{/each}
</div>
<p class="field-hint">{t('settings.historyBudgetHint')}</p>
</label>
</section>
<section class="panel">
<h1>{t('settings.shellSection')}</h1>
<p class="lead">{t('settings.shellLead')}</p>
<div class="callout">
<Icon name="alert" size={16} />
<p>
<strong>{t('settings.shellCalloutStrong')}</strong>{' '}
{t('settings.shellCalloutBody')}
</p>
</div>
<label class="check">
<input
type="checkbox"
checked={shellChecked(s)}
onchange={(e) => (draft.agent_shell_enabled = e.currentTarget.checked)}
/>
{t('settings.shellLabel')}
</label>
<p class="field-hint">{t('settings.shellHint')}</p>
</section>
<MemoryPanel />
{:else if tab === 'storage'}
@@ -640,6 +718,16 @@
/>
<p class="field-hint">{t('settings.current')} <code class="mono">{s.assets_dir}</code></p>
</label>
<label class="field">
<span class="field-label">{t('settings.workspaceDir')}</span>
<input
class="field-input"
value={String(fieldValue('agent_workspace_dir', s.agent_workspace_dir))}
oninput={(e) => (draft.agent_workspace_dir = e.currentTarget.value)}
/>
<p class="field-hint">{t('settings.workspaceDirHint')}</p>
<p class="field-hint">{t('settings.current')} <code class="mono">{s.agent_workspace_dir}</code></p>
</label>
</section>
{:else if tab === 'workflows'}
<WorkflowsLibrary />
@@ -734,6 +822,31 @@
.check input {
width: auto;
}
.preset-chips {
display: flex;
gap: 8px;
margin-top: 8px;
flex-wrap: wrap;
}
.preset-chip {
border: 1px solid var(--border);
background: transparent;
color: var(--text-secondary);
border-radius: 999px;
padding: 4px 12px;
font-size: 12px;
cursor: pointer;
transition: border-color 0.15s, color 0.15s, background 0.15s;
}
.preset-chip:hover {
border-color: var(--accent);
color: var(--text-primary);
}
.preset-chip.active {
border-color: var(--accent);
background: var(--accent);
color: var(--accent-contrast, #0b0e14);
}
.callout {
display: flex;
align-items: flex-start;