Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

feat(agent): introduce agent module — engine, tools, prompts, runtime

mrbizarroedf78adfb5bc
diff --git a/agent/__init__.py b/agent/__init__.py
new file mode 100644
index 0000000..f636507
--- /dev/null
+++ b/agent/__init__.py
@@ -0,0 +1,18 @@
+"""Agentic Flows runtime for Phosphene.
+
+A thin chat-driven planner that turns one user idea (or a full script) into
+a queue of LTX 2.3 renders. Engine-pluggable: ships with a local mlx-lm
+server pointed at the bundled Gemma encoder, but any OpenAI-compatible
+endpoint (mlx-lm, LM Studio, Ollama, OpenAI, Anthropic compat, ...) works.
+
+The agent is a guest of the existing panel — same process, same queue,
+same helper. No new microservice. The runtime composes existing primitives
+(`/queue/add`, multi-keyframe interpolation) via tool calls the model
+emits as fenced ```action JSON blocks in its replies.
+
+Public surface:
+ engine.EngineConfig, engine.chat
+ runtime.AgentSession, runtime.step
+ tools.TOOLS, tools.dispatch
+ prompts.build_system_prompt
+"""
diff --git a/agent/engine.py b/agent/engine.py
new file mode 100644
index 0000000..b788f4a
--- /dev/null
+++ b/agent/engine.py
@@ -0,0 +1,151 @@
+"""OpenAI-compatible chat client.
+
+One function: send a list of messages, get back the assistant's text.
+No streaming, no tool-calling spec — the agent emits actions as fenced
+```action JSON blocks in plain content (see prompts.py). That convention
+works on every Chat Completions server we'd want to support, regardless
+of whether the server / model implements OpenAI's tool-calling shape.
+
+Stdlib only. Phosphene's venv has urllib + json; we don't pull a new dep.
+"""
+
+from __future__ import annotations
+
+import json
+import urllib.error
+import urllib.request
+from dataclasses import asdict, dataclass, field
+
+
+# 5 minutes. Local models can take 30+ s to first token on a cold cache;
+# the first request after spawning mlx-lm.server is the slowest. Keep
+# this generous so an under-warmed model doesn't fail the first turn.
+DEFAULT_TIMEOUT_S = 300
+
+
+@dataclass
+class EngineConfig:
+ """How the agent talks to its LLM.
+
+ `kind` is informational — both branches end up calling the same
+ OpenAI-compatible /chat/completions endpoint. The local branch just
+ promises a panel-spawned mlx-lm.server on `base_url`.
+ """
+
+ kind: str = "phosphene_local" # "phosphene_local" | "custom"
+ base_url: str = "http://127.0.0.1:8200/v1"
+ model: str = "mlx-community/gemma-3-12b-it-4bit"
+ api_key: str = ""
+ temperature: float = 0.4
+ max_tokens: int = 3072
+ # mlx-lm.server boot args — only used when kind == "phosphene_local".
+ # `local_model_path` may be a Hugging Face id ("Qwen/Qwen3-30B-A3B-Instruct-4bit")
+ # OR an absolute path to a local model dir (the bundled Gemma path).
+ local_model_path: str = ""
+
+ def to_public_dict(self) -> dict:
+ """Strip the api_key for safe display in /agent/config GETs."""
+ d = asdict(self)
+ if d.get("api_key"):
+ d["api_key"] = ""
+ d["has_api_key"] = True
+ else:
+ d["has_api_key"] = False
+ return d
+
+
+@dataclass
+class ChatResult:
+ content: str
+ finish_reason: str = "stop"
+ usage: dict = field(default_factory=dict)
+ model: str = ""
+
+
+def chat(messages: list[dict], config: EngineConfig,
+ *, timeout: int = DEFAULT_TIMEOUT_S) -> ChatResult:
+ """Send a chat completion request. Returns the assistant text.
+
+ Raises RuntimeError on transport failure or non-200 response.
+ Server-side errors bubble up with the upstream body so the user
+ sees what the engine actually said (helpful for debugging API key
+ / model name typos in the Settings drawer).
+ """
+ url = config.base_url.rstrip("/") + "/chat/completions"
+ body = {
+ "model": config.model,
+ "messages": messages,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens,
+ "stream": False,
+ }
+ headers = {"Content-Type": "application/json"}
+ if config.api_key:
+ headers["Authorization"] = f"Bearer {config.api_key}"
+
+ req = urllib.request.Request(
+ url, data=json.dumps(body).encode("utf-8"), headers=headers, method="POST",
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ raw = resp.read()
+ except urllib.error.HTTPError as e:
+ # Read the body so the caller can see why the server rejected.
+ detail = ""
+ try:
+ detail = e.read().decode("utf-8", errors="replace")
+ except Exception:
+ pass
+ raise RuntimeError(
+ f"engine returned HTTP {e.code} ({e.reason}). "
+ f"URL: {url} Detail: {detail[:600]}"
+ ) from e
+ except urllib.error.URLError as e:
+ raise RuntimeError(
+ f"engine unreachable at {url}: {e.reason}. "
+ "If using Phosphene Local, the model server may not be up yet "
+ "— click Start Local Engine in the Agentic Flows settings drawer."
+ ) from e
+
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError as e:
+ raise RuntimeError(
+ f"engine returned non-JSON body ({len(raw)} bytes). "
+ f"First 200 chars: {raw[:200]!r}"
+ ) from e
+
+ if "choices" not in data or not data["choices"]:
+ raise RuntimeError(f"engine response missing 'choices': {data!r}")
+
+ msg = data["choices"][0].get("message") or {}
+ content = msg.get("content") or ""
+ finish = data["choices"][0].get("finish_reason") or "stop"
+ usage = data.get("usage") or {}
+ return ChatResult(content=content, finish_reason=finish, usage=usage,
+ model=data.get("model", config.model))
+
+
+def health_check(config: EngineConfig, *, timeout: int = 5) -> tuple[bool, str]:
+ """Light probe of the engine. Returns (ok, message).
+
+ `mlx-lm.server` exposes /v1/models. OpenAI / Anthropic / LM Studio
+ all expose the same. We don't insist on a specific shape — any 200
+ response means the endpoint is alive and accepts auth (if provided).
+ """
+ url = config.base_url.rstrip("/") + "/models"
+ headers = {}
+ if config.api_key:
+ headers["Authorization"] = f"Bearer {config.api_key}"
+ req = urllib.request.Request(url, headers=headers)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return True, f"engine reachable ({resp.status} on /v1/models)"
+ except urllib.error.HTTPError as e:
+ if e.code == 401:
+ return False, "engine returned 401 — check API key"
+ return False, f"engine returned HTTP {e.code}"
+ except urllib.error.URLError as e:
+ return False, f"unreachable: {e.reason}"
+ except Exception as e: # noqa: BLE001 — surface any other transport hiccup
+ return False, f"probe failed: {e}"
diff --git a/agent/local_server.py b/agent/local_server.py
new file mode 100644
index 0000000..cfb078a
--- /dev/null
+++ b/agent/local_server.py
@@ -0,0 +1,237 @@
+"""Lifecycle for the bundled `mlx-lm.server` subprocess.
+
+This is the engine the panel spawns when the user picks "Phosphene Local".
+It speaks OpenAI-compatible chat completions on 127.0.0.1:8200 by default,
+loaded against whatever model the user picks (or the bundled Gemma 3 12B
+that ships with Phosphene as the LTX text encoder — same weights, dual
+purpose).
+
+We follow the exact same shape as `mlx_warm_helper.py`'s subprocess:
+spawn from the venv, capture stdout/stderr to STATE['log'] for visibility,
+SIGTERM on shutdown.
+
+The model **stays loaded** between agent turns. Re-spawning per-turn
+would re-tokenize the system prompt every time and burn 20–60 s on cold
+weight reads. Kept warm, subsequent turns are first-token latency only.
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import subprocess
+import threading
+import time
+from pathlib import Path
+
+# Module-level state. One mlx-lm.server per panel process — the agent
+# isn't worth running two of side-by-side on a 64 GB machine since the
+# model already eats >10 GB.
+_LOCK = threading.Lock()
+_PROC: subprocess.Popen | None = None
+_PORT: int = int(os.environ.get("LTX_AGENT_LOCAL_PORT", "8200"))
+_MODEL_PATH: str = ""
+_LAST_ERROR: str = ""
+
+
+def status() -> dict:
+ """Snapshot for the UI: is the local engine running, and on what?"""
+ global _PROC
+ with _LOCK:
+ running = _PROC is not None and _PROC.poll() is None
+ return {
+ "running": running,
+ "port": _PORT,
+ "model_path": _MODEL_PATH,
+ "pid": _PROC.pid if running else None,
+ "last_error": _LAST_ERROR,
+ "base_url": f"http://127.0.0.1:{_PORT}/v1",
+ }
+
+
+def is_running() -> bool:
+ with _LOCK:
+ return _PROC is not None and _PROC.poll() is None
+
+
+def start(model_path: str, *, venv_python: str, log_sink=None) -> dict:
+ """Spawn `python -m mlx_lm.server --model <path> --host 127.0.0.1 --port <port>`.
+
+ `venv_python` is the same Python the helper subprocess uses. It must
+ have `mlx_lm` importable (Phosphene's bundled venv does).
+
+ `log_sink` is a callable `(line: str) -> None`. Each line of the
+ server's stdout/stderr is forwarded to it (plumbing into STATE['log']).
+
+ Returns the new status() dict.
+ """
+ global _PROC, _MODEL_PATH, _LAST_ERROR
+
+ with _LOCK:
+ if _PROC is not None and _PROC.poll() is None:
+ # Already running. If the requested model differs, kill + respawn.
+ if _MODEL_PATH and _MODEL_PATH == model_path:
+ return _status_locked()
+ _stop_locked(reason="model change")
+
+ if not Path(venv_python).exists():
+ _LAST_ERROR = f"venv python not found: {venv_python}"
+ return _status_locked()
+
+ cmd = [
+ venv_python, "-m", "mlx_lm.server",
+ "--model", model_path,
+ "--host", "127.0.0.1",
+ "--port", str(_PORT),
+ "--log-level", "WARNING",
+ ]
+ env = os.environ.copy()
+ # mlx-lm honors HF_HOME for model cache lookup. The bundled
+ # Gemma is already absolute-pathed so this is mostly hygiene.
+ try:
+ _PROC = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ env=env,
+ start_new_session=True,
+ )
+ except Exception as e: # noqa: BLE001
+ _LAST_ERROR = f"spawn failed: {e}"
+ _PROC = None
+ return _status_locked()
+
+ _MODEL_PATH = model_path
+ _LAST_ERROR = ""
+
+ # Outside the lock: pump output to the log sink in a daemon thread.
+ if log_sink is not None and _PROC is not None and _PROC.stdout is not None:
+ t = threading.Thread(
+ target=_pump_lines,
+ args=(_PROC, log_sink),
+ daemon=True,
+ name="mlx_lm_server_log_pump",
+ )
+ t.start()
+
+ # Tiny grace so callers polling status() right after start see the
+ # 'running' state instead of a race-window 'not running yet'.
+ time.sleep(0.2)
+ return status()
+
+
+def stop(reason: str = "manual stop") -> dict:
+ with _LOCK:
+ _stop_locked(reason)
+ return _status_locked()
+
+
+def _stop_locked(reason: str) -> None:
+ global _PROC, _LAST_ERROR
+ if _PROC is None:
+ return
+ if _PROC.poll() is None:
+ try:
+ os.killpg(os.getpgid(_PROC.pid), signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ # Give it 3 s to exit cleanly, then SIGKILL the group.
+ deadline = time.time() + 3.0
+ while time.time() < deadline and _PROC.poll() is None:
+ time.sleep(0.05)
+ if _PROC.poll() is None:
+ try:
+ os.killpg(os.getpgid(_PROC.pid), signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ _LAST_ERROR = f"stopped ({reason}, exit={_PROC.returncode})"
+ _PROC = None
+
+
+def _status_locked() -> dict:
+ running = _PROC is not None and _PROC.poll() is None
+ return {
+ "running": running,
+ "port": _PORT,
+ "model_path": _MODEL_PATH,
+ "pid": _PROC.pid if running else None,
+ "last_error": _LAST_ERROR,
+ "base_url": f"http://127.0.0.1:{_PORT}/v1",
+ }
+
+
+def _pump_lines(proc: subprocess.Popen, sink) -> None:
+ """Background pump: forward each stdout line to the panel's log sink.
+
+ mlx-lm's server emits structured log lines we want visible in the
+ panel's Logs tab so users can see startup ("Loaded weights in 4.2s")
+ and per-request progress.
+ """
+ if proc.stdout is None:
+ return
+ try:
+ for raw in proc.stdout:
+ try:
+ line = raw.decode("utf-8", errors="replace").rstrip()
+ except Exception: # noqa: BLE001
+ continue
+ if not line:
+ continue
+ try:
+ sink(f"[mlx-lm] {line}")
+ except Exception: # noqa: BLE001 — sink failure shouldn't break the pump
+ pass
+ except Exception: # noqa: BLE001 — process closed, exit pump
+ return
+
+
+# ---- Model discovery ----------------------------------------------------------
+def discover_local_models(repo_root: Path) -> list[dict]:
+ """List candidate chat models on disk under `mlx_models/`.
+
+ The agent doesn't need a special download — the bundled Gemma 3 12B IT
+ that ships as the LTX text encoder is also a perfectly capable chat
+ model. Users who want a stronger agent (Qwen 3 Coder 30B, Devstral 24B)
+ can drop them into `mlx_models/<name>/` and the picker shows them.
+
+ A model dir must contain config.json + at least one .safetensors to
+ be considered chat-usable.
+ """
+ models_root = repo_root / "mlx_models"
+ if not models_root.is_dir():
+ return []
+
+ candidates = []
+ for child in sorted(models_root.iterdir()):
+ if not child.is_dir():
+ continue
+ # Skip the LTX repos — those are video model weights, not chat.
+ name = child.name
+ if name.startswith("ltx-") or name == "loras":
+ continue
+ if not (child / "config.json").exists():
+ continue
+ has_weights = any(child.glob("*.safetensors")) or any(child.glob("*.npz"))
+ if not has_weights:
+ continue
+ # Heuristic for "chat-like": presence of tokenizer config and
+ # an instruction-tuned name suffix. Better than scanning configs.
+ is_chat_likely = (
+ (child / "tokenizer.json").exists()
+ or (child / "tokenizer_config.json").exists()
+ )
+ candidates.append({
+ "name": name,
+ "path": str(child),
+ "chat_likely": is_chat_likely,
+ "size_gb": _dir_size_gb(child),
+ })
+ return candidates
+
+
+def _dir_size_gb(p: Path) -> float:
+ try:
+ total = sum(f.stat().st_size for f in p.rglob("*") if f.is_file())
+ return round(total / (1024 ** 3), 2)
+ except Exception: # noqa: BLE001
+ return 0.0
diff --git a/agent/prompts.py b/agent/prompts.py
new file mode 100644
index 0000000..3a51f82
--- /dev/null
+++ b/agent/prompts.py
@@ -0,0 +1,217 @@
+"""System prompt builder for the Agentic Flows planner.
+
+The prompt encodes Phosphene's operator manual: capabilities, empirical
+wall times, failure modes, prompting rules, and tool semantics. The
+agent's value isn't IQ — it's that it knows Phosphene's quirks. This
+file is where that knowledge lives, sourced from STATE.md + CLAUDE.md
++ SDK_KEYFRAME_INTERPOLATION.md.
+
+Update those docs → re-render the prompt. Single source of truth.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+
+def build_system_prompt(*, capabilities: dict, tools_doc: str,
+ repo_version: str = "v2.0.4") -> str:
+ """Render the system prompt for the agent given the current panel state.
+
+ `capabilities` describes the host Mac (RAM tier, max dimensions,
+ whether Q8 is downloaded). The agent uses these to clamp its plan to
+ what this hardware can actually render.
+ """
+ tier = capabilities.get("tier", "standard")
+ friendly = {"base": "Compact", "standard": "Comfortable",
+ "high": "Roomy", "pro": "Studio"}.get(tier, tier)
+ max_dim_t2v = capabilities.get("max_dim_t2v", 1280)
+ max_dim_kf = capabilities.get("max_dim_kf", 768)
+ has_q8 = capabilities.get("allows_q8", False)
+ today = datetime.now().strftime("%Y-%m-%d")
+
+ return f"""You are the Phosphene Agentic Flows planner.
+
+You help a user turn ideas, scripts, or shot descriptions into a queued
+batch of LTX 2.3 video renders. The user goes to sleep; you queue the
+shots; in the morning the user wakes up to a folder of clips and a
+manifest.json they can stitch in their editor.
+
+You are running INSIDE a panel that already has a render queue, a
+helper subprocess, and gallery tooling. You don't render anything
+yourself — you submit jobs. The panel does the work.
+
+Today is {today}. Phosphene version: {repo_version}. Hardware tier:
+**{friendly}** ({tier}); Q8 weights {"available" if has_q8 else "NOT downloaded"}.
+
+# Rules of engagement (read every time)
+
+1. **Plan, then commit.** Default workflow:
+ a. User sends a script / idea / brief.
+ b. You reply with a numbered shot list IN PLAIN TEXT first — no
+ tool calls. Show duration, quality preset, mode, and a one-line
+ visual description per shot. End with a total wall-time estimate.
+ c. Wait for the user's signal to commit ("go", "yes", "approved",
+ "queue it", silence after a confirmation, etc.).
+ d. Once approved, call `submit_shot` for each shot in sequence,
+ then call `write_session_manifest`, then call `finish`.
+2. **One action block per turn.** Each model reply may contain at most
+ ONE tool call. The runtime will run it, append the result, and call
+ you again so you can decide the next step.
+3. **Never invent file paths.** If the user attaches an image, the
+ chat UI gives you its absolute path inline. Use that exact string.
+ If you need a frame from a previous render, use `extract_frame` and
+ pass the resulting `png_path` to your next `submit_shot`.
+4. **Honest ETAs.** Use `estimate_shot` if you're unsure. Don't promise
+ 1-minute wall times for a Standard 1280×704 render — those take 5–8
+ minutes each.
+5. **Short shots earn long batches.** Per-step cost grows ~T^1.5 with
+ frame count. Three 5-sec clips render in much less wall time than
+ one 15-sec clip at the same settings. Prefer 5–8 sec per shot
+ unless the user asks for longer.
+6. **No surprises while the user is asleep.** Don't switch quality
+ tiers, change resolutions, or generate extra "bonus" clips that
+ weren't in the approved plan. Honor the plan exactly.
+
+# How to call tools (the action-block protocol)
+
+Emit a fenced block in your reply, exactly like this:
+
+```action
+{{"tool": "submit_shot", "args": {{"prompt": "...", "mode": "t2v",
+ "quality": "balanced", "duration_seconds": 5, "label": "S1 anchor"}}}}
+```
+
+The block must be valid JSON. Always include both `tool` and `args`.
+Put it at the END of your reply. Anything before it is shown to the
+user as your prose. Anything after it is ignored.
+
+If you have nothing to do (a render is queued, the user has the
+information they asked for, the plan is shipped), DO NOT emit an
+action block. Just reply with text.
+
+When you're truly done with a workflow, emit `{{"tool": "finish",
+"args": {{"summary": "..."}}}}`. That stops the agent loop and the user
+can give you a new task.
+
+# Phosphene's modes
+
+| Mode | Use for | Notes |
+|---|---|---|
+| `t2v` | Pure prompt → video | Most common. Default for talking-head shots. |
+| `i2v` | Image + prompt → video | Anchors the FIRST frame to a still you provide. Use this for character continuity across shots. |
+| `keyframe` | List of stills + frame indices → video | Anchors multiple frames. Best for cross-cut continuity. Tier clamps to {max_dim_kf}px on Comfortable. |
+| `extend` | Append seconds to an existing clip | ~16 minutes per +3 s pass on this tier. Avoid unless the user explicitly asks. |
+
+# Quality tiers + empirical wall times (M4 Max 64 GB, Comfortable)
+
+| Quality | Resolution | 5-sec clip | 10-sec clip | Notes |
+|---|---|---|---|---|
+| `quick` | 640×480 | ~2m 14s | ~5m | Sanity check. Faces too small. |
+| `balanced` | 1024×576 + Sharp 720p export | ~3m 30s | ~8m 07s | **Recommended default**. Audio + visual + Sharp. |
+| `standard` | 1280×704 native | ~7m 40s exact / ~5m 26s turbo | — | Heavier but no upscale needed. |
+| `high` | 1280×704 Q8 two-stage | ~11m 51s | — | Best detail. {"" if has_q8 else "Q8 NOT installed — DO NOT pick this tier."} |
+
+Speed modes (`accel`):
+- `exact` — full sampler, baseline.
+- `boost` — skip up to 2 cached middle steps, ~17% faster.
+- `turbo` — skip up to 3, ~29% faster. **Default for batch overnight.**
+ Disabled automatically for High, Extend, FFLF.
+
+Hardware clamps on this tier:
+- t2v / i2v max dim: {max_dim_t2v}
+- keyframe / extend max dim: {max_dim_kf}
+
+# What LTX 2.3 is good at (lean in)
+
+- **Talking heads, medium shots, interviews.** Faces in the 80–300 px
+ in-frame range. This is the model's wheelhouse.
+- **2–3 dialogue turns per clip.** Lip-sync is jointly diffused —
+ uncannily tight when prompted correctly.
+- **Static or near-static cameras.** Slow push-ins, gentle handhelds.
+- **Atmospheric scenes, soft lighting, sterile/clinical environments,
+ natural settings.** Anything that doesn't lean on hands or fast motion.
+- **Mockumentary / news / interview formats.** Clean medium shots,
+ shallow DOF, professional delivery.
+
+# What LTX 2.3 is bad at (avoid in prompts)
+
+- **Hands and held objects** — fingers morph, written text squiggles,
+ pen/needle/cup interactions look off. Frame around the action;
+ don't show fingers gripping things.
+- **High-motion physics** — kickflips, splashes, motorcycle blur,
+ sports. Avoid entirely or describe them very loosely.
+- **Faces below ~80 px in-frame.** Wide shots show face-shapes but
+ break identity. If you need a wide shot, accept that the face will
+ be unrecognizable in those frames.
+- **Multi-shot character drift.** Same prompt + new seed = new person.
+ Use `i2v` or `keyframe` mode with an extracted reference frame to
+ anchor characters across shots.
+
+# How to write LTX prompts (follow these literally)
+
+- **Single continuous paragraph.** No screenplay format, no UPPERCASE
+ character cards. Run the description as one piece of prose.
+- **Voice descriptor on every speech beat**, not just the first.
+ ("She says clearly:", "He whispers:", "He answers slowly:" — every
+ time the speaker changes or pauses.)
+- **Single quotes around dialogue.** Inside the paragraph.
+- **Action density ~1 explicit beat per 2–3 seconds** of clip. A 5-sec
+ clip wants ~2 beats; a 10-sec clip wants 4–5. Less = stasis. More =
+ jitter.
+- **Anchor framing: medium shot, shallow depth of field, [lighting
+ type], [color tint], [camera direction].** Compose the frame in
+ words; the model anchors on these terms.
+- **Negative prompts via implicit phrasing.** "no text on screen, no
+ subtitles, no logos, no distorted hands" inside the prompt body
+ works better than a separate negative_prompt field.
+
+Example of a well-formed LTX prompt:
+
+> A serious future news anchor sits at a sleek studio desk in a
+> minimalist dark newsroom, medium shot, looking directly into camera.
+> Cool blue studio lighting, shallow depth of field, calm professional
+> delivery, subtle camera push in. The anchor says clearly: 'Tonight,
+> doctors are warning the public about a devastating new condition.'
+> Futuristic mockumentary news style, realistic face, natural lip
+> sync, no text on screen.
+
+# Cross-shot continuity (the keyframe SDK)
+
+For multi-shot pieces where the same character appears across cuts:
+
+1. Render shot 1 at the highest reasonable quality.
+2. After shot 1 finishes, call `extract_frame` with `which: "last"` to
+ pull the final PNG.
+3. For shot 2 (a different angle / location of the same character),
+ submit with `mode: "i2v"` and `ref_image_path: <png from step 2>`.
+ Shot 2 starts with shot 1's exact ending frame.
+4. The cut between shot 1 and shot 2 becomes seamless — same character,
+ same lighting, same pose.
+
+For more complex compositions (start, middle, end anchored): use
+`mode: "keyframe"` and pass a `keyframes` list. Indices are pixel-frame
+positions; the first must be 0, the last must be `frames - 1`.
+
+# Tools you can call
+
+{tools_doc}
+
+# When you're stuck
+
+If you don't have enough information to plan, ASK the user. Don't
+guess. Plain-text questions, no action block.
+
+If a tool errors, READ the error message. It usually tells you exactly
+what to fix. Don't retry the same call — adjust the args.
+
+If the user gives you a multi-page script (like the CAD: Claude
+Addiction Disorder mockumentary), break it into shots first as a
+plain-text plan. Don't start submitting until they approve.
+
+# Final word
+
+You are not the user's editor. You don't auto-stitch clips, don't
+add transitions, don't pick music. You queue the shots and write a
+manifest. The user cuts the film when they wake up.
+"""
diff --git a/agent/runtime.py b/agent/runtime.py
new file mode 100644
index 0000000..bbf8cb2
--- /dev/null
+++ b/agent/runtime.py
@@ -0,0 +1,287 @@
+"""Agent runtime: sessions, the chat→tool loop, persistence.
+
+A `Session` is one chat thread between the user and the agent. It owns
+the message history, the active engine config, and a small `tool_state`
+dict that tools mutate (e.g. `submitted_shots` from `submit_shot`).
+
+`run_turn(session, user_message, ...)` is the entry point. It does:
+
+ 1. Append user_message to session.
+ 2. Call engine.chat() — get assistant reply.
+ 3. If the reply contains a fenced action block:
+ - Dispatch the tool via tools.dispatch().
+ - Append both the assistant reply (with the tool intent) and a
+ synthetic user message containing <tool_result>...</tool_result>.
+ - Loop back to step 2.
+ 4. Otherwise, the reply is the final assistant message. Stop.
+
+The loop is bounded by `max_steps` so a misbehaving model can't burn the
+whole context window.
+
+Session state is persisted to `state/agent_sessions/<id>.json` after
+every turn so a panel restart doesn't lose the conversation.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+import uuid
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Callable, Iterator
+
+from agent import engine, tools, prompts
+
+
+MAX_STEPS_PER_TURN = 30 # safety cap on tool-loop iterations per user turn
+SESSION_VERSION = 1
+
+
+@dataclass
+class Session:
+ session_id: str
+ title: str
+ messages: list[dict] # OpenAI-style {role, content}
+ engine_config: engine.EngineConfig
+ tool_state: dict = field(default_factory=dict)
+ created_at: float = field(default_factory=time.time)
+ updated_at: float = field(default_factory=time.time)
+ finished: bool = False
+
+ def to_dict(self) -> dict:
+ return {
+ "version": SESSION_VERSION,
+ "session_id": self.session_id,
+ "title": self.title,
+ "messages": self.messages,
+ "engine_config": asdict(self.engine_config),
+ "tool_state": self.tool_state,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ "finished": self.finished,
+ }
+
+ @classmethod
+ def from_dict(cls, d: dict) -> "Session":
+ return cls(
+ session_id=d["session_id"],
+ title=d.get("title", "Untitled"),
+ messages=d.get("messages", []),
+ engine_config=engine.EngineConfig(**(d.get("engine_config") or {})),
+ tool_state=d.get("tool_state", {}),
+ created_at=d.get("created_at", time.time()),
+ updated_at=d.get("updated_at", time.time()),
+ finished=d.get("finished", False),
+ )
+
+
+# ---- Storage --------------------------------------------------------------
+def sessions_dir(state_dir: Path) -> Path:
+ d = state_dir / "agent_sessions"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def save_session(session: Session, state_dir: Path) -> None:
+ session.updated_at = time.time()
+ p = sessions_dir(state_dir) / f"{session.session_id}.json"
+ tmp = p.with_suffix(p.suffix + ".tmp")
+ tmp.write_text(json.dumps(session.to_dict(), indent=2), encoding="utf-8")
+ os.replace(tmp, p) # atomic — never see half-write on read
+
+
+def load_session(session_id: str, state_dir: Path) -> Session | None:
+ p = sessions_dir(state_dir) / f"{session_id}.json"
+ if not p.is_file():
+ return None
+ try:
+ data = json.loads(p.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ return Session.from_dict(data)
+
+
+def list_sessions(state_dir: Path) -> list[dict]:
+ """Compact summaries — id, title, message count, last update."""
+ out = []
+ d = sessions_dir(state_dir)
+ if not d.is_dir():
+ return out
+ for p in sorted(d.glob("*.json"), key=lambda x: x.stat().st_mtime, reverse=True):
+ try:
+ data = json.loads(p.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ out.append({
+ "session_id": data.get("session_id", p.stem),
+ "title": data.get("title", "Untitled"),
+ "messages": len(data.get("messages") or []),
+ "shots_submitted": len((data.get("tool_state") or {}).get("submitted_shots") or []),
+ "updated_at": data.get("updated_at", p.stat().st_mtime),
+ "created_at": data.get("created_at", p.stat().st_ctime),
+ "finished": data.get("finished", False),
+ })
+ return out
+
+
+def delete_session(session_id: str, state_dir: Path) -> bool:
+ p = sessions_dir(state_dir) / f"{session_id}.json"
+ if p.is_file():
+ p.unlink()
+ return True
+ return False
+
+
+def new_session(*, title: str, engine_config: engine.EngineConfig) -> Session:
+ sid = uuid.uuid4().hex[:12]
+ return Session(
+ session_id=sid,
+ title=title or f"Session {sid}",
+ messages=[],
+ engine_config=engine_config,
+ tool_state={"session_id": sid, "title": title},
+ )
+
+
+# ---- The turn loop --------------------------------------------------------
+@dataclass
+class TurnEvent:
+ """One observable event during a turn — for the UI's progressive feed."""
+ kind: str # "assistant" | "tool_call" | "tool_result" | "error" | "done"
+ payload: dict
+
+
+def run_turn(session: Session, user_message: str | None,
+ panel_ops: tools.PanelOps,
+ *,
+ tools_doc: str,
+ system_prompt_overrides: dict | None = None,
+ max_steps: int = MAX_STEPS_PER_TURN,
+ on_event: Callable[[TurnEvent], None] | None = None,
+ ) -> Iterator[TurnEvent]:
+ """Drive one user→assistant turn, including any tool-loop iterations.
+
+ Yields TurnEvent objects so the panel HTTP layer can stream progress
+ to the UI. The same events are also fed to `on_event` if provided
+ (use this when the caller is collecting into a list rather than
+ iterating).
+
+ `user_message` may be None — in that case we resume an in-flight
+ turn (e.g. after a panel restart left a half-finished session).
+ """
+ def emit(ev: TurnEvent):
+ if on_event is not None:
+ try:
+ on_event(ev)
+ except Exception: # noqa: BLE001
+ pass
+ return ev
+
+ # 1. Inject (or refresh) the system prompt at index 0.
+ sys_prompt = prompts.build_system_prompt(
+ capabilities=panel_ops.capabilities,
+ tools_doc=tools_doc,
+ repo_version=(system_prompt_overrides or {}).get("version", "v2.0.4"),
+ )
+ if not session.messages or session.messages[0].get("role") != "system":
+ session.messages.insert(0, {"role": "system", "content": sys_prompt})
+ else:
+ session.messages[0]["content"] = sys_prompt
+
+ if user_message is not None:
+ session.messages.append({"role": "user", "content": user_message})
+ # Clear finished flag — a new user message resets the loop.
+ session.finished = False
+
+ # 2. Drive the loop.
+ for step_i in range(max_steps):
+ # Call engine
+ try:
+ result = engine.chat(session.messages, session.engine_config)
+ except Exception as e: # noqa: BLE001
+ err_msg = f"engine error: {e}"
+ session.messages.append(
+ {"role": "user",
+ "content": f"<tool_result>{{\"ok\":false,\"error\":\"{_escape(err_msg)}\"}}</tool_result>"})
+ yield emit(TurnEvent("error", {"error": err_msg}))
+ return
+
+ assistant_content = result.content or ""
+ session.messages.append({"role": "assistant", "content": assistant_content})
+ yield emit(TurnEvent("assistant", {
+ "content": assistant_content,
+ "step": step_i,
+ "model": result.model,
+ "usage": result.usage,
+ }))
+
+ # 3. Look for an action block.
+ action = tools.parse_action_block(assistant_content)
+ if action is None:
+ # Plain text reply, conversation pauses awaiting next user msg.
+ yield emit(TurnEvent("done", {"reason": "no_action", "step": step_i}))
+ return
+
+ tool_name = action.get("tool", "")
+ tool_args = action.get("args") or {}
+ yield emit(TurnEvent("tool_call", {
+ "tool": tool_name, "args": tool_args, "step": step_i,
+ }))
+
+ result_obj = tools.dispatch(tool_name, tool_args, panel_ops, session.tool_state)
+ yield emit(TurnEvent("tool_result", {
+ "tool": tool_name, "result": result_obj, "step": step_i,
+ }))
+
+ # 4. Append tool result as a user-role message.
+ tool_result_msg = (
+ f"<tool_result tool=\"{tool_name}\">\n"
+ f"{json.dumps(result_obj, default=str)}\n"
+ f"</tool_result>"
+ )
+ session.messages.append({"role": "user", "content": tool_result_msg})
+
+ # 5. If the model called `finish`, stop the loop.
+ if tool_name == "finish":
+ session.finished = True
+ yield emit(TurnEvent("done", {"reason": "finished", "step": step_i}))
+ return
+
+ # Hit the cap — emit a synthetic "done" so the UI doesn't hang.
+ yield emit(TurnEvent("done", {"reason": "max_steps_hit", "step": max_steps}))
+
+
+def _escape(s: str) -> str:
+ return s.replace("\\", "\\\\").replace("\"", "\\\"")
+
+
+# ---- Tools doc renderer ----------------------------------------------------
+def render_tools_doc() -> str:
+ """Format the registered tools' docstrings for the system prompt.
+
+ Each tool's docstring is included verbatim so the agent has the same
+ contract as the dispatcher. Keep tool docstrings tight and accurate.
+ """
+ sections = []
+ # Stable order so the prompt is reproducible across reboots.
+ order = [
+ "estimate_shot", "submit_shot", "get_queue_status",
+ "wait_for_shot", "extract_frame", "upload_image",
+ "write_session_manifest", "finish",
+ ]
+ for name in order:
+ fn = tools.TOOL_HANDLERS.get(name)
+ if fn is None:
+ continue
+ doc = (fn.__doc__ or "").strip()
+ sections.append(f"## `{name}`\n\n{doc}")
+ # Any new tools registered later land at the bottom.
+ for name in sorted(tools.TOOL_HANDLERS.keys()):
+ if name in order:
+ continue
+ fn = tools.TOOL_HANDLERS[name]
+ doc = (fn.__doc__ or "").strip()
+ sections.append(f"## `{name}`\n\n{doc}")
+ return "\n\n".join(sections)
diff --git a/agent/tools.py b/agent/tools.py
new file mode 100644
index 0000000..00649ef
--- /dev/null
+++ b/agent/tools.py
@@ -0,0 +1,802 @@
+"""Tools the agent can call from inside its replies.
+
+Convention: the model emits actions as fenced blocks like
+
+ ```action
+ {"tool": "submit_shot", "args": {...}}
+ ```
+
+The runtime extracts the JSON, calls `dispatch(name, args, ops)`, and
+feeds the result back as a `<tool_result>...</tool_result>` user message.
+The model loops on its next turn.
+
+Why no OpenAI tool-calling spec: that spec varies across servers and is
+fragile when the model is small or local. Fenced JSON blocks are
+universal — every Chat Completions server passes them through verbatim,
+the model can self-correct on malformed output, and a human reading the
+transcript can see exactly what the agent intended.
+
+`PanelOps` is the only interface to the rest of Phosphene. The panel
+constructs an instance and passes it to `dispatch()`; tests can pass a
+fake. tools.py imports nothing from mlx_ltx_panel.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import subprocess
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable
+
+
+# ---- PanelOps: the surface the agent calls --------------------------------
+@dataclass
+class PanelOps:
+ """Callbacks that let the agent reach into the running panel.
+
+ All callables are concrete — the panel wires them up at startup. We use
+ a dataclass of callables rather than an abstract base class so a test
+ harness can construct one inline with lambdas.
+ """
+
+ # Submit a fully-built job dict to the queue. Returns the job dict
+ # (with an `id` field). The panel implementation calls make_job() then
+ # appends to STATE['queue'] under STATE['lock'].
+ submit_job: Callable[[dict], dict]
+
+ # Query the queue + history + current. Returns a snapshot dict shaped
+ # like {"running": bool, "current": dict|None, "queue": [...], "history": [...]}.
+ queue_snapshot: Callable[[], dict]
+
+ # Look up a specific job by id across queue+history+current. Returns
+ # the job dict or None.
+ find_job: Callable[[str], dict | None]
+
+ # Where the panel writes outputs. Used for resolving relative paths and
+ # placing per-session manifest files.
+ outputs_dir: Path
+
+ # Where uploaded images go. The agent's keyframe_image arg can be an
+ # absolute path; if it's relative, we resolve under uploads_dir.
+ uploads_dir: Path
+
+ # Hardware capabilities — `{"max_dim_t2v": 1280, "max_dim_kf": 768,
+ # "allows_q8": True, "tier": "standard"}`. Lets the agent clamp its
+ # plan to what this Mac can actually render.
+ capabilities: dict
+
+
+# ---- Tool registry ---------------------------------------------------------
+TOOL_HANDLERS: dict[str, Callable] = {}
+
+
+def tool(name: str):
+ def deco(fn):
+ TOOL_HANDLERS[name] = fn
+ return fn
+ return deco
+
+
+def dispatch(tool_name: str, args: dict, ops: PanelOps,
+ session_state: dict) -> dict:
+ """Run a tool and return a JSON-serializable result.
+
+ Result shape: `{"ok": bool, "result": Any, "error": str|None}`.
+ The caller wraps this in a <tool_result> message back to the model.
+ """
+ handler = TOOL_HANDLERS.get(tool_name)
+ if handler is None:
+ return {
+ "ok": False,
+ "result": None,
+ "error": (
+ f"unknown tool {tool_name!r}. "
+ f"Available: {sorted(TOOL_HANDLERS.keys())}"
+ ),
+ }
+ try:
+ result = handler(args, ops, session_state)
+ return {"ok": True, "result": result, "error": None}
+ except _ToolValidationError as e:
+ return {"ok": False, "result": None, "error": f"validation: {e}"}
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "result": None, "error": f"{type(e).__name__}: {e}"}
+
+
+class _ToolValidationError(Exception):
+ pass
+
+
+def _required(args: dict, key: str, kind: type = str):
+ if key not in args:
+ raise _ToolValidationError(f"missing required arg: {key}")
+ val = args[key]
+ if kind is int:
+ try:
+ return int(val)
+ except Exception:
+ raise _ToolValidationError(f"{key} must be int, got {val!r}")
+ if kind is float:
+ try:
+ return float(val)
+ except Exception:
+ raise _ToolValidationError(f"{key} must be float, got {val!r}")
+ return val
+
+
+# ---- The actual tools ------------------------------------------------------
+# Tool docstrings are embedded into the system prompt verbatim — keep
+# them tight, factual, and aligned with what the implementation actually
+# does. The agent reads them every turn.
+
+@tool("estimate_shot")
+def _estimate_shot(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Return the empirical wall-time for a planned shot.
+
+ Numbers come from the published M4 Max 64 GB benchmark table. Lets the
+ agent budget the overnight queue without trial-and-error.
+
+ Args:
+ duration_seconds: 5 | 10 | 20 (or close — we round to the nearest measured point)
+ quality: "quick" | "balanced" | "standard" | "high"
+ accel: "exact" | "boost" | "turbo" (ignored for high)
+ mode: "t2v" | "i2v" | "keyframe" | "extend"
+ sharp: bool — adds ~26 s for the PiperSR pass
+ """
+ duration = float(args.get("duration_seconds", 5))
+ quality = (args.get("quality") or "balanced").lower()
+ accel = (args.get("accel") or "turbo").lower()
+ mode = (args.get("mode") or "t2v").lower()
+ sharp = bool(args.get("sharp", quality == "balanced"))
+
+ seconds = _estimate_wall_seconds(
+ duration=duration, quality=quality, accel=accel, mode=mode, sharp=sharp,
+ )
+ return {
+ "estimate_wall_seconds": seconds,
+ "estimate_wall_human": _fmt_dur(seconds),
+ "params_used": {"duration_seconds": duration, "quality": quality,
+ "accel": accel, "mode": mode, "sharp": sharp},
+ "note": ("Empirical from M4 Max 64 GB; other Macs vary. Tier-clamped "
+ "modes (FFLF, Extend on Comfortable) max out at 768 px."),
+ }
+
+
+def _estimate_wall_seconds(*, duration: float, quality: str, accel: str,
+ mode: str, sharp: bool) -> float:
+ """Single source of truth for shot wall-time estimates.
+
+ Anchored on the table in CLAUDE.md §0 + STATE.md §3. Linear-interpolated
+ along T^1.5 for non-canonical durations. Conservative side: round up.
+ """
+ # Per-mode per-quality 5-second baseline, in seconds
+ base_5s: dict = {
+ ("t2v", "quick"): 134, # 2 m 14 s, 640×480
+ ("t2v", "balanced"): 210, # 3 m 30 s, 1024×576 + 720p Sharp + Turbo
+ ("t2v", "standard"): 460, # 7 m 40 s exact / 326 s turbo (~5 m 26 s)
+ ("t2v", "high"): 711, # 11 m 51 s, Q8 two-stage HQ
+ ("i2v", "quick"): 150,
+ ("i2v", "balanced"): 217, # 3 m 37 s
+ ("i2v", "standard"): 471, # 7 m 51 s
+ ("i2v", "high"): 750,
+ ("keyframe", "balanced"): 329, # ~ 5 m 29 s @ 768 px clamp on Comfortable
+ ("keyframe", "standard"): 329,
+ ("keyframe", "high"): 390,
+ ("extend", "balanced"): 950, # +3 s pass, ~15 m 50 s
+ ("extend", "standard"): 950,
+ ("extend", "high"): 1100,
+ }
+ key = (mode, quality)
+ if key not in base_5s:
+ # Fall back to T2V Standard if the agent picked a weird combo.
+ base = base_5s[("t2v", "standard")]
+ else:
+ base = base_5s[key]
+ # Accel discount only for t2v/i2v Standard. CLAUDE.md says boost ≈ -17%, turbo ≈ -29%.
+ if mode in ("t2v", "i2v") and quality == "standard":
+ if accel == "boost":
+ base *= 0.83
+ elif accel == "turbo":
+ base *= 0.71
+ # Length scaling: per-step cost grows ~T^1.5 with frame count.
+ if duration > 0 and duration != 5:
+ base *= (duration / 5.0) ** 1.5
+ if sharp and mode in ("t2v", "i2v") and quality in ("balanced", "quick"):
+ # Sharp wall-time is amortized into balanced's 210 s baseline already;
+ # only add it for explicit sharp-on-quick or sharp-on-standard which
+ # aren't in the table.
+ if quality != "balanced":
+ base += 26
+ return round(base)
+
+
+def _fmt_dur(seconds: float) -> str:
+ s = int(round(seconds))
+ h, rem = divmod(s, 3600)
+ m, s = divmod(rem, 60)
+ if h:
+ return f"{h}h {m:02d}m {s:02d}s"
+ return f"{m}m {s:02d}s"
+
+
+@tool("submit_shot")
+def _submit_shot(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Append a render job to the panel's existing FIFO queue.
+
+ Args (most map 1:1 to the panel's job spec — see CLAUDE.md §12):
+ prompt: str (required) — LTX prompt; follow the docs format
+ (single paragraph, voice descriptor on
+ every speech beat, single quotes around
+ dialogue, ~1 action per 2-3 s).
+ mode: str = "t2v" — "t2v" | "i2v" | "keyframe" | "extend"
+ quality: str = "balanced" — "quick" | "balanced" | "standard" | "high"
+ accel: str = "turbo" — "exact" | "boost" | "turbo" (ignored for high/extend/keyframe)
+ duration_seconds: float = 5 — clip length. Mapped to frames as 24*duration+1, snapped to 8k+1.
+ width, height: int — only for t2v. Falls back to the quality default.
+ ref_image_path: str — for i2v: absolute path to a previously-uploaded reference.
+ keyframes: list[dict] — for keyframe mode: [{image_path: str, frame_index: int}, ...]
+ ≥2 items. Indices must be in [0, frames-1] and strictly increasing.
+ source_clip: str — for extend mode: absolute path to source mp4.
+ extend_seconds: float = 2 — for extend: how much to add. Maps to extend_frames.
+ label: str — human-readable label visible in queue/history.
+ no_music: bool = False — append no-music constraint to prompt.
+ upscale_method: str — "lanczos" (default) | "pipersr" (Sharp ANE).
+ session_tag: str — copied to params for later filtering. The runtime
+ passes the active agent session id automatically.
+
+ Returns: {"job_id": "...", "queued_position": int, "estimated_wall_seconds": int, ...}
+ """
+ prompt = (args.get("prompt") or "").strip()
+ if not prompt:
+ raise _ToolValidationError("prompt is required and must not be empty")
+
+ mode = (args.get("mode") or "t2v").lower()
+ if mode not in ("t2v", "i2v", "keyframe", "extend"):
+ raise _ToolValidationError(f"mode must be t2v|i2v|keyframe|extend, got {mode!r}")
+
+ quality = (args.get("quality") or "balanced").lower()
+ if quality not in ("quick", "balanced", "standard", "high"):
+ raise _ToolValidationError(f"quality must be quick|balanced|standard|high, got {quality!r}")
+
+ accel = (args.get("accel") or "turbo").lower()
+ if accel not in ("exact", "boost", "turbo"):
+ accel = "turbo"
+ # Modes that don't allow acceleration are normalized later by the panel
+ # but we mirror the rule here so estimates match what the queue runs.
+ if mode in ("extend", "keyframe") or quality == "high":
+ accel = "exact"
+
+ duration = float(args.get("duration_seconds", 5.0))
+ if duration <= 0:
+ raise _ToolValidationError("duration_seconds must be > 0")
+ # LTX latents are groups of 8: frames = 24*duration + 1, snapped to 8k+1.
+ target_frames = int(round(24 * duration)) + 1
+ target_frames = ((target_frames - 1) // 8) * 8 + 1
+ target_frames = max(25, target_frames)
+
+ # Tier clamps (mirrors panel's HW tier system; agent is told these
+ # via the system prompt, but enforce here as a guardrail).
+ caps = ops.capabilities or {}
+ max_dim_kf = int(caps.get("max_dim_kf") or 768)
+ max_dim_t2v = int(caps.get("max_dim_t2v") or 1280)
+
+ if mode == "t2v" or mode == "i2v":
+ if quality == "quick":
+ w_default, h_default = 640, 480
+ elif quality in ("standard", "high"):
+ w_default, h_default = 1280, 704
+ else:
+ w_default, h_default = 1024, 576
+ else:
+ # FFLF / Extend: clamp to tier
+ w_default, h_default = min(768, max_dim_kf), min(416, max_dim_kf)
+
+ width = int(args.get("width") or w_default)
+ height = int(args.get("height") or h_default)
+ if mode in ("t2v", "i2v"):
+ width = min(width, max_dim_t2v)
+ height = min(height, max_dim_t2v)
+ else:
+ width = min(width, max_dim_kf)
+ height = min(height, max_dim_kf)
+
+ # Build the form dict that make_job() consumes.
+ form: dict[str, str] = {
+ "mode": mode,
+ "prompt": prompt + (
+ ". Audio: no music, dialogue and ambient room tone only."
+ if args.get("no_music") else ""
+ ),
+ "quality": quality,
+ "accel": accel,
+ "frames": str(target_frames),
+ "width": str(width),
+ "height": str(height),
+ "seed": str(args.get("seed", -1)),
+ "preset_label": (args.get("label") or "")[:80],
+ "open_when_done": "off",
+ "stop_comfy": "off",
+ }
+
+ if mode == "i2v":
+ ref = args.get("ref_image_path") or ""
+ if not ref:
+ raise _ToolValidationError("ref_image_path is required for mode=i2v")
+ ref = _resolve_path(ref, ops.uploads_dir)
+ if not Path(ref).is_file():
+ raise _ToolValidationError(f"ref_image_path not found: {ref}")
+ form["image"] = ref
+
+ elif mode == "extend":
+ src = args.get("source_clip") or ""
+ if not src:
+ raise _ToolValidationError("source_clip is required for mode=extend")
+ src = _resolve_path(src, ops.outputs_dir)
+ if not Path(src).is_file():
+ raise _ToolValidationError(f"source_clip not found: {src}")
+ ext_secs = float(args.get("extend_seconds", 2.0))
+ # Each extend latent = 8 video frames at 24 fps. So latents = secs * 24 / 8 = secs * 3.
+ ext_latents = max(1, int(round(ext_secs * 3)))
+ form["video_path"] = src
+ form["extend_frames"] = str(ext_latents)
+ form["extend_direction"] = (args.get("extend_direction") or "after")
+ form["extend_steps"] = "12"
+ form["extend_cfg"] = "1.0"
+
+ elif mode == "keyframe":
+ kfs = args.get("keyframes") or []
+ if not isinstance(kfs, list) or len(kfs) < 2:
+ raise _ToolValidationError(
+ "keyframes must be a list with ≥2 items "
+ "(each {image_path, frame_index})"
+ )
+ # Validate ordering + bounds, resolve paths
+ last_idx = -1
+ normalized = []
+ for kf in kfs:
+ if not isinstance(kf, dict):
+ raise _ToolValidationError("each keyframe must be a dict")
+ img = _resolve_path(kf.get("image_path", ""), ops.uploads_dir)
+ if not Path(img).is_file():
+ raise _ToolValidationError(f"keyframe image not found: {img}")
+ idx = int(kf.get("frame_index", 0))
+ if idx < 0 or idx >= target_frames:
+ raise _ToolValidationError(
+ f"frame_index {idx} out of range [0, {target_frames - 1}]"
+ )
+ if idx <= last_idx:
+ raise _ToolValidationError("frame_index values must strictly increase")
+ last_idx = idx
+ normalized.append({"image_path": img, "frame_index": idx})
+ # The first and last keyframes drop into the legacy two-keyframe panel
+ # contract; intermediate keyframes go through the new `keyframes_json`
+ # form field (see Layer 2 in mlx_ltx_panel.py).
+ form["start_image"] = normalized[0]["image_path"]
+ form["end_image"] = normalized[-1]["image_path"]
+ if len(normalized) > 2:
+ form["keyframes_json"] = json.dumps(normalized)
+ form["keyframes_total_frames"] = str(target_frames)
+
+ # Sharp upscale path. Default: pipersr ON for balanced, off otherwise.
+ method = (args.get("upscale_method") or "").lower()
+ if not method:
+ method = "pipersr" if quality == "balanced" else "lanczos"
+ form["upscale_method"] = method
+ form["upscale"] = (
+ "fit_720p" if quality == "balanced"
+ else (args.get("upscale") or "off")
+ )
+
+ # Tag for session filtering. Stored on the job's params so the runtime
+ # can later pick out "all jobs from this agent session" without grepping
+ # labels.
+ session_tag = (args.get("session_tag") or session.get("session_id") or "")
+ form["session_tag"] = session_tag
+
+ # Submit through the panel callback. It builds the job + appends to queue.
+ job = ops.submit_job(form)
+ snap = ops.queue_snapshot()
+ queue_pos = next(
+ (i + 1 for i, j in enumerate(snap.get("queue") or []) if j["id"] == job["id"]),
+ None,
+ )
+
+ est = _estimate_wall_seconds(
+ duration=duration, quality=quality, accel=accel, mode=mode,
+ sharp=(method == "pipersr"),
+ )
+
+ # Track the submitted shot in session state for later manifest writing.
+ session.setdefault("submitted_shots", []).append({
+ "job_id": job["id"],
+ "label": form.get("preset_label") or "",
+ "mode": mode,
+ "quality": quality,
+ "duration_seconds": duration,
+ "frames": target_frames,
+ "estimate_wall_seconds": est,
+ "submitted_at": time.time(),
+ })
+
+ return {
+ "job_id": job["id"],
+ "queued_position": queue_pos,
+ "queue_depth": len(snap.get("queue") or []),
+ "estimated_wall_seconds": est,
+ "estimated_wall_human": _fmt_dur(est),
+ "frames": target_frames,
+ "width": width,
+ "height": height,
+ }
+
+
+@tool("get_queue_status")
+def _get_queue_status(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Read the FIFO queue + currently running job + recent history.
+
+ Use this between submissions to confirm the queue is moving, or at
+ end-of-plan to summarize ETA.
+
+ Returns: {
+ running: bool, current: dict|None, queue: [...], queue_depth: int,
+ total_estimated_wall_seconds: int, history_recent: [...]
+ }
+ """
+ snap = ops.queue_snapshot()
+ queue = snap.get("queue") or []
+ history = (snap.get("history") or [])[:10]
+ total = 0
+ for j in queue:
+ p = j.get("params", {})
+ total += _estimate_wall_seconds(
+ duration=max(1, int(p.get("frames", 121)) - 1) / 24.0,
+ quality=p.get("quality", "balanced"),
+ accel=p.get("accel", "turbo"),
+ mode=p.get("mode", "t2v"),
+ sharp=(p.get("upscale_method") == "pipersr"),
+ )
+ return {
+ "running": snap.get("running", False),
+ "current": _trim_job(snap.get("current")),
+ "queue_depth": len(queue),
+ "queue": [_trim_job(j) for j in queue],
+ "total_estimated_wall_seconds": total,
+ "total_estimated_wall_human": _fmt_dur(total),
+ "history_recent": [_trim_job(j) for j in history],
+ }
+
+
+@tool("wait_for_shot")
+def _wait_for_shot(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Block until the named job finishes (status in {"done","error","cancelled"}).
+
+ Args:
+ job_id: str (required)
+ timeout_seconds: int = 1800 — hard cap. Returns timeout=true if hit.
+ poll_seconds: float = 5
+
+ Returns: {status, output_path, elapsed_sec, error, timed_out, job}
+ """
+ job_id = _required(args, "job_id")
+ timeout = float(args.get("timeout_seconds", 1800))
+ poll = max(1.0, float(args.get("poll_seconds", 5)))
+ start = time.time()
+ while True:
+ j = ops.find_job(job_id)
+ if j is None:
+ return {"status": "missing", "error": "job not found",
+ "output_path": None, "elapsed_sec": None,
+ "timed_out": False, "job": None}
+ status = j.get("status")
+ if status in ("done", "error", "cancelled"):
+ return {
+ "status": status,
+ "output_path": j.get("output_path"),
+ "elapsed_sec": j.get("elapsed_sec"),
+ "error": j.get("error"),
+ "timed_out": False,
+ "job": _trim_job(j),
+ }
+ if time.time() - start > timeout:
+ return {
+ "status": status,
+ "output_path": j.get("output_path"),
+ "elapsed_sec": time.time() - start,
+ "error": None,
+ "timed_out": True,
+ "job": _trim_job(j),
+ }
+ time.sleep(poll)
+
+
+@tool("extract_frame")
+def _extract_frame(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Extract a single frame from a finished clip as a PNG.
+
+ Use the `last` frame of shot N as the keyframe-0 of shot N+1 to anchor
+ character continuity across cuts (see SDK_KEYFRAME_INTERPOLATION.md
+ Problem 4).
+
+ Args:
+ job_id OR clip_path: identify the source. job_id resolves via the panel.
+ which: "first" | "last" | "middle" | a specific frame index (int)
+ output_name: optional override for the saved filename (under panel_uploads).
+
+ Returns: {png_path, frame_index, source_clip}
+ """
+ clip = args.get("clip_path") or ""
+ job_id = args.get("job_id")
+ if job_id and not clip:
+ j = ops.find_job(job_id)
+ if not j:
+ raise _ToolValidationError(f"job {job_id} not found")
+ clip = j.get("output_path") or ""
+ if not clip:
+ raise _ToolValidationError("provide either job_id (finished) or clip_path")
+ if not Path(clip).is_file():
+ raise _ToolValidationError(f"clip not found: {clip}")
+
+ which = args.get("which", "last")
+ nb = _probe_frame_count(clip)
+ if isinstance(which, int) or (isinstance(which, str) and which.isdigit()):
+ idx = max(0, min(int(which), nb - 1))
+ elif which == "first":
+ idx = 0
+ elif which == "middle":
+ idx = max(0, nb // 2)
+ else: # "last" or anything else
+ idx = max(0, nb - 1)
+
+ out_name = (args.get("output_name") or
+ f"frame_{Path(clip).stem}_{idx:04d}.png")
+ out_path = ops.uploads_dir / out_name
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # ffmpeg seek-by-index. -frames:v 1 + select+filter is precise but slow
+ # on long clips; we use trim by frame number which is exact for H.264.
+ cmd = [
+ "ffmpeg", "-y", "-loglevel", "error",
+ "-i", clip,
+ "-vf", f"select=eq(n\\,{idx})",
+ "-vframes", "1",
+ str(out_path),
+ ]
+ completed = subprocess.run(cmd, capture_output=True, text=True)
+ if completed.returncode != 0 or not out_path.is_file():
+ raise RuntimeError(
+ f"ffmpeg failed extracting frame {idx} from {clip}: "
+ f"{completed.stderr[:400]}"
+ )
+
+ return {
+ "png_path": str(out_path),
+ "frame_index": idx,
+ "source_clip": clip,
+ "total_frames": nb,
+ }
+
+
+@tool("write_session_manifest")
+def _write_session_manifest(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Write a JSON manifest listing the agent's submitted shots in cut order.
+
+ The manifest is the deliverable for an overnight render: in the morning,
+ the user opens `mlx_outputs/agentflow_<id>/manifest.json` and sees what
+ the agent built. ffmpeg-concat is the user's choice in their editor —
+ we deliberately do NOT auto-stitch.
+
+ Args:
+ output_name: str = "manifest.json"
+ title: str — human-friendly project title
+ shot_order: list[str] — explicit order of job_ids; defaults to
+ submission order from session state.
+
+ Returns: {manifest_path, shot_count, missing_outputs}
+ """
+ title = args.get("title") or session.get("title") or "Untitled session"
+ submitted = session.get("submitted_shots") or []
+ order = args.get("shot_order") or [s["job_id"] for s in submitted]
+
+ # Resolve current state of each shot
+ rows = []
+ missing = []
+ for jid in order:
+ j = ops.find_job(jid)
+ if not j:
+ missing.append(jid)
+ continue
+ p = j.get("params", {})
+ rows.append({
+ "job_id": jid,
+ "label": p.get("label"),
+ "mode": p.get("mode"),
+ "quality": p.get("quality"),
+ "frames": p.get("frames"),
+ "status": j.get("status"),
+ "output_path": j.get("output_path"),
+ "elapsed_sec": j.get("elapsed_sec"),
+ "prompt": p.get("prompt"),
+ })
+
+ session_id = session.get("session_id") or "session"
+ out_dir = ops.outputs_dir / f"agentflow_{session_id}"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ out_path = out_dir / (args.get("output_name") or "manifest.json")
+ manifest = {
+ "schema": "phosphene/agentflow/manifest@1",
+ "title": title,
+ "session_id": session_id,
+ "created_at_unix": time.time(),
+ "shots": rows,
+ "missing": missing,
+ "stitching_hint": (
+ "Cut these in your NLE in the order listed. "
+ "Use first-frame-anchored keyframes (extracted via extract_frame) "
+ "to make cross-shot cuts invisible."
+ ),
+ }
+ out_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
+ return {
+ "manifest_path": str(out_path),
+ "shot_count": len(rows),
+ "missing_outputs": missing,
+ "title": title,
+ }
+
+
+@tool("upload_image")
+def _upload_image(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Resolve an image path the user attached to the chat.
+
+ The chat UI persists user-attached files to `panel_uploads/` and
+ surfaces the absolute path in the user message. This tool exists so
+ the agent can refer to the file by its `attachment_id` (the path the
+ chat injected) and confirm it's there before passing it as
+ ref_image_path or in keyframes.
+
+ Args:
+ attachment_id: str — absolute path of an uploaded image
+ """
+ p = _required(args, "attachment_id")
+ p = _resolve_path(p, ops.uploads_dir)
+ pp = Path(p)
+ if not pp.is_file():
+ raise _ToolValidationError(f"attachment not found: {p}")
+ return {
+ "absolute_path": p,
+ "size_bytes": pp.stat().st_size,
+ "name": pp.name,
+ }
+
+
+@tool("finish")
+def _finish(args: dict, ops: PanelOps, session: dict) -> dict:
+ """Signal that the agent has finished its current task.
+
+ The runtime uses this as an explicit loop terminator so the agent
+ doesn't keep spinning after committing the plan. The summary is
+ shown to the user as the final assistant message.
+
+ Args:
+ summary: str — one-paragraph wrap-up
+ next_steps: str — optional. What the user should do when they wake.
+ """
+ session["finished"] = True
+ return {
+ "summary": args.get("summary", ""),
+ "next_steps": args.get("next_steps", ""),
+ }
+
+
+# ---- helpers ---------------------------------------------------------------
+def _trim_job(j: dict | None) -> dict | None:
+ if not j:
+ return None
+ p = j.get("params", {}) or {}
+ return {
+ "id": j.get("id"),
+ "status": j.get("status"),
+ "label": p.get("label"),
+ "mode": p.get("mode"),
+ "quality": p.get("quality"),
+ "frames": p.get("frames"),
+ "width": p.get("width"),
+ "height": p.get("height"),
+ "session_tag": p.get("session_tag"),
+ "output_path": j.get("output_path"),
+ "elapsed_sec": j.get("elapsed_sec"),
+ "queued_at": j.get("queued_at"),
+ "started_at": j.get("started_at"),
+ "finished_at": j.get("finished_at"),
+ "error": j.get("error"),
+ }
+
+
+def _resolve_path(p: str, base: Path) -> str:
+ """Make absolute. If `p` is relative, resolve under `base`."""
+ if not p:
+ return p
+ pp = Path(p)
+ if pp.is_absolute():
+ return str(pp)
+ return str(base / pp)
+
+
+def _probe_frame_count(clip_path: str) -> int:
+ """Get nb_frames via ffprobe. Falls back to a duration*fps estimate.
+
+ Used for clamping `which` indices in extract_frame.
+ """
+ try:
+ r = subprocess.run(
+ ["ffprobe", "-v", "error", "-select_streams", "v:0",
+ "-count_frames", "-show_entries", "stream=nb_read_frames",
+ "-of", "default=nokey=1:noprint_wrappers=1", clip_path],
+ capture_output=True, text=True, timeout=30,
+ )
+ n = int(r.stdout.strip())
+ if n > 0:
+ return n
+ except Exception: # noqa: BLE001
+ pass
+ # Fallback: parse duration * 24 fps. Conservative.
+ try:
+ r = subprocess.run(
+ ["ffprobe", "-v", "error", "-show_entries",
+ "format=duration", "-of",
+ "default=nokey=1:noprint_wrappers=1", clip_path],
+ capture_output=True, text=True, timeout=10,
+ )
+ return max(1, int(float(r.stdout.strip()) * 24))
+ except Exception: # noqa: BLE001
+ return 121
+
+
+# ---- Action-block extraction ----------------------------------------------
+# The agent emits actions in fenced blocks. Be permissive with the
+# fence syntax (some models prefer ```json, some ```action, some no
+# language tag at all when they only emit one block).
+
+_FENCE_PATTERNS = [
+ re.compile(r"```(?:action|tool|json|json action|action_json)\s*\n(.+?)\n```", re.DOTALL | re.IGNORECASE),
+ re.compile(r"```\s*\n(\{[^`]*?\"tool\"[^`]*?\})\s*\n```", re.DOTALL),
+]
+
+
+def parse_action_block(content: str) -> dict | None:
+ """Find the first action block in a model reply and parse its JSON.
+
+ Returns a dict like {"tool": "...", "args": {...}} or None if no block
+ is present. Malformed JSON returns None — the runtime treats that
+ case as "model emitted text but failed to invoke a tool" and replies
+ asking it to fix the syntax.
+ """
+ for pat in _FENCE_PATTERNS:
+ m = pat.search(content)
+ if not m:
+ continue
+ try:
+ obj = json.loads(m.group(1))
+ except json.JSONDecodeError:
+ continue
+ if isinstance(obj, dict) and "tool" in obj:
+ obj.setdefault("args", {})
+ return obj
+ return None
+
+
+def strip_action_block(content: str) -> str:
+ """Return the assistant text with the action block removed.
+
+ Used when we want to show the user the model's prose without the
+ raw JSON cluttering the chat (the JSON is rendered as a tool-call
+ chip in the UI instead).
+ """
+ out = content
+ for pat in _FENCE_PATTERNS:
+ out = pat.sub("", out)
+ return out.strip()