Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

feat(media): an agent can make video, images and speech, and never holds the key

richard-epsillac7502b49195e
diff --git a/Dockerfile b/Dockerfile
index d5321899..7c087cc1 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -73,6 +73,17 @@ RUN set -eux; \
&& rm -rf /var/lib/apt/lists/*; \
fi
+# Assembling generated clips into one film. ffmpeg cuts and letterboxes the shots; ffprobe is how
+# the gateway learns a clip's real duration and how the assembled film's length is checked against
+# the timeline it was cut from. Built without it, the media server reports export unavailable and
+# refuses honestly — every clip is still downloadable on its own — rather than degrading silently.
+ARG WITH_MEDIA=1
+RUN set -eux; \
+ if [ "$WITH_MEDIA" = "1" ]; then \
+ apt-get update -y && apt-get install -y --no-install-recommends ffmpeg \
+ && rm -rf /var/lib/apt/lists/*; \
+ fi
+
# Node is needed for the UI server and for the npm-based agent CLIs.
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
diff --git a/gateway/app.py b/gateway/app.py
index bca06c7b..5f1af44b 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -41,6 +41,7 @@ from starlette.background import BackgroundTask
from pydantic import BaseModel
import backing # pluggable graph/blob/secret stores (vg | local)
+import media_plane # the media plane (capability catalog, provider adapters, ffmpeg)
import sql_plane # the read-only SQL data plane (gate, row cap, introspection)
import control_store # durable transactional control state (idempotency / lease / monotonic cancel)
@@ -3231,8 +3232,9 @@ async def delete_trace(sid: str, request: Request) -> dict:
# remove the flat index AND the per-harness/per-member mirrors (harness/member from the
# manifest we just read; falls back to a bare flat-key delete if the manifest was unreadable)
await _deindex_manifest(base, manifest)
- # 2) durable session workspace tarball
+ # 2) durable session workspace tarball, and anything the media server holds for it
await _blob_delete(_ws_blob(sid), kb=BLOB_KB)
+ await _media_session_purge(sid)
# 3) tombstone the session vertex + drop in-process state
try:
# Mark deleted but DON'T blank trace_blob — a blank prefix silently disables the trace if the
@@ -4313,6 +4315,22 @@ async def _resp_resolve_session(org: str, member: str, prev: str | None, backend
# Workspace sticks to the session: the vertex's stamp wins (set at creation/backfill);
# the caller's workspace only fills the gap for pre-stamping sessions.
tr["workspace"] = str((v or {}).get("workspace") or "") or tr.get("workspace") or workspace or ""
+ # The vertex names the harness the session belongs to, and every app route addressed to a
+ # harness refuses a session that names none — correctly, since an unnamed session cannot be
+ # proved to be this harness's. But the stamp is written at CREATION only, and this is the
+ # other moment the answer is known: a session made before the stamp existed, or made with no
+ # harness at all and later run on one, would name none forever and its canvas would 404 for
+ # good. So fill it in here — ONCE, and only into a blank.
+ #
+ # NEVER OVERWRITE. Re-pointing a session that already names a harness at whoever happened to
+ # run the next turn is exactly the cross-harness read those routes exist to refuse: two
+ # agents in one org, both legitimate callers, and the second one silently inherits the
+ # first's canvas, jobs and rendered bytes. `harness_id` is caller-supplied; a blank is the
+ # only state where nobody's claim is being taken away.
+ if harness_id and v is not None and not str(v.get("harness_id") or ""):
+ await _vertex_upsert(sid, {"harness_id": harness_id, "harness_name": harness_name or ""})
+ await _vg_edge("USES", sid, harness_id) # same topology edge the create path stamps
+ v["harness_id"], v["harness_name"] = harness_id, harness_name or ""
if not tr.get("prefix"):
vv = v or await _vertex_get(sid)
tr["prefix"] = _prefix_from_vertex(sid, vv)
@@ -4647,6 +4665,11 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
rec["usage"] = translator.usage
_cancel_req.pop(sid, None) # turn settled — a leftover Stop must not hit the next turn
await _checkpoint(sid, rec)
+ # The checkpoint replaced the workspace tarball with the sandbox's own copy, so anything the
+ # media server wrote into it during the turn is gone. Re-project here — one line, one place,
+ # and the only ordering at which a hosted write survives.
+ if sid in _media_project_due:
+ await _media_project(sid)
await _trace_finalize(sid, rec)
# Release the session lease so a follow-up turn admits immediately (no TTL wait). Best-effort.
if rec.get("lease_fence") and control_store.enabled():
@@ -6636,16 +6659,30 @@ def _internal_target(host: str, port: int) -> str | None:
metadata lives), RFC1918, IPv6 private, reserved — so a name cannot rebind to an internal
target between the check and the connection.
- Shared by MCP URLs and database hosts because it is one question, not two: both are a target
- a customer names and this server then opens a socket to. A second copy of this rule would be
- a second thing to remember to fix.
+ Shared by MCP URLs, database hosts and provider-supplied file URLs because it is one question,
+ not three: each is a target somebody else names and this server then opens a socket to. A
+ second copy of this rule would be a second thing to remember to fix.
+
+ A LOOKUP THAT DID NOT ANSWER IS NOT AN ANSWER. This used to take an `allow_unresolvable` flag,
+ on the reasoning that a name which does not resolve is not internal and cannot be reached
+ anyway — and its `except Exception` swallowed a resolver timeout, an EAI_AGAIN under load and
+ a resolver that was down along with the genuine NXDOMAIN. Our lookup failing says nothing
+ about what the socket does a millisecond later: the caller resolves again, from its own
+ resolver, in a cluster where `.svc` is a search domain. So there is no allow branch at all —
+ an address this server could not classify is one it does not open a socket to.
+
+ The two failures are still told apart, because the operator reading the log needs them apart:
+ one of them is a bad URL and the other is a broken resolver.
"""
import ipaddress
import socket
try:
infos = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)
+ except socket.gaierror as e:
+ no_such = {socket.EAI_NONAME, getattr(socket, "EAI_NODATA", socket.EAI_NONAME)}
+ return "host does not resolve" if e.errno in no_such else "host could not be resolved"
except Exception: # noqa: BLE001
- return "host does not resolve"
+ return "host could not be resolved"
for info in infos:
ip = ipaddress.ip_address(info[4][0])
if (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved
@@ -6844,17 +6881,29 @@ def _hosted_secret_key(hid: str, entry_id: str) -> str:
return f"{_HOSTED_SECRET_PREFIX}{safe(hid) or 'harness'}-{safe(entry_id) or 'server'}"
-async def _hosted_put_record(org: str, key: str, record: dict) -> None:
- """Write a hosted server's record. ALWAYS encrypted: the connection string is in it, and so
- are the host and the database name, which is strictly more than the vertex ever protected."""
+async def _hosted_put_record(org: str, key: str, record: dict, *, secret: bool = True,
+ param: str = "connection_string") -> None:
+ """Write a hosted server's record.
+
+ `secret=True` — the default, and the database's case — says the record holds a customer
+ credential: the connection string is in it, and so are the host and the database name, which
+ is strictly more than the vertex ever protected. A store that cannot encrypt must refuse
+ rather than write that in the clear.
+
+ `secret=False` is for a record that holds only a BINDING, {server, harness}, with no credential
+ in it at all — the media server's case, where the provider key belongs to this deployment's own
+ integrations and never becomes a per-harness secret. It is still written encrypted wherever
+ encryption is available; what changes is that an instance with no passphrase is not blocked
+ from a feature that has no secret to protect.
+ """
tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT
try:
- await BACKING.secrets.put(tenant, key, json.dumps(record), require_encryption=True)
+ await BACKING.secrets.put(tenant, key, json.dumps(record), require_encryption=secret)
except backing.SecretsNotConfigured as e:
# 501 rather than 500: nothing is broken. This instance has not been given a key to
# encrypt with, and refusing is the correct behaviour — the message names the variable
# that fixes it, because a stack trace would not.
- raise uhp_error(501, "secrets_not_configured", str(e), "connection_string") from e
+ raise uhp_error(501, "secrets_not_configured", str(e), param) from e
async def _hosted_record(org: str, key: str) -> dict | None:
@@ -6935,6 +6984,13 @@ def _connection_out(rec: dict) -> dict:
# entry", "its record is gone" and "that record is not yours" are the same fact: nothing here is
# connected to read.
_NOT_CONNECTED = "No database is connected to this agent yet."
+# Per hosted server, because "No database is connected" is a lie about a media server and a lie in
+# a refusal is worse than a vague one. Keyed by the server name _hosted_resolve was asked for, so
+# a server added later declares its own sentence here and nowhere else.
+_HOSTED_NOT_CONNECTED = {
+ "database": ("database_not_connected", _NOT_CONNECTED),
+ "media": ("media_not_connected", "No media tools are connected to this agent yet."),
+}
async def _hosted_resolve(server: str, hid: str, org: str, servers: list[dict], *,
@@ -6957,6 +7013,8 @@ async def _hosted_resolve(server: str, hid: str, org: str, servers: list[dict],
what an AGENT is handed, and a dashboard refresh is not a turn. A token minted before the
switch stays valid for hours, so the refusal has to be here and not only where turns are built.
"""
+ code, msg = _HOSTED_NOT_CONNECTED.get(server, ("server_not_connected",
+ "That is not connected to this agent yet."))
if key:
entry = next((e for e in servers if _vault_key(e.get("auth")) == key), None)
elif entry_id:
@@ -6964,12 +7022,12 @@ async def _hosted_resolve(server: str, hid: str, org: str, servers: list[dict],
else:
entry = None
if not entry:
- raise uhp_error(404, "database_not_connected", _NOT_CONNECTED, "harness_id")
+ raise uhp_error(404, code, msg, "harness_id")
if check_enabled and str(entry.get("enabled")) in ("False", "false", "0"):
- raise uhp_error(404, "database_not_connected", _NOT_CONNECTED, "harness_id")
+ raise uhp_error(404, code, msg, "harness_id")
rec = await _hosted_record(org, _vault_key(entry.get("auth")))
if not rec or rec.get("server") != server or rec.get("harness") != hid:
- raise uhp_error(404, "database_not_connected", _NOT_CONNECTED, "harness_id")
+ raise uhp_error(404, code, msg, "harness_id")
return entry, rec
@@ -7210,10 +7268,39 @@ async def get_harness_server(hid: str, sid: str, request: Request) -> dict:
"""
org, _ = await _pub_org_member(request)
v = await _harness_for_route(hid, org)
- entry, rec = await _hosted_resolve("database", hid, org, _mcp_list(v), entry_id=sid)
- return {"id": entry.get("id"), "name": entry.get("name"),
- "enabled": str(entry.get("enabled", True)) not in ("False", "false", "0"),
- "connection": _connection_out(rec)}
+ # WHICH server this is comes from the record, not from a field on the entry and not from the
+ # route. One route, because "the server describing itself" is one question — and the entry has
+ # nothing on it to branch on, which is the property this whole shape exists to keep.
+ entry, rec = await _hosted_resolve_any(hid, org, _mcp_list(v), entry_id=sid)
+ out = {"id": entry.get("id"), "name": entry.get("name"),
+ "enabled": str(entry.get("enabled", True)) not in ("False", "false", "0")}
+ if str(rec.get("server") or "") == _MEDIA_SERVER:
+ return {**out, **await _media_server_out()}
+ return {**out, "connection": _connection_out(rec)}
+
+
+def _hosted_server_name(entry: dict | None) -> str:
+ """Which server an entry SAYS it is, from its own url. "" for anything not ours.
+
+ The entry's url, and not the record it names: the url is the caller's own statement about what
+ they are addressing, so shaping a refusal with it tells them nothing they did not already say.
+ Reading the server name off a record they merely named would answer "that key is a database"
+ to anyone who guessed a key.
+ """
+ path = _hosted_mcp_path(str((entry or {}).get("url") or ""))
+ return path[len(_HOSTED_MCP_PREFIX):] if path else ""
+
+
+async def _hosted_resolve_any(hid: str, org: str, servers: list[dict], *,
+ entry_id: str) -> tuple[dict, dict]:
+ """(entry, record) for whichever server this gateway hosts at that entry.
+
+ Not a second resolution — the same one, with the server name taken from the entry instead of
+ asserted by the caller. Used only where the question is "what is this", never where it is
+ "read this": every route that acts on a server still names the server it means.
+ """
+ entry = next((e for e in servers if str(e.get("id") or "") == entry_id), None)
+ return await _hosted_resolve(_hosted_server_name(entry), hid, org, servers, entry_id=entry_id)
@app.post("/v1/harnesses/{hid}/servers/{sid}/query")
@@ -7389,6 +7476,1941 @@ def _uhp_message(e: HTTPException) -> str:
return str(d.get("message")) if isinstance(d, dict) and d.get("__uhp__") else str(d)
+# ── Media, an ordinary MCP server ─────────────────────────────────────────────────────────────
+# Making a picture, a clip or a line of speech, and cutting the clips into one film. Same shape as
+# the database next door and for the same reasons: its entry in `mcp_servers` is INDISTINGUISHABLE
+# from a third-party one, a server is ours because its url is one of our own addresses, and the
+# record the entry's `auth` names is owned BY THE SERVER.
+#
+# WHAT IS DIFFERENT FROM THE DATABASE, and it is only this: nothing is collected from anyone. A
+# database record holds a customer's connection string; a media record holds only the binding
+# {server, harness}, because the provider credential is THIS DEPLOYMENT'S OWN INTEGRATION and must
+# never become a per-harness secret. The record with no secret in it is the whole trick — the
+# `harness-hosted-` prefix is still what makes the entry offerable, and `rec["harness"] == hid` is
+# still what stops one harness addressing another's canvas.
+#
+# THE AGENT NEVER NAMES A MODEL. It asks for a capability; media_plane walks that capability's
+# ordered candidate list and the tool reports which model actually ran. Four video models are
+# listed and two are broken, which is exactly why.
+#
+# THE CANVAS IS OWNED BY THIS SERVER, not by the session workspace. Hosted, the gateway cannot
+# durably write a live sandbox's workspace mid-turn — `_checkpoint` replaces the whole tarball from
+# the sandbox at turn end, so anything written into it in between is gone (which is why
+# PUT /v1/sessions/{sid}/files/{path} answers 409). So the scene lives in blob storage and is
+# PROJECTED into the workspace after every mutation and after every checkpoint, write-only, so
+# `scene.excalidraw` is still an ordinary artifact the console lists. Generated media are NOT
+# projected: the workspace is a tarball rewritten whole at every checkpoint, and a ten-clip project
+# would re-upload two hundred megabytes on every subsequent turn.
+
+_MEDIA_SERVER = "media"
+_MEDIA_SCENE_FILE = "scene.excalidraw"
+# Candidates stood down after a BILLABLE failure. Per-replica and in memory on purpose: it is a
+# hint that saves money, not state anything depends on, and a replica that has not seen the
+# failure simply pays for one more attempt rather than serving a stale verdict for half an hour.
+_media_quarantine: dict[str, float] = {}
+# One lock per session, so read-modify-write of a scene is serialised and the canvas tools never
+# have to fail on concurrency.
+_media_scene_locks: dict[str, asyncio.Lock] = {}
+_media_job_locks: dict[str, asyncio.Lock] = {}
+# Sessions whose scene moved since the last projection. The sweeper drains this, so a job that
+# lands with no turn running still leaves an up-to-date artifact behind.
+_media_project_due: set[str] = set()
+
+# What each capability produces. The one place kind is decided, so a job, an element and a stored
+# file cannot disagree about whether a thing is a video.
+_MEDIA_KIND = {"text_to_video": "video", "image_to_video": "video",
+ "text_to_image": "image", "image_to_image": "image",
+ "text_to_speech": "audio", "text_to_music": "audio", "export": "film"}
+
+
+def _media_scene_lock(sid: str) -> asyncio.Lock:
+ lk = _media_scene_locks.get(sid)
+ if lk is None:
+ lk = _media_scene_locks[sid] = asyncio.Lock()
+ if len(_media_scene_locks) > 4000: # bounded; an unheld lock is free to drop
+ for k in [k for k, v in list(_media_scene_locks.items()) if not v.locked()][:2000]:
+ _media_scene_locks.pop(k, None)
+ return lk
+
+
+def _media_job_lock(jid: str) -> asyncio.Lock:
+ """One advance per job at a time. The sweeper, the agent's check_jobs and the app's poll route
+ all advance jobs, and they run concurrently by design — so without this they each saw the same
+ SUCCESS, each downloaded the same clip and each stored it under a NEW media id. Measured: one
+ 6 s clip landed three times, ~4 MB apiece, two of them orphaned the moment the third won the
+ vertex. Same shape and same bound as the scene lock, because it is the same problem.
+ """
+ lk = _media_job_locks.get(jid)
+ if lk is None:
+ lk = _media_job_locks[jid] = asyncio.Lock()
+ if len(_media_job_locks) > 4000:
+ for k in [k for k, v in list(_media_job_locks.items()) if not v.locked()][:2000]:
+ _media_job_locks.pop(k, None)
+ return lk
+
+
+def _media_client() -> httpx.AsyncClient:
+ """The client every provider call goes through. One seam, so a test can drive all five
+ adapters through a transport it controls without stubbing the adapters themselves."""
+ return _client()
+
+
+async def _media_providers() -> dict[str, dict]:
+ """{provider: {api_key, base_url}} for every catalog provider this deployment can reach.
+
+ Read HERE, at the moment of use, from the integrations document — the same document the model
+ broker reads. The key is returned to this process and to nothing else: it is never written into
+ a record, never put on a vertex, never handed to the runner and never sent to a browser.
+ """
+ out: dict[str, dict] = {}
+ integrations = await _integrations_doc()
+ for pname, pmeta in (media_plane.catalog().get("providers") or {}).items():
+ want = str((pmeta or {}).get("integration_provider") or pname).strip().lower()
+ for integ in integrations:
+ if str(integ.get("provider") or "").strip().lower() != want:
+ continue
+ cfg = integ.get("config") or {}
+ key = str(cfg.get("api_key") or "").strip()
+ if not key:
+ continue
+ base = str(cfg.get("base_url") or (pmeta or {}).get("base_url") or "").rstrip("/")
+ if not base:
+ continue
+ out[pname] = {"api_key": key, "base_url": base}
+ # The one place the key is resolved is the one place that can say what must never be
+ # relayed back. Every provider sentence this process produces is scrubbed of it —
+ # a 401 quotes the key it rejected, and that sentence reaches an agent, a vertex and
+ # a browser.
+ media_plane.remember_secret(key)
+ break
+ return out
+
+
+class _MediaNoModel(Exception):
+ """No candidate could serve this request. Carries the refusal the agent is shown and the
+ attempts that led to it.
+
+ Usually nothing was generated and nothing was charged. Not always: a candidate that answers
+ 200 with nothing in it has billed, and a request may reach its billable ceiling before any
+ candidate delivers. The refusal says which of the two happened — see `_media_billed_out` —
+ because "nothing was charged" is the one sentence an agent must never be told wrongly.
+ """
+
+ def __init__(self, text: str, attempts: list[dict]):
+ super().__init__(text)
+ self.text, self.attempts = text, attempts
+
+
+def _media_json(body: bytes):
+ try:
+ return json.loads(body or b"{}")
+ except Exception: # noqa: BLE001
+ return None
+
+
+async def _media_call(cand: dict, prov: dict, params: dict) -> tuple[str, object, dict]:
+ """One provider call: (task_id, payload, response doc). The ONLY blocking provider call.
+
+ A shape that hands back a task id returns in about a second. A synchronous shape renders
+ inside this call, which is why the timeout is the candidate's own measured latency with room
+ rather than one number for a four-second model and a ninety-second one.
+ """
+ sub = media_plane.build_submit(cand, prov["base_url"], params)
+ headers = {"authorization": f"Bearer {prov['api_key']}", "content-type": "application/json"}
+ cl = _media_client()
+ try:
+ if sub.stream:
+ # gpt-audio refuses without stream:true and then delivers audio in deltas.
+ chunks: list[str] = []
+ async with cl.stream(sub.method, sub.url, json=sub.body, headers=headers,
+ timeout=sub.timeout) as r:
+ if r.status_code >= 400:
+ raise media_plane.MediaRefused(
+ media_plane.provider_message(_media_json(await r.aread()), r.status_code))
+ async for line in r.aiter_lines():
+ chunks.append(line)
+ return "", media_plane.read_stream_audio(cand, chunks), {}
+ r = await cl.request(sub.method, sub.url, json=sub.body, headers=headers,
+ timeout=sub.timeout)
+ except (media_plane.MediaError, HTTPException):
+ raise
+ except Exception as e: # noqa: BLE001 — a timeout or a reset is a refusal, not a crash
+ raise media_plane.MediaRefused(
+ f"the provider did not answer ({type(e).__name__})") from e
+ doc = _media_json(r.content)
+ task_id, payload = media_plane.read_submit(cand, r.status_code, doc)
+ return task_id, payload, doc if isinstance(doc, dict) else {}
+
+
+# How many times ONE REQUEST may fall down its chain after a candidate has already billed. One.
+# Every advance is another full-price render, so a second one is the agent's decision, made with
+# the first one's cost in front of it.
+#
+# ONE BUDGET, TWO WALKS. A request can fall down the chain in two places — here at SUBMIT, when a
+# candidate answers 200 with nothing in it, and later at POLL, when a render that billed comes
+# back failed — and they are the same event to whoever is paying. The submit walk was uncapped
+# while the poll walk was capped, so one generate_image whose candidates all answered
+# 200-with-no-image bought the entire eleven-model chain inside a single tool call. What the
+# submit walk spent is therefore written onto the job (`advances`), which is the only thing that
+# outlives the tool call and the only place the poll walk can read it from.
+_MEDIA_MAX_ADVANCES = 1
+
+
+def _media_billed_out(err: str, billed: int) -> str:
+ """What an agent is told when its request has spent the whole billable budget. ONE sentence
+ for both walks, because a second one would drift and only one of them would be true."""
+ what = "1 model has" if billed == 1 else f"{billed} models have"
+ return (f"{err} — {what} now billed for this one request and nothing further was bought. "
+ f"Ask again if you want another attempt.")
+
+
+async def _media_chain(cap: str, params: dict, providers: dict) -> tuple[dict, str, object, dict, dict]:
+ """Walk the capability's chain until one candidate actually runs. Returns the tally of what
+ the walk cost along with what it produced, because the job that comes out of it has to carry
+ the spend forward.
+
+ A candidate that fails AT SUBMIT is retried on the very next call and never quarantined —
+ retrying is free, and that is precisely what lets `dreamina-seedance-2-5-hc` sit permanently at
+ rank 1 and start working the day the relay's mapping is fixed, with no code change and no cost.
+ A candidate that fails having ALREADY BILLED is `_media_billed` — written down, stood down and
+ counted — and counted against _MEDIA_MAX_ADVANCES, which is the whole request's budget and not
+ this walk's: free failures and paid ones look identical in a list of attempts, and only one of
+ them may end the walk.
+ """
+ tally: dict = {"attempts": [], "billed_usd": 0.0}
+ tried: set[str] = set()
+ while True:
+ cand, skipped = media_plane.resolve(cap, params, set(providers), _media_quarantine,
+ exclude=tried)
+ billed = sum(1 for a in tally["attempts"] if a.get("billed"))
+ if not cand:
+ reasons = [f"{a['model']} — {a['error']}" for a in tally["attempts"]] + skipped
+ # `refusal` ends with "nothing was charged", which is only true when nothing billed.
+ text = (media_plane.refusal(cap, reasons) if not billed
+ else _media_billed_out("; ".join(reasons), billed))
+ raise _MediaNoModel(text, tally["attempts"])
+ model = str(cand.get("model") or "")
+ tried.add(model)
+ try:
+ task_id, payload, doc = await _media_call(cand, providers[cand["provider"]], params)
+ except media_plane.MediaEmpty as e:
+ # It answered and it billed. Stand it down so the next request does not pay again —
+ # and stop here if this request has now bought everything it is allowed to buy.
+ _media_billed(tally, model, media_plane.estimated_usd(cand) or 0.0, str(e))
+ if billed + 1 > _MEDIA_MAX_ADVANCES:
+ raise _MediaNoModel(_media_billed_out(str(e), billed + 1),
+ tally["attempts"]) from e
+ continue
+ except media_plane.MediaError as e:
+ tally["attempts"].append({"model": model, "error": str(e)})
+ continue
+ return cand, task_id, payload, doc, tally
+
+
+# ── the job store ─────────────────────────────────────────────────────────────────────────────
+# One vertex per job. A vertex and not an in-memory dict because a job outlives the turn, the tab
+# and a gateway restart — a clip takes about four minutes and nobody watches it arrive.
+#
+# NOTE FOR A HOSTED DEPLOYMENT: the graph is closed-world on labels, so `MediaJob` has to be
+# registered there exactly as `HarnessSession` and `Harness` are, or every upsert silently no-ops.
+_MEDIA_JOB_LABEL = "MediaJob"
+_MEDIA_JOB_NUM = ("bytes", "width", "height", "next_poll_at", "poll_backoff_s", "created_at",
+ "updated_at", "shots", "advances")
+_MEDIA_JOB_FLOAT = ("seconds", "usd", "quota", "planned_seconds", "billed_usd")
+
+
+def _media_job_props(job: dict) -> dict:
+ """A job as flat string props. The graph stores strings; keeping the conversion in one place
+ is what stops a job that reads back as the string "None".
+
+ `attempts` and `params` are stored ONCE, as their _json siblings. Writing both would be two
+ copies of the same fact, and the day they disagree is the day a job's history is a coin toss.
+ """
+ out = {}
+ for k, v in job.items():
+ if k in ("id", "attempts", "params"):
+ continue
+ out[k] = json.dumps(v) if isinstance(v, (dict, list)) else ("" if v is None else str(v))
+ return out
+
+
+def _media_job_out(v: dict | None) -> dict | None:
+ if not v:
+ return None
+ job = {"id": str(v.get("id") or "")}
+ for k, val in v.items():
+ if k in ("id", "pk", "label"):
+ continue
+ job[k] = val
+ for k in _MEDIA_JOB_NUM:
+ job[k] = int(float(job.get(k) or 0) or 0)
+ for k in _MEDIA_JOB_FLOAT:
+ job[k] = float(job.get(k) or 0) or 0.0
+ for k, empty in (("attempts", []), ("params", {})):
+ try:
+ job[k] = json.loads(job.get(k + "_json") or json.dumps(empty))
+ except Exception: # noqa: BLE001
+ job[k] = empty
+ return job
+
+
+async def _media_job_save(job: dict) -> None:
+ job["updated_at"] = int(time.time() * 1000)
+ await _vg_upsert(_MEDIA_JOB_LABEL, job["id"], _media_job_props(job))
+
+
+async def _media_job_get(jid: str) -> dict | None:
+ if not jid or not jid.startswith("mjob_"):
+ return None
+ return _media_job_out(await BACKING.graph.get(jid, label=_MEDIA_JOB_LABEL))
+
+
+async def _media_jobs_of(sid: str) -> list[dict]:
+ rows = await BACKING.graph.find(_MEDIA_JOB_LABEL, {"session": sid})
+ return [j for j in (_media_job_out(r) for r in rows) if j and j.get("deleted") != "1"]
+
+
+async def _media_spend(sid: str) -> float:
+ """What this session has actually cost: the summed MEASURED usd of everything that billed.
+
+ A render that billed and then failed is money spent. Summing only the SUCCEEDED jobs is how a
+ session that burned six full-price renders read as $0.00 and the budget cap never fired —
+ `billed_usd` is what each failed candidate cost, banked as the chain moved off it.
+
+ Measured only. A session whose jobs reported no cost sums to nothing and the caller shows
+ nothing — never "$0.00", which reads as free rather than as unknown. Most candidates carry no
+ measured price, so this is a floor on what was spent and never an estimate of it.
+ """
+ jobs = await _media_jobs_of(sid)
+ return round(sum(float(j.get("usd") or 0.0) for j in jobs if j.get("status") == "succeeded")
+ + sum(float(j.get("billed_usd") or 0.0) for j in jobs), 4)
+
+
+# ── the media store ───────────────────────────────────────────────────────────────────────────
+def _media_blob(sid: str, med: str, ext: str) -> str:
+ return f"media/{sid}/{med}.{ext}"
+
+
+def _media_url(hid: str, eid: str, sid: str, med: str) -> str:
+ """Where the app fetches these bytes. A PATH, not an absolute URL: an absolute one breaks the
+ moment the deployment moves, which is the same lesson `_harness_plugins` already encodes by
+ re-deriving hosted server addresses at turn time instead of trusting the stored one."""
+ return f"/v1/harnesses/{hid}/servers/{eid}/sessions/{sid}/media/{med}"
+
+
+async def _media_store(sid: str, kind: str, data: bytes, meta: dict) -> dict:
+ """Verify these bytes really are that media, then keep our own copy.
+
+ THE PROVIDER URL IS NEVER STORED. Every one of them is signed or short-lived — happyhorse's
+ lasts a day — so a scene holding one is a scene that stops working tomorrow.
+ """
+ info = media_plane.verify(kind, data)
+ med = "med_" + uuid.uuid4().hex[:16]
+ ok = await _blob_put(_media_blob(sid, med, info["ext"]), data, kb=BLOB_KB)
+ if not ok:
+ raise media_plane.MediaError("the generated file could not be stored")
+ rec = {"media_id": med, "kind": kind, "ext": info["ext"], "mime": info["mime"],
+ "bytes": info["bytes"], "width": info.get("width") or 0,
+ "height": info.get("height") or 0, "seconds": info.get("seconds") or 0.0,
+ "created_at": int(time.time() * 1000), **meta}
+ await _blob_put(_media_blob(sid, med, info["ext"]) + ".meta",
+ json.dumps(rec).encode(), kb=BLOB_KB)
+ return rec
+
+
+async def _media_meta(sid: str, med: str) -> dict | None:
+ """The record beside the bytes, found without knowing the extension."""
+ listing = await _blob_list_all(f"media/{sid}/{med}.", kb=BLOB_KB)
+ for it in listing:
+ fid = str(it.get("file_id") or "")
+ if fid.endswith(".meta"):
+ raw = await _blob_get(fid, kb=BLOB_KB)
+ if raw:
+ try:
+ return json.loads(raw)
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+
+def _provider_url_check(url: str) -> str | None:
+ """Whether this server may fetch an address THE PROVIDER named. The rule _ssrf_check applies
+ to a customer's MCP endpoint, minus its self-hosted exemption.
+
+ That exemption exists because a local MCP server on 127.0.0.1 is one the OPERATOR typed on a
+ machine they already own. A result_url is chosen by a remote relay, so on a self-hosted box
+ the operator's own network is exactly what a hostile relay would reach for — the reasoning
+ that makes the exemption right there makes it wrong here.
+
+ Nor is there an exemption for a name that did not resolve. This is the one caller whose
+ address a REMOTE PARTY chose, and it is polled again and again — so "our lookup failed, allow
+ it" is not one gamble, it is a fresh roll on every poll until one of them lands.
+ """
+ from urllib.parse import urlparse
+ refused = "the finished file was offered from an address this will not fetch"
+ try:
+ u = urlparse(url)
+ except Exception: # noqa: BLE001
+ return refused
+ if u.scheme not in ("http", "https") or not u.hostname:
+ return refused
+ bad = _internal_target(u.hostname, u.port or (443 if u.scheme == "https" else 80))
+ if not bad:
+ return None
+ # The host, in the log, where an operator can act on it — and only the host: a result_url
+ # carries a signature, and that is a credential like any other.
+ print(f"[media] refused a provider file address at {u.hostname}: {bad}", flush=True)
+ return refused
+
+
+async def _media_fetch(url: str) -> bytes:
+ """Pull a finished render off the provider, capped. Streamed rather than read whole, so a
+ provider that answers with a gigabyte is a refused job and not an out-of-memory.
+
+ The response's content-type is deliberately NOT returned: what the bytes are is decided by the
+ bytes (media_plane.verify), and a header is a claim.
+
+ WHERE it is pulled from is a claim too, and one the provider makes: a relay that answers a
+ poll with `result_url: http://169.254.169.254/…` had this server fetching cloud metadata and
+ storing the answer. No credential rides along and the body is never echoed, but a status and
+ a size still leak through `attempts`, and that is a probe of our own network either way.
+ """
+ refused = _provider_url_check(url)
+ if refused:
+ raise media_plane.MediaEmpty(refused)
+ buf = bytearray()
+ async with _media_client().stream("GET", url, timeout=300) as r:
+ if r.status_code >= 400:
+ raise media_plane.MediaEmpty(f"the finished file could not be fetched "
+ f"(HTTP {r.status_code})")
+ async for chunk in r.aiter_bytes():
+ buf.extend(chunk)
+ if len(buf) > media_plane.MAX_BYTES:
+ raise media_plane.MediaEmpty(
+ f"the provider returned more than {media_plane.MAX_BYTES} bytes")
+ return bytes(buf)
+
+
+# ── the scene ─────────────────────────────────────────────────────────────────────────────────
+def _media_scene_key(sid: str) -> str:
+ return f"sessions/{sid}/{_MEDIA_SCENE_FILE}"
+
+
+async def _media_scene_read(sid: str) -> dict:
+ raw = await _blob_get(_media_scene_key(sid), kb=BLOB_KB)
+ if not raw:
+ return media_plane.new_scene()
+ try:
+ return media_plane.sanitize_scene(json.loads(raw))
+ except Exception: # noqa: BLE001
+ return media_plane.new_scene()
+
+
+async def _media_scene_write(sid: str, scene: dict) -> int:
+ """Store the scene and bump its revision. The revision lives IN the document, so there is one
+ thing to read and one thing to write and they cannot disagree."""
+ scene = media_plane.sanitize_scene(scene)
+ meta = scene.get("meta") or {}
+ rev = int(float(meta.get("rev") or 0)) + 1
+ scene["meta"] = {**meta, "rev": rev}
+ (scene.get("timeline") or {})["updatedAt"] = int(time.time() * 1000)
+ await _blob_put(_media_scene_key(sid), json.dumps(scene).encode(), kb=BLOB_KB)
+ _media_project_due.add(sid)
+ await _media_project(sid, scene)
+ return rev
+
+
+async def _media_project(sid: str, scene: dict | None = None) -> None:
+ """Write the scene into the session's workspace, so it is an ordinary artifact.
+
+ WRITE-ONLY, store → workspace. Nothing ever reads it back as authority. Self-hosted it is
+ live; hosted it is up to one turn stale, because a live sandbox's tarball is replaced wholesale
+ at checkpoint — which is the same staleness the console already shows for every other kit
+ mid-turn. Best-effort: a projection that fails must never fail the generation it describes.
+ """
+ try:
+ doc = scene if scene is not None else await _media_scene_read(sid)
+ if not (doc.get("elements") or doc.get("timeline", {}).get("shots")):
+ _media_project_due.discard(sid)
+ return # nothing to project yet; don't create an empty artifact
+ ok = await BACKING.workspace.write(sid, _MEDIA_SCENE_FILE,
+ json.dumps(doc, indent=2).encode())
+ if ok:
+ _media_project_due.discard(sid)
+ else:
+ # Hosted, mid-turn, this is EXPECTED — the live sandbox owns the tarball and its own
+ # checkpoint will replace whatever we wrote. Leaving it queued is what makes the
+ # re-projection after `_checkpoint` land, so the artifact is at most one turn stale.
+ print(f"[media] projection of {sid} deferred to the next checkpoint", flush=True)
+ except Exception as e: # noqa: BLE001
+ print(f"[media] projection of {sid} deferred: {type(e).__name__}", flush=True)
+
+
+async def _media_scene_touch(sid: str, mutate) -> tuple[int, object]:
+ """Read-modify-write one scene under its lock. Every canvas tool comes through here, so the
+ agent's edits and a landing render cannot interleave into a broken document."""
+ async with _media_scene_lock(sid):
+ scene = await _media_scene_read(sid)
+ out = mutate(scene)
+ rev = await _media_scene_write(sid, scene)
+ return rev, out
+
+
+# ── running a job ─────────────────────────────────────────────────────────────────────────────
+async def _media_job_land(job: dict, data: bytes, transcript: str = "") -> dict:
+ """A finished render becomes our own file, and the element that was holding its place becomes
+ the clip. Verification first: a body that is not media is a failure, not a success."""
+ kind = _MEDIA_KIND.get(str(job.get("capability") or ""), "image")
+ rec = await _media_store(str(job["session"]), kind, data,
+ {"model": job.get("model") or "", "capability": job.get("capability"),
+ "job_id": job["id"], "prompt": (job.get("params") or {}).get("prompt") or ""})
+ job.update({"status": "succeeded", "media_id": rec["media_id"], "bytes": rec["bytes"],
+ "width": rec["width"], "height": rec["height"], "seconds": rec["seconds"],
+ "error": ""})
+ if transcript:
+ job["spoken_text"] = transcript
+ await _media_job_save(job)
+ await _media_element_ready(job, rec)
+ return job
+
+
+async def _media_element_ready(job: dict, rec: dict) -> None:
+ """Swap the placeholder for the real thing, server-side.
+
+ Server-side is the point: the scene is mutated in the store, not in a browser reacting to a
+ stream, so a clip cannot go missing because nobody had the canvas tab open when it landed.
+ """
+ eid = str(job.get("element_id") or "")
+ if not eid:
+ return
+ sid = str(job["session"])
+
+ def mutate(scene: dict):
+ for el in scene.get("elements") or []:
+ if el.get("id") != eid:
+ continue
+ m = media_plane.media_of(el)
+ m.update({"status": "ready", "mediaId": rec["media_id"], "model": job.get("model"),
+ "seconds": rec.get("seconds") or None, "width": rec.get("width") or None,
+ "height": rec.get("height") or None})
+ if el.get("type") == "image":
+ # A NEW fileId, equal to the new media id. Excalidraw's addFiles will not update a
+ # fileId that already exists, so reusing one leaves the placeholder on screen
+ # forever.
+ el["fileId"] = rec["media_id"]
+ el["status"] = "saved"
+ scene.setdefault("files", {})[rec["media_id"]] = media_plane.file_entry(
+ rec["media_id"], rec["mime"],
+ _media_url(str(job.get("harness") or ""), str(job.get("entry") or "mcp.media"),
+ sid, rec["media_id"]))
+ else:
+ el["link"] = _media_url(str(job.get("harness") or ""),
+ str(job.get("entry") or "mcp.media"), sid,
+ rec["media_id"])
+ return None
+ return None
+
+ await _media_scene_touch(sid, mutate)
+
+
+async def _media_element_failed(job: dict) -> None:
+ eid = str(job.get("element_id") or "")
+ if not eid:
+ return
+
+ def mutate(scene: dict):
+ for el in scene.get("elements") or []:
+ if el.get("id") == eid:
+ media_plane.media_of(el).update({"status": "failed"})
+ return None
+
+ await _media_scene_touch(str(job["session"]), mutate)
+
+
+async def _media_job_live(job: dict) -> bool:
+ """May this job still spend? Asked before every poll it would pay for.
+
+ A running job IS money: each poll carries this deployment's provider key, and a poll that
+ reports SUCCESS downloads a file and stores it. So the question is not "does this job exist"
+ but "is the server that started it still connected and still switched on".
+
+ Asked here rather than in the sweeper because check_jobs and the app's jobs route advance jobs
+ too, and `check_enabled` only ever refused a TURN — a media server the owner switched off went
+ on polling and paying for everything earlier turns had started. Switching it back on resumes
+ the same job, which is the difference between this and deleting the agent (that buries them).
+ """
+ hid = str(job.get("harness") or "")
+ v = await _vertex_get(hid) if hid else None
+ if not v or str(v.get("deleted")) in ("1", "true", "True"):
+ return False
+ try:
+ await _hosted_resolve(_MEDIA_SERVER, hid, str(v.get("org") or ""), _mcp_list(v),
+ entry_id=str(job.get("entry") or ""), check_enabled=True)
+ except HTTPException:
+ return False
+ return True
+
+
+async def _media_job_advance(job: dict) -> dict:
+ """Move one job forward. THE one function that does — check_jobs, the app's poll route and the
+ sweeper all call it, so a job cannot mean one thing to a browser and another to an agent."""
+ if job.get("status") != "running" or not job.get("provider_task_id"):
+ return job
+ if float(job.get("next_poll_at") or 0) > time.time() * 1000:
+ return job
+ if not await _media_job_live(job):
+ return job
+ # Serialise from here: everything below can DOWNLOAD AND STORE, and those callers overlap.
+ async with _media_job_lock(str(job.get("id") or "")):
+ fresh = await _media_job_get(str(job.get("id") or "")) or job
+ # Re-check under the lock. A caller that queued behind the one that landed this job must
+ # return the landed answer, not fetch the same clip a second time.
+ if fresh.get("status") != "running" or not fresh.get("provider_task_id"):
+ return fresh
+ if float(fresh.get("next_poll_at") or 0) > time.time() * 1000:
+ return fresh
+ return await _media_job_poll(fresh)
+
+
+async def _media_job_poll(job: dict) -> dict:
+ """One poll of one job, under its lock. Split out so the locking above reads as one thought."""
+ now = time.time()
+ age_s = (now * 1000 - float(job.get("created_at") or 0)) / 1000.0
+ cand = _media_candidate(str(job.get("capability") or ""), str(job.get("model") or ""))
+ providers = await _media_providers()
+ prov = providers.get(str(job.get("provider") or ""))
+ if not cand or not prov:
+ job["next_poll_at"] = int((now + 60) * 1000)
+ await _media_job_save(job)
+ return job
+
+ method, url = media_plane.build_poll(cand, prov["base_url"], str(job["provider_task_id"]))
+ try:
+ r = await _media_client().request(
+ method, url, headers={"authorization": f"Bearer {prov['api_key']}"},
+ timeout=media_plane.POLL_TIMEOUT_S)
+ status, payload, err, progress = media_plane.read_poll(cand, r.status_code,
+ _media_json(r.content))
+ except Exception: # noqa: BLE001 — a poll that did not answer is unknown, never failed
+ status, payload, err, progress = "unknown", None, "", ""
+
+ job["progress"] = progress
+ if status == "succeeded" and payload is not None:
+ try:
+ data = await _media_fetch(payload.url)
+ return await _media_job_land(job, data)
+ except media_plane.MediaError as e:
+ status, err = "failed", str(e)
+
+ if status == "failed":
+ await _media_job_billable_failure(job, err)
+ return job
+
+ # WHAT THE LAST POLL SAID, kept beside the status rather than in it. `unknown` is never a
+ # state a job is IN — it is what one answer was — so recording it here lets check_jobs tell the
+ # agent "ask again" without a poll that came back empty ever becoming terminal.
+ job["last_poll"] = status
+ if status == "unknown":
+ job["poll_backoff_s"] = min(60, int(job.get("poll_backoff_s") or 20) * 2)
+ if age_s > media_plane.JOB_MAX_S:
+ job.update({"status": "failed", "error": "The provider never finished this render."})
+ await _media_job_save(job)
+ await _media_element_failed(job)
+ return job
+ job["next_poll_at"] = int((now + int(job.get("poll_backoff_s") or 20)) * 1000)
+ await _media_job_save(job)
+ return job
+
+
+def _media_candidate(cap: str, model: str) -> dict | None:
+ for c in media_plane.capability(cap).get("candidates") or []:
+ if isinstance(c, dict) and str(c.get("model") or "") == model:
+ return c
+ return None
+
+
+def _media_params_stored(params: dict) -> dict:
+ """What of a job's parameters is written down: everything except the image bytes."""
+ return {k: v for k, v in params.items() if k not in ("image", "image_mime")}
+
+
+async def _media_land_payload(job: dict, payload) -> bool:
+ """Turn a payload that is already in hand into our own file. True when it landed.
+
+ The ONE place a synchronous result lands, shared by the first submit and by a chain that
+ advanced — so "the file was verified before it was stored" cannot be true of one and not the
+ other. It records the reason and DECIDES NOTHING: whether a failure here advances the chain is
+ a policy the caller holds, which is what keeps the advance to exactly one.
+ """
+ try:
+ data = (payload.data if getattr(payload, "data", None)
+ else await _media_fetch(payload.url))
+ await _media_job_land(job, data, getattr(payload, "transcript", ""))
+ return True
+ except media_plane.MediaError as e:
+ job["error"] = str(e)
+ return False
+
+
+def _media_billed(job: dict, model: str, usd: float, err: str) -> None:
+ """Write down that a candidate BILLED and gave us nothing: the attempt, the stand-down, and
+ the money.
+
+ One function, because those three always go together and every place that did them by hand
+ got a different subset right. The advance that a chain then makes is NOT here: whether this
+ request may buy another render is the caller's decision, and keeping it there is what keeps
+ the count at one per request rather than one per place that noticed.
+ """
+ job.setdefault("attempts", []).append({"model": model, "error": err, "billed": True})
+ job["attempts_json"] = json.dumps(job["attempts"])
+ _media_quarantine[model] = time.time() + media_plane.QUARANTINE_S
+ # Banked BEFORE the next candidate overwrites `usd`. A render that billed and failed is money
+ # the session spent, and the job ends at `failed`, so the succeeded-sum never sees it.
+ job["billed_usd"] = round(float(job.get("billed_usd") or 0.0) + float(usd or 0.0), 6)
+
+
+async def _media_job_billable_failure(job: dict, err: str) -> bool:
+ """A candidate that had already billed has failed. Record it, stand it down, count what it
+ cost, and advance the chain EXACTLY ONCE PER JOB.
+
+ Once per JOB, which is what this always said and never did: it advanced once per FAILURE, and
+ there is a poll after every advance, so a CDN briefly answering 503 on an otherwise-fine render
+ walked one generate_video down the entire six-model chain — six full-price renders, $1.96 of
+ list price, from one tool call. The count lives on the job because the job is what outlives
+ the poll that reads it.
+
+ Shared by the poll path and by a synchronous render whose file turned out not to be a file,
+ because they are the same event. `advances` may already be non-zero when this is first
+ reached: the submit walk spends out of the same budget and writes what it spent onto the job.
+ """
+ _media_billed(job, str(job.get("model") or ""), float(job.get("usd") or 0.0), err)
+ if int(job.get("advances") or 0) < _MEDIA_MAX_ADVANCES:
+ job["advances"] = int(job.get("advances") or 0) + 1
+ if await _media_job_resubmit(job):
+ return True
+ else:
+ # advances + this one. NOT len(attempts): that also counts candidates that were refused
+ # at submit, which cost nothing — a count of what was spent has to be a count of what
+ # actually billed.
+ err = _media_billed_out(err, int(job.get("advances") or 0) + 1)
+ job.update({"status": "failed", "error": err or "the render failed upstream"})
+ await _media_job_save(job)
+ await _media_element_failed(job)
+ return False
+
+
+async def _media_job_resubmit(job: dict) -> bool:
+ """After a billable failure, try the next candidate — once. True when one took the job."""
+ providers = await _media_providers()
+ tried = {str(a.get("model") or "") for a in job.get("attempts") or []}
+ tried.add(str(job.get("model") or ""))
+ params = dict(job.get("params") or {})
+ if params.get("from_media") and not params.get("image"):
+ # Read back from OUR copy, not from the provider's expiring one — and this is also what
+ # makes a chain advance work after a restart, when the job came back off a vertex.
+ try:
+ params["image"], params["image_mime"] = await _media_read_image(
+ str(job["session"]), str(params["from_media"]))
+ except media_plane.MediaError as e:
+ job.setdefault("attempts", []).append({"model": "", "error": str(e)})
+ job["attempts_json"] = json.dumps(job["attempts"])
+ return False
+ cand, _skipped = media_plane.resolve(str(job["capability"]), params, set(providers),
+ _media_quarantine, exclude=tried)
+ if not cand:
+ return False
+ model = str(cand.get("model") or "")
+ usd = media_plane.estimated_usd(cand) or 0.0
+ try:
+ task_id, payload, doc = await _media_call(cand, providers[cand["provider"]], params)
+ except media_plane.MediaEmpty as e:
+ # The SECOND render this request bought, and it answered with nothing either. Banked and
+ # stood down exactly as the first one was — the submit walk in _media_chain treats this
+ # case that way, and a candidate that bills for nothing must not stay in the chain because
+ # it happened to be reached from the poll path instead.
+ _media_billed(job, model, usd, str(e))
+ return False
+ except media_plane.MediaError as e:
+ # Refused before any billable work started; retrying it is free and it is not stood down.
+ job.setdefault("attempts", []).append({"model": model, "error": str(e)})
+ job["attempts_json"] = json.dumps(job["attempts"])
+ return False
+ job.update({"model": model, "provider": str(cand.get("provider") or ""), "usd": usd})
+ if task_id:
+ job.update({"provider_task_id": task_id, "status": "running",
+ "next_poll_at": int((time.time() + 20) * 1000)})
+ await _media_job_save(job)
+ return True
+ if payload is None:
+ return False
+ if await _media_land_payload(job, payload):
+ return True
+ _media_billed(job, model, usd, str(job.get("error") or ""))
+ return False
+
+
+async def _media_generate(cap: str, params: dict, hid: str, sid: str, org: str,
+ entry_id: str) -> dict:
+ """Resolve the chain, start the work, and record a job. Nothing is written when nothing ran:
+ a refusal leaves no vertex behind, because nothing happened."""
+ providers = await _media_providers()
+ cand, task_id, payload, doc, tally = await _media_chain(cap, params, providers)
+ attempts = tally["attempts"]
+ now = int(time.time() * 1000)
+ job = {"id": "mjob_" + uuid.uuid4().hex[:16], "org": org, "harness": hid, "session": sid,
+ "entry": entry_id, "capability": cap,
+ # WITHOUT the input image. A vertex property has a size cap and a base64 frame is
+ # megabytes; the media id is kept instead and the bytes are re-read from our own store
+ # if the chain has to advance (see _media_job_resubmit).
+ "params_json": json.dumps(_media_params_stored(params)),
+ "params": params, "status": "running",
+ "model": str(cand.get("model") or ""), "provider": str(cand.get("provider") or ""),
+ "provider_task_id": task_id, "attempts_json": json.dumps(attempts),
+ "attempts": attempts, "next_poll_at": now + 20_000, "poll_backoff_s": 20,
+ "media_id": "", "bytes": 0, "width": 0, "height": 0, "seconds": 0.0,
+ "quota": float(cand.get("quota") or 0), "usd": media_plane.estimated_usd(cand) or 0.0,
+ # WHAT THE SUBMIT WALK ALREADY SPENT, carried onto the job so the poll walk reads the
+ # same budget rather than opening a second one. Without this, a request that billed
+ # getting here bills again on its first failed poll — the two walks are one request.
+ "advances": sum(1 for a in attempts if a.get("billed")),
+ "billed_usd": tally["billed_usd"],
+ "element_id": "", "error": "", "created_at": now, "updated_at": now}
+ inline_usd = media_plane.usage_usd(doc)
+ if inline_usd is not None:
+ job["usd"] = inline_usd # a cost the provider reported itself; measured, so used
+ # SAVED BEFORE THE FILE IS FETCHED, always. A synchronous shape has already billed by the time
+ # we get here, so a fetch that then fails must leave a job that says so rather than no record
+ # at all — an untraceable charge is worse than a visible failure.
+ await _media_job_save(job)
+ if task_id:
+ return job
+ # A synchronous shape rendered inside the submit. Reporting it as "running" would be a lie the
+ # very next call exposes, so the job carries the truth and the agent's loop is unchanged.
+ if not await _media_land_payload(job, payload):
+ await _media_job_billable_failure(job, str(job.get("error") or ""))
+ return job
+
+
+# ── the sweeper ───────────────────────────────────────────────────────────────────────────────
+_MEDIA_SWEEP_EVERY_S = int(os.environ.get("HR_MEDIA_SWEEP_S", "10"))
+
+
+async def _media_sweep() -> int:
+ """Advance every job nobody is watching.
+
+ Not an optimisation. Without it a job whose turn ended and whose tab is closed never completes,
+ and its provider URL expires — happyhorse's in a day, every kling and seedream URL signed. This
+ is what makes "generation outlives the session being watched" true rather than aspirational.
+ """
+ rows = await BACKING.graph.find(_MEDIA_JOB_LABEL, {"status": "running"})
+ now_ms = time.time() * 1000
+ moved = 0
+ for r in rows:
+ job = _media_job_out(r)
+ if not job or float(job.get("next_poll_at") or 0) > now_ms:
+ continue
+ try:
+ before = job.get("status")
+ job = await _media_job_advance(job)
+ moved += int(job.get("status") != before)
+ except Exception as e: # noqa: BLE001 — one bad job must not stop the sweep
+ print(f"[media] sweep: {job.get('id')} {type(e).__name__}", flush=True)
+ for sid in list(_media_project_due)[:20]:
+ await _media_project(sid)
+ return moved
+
+
[email protected]_event("startup")
+async def _start_media_sweep() -> None:
+ async def loop() -> None:
+ while True:
+ try:
+ run_it = True
+ if control_store.enabled():
+ try:
+ run_it = await control_store.try_lock("media-sweep",
+ _MEDIA_SWEEP_EVERY_S - 2)
+ except Exception: # noqa: BLE001 — store down: sweep anyway. A duplicate GET
+ run_it = True # poll is idempotent and free, and a stalled job is not.
+ if run_it:
+ await _media_sweep()
+ except Exception: # noqa: BLE001
+ pass
+ await asyncio.sleep(_MEDIA_SWEEP_EVERY_S)
+ asyncio.create_task(loop())
+
+
+# ── the agent's tools ─────────────────────────────────────────────────────────────────────────
+# Thirteen. Not eighteen: there is no concatenate_audio, no select_background_music and no
+# mix_audio_with_bgm, because set_timeline + export_timeline express all three — and a matcher that
+# cannot report "no match" is how a silent-substitution bug ships.
+_MEDIA_MCP_TOOLS = [
+ {"name": "list_capabilities",
+ "description": ("What can actually be made right now, which model each capability resolves "
+ "to, and roughly what a unit costs. CALL THIS FIRST, before planning "
+ "anything expensive — it is free and it is the only way to know that a model "
+ "is broken today. A capability with no model returns a plain refusal: "
+ "believe it."),
+ "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
+
+ {"name": "generate_video",
+ "description": ("Start one shot rendering. Returns a job id immediately — a clip takes about "
+ "four minutes. Submit every shot you have planned, place them all straight "
+ "away, then call check_jobs once. Never submit one clip and wait for it."),
+ "inputSchema": {"type": "object", "required": ["prompt", "seconds"],
+ "additionalProperties": False,
+ "properties": {
+ "prompt": {"type": "string", "maxLength": 2000,
+ "description": "What the shot shows. One shot, not a script."},
+ "seconds": {"type": "number", "minimum": 1, "maximum": 15,
+ "description": ("REQUIRED. Every model bills by length and "
+ "one of them defaults to 15 s.")},
+ "from_image": {"type": "string",
+ "description": ("A media id (med_…) or job id (mjob_…) "
+ "from an earlier image. Animates that "
+ "image instead of generating from text. "
+ "Only some models can do this and the "
+ "tool says which one it used.")},
+ "aspect": {"enum": ["16:9", "9:16", "1:1"]},
+ "allow_watermark": {"type": "boolean", "default": False},
+ "shot": {"type": "string", "maxLength": 60,
+ "description": ("A label, e.g. 'Shot 3'. Groups the clip with "
+ "its caption on the canvas.")}}}},
+
+ {"name": "generate_image",
+ "description": ("Make one still. Seconds and cents, where a clip is minutes and dollars — "
+ "generate every frame first and show them before you render anything. Use "
+ "from_image to keep a character the same across shots."),
+ "inputSchema": {"type": "object", "required": ["prompt"], "additionalProperties": False,
+ "properties": {
+ "prompt": {"type": "string", "maxLength": 2000},
+ "size": {"type": "string", "pattern": "^[0-9]{3,5}x[0-9]{3,5}$",
+ "default": "1024x1024"},
+ "from_image": {"type": "string",
+ "description": ("A media id or job id to edit or restyle. "
+ "Use this to keep a character consistent "
+ "across shots rather than re-generating "
+ "them.")},
+ "shot": {"type": "string", "maxLength": 60}}}},
+
+ {"name": "generate_speech",
+ "description": ("Speak a line. The models available here ANSWER a prompt rather than reading "
+ "it, so check_jobs returns what was actually said."),
+ "inputSchema": {"type": "object", "required": ["text"], "additionalProperties": False,
+ "properties": {"text": {"type": "string", "maxLength": 4000},
+ "voice": {"type": "string", "default": "alloy"},
+ "shot": {"type": "string", "maxLength": 60}}}},
+
+ {"name": "generate_music",
+ "description": ("Scored music for a film. Says plainly what is missing if it cannot be made "
+ "— a speech model is not a substitute and will not be used."),
+ "inputSchema": {"type": "object", "required": ["prompt"], "additionalProperties": False,
+ "properties": {"prompt": {"type": "string", "maxLength": 2000},
+ "seconds": {"type": "number", "minimum": 1, "maximum": 300}}}},
+
+ {"name": "check_jobs",
+ "description": ("Status for jobs you started. `unknown` is NOT a failure — it is a poll that "
+ "came back empty, and it means ask again. A job that succeeded reports the "
+ "model that actually ran and what it cost."),
+ "inputSchema": {"type": "object", "required": ["job_ids"], "additionalProperties": False,
+ "properties": {"job_ids": {"type": "array", "maxItems": 50,
+ "items": {"type": "string"}}}}},
+
+ {"name": "describe_canvas",
+ "description": ("What is on the canvas: every element, where it is, whether it is ready, and "
+ "where the next thing would land. This is your ONLY read of it — never open "
+ "or edit the scene file."),
+ "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
+
+ {"name": "place",
+ "description": ("Put media, a running job or a caption on the canvas. Place a job the moment "
+ "you submit it: a placeholder appears now and becomes the clip when the "
+ "render lands, so the person watches the film arrive."),
+ "inputSchema": {"type": "object", "required": ["items"], "additionalProperties": False,
+ "properties": {
+ "items": {"type": "array", "minItems": 1, "maxItems": 20,
+ "items": {"type": "object", "additionalProperties": False,
+ "properties": {
+ "job_id": {"type": "string"},
+ "media_id": {"type": "string"},
+ "text": {"type": "string", "maxLength": 280},
+ "x": {"type": "number"}, "y": {"type": "number"},
+ "w": {"type": "number"}, "h": {"type": "number"},
+ "caption": {"type": "string", "maxLength": 280},
+ "shot": {"type": "string", "maxLength": 60}}}},
+ "arrange": {"enum": ["auto", "none"], "default": "auto"}}}},
+
+ {"name": "move",
+ "description": "Move or resize elements. Moving one inside a shot moves the shot with it.",
+ "inputSchema": {"type": "object", "required": ["moves"], "additionalProperties": False,
+ "properties": {"moves": {"type": "array", "minItems": 1, "maxItems": 50,
+ "items": {"type": "object",
+ "required": ["element_id"],
+ "additionalProperties": False,
+ "properties": {
+ "element_id": {"type": "string"},
+ "x": {"type": "number"},
+ "y": {"type": "number"},
+ "w": {"type": "number"},
+ "h": {"type": "number"}}}}}}},
+
+ {"name": "arrange",
+ "description": ("Lay the canvas out. Use storyboard after every batch — one row per shot, "
+ "caption beneath — rather than computing coordinates by hand."),
+ "inputSchema": {"type": "object", "additionalProperties": False,
+ "properties": {
+ "layout": {"enum": ["grid", "row", "column", "storyboard"],
+ "default": "grid"},
+ "element_ids": {"type": "array", "items": {"type": "string"}},
+ "columns": {"type": "integer", "minimum": 1, "maximum": 8, "default": 4},
+ "gutter": {"type": "integer", "minimum": 0, "maximum": 200,
+ "default": 24},
+ "origin": {"type": "object", "additionalProperties": False,
+ "properties": {"x": {"type": "number"},
+ "y": {"type": "number"}}}}}},
+
+ {"name": "remove",
+ "description": ("Take elements off the canvas. This never deletes media — the file stays and "
+ "can be placed again, so tidying a canvas is safe."),
+ "inputSchema": {"type": "object", "required": ["element_ids"], "additionalProperties": False,
+ "properties": {"element_ids": {"type": "array", "minItems": 1, "maxItems": 50,
+ "items": {"type": "string"}}}}},
+
+ {"name": "set_timeline",
+ "description": ("The cut: which shots, in what order, at what length. ARRAY ORDER IS THE CUT "
+ "ORDER — it is never inferred from where things sit on the canvas."),
+ "inputSchema": {"type": "object", "required": ["shots"], "additionalProperties": False,
+ "properties": {
+ "shots": {"type": "array", "minItems": 1, "maxItems": 40,
+ "items": {"type": "object", "required": ["element_id"],
+ "additionalProperties": False,
+ "properties": {"element_id": {"type": "string"},
+ "in_s": {"type": "number",
+ "minimum": 0},
+ "out_s": {"type": "number",
+ "minimum": 0}}}},
+ "audio": {"type": "array", "maxItems": 8,
+ "items": {"type": "object", "required": ["element_id"],
+ "additionalProperties": False,
+ "properties": {"element_id": {"type": "string"},
+ "start_s": {"type": "number",
+ "minimum": 0,
+ "default": 0},
+ "gain_db": {"type": "number",
+ "minimum": -40,
+ "maximum": 6,
+ "default": 0}}}},
+ "fps": {"enum": [24, 25, 30], "default": 30},
+ "resolution": {"enum": ["1920x1080", "1080x1920", "1080x1080"],
+ "default": "1920x1080"}}}},
+
+ {"name": "export_timeline",
+ "description": ("Assemble the timeline into one video. Refuses while any shot is still "
+ "rendering. Progress is reported as a real count of shots, never an ETA."),
+ "inputSchema": {"type": "object", "additionalProperties": False,
+ "properties": {"filename": {"type": "string", "maxLength": 120}}}},
+]
+
+# The refusal a tool gives when the credential carries no session. There is nowhere to put media,
+# so saying so beats generating something that lands nowhere.
+_MEDIA_NO_SESSION = ("This agent has no workspace, so there is nowhere to place media. "
+ "Nothing was generated.")
+
+
+def _media_json_text(obj) -> dict:
+ return _tool_text(json.dumps(obj, ensure_ascii=False))
+
+
+async def _media_read_image(sid: str, med: str) -> tuple[str, str]:
+ """(base64, mime) for one image OUT OF OUR OWN STORE. Never out of a provider URL: those
+ expire, and a continuity frame that stops resolving is a different character in shot four."""
+ meta = await _media_meta(sid, med)
+ if not meta:
+ raise media_plane.MediaError(f"There is no media with the id {med} in this session.")
+ data = await _blob_get(_media_blob(sid, med, str(meta.get("ext") or "png")), kb=BLOB_KB)
+ if not data:
+ raise media_plane.MediaError(f"The file behind {med} is no longer readable.")
+ return base64.b64encode(data).decode(), str(meta.get("mime") or "image/png")
+
+
+async def _media_resolve_input_image(sid: str, ref: str) -> tuple[str, str, str]:
+ """(media id, base64, mime) for a media id or job id the agent named as the input to a render.
+
+ The id comes back too: it is what gets written down, so a chain that has to advance can
+ re-read the frame instead of carrying megabytes of base64 on a graph vertex.
+ """
+ med = ref
+ if ref.startswith("mjob_"):
+ job = await _media_job_get(ref)
+ if not job or str(job.get("session") or "") != sid:
+ raise media_plane.MediaError(f"No job with the id {ref} in this session.")
+ if not job.get("media_id"):
+ raise media_plane.MediaError(f"Job {ref} has produced nothing to work from yet.")
+ med = str(job["media_id"])
+ b64, mime = await _media_read_image(sid, med)
+ return med, b64, mime
+
+
+async def _media_tool_call(name: str, args: dict, hid: str, sid: str, org: str,
+ entry_id: str) -> dict:
+ """One tool. Every failure is a TOOL RESULT and never an HTTP error, because an agent can read
+ a sentence and cannot read a 500."""
+ # ---- what can be made ----
+ if name == "list_capabilities":
+ providers = await _media_providers()
+ out = []
+ for cap_name in media_plane.capability_names():
+ cap = media_plane.capability(cap_name)
+ if cap.get("local"):
+ ok = media_plane.have_ffmpeg()
+ out.append({"name": cap_name, "available": ok, "model": None,
+ "limits": {"max_shots": cap.get("max_shots"),
+ "max_total_s": cap.get("max_total_s")},
+ **({} if ok else {"reason": "This deployment cannot assemble video — "
+ "ffmpeg is not installed."})})
+ continue
+ probe = {"seconds": 6} if cap_name.endswith("_video") else {}
+ if cap_name.startswith("image_to"):
+ probe["image"] = "probe"
+ cand, skipped = media_plane.resolve(cap_name, probe, set(providers),
+ _media_quarantine)
+ row = {"name": cap_name, "available": bool(cand),
+ "model": str(cand.get("model")) if cand else None,
+ "limits": media_plane.limits_of(cand) if cand else {}}
+ usd = media_plane.estimated_usd(cand) if cand else None
+ if usd is not None:
+ row["estimated_usd_per_unit"] = usd
+ if not cand:
+ # The first thing the chain skipped, which is the most specific reason there is.
+ # A capability-level refusal string used to win here; it was a second answer to
+ # the same question, kept in step with the candidates by hand.
+ row["reason"] = skipped[0] if skipped else "No connected provider serves it."
+ if skipped:
+ row["skipped"] = [{"reason": s} for s in skipped[:6]]
+ out.append(row)
+ return _media_json_text({"capabilities": out})
+
+ # ---- generation ----
+ if name in ("generate_video", "generate_image", "generate_speech", "generate_music"):
+ if not sid:
+ return _tool_text(_MEDIA_NO_SESSION, True)
+ spent = await _media_spend(sid)
+ if spent >= media_plane.SESSION_BUDGET_USD:
+ return _tool_text(
+ f"This video has already cost ${spent:.2f}, which is the ${media_plane.SESSION_BUDGET_USD:.2f} "
+ f"limit for one session. Nothing was generated. Ask the person whether to carry "
+ f"on — you cannot raise the limit yourself.", True)
+ params: dict = {}
+ note = ""
+ if name == "generate_video":
+ params = {"prompt": str(args.get("prompt") or ""),
+ "seconds": float(args.get("seconds") or 0),
+ "allow_watermark": bool(args.get("allow_watermark"))}
+ cap = "text_to_video"
+ elif name == "generate_image":
+ size = str(args.get("size") or "1024x1024")
+ params = {"prompt": str(args.get("prompt") or ""), "size": size}
+ cap = "text_to_image"
+ elif name == "generate_music":
+ # The same path as every other generation, so the refusal is the chain's own answer
+ # rather than a second sentence kept in step by hand. It exists as a tool at all so
+ # that "no music model" is a stated fact and not a missing tool a model works around
+ # by reaching for speech.
+ params = {"prompt": str(args.get("prompt") or "")}
+ if args.get("seconds"):
+ params["seconds"] = float(args["seconds"])
+ cap = "text_to_music"
+ else:
+ text = str(args.get("text") or "")
+ params = {"prompt": ("Read this aloud exactly as written, and say nothing else: "
+ + text),
+ "voice": str(args.get("voice") or "alloy"), "text": text}
+ cap = "text_to_speech"
+ if args.get("from_image"):
+ try:
+ med, b64, mime = await _media_resolve_input_image(sid, str(args["from_image"]))
+ except media_plane.MediaError as e:
+ return _tool_text(str(e), True)
+ params.update({"image": b64, "image_mime": mime, "from_media": med})
+ cap = "image_to_video" if name == "generate_video" else "image_to_image"
+ try:
+ job = await _media_generate(cap, params, hid, sid, org, entry_id)
+ except _MediaNoModel as e:
+ return _tool_text(e.text, True)
+ except media_plane.MediaError as e:
+ return _tool_text(str(e), True)
+ cand = _media_candidate(cap, str(job["model"])) or {}
+ out = {"job_id": job["id"], "capability": cap, "model": job["model"],
+ "status": job["status"]}
+ if name == "generate_video":
+ out["seconds"] = params["seconds"]
+ allowed = cand.get("durations_s")
+ if allowed:
+ note = (f"This model renders {' and '.join(str(a) for a in allowed)} s only; "
+ f"{params['seconds']:g} s was requested and accepted.")
+ elif cand.get("duration_ignored"):
+ # Measured: it takes the duration and returns whatever length it likes. Anything
+ # that needs an exact length has to read the one that actually landed.
+ obs = cand.get("duration_observed_s")
+ note = ("This model does not honour a requested duration"
+ + (f" — the clip measured came back {float(obs):g} s" if obs else "")
+ + ". check_jobs reports the real length once it lands; cut from that "
+ "rather than from the seconds you asked for.")
+ if name == "generate_image":
+ out["size"] = params["size"]
+ if job.get("usd"):
+ out["estimated_usd"] = round(float(job["usd"]), 4)
+ if job.get("attempts"):
+ out["attempts"] = job["attempts"]
+ if job.get("media_id"):
+ out["media_id"] = job["media_id"]
+ if name == "generate_speech":
+ out["warning"] = ("This model answers prompts rather than reading them. check_jobs "
+ "returns spoken_text — compare it with what you asked for before "
+ "you use the audio.")
+ if job.get("spoken_text"):
+ out["spoken_text"] = job["spoken_text"]
+ out["verbatim"] = media_plane.levenshtein_ratio(
+ params.get("text") or "", str(job["spoken_text"])) >= 0.9
+ if note:
+ out["note"] = note
+ return _media_json_text(out)
+
+ if name == "check_jobs":
+ ids = [str(j) for j in (args.get("job_ids") or [])][:50]
+ rows = []
+ for jid in ids:
+ job = await _media_job_get(jid)
+ if not job or str(job.get("session") or "") != sid:
+ # NEVER omitted: a missing row reads as "still running".
+ rows.append({"job_id": jid, "status": "failed",
+ "error": "No job with that id in this session."})
+ continue
+ try:
+ job = await _media_job_advance(job)
+ except Exception as e: # noqa: BLE001
+ print(f"[media] advance {jid}: {type(e).__name__}", flush=True)
+ row = {"job_id": jid, "status": job.get("status"),
+ "capability": job.get("capability"), "model": job.get("model")}
+ if job.get("status") == "running" and job.get("last_poll") == "unknown":
+ # The known background-response race. Said plainly, because a model that reads an
+ # empty record as failure throws away a render that is about to land.
+ row["status"] = "unknown"
+ row["note"] = ("The provider returned an empty record. This is transient — ask "
+ "again.")
+ if job.get("status") == "succeeded":
+ row.update({"media_id": job.get("media_id"),
+ "kind": _MEDIA_KIND.get(str(job.get("capability")), "image"),
+ "seconds": job.get("seconds") or None,
+ "width": job.get("width") or None, "height": job.get("height") or None,
+ "bytes": job.get("bytes") or None})
+ if job.get("usd"):
+ row["usd"] = round(float(job["usd"]), 4)
+ if job.get("spoken_text"):
+ row["spoken_text"] = job["spoken_text"]
+ row["verbatim"] = media_plane.levenshtein_ratio(
+ (job.get("params") or {}).get("text") or "",
+ str(job["spoken_text"])) >= 0.9
+ elif job.get("status") == "failed":
+ row["error"] = job.get("error") or "the render failed"
+ if job.get("attempts"):
+ row["attempts"] = job["attempts"]
+ elif job.get("progress"):
+ row["progress"] = job["progress"]
+ if job.get("element_id"):
+ row["element_id"] = job["element_id"]
+ rows.append(row)
+ # `unknown` never appears as a terminal state here; it is a poll that came back empty and
+ # the tool description says to ask again.
+ return _media_json_text({"jobs": rows})
+
+ # ---- the canvas ----
+ if not sid:
+ return _tool_text(_MEDIA_NO_SESSION, True)
+
+ if name == "describe_canvas":
+ scene = await _media_scene_read(sid)
+ els = [e for e in scene.get("elements") or [] if not e.get("isDeleted")]
+ tl = scene.get("timeline") or {}
+ shots = {}
+ for e in els:
+ label = ((e.get("customData") or {}).get("shot") or "")
+ if label:
+ shots.setdefault(label, []).append(e.get("id"))
+ x, y = media_plane.next_free(els)
+ return _media_json_text({
+ "scene_rev": int(float((scene.get("meta") or {}).get("rev") or 0)),
+ "bounds": media_plane.scene_bounds(els),
+ "elements": [media_plane.element_summary(e) for e in els],
+ "shots": [{"name": k, "element_ids": v} for k, v in shots.items()],
+ "timeline": {"shots": len(tl.get("shots") or []),
+ "total_seconds": media_plane.timeline_total(scene),
+ "fps": tl.get("fps"), "resolution": tl.get("resolution")},
+ "free_space": {"x": x, "y": y}})
+
+ if name == "place":
+ items = args.get("items") or []
+ for i, it in enumerate(items, 1):
+ named = [k for k in ("job_id", "media_id", "text") if it.get(k)]
+ if len(named) != 1:
+ return _tool_text(f"An item must name a job, a media id or text — item {i} named "
+ f"{'both' if len(named) > 1 else 'neither'}.", True)
+ placed: list[dict] = []
+ # "auto" packs anything you gave no coordinates for into the next free row. "none" means
+ # exactly that: an item with no coordinates lands at the canvas origin and moving it is
+ # yours to do. A parameter whose two values behave identically is a lie in a schema.
+ auto = str(args.get("arrange") or "auto") == "auto"
+
+ prepared = []
+ for it in items:
+ if it.get("job_id"):
+ job = await _media_job_get(str(it["job_id"]))
+ if not job or str(job.get("session") or "") != sid:
+ return _tool_text(f"No job with the id {it['job_id']} in this session.", True)
+ prepared.append((it, job, None))
+ elif it.get("media_id"):
+ meta = await _media_meta(sid, str(it["media_id"]))
+ if not meta:
+ return _tool_text(f"There is no media with the id {it['media_id']} in this "
+ f"session.", True)
+ prepared.append((it, None, meta))
+ else:
+ prepared.append((it, None, None))
+
+ def mutate(scene: dict):
+ els = scene.get("elements") or []
+ for it, job, meta in prepared:
+ x, y = it.get("x"), it.get("y")
+ if x is None or y is None:
+ x, y = (media_plane.next_free([e for e in els if not e.get("isDeleted")])
+ if auto else (0.0, 0.0))
+ w = float(it.get("w") or media_plane.TILE_W)
+ h = float(it.get("h") or media_plane.TILE_H)
+ shot = str(it.get("shot") or "")
+ if it.get("text"):
+ el = media_plane.text_element(str(it["text"]), x=x, y=y, w=w)
+ else:
+ kind = (_MEDIA_KIND.get(str((job or {}).get("capability")), "image")
+ if job else str((meta or {}).get("kind") or "image"))
+ med = str((job or {}).get("media_id") or (meta or {}).get("media_id") or "")
+ ready = bool(med)
+ el = media_plane.media_element(
+ kind, x=x, y=y, w=w, h=h, media_id=med,
+ job_id=str((job or {}).get("id") or ""),
+ status="ready" if ready else str((job or {}).get("status") or "running"),
+ model=str((job or {}).get("model") or (meta or {}).get("model") or ""),
+ cap=str((job or {}).get("capability") or (meta or {}).get("capability") or ""),
+ seconds=float((job or {}).get("seconds") or (meta or {}).get("seconds") or 0),
+ width=int((job or {}).get("width") or (meta or {}).get("width") or 0),
+ height=int((job or {}).get("height") or (meta or {}).get("height") or 0),
+ prompt=str(((job or {}).get("params") or {}).get("prompt")
+ or (meta or {}).get("prompt") or ""),
+ label=shot,
+ media_url=_media_url(hid, entry_id, sid, med) if med else "")
+ if kind == "image" and med:
+ scene.setdefault("files", {})[med] = media_plane.file_entry(
+ med, str((meta or {}).get("mime") or "image/png"),
+ _media_url(hid, entry_id, sid, med))
+ if job:
+ job["element_id"] = el["id"]
+ if shot:
+ el.setdefault("customData", {})["shot"] = shot
+ els.append(el)
+ placed.append({"element_id": el["id"], "kind": media_plane.media_of(el).get("kind")
+ or "text", "status": media_plane.media_of(el).get("status"),
+ "x": el["x"], "y": el["y"], "w": el["width"], "h": el["height"],
+ **({"job_id": it["job_id"]} if it.get("job_id") else {}),
+ **({"media_id": it["media_id"]} if it.get("media_id") else {})})
+ if it.get("caption"):
+ cap_el = media_plane.text_element(str(it["caption"]), x=el["x"],
+ y=el["y"] + el["height"] + 8, w=el["width"])
+ if shot:
+ cap_el.setdefault("customData", {})["shot"] = shot
+ els.append(cap_el)
+ placed.append({"element_id": cap_el["id"], "kind": "text",
+ "x": cap_el["x"], "y": cap_el["y"], "w": cap_el["width"],
+ "h": cap_el["height"]})
+ scene["elements"] = els
+ return None
+
+ rev, _ = await _media_scene_touch(sid, mutate)
+ for _it, job, _meta in prepared:
+ if job and job.get("element_id"):
+ await _media_job_save(job)
+ return _media_json_text({"scene_rev": rev, "placed": placed})
+
+ if name == "move":
+ moves = {str(m.get("element_id")): m for m in (args.get("moves") or [])}
+ moved: list[str] = []
+ missing: list[str] = []
+
+ def mutate(scene: dict):
+ by_id = {e.get("id"): e for e in scene.get("elements") or []}
+ for eid, m in moves.items():
+ el = by_id.get(eid)
+ if not el:
+ missing.append(eid)
+ continue
+ dx = float(m["x"]) - float(el.get("x") or 0) if m.get("x") is not None else 0.0
+ dy = float(m["y"]) - float(el.get("y") or 0) if m.get("y") is not None else 0.0
+ for key, src in (("x", "x"), ("y", "y"), ("width", "w"), ("height", "h")):
+ if m.get(src) is not None:
+ el[key] = float(m[src])
+ moved.append(eid)
+ shot = (el.get("customData") or {}).get("shot")
+ if shot and (dx or dy):
+ # Moving one element of a shot moves the shot: a caption left behind is a
+ # caption under the wrong clip.
+ for other in scene.get("elements") or []:
+ if other is el or (other.get("customData") or {}).get("shot") != shot:
+ continue
+ other["x"] = float(other.get("x") or 0) + dx
+ other["y"] = float(other.get("y") or 0) + dy
+ return None
+
+ rev, _ = await _media_scene_touch(sid, mutate)
+ return _media_json_text({"scene_rev": rev, "moved": moved, "not_found": missing})
+
+ if name == "arrange":
+ layout = str(args.get("layout") or "grid")
+ want = {str(e) for e in (args.get("element_ids") or [])}
+ columns = int(args.get("columns") or 4)
+ gutter = int(args.get("gutter") if args.get("gutter") is not None else media_plane.GUTTER)
+ origin = args.get("origin") or {}
+ ox = float(origin.get("x", 40)); oy = float(origin.get("y", 40))
+ positions: list[dict] = []
+
+ def mutate(scene: dict):
+ positions.clear() # mutate may be re-run; positions is the caller's answer
+ els = [e for e in scene.get("elements") or [] if not e.get("isDeleted")]
+ # Named ids, or every media element when none were named. A named set that matches
+ # nothing arranges NOTHING — falling back to "everything" would rearrange a board the
+ # caller was trying to leave alone.
+ chosen = ([e for e in els if e.get("id") in want] if want
+ else [e for e in els if media_plane.is_media(e)])
+ if layout == "storyboard":
+ items = media_plane.storyboard_items(els, chosen)
+ else:
+ items = [{"id": e.get("id"),
+ "w": float(e.get("width") or media_plane.TILE_W),
+ "h": float(e.get("height") or media_plane.TILE_H)} for e in chosen]
+ positions.extend(media_plane.layout_positions(items, layout, columns=columns,
+ gutter=gutter, origin=(ox, oy)))
+ by_id = {e.get("id"): e for e in els}
+ for p in positions:
+ el = by_id.get(p["element_id"])
+ if el:
+ el["x"], el["y"] = float(p["x"]), float(p["y"])
+ return None
+
+ rev, _ = await _media_scene_touch(sid, mutate)
+ return _media_json_text({"scene_rev": rev, "positions": positions})
+
+ if name == "remove":
+ ids = {str(e) for e in (args.get("element_ids") or [])}
+ removed: list[str] = []
+ missing: list[str] = []
+
+ def mutate(scene: dict):
+ keep = []
+ found = set()
+ for el in scene.get("elements") or []:
+ if el.get("id") in ids:
+ found.add(el.get("id"))
+ continue
+ keep.append(el)
+ scene["elements"] = keep
+ removed.extend(sorted(found))
+ missing.extend(sorted(ids - found))
+ tl = scene.get("timeline") or {}
+ tl["shots"] = [s for s in tl.get("shots") or [] if s.get("elementId") not in ids]
+ tl["audio"] = [a for a in tl.get("audio") or [] if a.get("elementId") not in ids]
+ return None
+
+ rev, _ = await _media_scene_touch(sid, mutate)
+ # Said in the return, because an agent that believes remove is destructive will not tidy.
+ return _media_json_text({"scene_rev": rev, "removed": removed, "not_found": missing,
+ "media_kept": True})
+
+ if name == "set_timeline":
+ shots_in = args.get("shots") or []
+ audio_in = args.get("audio") or []
+ cap = media_plane.capability("export")
+ max_shots = int(cap.get("max_shots") or 40)
+ if len(shots_in) > max_shots:
+ return _tool_text(f"A timeline holds at most {max_shots} shots; this one has "
+ f"{len(shots_in)}.", True)
+ warnings: list[str] = []
+ result: dict = {}
+
+ def mutate(scene: dict):
+ by_id = {e.get("id"): e for e in scene.get("elements") or []}
+ shots = []
+ for i, s in enumerate(shots_in, 1):
+ eid = str(s.get("element_id") or "")
+ el = by_id.get(eid)
+ if not el:
+ warnings.append(f"Shot {i} names {eid}, which is not on the canvas.")
+ continue
+ m = media_plane.media_of(el)
+ if m.get("status") != "ready":
+ warnings.append(f"Shot {i} ({eid}) is still rendering — export will refuse "
+ f"until it lands.")
+ w, h = int(m.get("width") or 0), int(m.get("height") or 0)
+ res = str(args.get("resolution") or "1920x1080")
+ rw, rh = media_plane.parse_size(res)
+ if w and h and rw and rh and abs(w / h - rw / rh) > 0.02:
+ warnings.append(f"Shot {i} is {w}x{h} and will be letterboxed into {res}.")
+ shots.append({"elementId": eid, "inS": float(s.get("in_s") or 0.0),
+ "outS": float(s.get("out_s") or m.get("seconds") or 0.0)})
+ audio = [{"elementId": str(a.get("element_id") or ""),
+ "startS": float(a.get("start_s") or 0.0),
+ "gainDb": float(a.get("gain_db") or 0.0)} for a in audio_in]
+ scene["timeline"] = {"v": 1, "fps": int(args.get("fps") or 30),
+ "resolution": str(args.get("resolution") or "1920x1080"),
+ # ARRAY ORDER IS THE CUT ORDER. Never derived from canvas
+ # position: dragging a card would silently re-cut the film.
+ "shots": shots, "audio": audio,
+ "updatedAt": int(time.time() * 1000)}
+ result["total"] = media_plane.timeline_total(scene)
+ result["ready"] = bool(shots) and all(
+ media_plane.media_of(by_id.get(s["elementId"], {})).get("status") == "ready"
+ for s in shots)
+ result["n"] = len(shots)
+ return None
+
+ rev, _ = await _media_scene_touch(sid, mutate)
+ out = {"scene_rev": rev,
+ "timeline": {"shots": result.get("n", 0), "fps": int(args.get("fps") or 30),
+ "resolution": str(args.get("resolution") or "1920x1080")},
+ "total_seconds": result.get("total", 0.0), "ready": bool(result.get("ready"))}
+ if warnings:
+ out["warnings"] = warnings
+ return _media_json_text(out)
+
+ if name == "export_timeline":
+ if not media_plane.have_ffmpeg():
+ return _tool_text("This deployment cannot assemble video — ffmpeg is not installed. "
+ "The clips are all still here to download individually.", True)
+ try:
+ job = await _media_export_start(hid, sid, org, entry_id,
+ str(args.get("filename") or ""))
+ except media_plane.MediaError as e:
+ return _tool_text(str(e), True)
+ return _media_json_text({"job_id": job["id"], "capability": "export",
+ "shots": int(job.get("shots") or 0),
+ "total_seconds": float(job.get("planned_seconds") or 0.0),
+ "status": job["status"]})
+
+ return _tool_text(f"No tool named {name!r} on this server.", True)
+
+
+# ── export ────────────────────────────────────────────────────────────────────────────────────
+async def _media_export_start(hid: str, sid: str, org: str, entry_id: str,
+ filename: str) -> dict:
+ """Check the cut is assemblable, then run ffmpeg off the event loop as an ordinary job."""
+ scene = await _media_scene_read(sid)
+ tl = scene.get("timeline") or {}
+ shots = tl.get("shots") or []
+ if not shots:
+ raise media_plane.ExportRefused("There is nothing in the timeline to export. Use "
+ "set_timeline first.")
+ cap = media_plane.capability("export")
+ if len(shots) > int(cap.get("max_shots") or 40):
+ raise media_plane.ExportRefused(f"A film here is at most {cap.get('max_shots')} shots.")
+ running = [j for j in await _media_jobs_of(sid)
+ if j.get("capability") == "export" and j.get("status") == "running"]
+ if running:
+ raise media_plane.ExportRefused("An export of this video is already running.")
+ by_id = {e.get("id"): e for e in scene.get("elements") or []}
+ plan: list[dict] = []
+ for i, s in enumerate(shots, 1):
+ m = media_plane.media_of(by_id.get(s.get("elementId")) or {})
+ if m.get("status") != "ready" or not m.get("mediaId"):
+ raise media_plane.ExportRefused(
+ f"Shot {i} is still rendering. Every shot has to have landed before the film can "
+ f"be cut.")
+ plan.append({"media_id": str(m["mediaId"]), "in_s": float(s.get("inS") or 0.0),
+ "out_s": float(s.get("outS") or m.get("seconds") or 0.0)})
+ total = media_plane.timeline_total(scene)
+ if total > float(cap.get("max_total_s") or 600):
+ raise media_plane.ExportRefused(
+ f"That film is {total:.0f}s and the limit here is {cap.get('max_total_s')}s.")
+ audio_plan = [{"media_id": str(media_plane.media_of(by_id.get(a.get("elementId")) or {})
+ .get("mediaId") or ""),
+ "start_s": float(a.get("startS") or 0.0),
+ "gain_db": float(a.get("gainDb") or 0.0)}
+ for a in tl.get("audio") or []]
+ audio_plan = [a for a in audio_plan if a["media_id"]]
+
+ now = int(time.time() * 1000)
+ job = {"id": "mjob_" + uuid.uuid4().hex[:16], "org": org, "harness": hid, "session": sid,
+ "entry": entry_id, "capability": "export", "params_json": json.dumps({}), "params": {},
+ "status": "running", "model": "", "provider": "local", "provider_task_id": "",
+ "attempts_json": "[]", "attempts": [], "next_poll_at": 0, "poll_backoff_s": 0,
+ "media_id": "", "bytes": 0, "width": 0, "height": 0, "seconds": 0.0, "quota": 0.0,
+ "usd": 0.0, "element_id": "", "error": "", "created_at": now, "updated_at": now,
+ "shots": len(plan), "planned_seconds": total,
+ "progress": f"0/{len(plan)} shots", "filename": filename or "film.mp4"}
+ await _media_job_save(job)
+ asyncio.create_task(_media_export_run(job, plan, audio_plan, int(tl.get("fps") or 30),
+ str(tl.get("resolution") or "1920x1080")))
+ return job
+
+
+async def _media_export_run(job: dict, plan: list[dict], audio_plan: list[dict], fps: int,
+ resolution: str) -> None:
+ sid = str(job["session"])
+ tmp = tempfile.mkdtemp(prefix="hr-media-")
+ try:
+ shots = []
+ for i, s in enumerate(plan):
+ meta = await _media_meta(sid, s["media_id"]) or {}
+ data = await _blob_get(_media_blob(sid, s["media_id"], str(meta.get("ext") or "mp4")),
+ kb=BLOB_KB)
+ if not data:
+ raise media_plane.ExportRefused(f"Shot {i + 1} is no longer readable.")
+ path = os.path.join(tmp, f"shot{i}.{meta.get('ext') or 'mp4'}")
+ pathlib.Path(path).write_bytes(data)
+ shots.append({"path": path, "in_s": s["in_s"], "out_s": s["out_s"]})
+ job["progress"] = f"{i + 1}/{len(plan)} shots"
+ await _media_job_save(job)
+ tracks = []
+ for j, a in enumerate(audio_plan):
+ meta = await _media_meta(sid, a["media_id"]) or {}
+ data = await _blob_get(_media_blob(sid, a["media_id"], str(meta.get("ext") or "wav")),
+ kb=BLOB_KB)
+ if not data:
+ continue
+ path = os.path.join(tmp, f"track{j}.{meta.get('ext') or 'wav'}")
+ pathlib.Path(path).write_bytes(data)
+ tracks.append({"path": path, "start_s": a["start_s"], "gain_db": a["gain_db"]})
+ out_path = os.path.join(tmp, "film.mp4")
+ info = await media_plane.to_thread(media_plane.assemble, shots, tracks, fps=fps,
+ resolution=resolution, out_path=out_path)
+ data = pathlib.Path(out_path).read_bytes()
+ await _media_job_land(job, data)
+ print(f"[media] {sid}: exported {len(shots)} shots, {info['seconds']}s", flush=True)
+ except Exception as e: # noqa: BLE001
+ job.update({"status": "failed", "error": str(e)})
+ await _media_job_save(job)
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+
+
+# ── the MCP endpoint ──────────────────────────────────────────────────────────────────────────
[email protected]("/v1/mcp/media")
+async def media_mcp(request: Request):
+ """The MCP endpoint the agent's CLI talks to. The database server's twin: streamable HTTP,
+ stateless, `initialize` echoes the client's protocol version, a notification is a 202.
+
+ THE SESSION COMES FROM THE CREDENTIAL. No tool takes one as an argument and every schema is
+ `additionalProperties: false`, so an agent cannot address another session's canvas — it cannot
+ mint another session's token.
+ """
+ claims = _verify_hosted_cred(_broker_token(request))
+ if not claims:
+ raise HTTPException(401, "invalid or expired turn credential")
+ hid, sid, key = claims
+ try:
+ req = json.loads(await request.body() or b"{}")
+ except Exception: # noqa: BLE001
+ raise HTTPException(400, "malformed JSON-RPC request") from None
+ method, rid, params = req.get("method") or "", req.get("id"), req.get("params") or {}
+
+ if method == "initialize":
+ return _jsonrpc_result(rid, {
+ "protocolVersion": str(params.get("protocolVersion") or "2024-11-05"),
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "media", "version": "1"}})
+ if rid is None:
+ return Response(status_code=202)
+ if method == "tools/list":
+ return _jsonrpc_result(rid, {"tools": _MEDIA_MCP_TOOLS})
+ if method != "tools/call":
+ return JSONResponse({"jsonrpc": "2.0", "id": rid,
+ "error": {"code": -32601, "message": f"method not found: {method}"}})
+
+ v = await _harness_vertex(hid)
+ if v and str(v.get("deleted")) in ("1", "true", "True"):
+ v = None # a token outlives the agent it was minted for; its tools must not
+ org = str((v or {}).get("org") or "")
+ try:
+ entry, _rec = await _hosted_resolve(_MEDIA_SERVER, hid, org, _mcp_list(v),
+ key=key, check_enabled=True)
+ except HTTPException:
+ return _jsonrpc_result(rid, _tool_text(
+ "This agent cannot make media — no media tools are connected to it. Ask the person to "
+ "add them, then try again — you cannot connect them yourself.", True))
+ try:
+ out = await _media_tool_call(str(params.get("name") or ""), params.get("arguments") or {},
+ hid, sid, org, str(entry.get("id") or "mcp.media"))
+ except media_plane.MediaError as e:
+ return _jsonrpc_result(rid, _tool_text(str(e), True))
+ except HTTPException as e:
+ return _jsonrpc_result(rid, _tool_text(_uhp_message(e), True))
+ return _jsonrpc_result(rid, out)
+
+
+# ── the app's data plane ──────────────────────────────────────────────────────────────────────
+# A browser is not an MCP client and must never hold a turn credential, so the app reaches the same
+# store through routes that carry the harness (which binds the entry) and the session (which owns
+# the document) explicitly. Every one: member of the org → the harness → the session → the entry.
+
+async def _media_server_out() -> dict:
+ """What the media server says about itself: what can be made right now, which model each
+ capability resolves to, and whether this deployment can assemble a film.
+
+ Derived at read time, never stored. A model breaks or a provider is connected and the answer
+ changes with no form re-saved — the same rule the integration model list already follows.
+ """
+ providers = await _media_providers()
+ caps = []
+ for cap_name in media_plane.capability_names():
+ cap = media_plane.capability(cap_name)
+ if cap.get("local"):
+ caps.append({"name": cap_name, "available": media_plane.have_ffmpeg(), "model": None})
+ continue
+ probe = {"seconds": 6} if cap_name.endswith("_video") else {}
+ if cap_name.startswith("image_to"):
+ probe["image"] = "probe"
+ cand, _sk = media_plane.resolve(cap_name, probe, set(providers), _media_quarantine)
+ row = {"name": cap_name, "available": bool(cand),
+ "model": str(cand.get("model")) if cand else None}
+ usd = media_plane.estimated_usd(cand) if cand else None
+ if usd is not None:
+ row["estimatedUsdPerUnit"] = usd
+ caps.append(row)
+ return {"capabilities": caps, "export": {"available": media_plane.have_ffmpeg()}}
+
+
+async def _media_route(hid: str, sid: str, eid: str, request: Request) -> tuple[str, dict, dict]:
+ """(org, entry, session vertex) — the FOUR binds every app route to this server shares.
+
+ Member of the org → the harness → the entry on that harness → AND THE SESSION ON THAT
+ HARNESS. The fourth was missing and each of the first three looks like it covers it: the entry
+ is bound to the harness, the session is bound to the org, so a second agent in the same org
+ presenting its OWN media entry and this session's id was served this session's jobs, this
+ session's canvas and the bytes of its renders. Harness ids and session ids are both public.
+
+ The session vertex has said which harness it belongs to since it was created (`harness_id`,
+ stamped by the session-create path, and filled in by _resp_resolve_session's continue branch for
+ a session that reached a harness without one); it was written and never read. A session that
+ names no harness cannot be proved to belong to this one, so it is refused rather than assumed —
+ the routes are always addressed to a harness, so a session with no harness has no business here.
+
+ Refusing is right and it is also a dead end: the person is holding a link to something the list
+ still offers them. The app that owns that screen has to say so and offer the way back, which is
+ why the kit renders this 404 as a video that cannot be opened rather than as a bare canvas.
+ """
+ org, _ = await _pub_org_member(request)
+ v = await _harness_for_route(hid, org)
+ entry, _rec = await _hosted_resolve(_MEDIA_SERVER, hid, org, _mcp_list(v), entry_id=eid)
+ sv: dict = {}
+ if sid:
+ _o, sv = await _owned_session(request, sid)
+ if str(sv.get("harness_id") or "") != hid:
+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")
+ return org, entry, sv
+
+
+class SceneWrite(BaseModel):
+ scene: dict
+
+
[email protected]("/v1/harnesses/{hid}/servers/{eid}/sessions/{sid}/scene")
+async def get_media_scene(hid: str, eid: str, sid: str, request: Request) -> dict:
+ await _media_route(hid, sid, eid, request)
+ scene = await _media_scene_read(sid)
+ return {"rev": int(float((scene.get("meta") or {}).get("rev") or 0)), "scene": scene}
+
+
[email protected]("/v1/harnesses/{hid}/servers/{eid}/sessions/{sid}/scene")
+async def put_media_scene(hid: str, eid: str, sid: str, body: SceneWrite,
+ request: Request) -> dict:
+ """The app's write, with the whole conflict story in three status codes.
+
+ 409 while a turn is running — the agent owns the document during a turn, the same rule
+ write_session_file holds for the same reason. 412 when the revision has moved, so a stale tab
+ merges rather than clobbers. 422 when the write would add or delete a generated media element:
+ a browser bug must not be able to orphan a rendered clip or resurrect a deleted one.
+ """
+ _org, _entry, v = await _media_route(hid, sid, eid, request)
+ live = {"running", "starting"} & {str(v.get("turn_status") or ""), str(v.get("status") or "")}
+ if live:
+ raise uhp_error(409, "session_busy",
+ "The agent is working on this video. Wait for the turn to finish before "
+ "saving.")
+ want = request.headers.get("if-match") or ""
+ async with _media_scene_lock(sid):
+ cur = await _media_scene_read(sid)
+ rev = int(float((cur.get("meta") or {}).get("rev") or 0))
+ if want and want.strip('"') != str(rev):
+ raise uhp_error(412, "scene_moved",
+ "This canvas changed while you were editing it.", "If-Match",
+ {"rev": rev})
+ incoming = media_plane.sanitize_scene(body.scene)
+ before = {e.get("id") for e in cur.get("elements") or [] if media_plane.is_media(e)}
+ after = {e.get("id") for e in incoming.get("elements") or [] if media_plane.is_media(e)}
+ if before != after:
+ raise uhp_error(422, "media_elements_are_the_agents",
+ "Media elements are placed and removed by the agent.")
+ incoming["meta"] = {**(incoming.get("meta") or {}), "rev": rev}
+ new_rev = await _media_scene_write(sid, incoming)
+ return {"rev": new_rev}
+
+
[email protected]("/v1/harnesses/{hid}/servers/{eid}/sessions/{sid}/jobs")
+async def get_media_jobs(hid: str, eid: str, sid: str, request: Request,
+ ids: str = "") -> dict:
+ """The same _media_job_advance path the agent's check_jobs takes, so a browser and an agent
+ cannot see a job differently."""
+ await _media_route(hid, sid, eid, request)
+ wanted = {i.strip() for i in (ids or "").split(",") if i.strip()}
+ out = []
+ for job in await _media_jobs_of(sid):
+ if wanted and job["id"] not in wanted:
+ continue
+ try:
+ job = await _media_job_advance(job)
+ except Exception: # noqa: BLE001
+ pass
+ out.append({"job_id": job["id"], "status": job.get("status"),
+ "capability": job.get("capability"), "model": job.get("model"),
+ "media_id": job.get("media_id") or None,
+ "element_id": job.get("element_id") or None,
+ "seconds": job.get("seconds") or None, "progress": job.get("progress") or None,
+ "error": job.get("error") or None,
+ **({"usd": round(float(job["usd"]), 4)} if job.get("usd") else {})})
+ return {"jobs": out, "spend_usd": await _media_spend(sid)}
+
+
[email protected]("/v1/harnesses/{hid}/servers/{eid}/sessions/{sid}/export")
+async def post_media_export(hid: str, eid: str, sid: str, request: Request) -> dict:
+ org, entry, _sv = await _media_route(hid, sid, eid, request)
+ if not media_plane.have_ffmpeg():
+ raise uhp_error(501, "export_unavailable",
+ "This deployment cannot assemble video — ffmpeg is not installed. The "
+ "clips are all still here to download individually.")
+ try:
+ job = await _media_export_start(hid, sid, org, str(entry.get("id") or eid), "")
+ except media_plane.MediaError as e:
+ raise uhp_error(400, "export_refused", str(e)) from e
+ return {"job_id": job["id"], "shots": job.get("shots"),
+ "total_seconds": job.get("planned_seconds"), "status": job["status"]}
+
+
[email protected]("/v1/harnesses/{hid}/servers/{eid}/sessions/{sid}/media/{med}")
+async def get_media_bytes(hid: str, eid: str, sid: str, med: str, request: Request) -> Response:
+ """The bytes, with Range support.
+
+ Range is not a nicety: without it Safari refuses to play at all and a timeline cannot scrub.
+ The media id is immutable, so it is its own ETag and may be cached forever.
+ """
+ await _media_route(hid, sid, eid, request)
+ meta = await _media_meta(sid, med)
+ if not meta:
+ raise uhp_error(404, "media_not_found", "No media with that id in this video.", "med")
+ data = await _blob_get(_media_blob(sid, med, str(meta.get("ext") or "bin")), kb=BLOB_KB)
+ if data is None:
+ raise uhp_error(404, "media_not_found", "No media with that id in this video.", "med")
+ mime = str(meta.get("mime") or "application/octet-stream")
+ headers = {"accept-ranges": "bytes", "etag": f'"{med}"',
+ "cache-control": "private, max-age=31536000, immutable"}
+ rng = request.headers.get("range") or ""
+ m = re.match(r"bytes=(\d*)-(\d*)$", rng.strip()) if rng else None
+ if m and (m.group(1) or m.group(2)):
+ total = len(data)
+ if m.group(1):
+ start = int(m.group(1))
+ end = int(m.group(2)) if m.group(2) else total - 1
+ else: # bytes=-N — the last N bytes
+ start, end = max(0, total - int(m.group(2))), total - 1
+ if start >= total:
+ return Response(status_code=416, headers={**headers,
+ "content-range": f"bytes */{total}"})
+ end = min(end, total - 1)
+ return Response(content=data[start:end + 1], status_code=206, media_type=mime,
+ headers={**headers, "content-range": f"bytes {start}-{end}/{total}",
+ "content-length": str(end - start + 1)})
+ return Response(content=data, media_type=mime, headers=headers)
+
+
+# ── what launch provisions ────────────────────────────────────────────────────────────────────
+def _kit_launch_media(kit: dict) -> dict | None:
+ """What this kit needs provisioned at launch: an entry pointing at the media server we host.
+
+ Unlike a database this collects NOTHING from the person. The provider credential is this
+ deployment's own integration and must never become a per-harness secret — so the record holds
+ only the binding, which is what _hosted_resolve checks, and holds no secret at all.
+ """
+ d = ((kit.get("harness") or {}).get("launch") or {}).get("media")
+ if not isinstance(d, dict):
+ return None
+ return {"name": str(d.get("name") or "media"), "id": str(d.get("id") or "mcp.media")}
+
+
+async def _hosted_media_attach(org: str, hid: str, v: dict | None, decl: dict) -> None:
+ origins = _own_origins()
+ if not origins:
+ raise uhp_error(501, "gateway_address_not_configured",
+ "This server has no address an agent could reach it on — set "
+ "HARNESS_PUBLIC_BASE_URL.", "media")
+ cur = _mcp_list(v)
+ prev = next((e for e in cur if str(e.get("id") or "") == decl["id"]), None) or {}
+ prev_key = _vault_key(prev.get("auth"))
+ key = (prev_key if prev_key.startswith(_HOSTED_SECRET_PREFIX)
+ else _hosted_secret_key(hid, decl["id"]))
+ # No secret in it, so no passphrase is demanded to write it: this record is a binding and
+ # nothing else, and the provider key it does NOT contain lives in the integrations document.
+ await _hosted_put_record(org, key, {"server": _MEDIA_SERVER, "harness": hid,
+ "updated_at": int(time.time() * 1000)},
+ secret=False, param="media")
+ entry = {"id": decl["id"], "name": str(prev.get("name") or decl["name"]),
+ "url": origins[0] + _HOSTED_MCP_PREFIX + _MEDIA_SERVER, "transport": "http",
+ "auth": f"vault:{key}",
+ "enabled": str(prev.get("enabled", True)) not in ("False", "false", "0")}
+ await _mcp_write(hid, [e for e in cur if str(e.get("id") or "") != decl["id"]] + [entry])
+ print(f"[media] {hid}: media tools attached", flush=True)
+
+
+async def _media_harness_purge(hid: str) -> None:
+ """Deleting the agent stops the jobs it started. Called from the one place that deletes a
+ harness, so there is no second answer to 'is it gone'.
+
+ The same method _media_session_purge already uses, because it is the same problem: the sweeper
+ finds work by STATUS, so the only thing that stops a job is no longer being running. Without
+ it, DELETE returned 200 and the sweeper carried on — provider calls carrying the key, and a
+ finished file written into the store, for an agent that no longer existed.
+
+ Only the jobs still running. A finished one is the record of a clip that is still in the
+ session's canvas, and the sessions outlive the agent that made them.
+ """
+ with contextlib.suppress(Exception):
+ for row in await BACKING.graph.find(_MEDIA_JOB_LABEL, {"harness": hid,
+ "status": "running"}):
+ job = _media_job_out(row) or {}
+ if not job.get("id"):
+ continue
+ await _vg_upsert(_MEDIA_JOB_LABEL, job["id"], {"deleted": "1", "status": "deleted"})
+ # A placeholder that spins forever is a lie the canvas keeps telling.
+ with contextlib.suppress(Exception):
+ await _media_element_failed(job)
+
+
+async def _media_session_purge(sid: str) -> None:
+ """Deleting the video deletes its media and tombstones its jobs. Called from the one place
+ that deletes a session, so there is no second answer to 'is it gone'."""
+ with contextlib.suppress(Exception):
+ for it in await _blob_list_all(f"media/{sid}/", kb=BLOB_KB):
+ await _blob_delete(str(it.get("file_id") or ""), kb=BLOB_KB)
+ with contextlib.suppress(Exception):
+ await _blob_delete(_media_scene_key(sid), kb=BLOB_KB)
+ with contextlib.suppress(Exception):
+ for job in await _media_jobs_of(sid):
+ await _vg_upsert(_MEDIA_JOB_LABEL, job["id"], {"deleted": "1", "status": "deleted"})
+
+
# ── Starter Kits ──────────────────────────────────────────────────────────────────────────────
# A kit is a whole product in a folder: the Harness it needs, and a UI that talks to that Harness
# as its backend. Both are baked into the image from HarnessRouter/starter-kit (see
@@ -7944,8 +9966,10 @@ async def delete_harness(org: str, hid: str, request: Request) -> dict:
raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
cur = await _mcp_migrate(org, hid, cur)
await _vg_upsert("Harness", hid, {"deleted": "1"})
- # a deleted agent must not still be holding a database password
+ # a deleted agent must not still be holding a database password, and must not still be
+ # spending at a provider
await _hosted_scrub_removed(org, hid, _mcp_list(cur), [])
+ await _media_harness_purge(hid)
return {"id": hid, "deleted": True}
@@ -8067,6 +10091,7 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
raise uhp_error(404, "kit_not_found", f"No starter kit '{kit_id}' in this build.")
decl = _kit_launch_database(kit)
+ media_decl = _kit_launch_media(kit)
db_in = body_in.database if body_in else None
if db_in and not decl:
raise uhp_error(400, "connection_not_used",
@@ -8094,6 +10119,11 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
existing = await _mcp_migrate(org, hid0, existing) or existing
await _hosted_db_attach(org, hid0, existing, decl, checked, db_in.sample_rows)
existing = await _vertex_get(hid0) or existing
+ if media_decl:
+ # Idempotent, like the database one: pressing Launch twice must leave one entry and
+ # one record, not two of each.
+ await _hosted_media_attach(org, hid0, existing, media_decl)
+ existing = await _vertex_get(hid0) or existing
return {"kit": kit_id, "harnessId": hid0,
"route": (kit.get("app") or {}).get("route") or "", "created": False,
"harness": _harness_out(existing)}
@@ -8136,6 +10166,9 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
if db_in:
await _hosted_db_attach(org, hid, v, decl, checked, db_in.sample_rows)
v = await _vertex_get(hid) or v
+ if media_decl:
+ await _hosted_media_attach(org, hid, v, media_decl)
+ v = await _vertex_get(hid) or v
print(f"[kits] launched {kit_id} -> {hid}", flush=True)
return {"kit": kit_id, "harnessId": hid,
"route": (kit.get("app") or {}).get("route") or "", "created": True,
@@ -8282,6 +10315,8 @@ async def delete_harness_public(hid: str, request: Request) -> dict:
raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
v = await _mcp_migrate(org, hid, v)
await _vg_upsert("Harness", hid, {"deleted": "1"})
- # a deleted agent must not still be holding a database password
+ # a deleted agent must not still be holding a database password, and must not still be
+ # spending at a provider
await _hosted_scrub_removed(org, hid, _mcp_list(v), [])
+ await _media_harness_purge(hid)
return {"id": hid, "deleted": True}
diff --git a/gateway/media_catalog.json b/gateway/media_catalog.json
new file mode 100644
index 00000000..3ca12707
--- /dev/null
+++ b/gateway/media_catalog.json
@@ -0,0 +1,221 @@
+{
+ "$comment": [
+ "Measured 2026-08-15 against api.tokenrouter.com. `verified` = a call was issued and the response read.",
+ "`quota` is TokenRouter's own per-job integer; 500000 == $1.00 held on every observed job.",
+ "Order is preference order. Nothing here is sorted at run time.",
+ "Read from disk, never compiled in: a catalog in source goes stale the moment a provider fixes",
+ "or breaks a model, and nothing says so. Same rule as kits and skills.",
+ "`measured` on a candidate is a LATER observation than this file's own sweep, and says what was",
+ "run to learn it. A correction and a first measurement are not the same kind of fact, and the",
+ "difference has to survive in the file or the next person cannot tell which they are reading."
+ ],
+ "providers": {
+ "tokenrouter": { "integration_provider": "tokenrouter", "base_url": "https://api.tokenrouter.com/v1" },
+ "elevenlabs": { "integration_provider": "elevenlabs", "base_url": "https://api.elevenlabs.io/v1" }
+ },
+
+ "capabilities": {
+
+ "text_to_video": {
+ "unit": "clip",
+ "candidates": [
+ { "model": "dreamina-seedance-2-5-hc", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration"], "in": ["text"], "out": ["video"],
+ "resolution": "1280x720", "accepts_input_image": false,
+ "duration_ignored": true, "duration_observed_s": 6.08,
+ "keep": "Owner's preferred model, and the reason nothing here skips a candidate for being marked broken: it sat at rank 1 through the whole outage, cost nothing to keep trying, and started working again on its own.",
+ "measured": "e2e run 2026-08-15, later than the sweep above: TokenRouter fixed the upstream mapping (eva-video-2.5-t2v-480p-720p) and it rendered a real 1280x720 clip. It IGNORES duration — 1 s was asked for and 6.08 s came back — and it REJECTS an input image url, so it is not a candidate for image_to_video. `duration` is still sent because a video submit that carries none lets the model pick its own, which is how kling bills 15 s.",
+ "verification": "verified" },
+
+ { "model": "MiniMax-Hailuo-2.3", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration"], "in": ["text"], "out": ["video"],
+ "durations_s": [6, 10], "duration_required": true,
+ "resolution": "1366x768", "accepts_input_image": false,
+ "quota": 140000, "quota_measured": true, "usd": 0.28, "latency_s": 240,
+ "output_url_expires": false,
+ "note": "image/image_url/resolution/size/aspect_ratio/mode are ALL silently ignored and still bill.",
+ "verification": "verified" },
+
+ { "model": "kling-v3", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration", "image", "mode"], "in": ["text", "image"], "out": ["video"],
+ "duration_max_s": 15, "durations_rejected_s": [1], "duration_required": true,
+ "default_duration_s": 15.041,
+ "accepts_input_image": true, "input_image_param": "image", "input_image_encoding": "base64",
+ "quota": 840000, "quota_measured": true, "usd": 1.68, "latency_s": 240,
+ "output_url_expires": true,
+ "note": "Sending no duration yields a 15.041 s clip at 6x MiniMax's price. duration is REQUIRED here.",
+ "measured": "e2e run 2026-08-15: REJECTS duration 1, which this file had claimed as its floor. The claimed floor is gone rather than moved — what the shortest accepted duration is was not measured, and a number nobody measured is worse than no number.",
+ "verification": "verified" },
+
+ { "model": "kling-v2-6", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration", "image", "mode"], "in": ["text", "image"], "out": ["video"],
+ "duration_max_s": 15, "durations_rejected_s": [1], "duration_required": true,
+ "accepts_input_image": true, "input_image_param": "image", "input_image_encoding": "base64",
+ "output_url_expires": true,
+ "note": "Submit verified; limits inferred from kling-v3 (same family, same relay path).",
+ "measured": "e2e run 2026-08-15: REJECTS duration 1, same as kling-v3. Floor removed for the same reason.",
+ "verification": "verified" },
+
+ { "model": "happyhorse-1.0-t2v", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration", "size"], "in": ["text"], "out": ["video"],
+ "duration_min_s": 3, "duration_max_s": 15, "duration_required": true,
+ "size_format": "W*H", "resolution": "1920*1080", "accepts_input_image": false,
+ "quota": 500000, "quota_measured": true, "usd": 1.00, "latency_s": 240,
+ "output_url_expires": true, "output_url_ttl_s": 86400,
+ "watermark": true,
+ "note": "Output file is named '…_refiner_watermark.mp4'. Never selected unless allow_watermark:true.",
+ "verification": "verified" },
+
+ { "model": "kling-v3-omni", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration"],
+ "status": "broken", "error": "400 fail_to_fetch_task — upstream 'model is not supported'",
+ "in": ["text"], "out": ["video"], "verification": "verified_prior" },
+
+ { "model": "kling-3.0-turbo", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration"],
+ "status": "broken", "error": "500 api_panic 'assignment to entry in nil map' (relay crash)",
+ "in": ["text"], "out": ["video"], "verification": "verified_prior" }
+ ]
+ },
+
+ "image_to_video": {
+ "unit": "clip",
+ "no_fallback_note": "Only kling accepts an input image. MiniMax and happyhorse IGNORE image/image_url and bill for a text-only clip — verified. dreamina REJECTS one outright and is not listed here at all. If both kling models are down this capability has NO substitute and must refuse.",
+ "candidates": [
+ { "model": "kling-v3", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration", "image", "mode"], "in": ["text", "image"], "out": ["video"],
+ "input_image_param": "image", "input_image_encoding": "base64", "duration_required": true,
+ "duration_max_s": 15, "durations_rejected_s": [1],
+ "accepts_input_image": true,
+ "quota": 840000, "quota_measured": true, "usd": 1.68, "latency_s": 240,
+ "output_url_expires": true,
+ "note": "The image param is recognised and validated (400 code 1201 on non-base64) — verified. An end-to-end i2v render was NOT run.",
+ "measured": "e2e run 2026-08-15: REJECTS duration 1; claimed floor removed. dreamina-seedance-2-5-hc was REMOVED from this chain the same day — it rejects an input image url, so listing it here would spend a rank-1 slot on a model that cannot do this capability at all.",
+ "verification": "inferred" },
+ { "model": "kling-v2-6", "provider": "tokenrouter", "shape": "video-generation",
+ "params": ["prompt", "duration", "image", "mode"], "in": ["text", "image"], "out": ["video"],
+ "input_image_param": "image", "input_image_encoding": "base64", "duration_required": true,
+ "duration_max_s": 15, "durations_rejected_s": [1],
+ "accepts_input_image": true, "output_url_expires": true,
+ "measured": "e2e run 2026-08-15: REJECTS duration 1; claimed floor removed.",
+ "verification": "inferred" }
+ ]
+ },
+
+ "text_to_image": {
+ "unit": "image",
+ "$order": "Ordered by latency, not by prestige: an image here is almost always a FRAME on the way to a video, so a 91-second model at the head of the chain turns a four-shot storyboard into six minutes of waiting.",
+ "candidates": [
+ { "model": "google/gemini-3.1-flash-lite-image", "provider": "tokenrouter", "shape": "gemini",
+ "params": ["prompt"], "in": ["text", "image"], "out": ["image", "text"], "latency_s": 4.15,
+ "output_mime": "image/jpeg", "accepts_input_image": true, "verification": "verified" },
+ { "model": "bytedance-seed/seedream-4.5", "provider": "tokenrouter", "shape": "image-generation",
+ "params": ["prompt", "n", "size"], "in": ["text", "image"], "out": ["image"], "latency_s": 6.05,
+ "min_pixels": 3686400, "sizes_verified": ["1920x1920"],
+ "output_url_expires": true, "accepts_input_image": true,
+ "note": "Rejects anything under 3,686,400 px with 400 InvalidParameter — skipped when a smaller size is asked for.",
+ "verification": "verified" },
+ { "model": "google/gemini-3.1-flash-image-preview", "provider": "tokenrouter", "shape": "gemini",
+ "params": ["prompt"], "in": ["text", "image"], "out": ["image", "text"], "latency_s": 14.48,
+ "output_mime": "image/png", "accepts_input_image": true, "verification": "verified" },
+ { "model": "bytedance-seed/seedream-5.0-lite", "provider": "tokenrouter", "shape": "image-generation",
+ "params": ["prompt", "n", "size"], "in": ["text", "image"], "out": ["image"], "latency_s": 17.74,
+ "min_pixels": 3686400, "sizes_verified": ["1920x1920"], "output_url_expires": true,
+ "accepts_input_image": true, "verification": "verified" },
+ { "model": "microsoft/mai-image-2.5", "provider": "tokenrouter", "shape": "openai",
+ "params": ["prompt"], "in": ["text", "image"], "out": ["image"], "latency_s": 21.95,
+ "usd": 0.048188, "quota_measured": true, "usd_source": "usage.cost reported inline",
+ "accepts_input_image": true, "verification": "verified" },
+ { "model": "openai/gpt-5.4-image-2", "provider": "tokenrouter", "shape": "image-generation",
+ "params": ["prompt", "n", "size"], "in": ["text"], "out": ["image"],
+ "sizes_verified": ["1024x1024"], "output_field": "b64_json", "verification": "verified_prior" },
+ { "model": "google/gemini-2.5-flash-image", "provider": "tokenrouter", "shape": "gemini",
+ "params": ["prompt"], "in": ["text", "image"], "out": ["image", "text"], "output_mime": "image/png",
+ "accepts_input_image": true, "verification": "verified" },
+ { "model": "openai/gpt-5-image-mini", "provider": "tokenrouter", "shape": "openai",
+ "params": ["prompt"], "in": ["text", "image"], "out": ["image"], "latency_s": 41.67,
+ "accepts_input_image": true, "note": "Returns an encrypted reasoning block beside the image; ignore it.",
+ "verification": "verified" },
+ { "model": "openai/gpt-5-image", "provider": "tokenrouter", "shape": "openai",
+ "params": ["prompt"], "in": ["text", "image"], "out": ["image"], "latency_s": 57.08,
+ "accepts_input_image": true, "verification": "verified" },
+ { "model": "bytedance-seed/seedream-5.0-pro", "provider": "tokenrouter", "shape": "image-generation",
+ "params": ["prompt", "n", "size"], "in": ["text", "image"], "out": ["image"], "latency_s": 91.05,
+ "sizes_verified": ["1024x1024"], "output_url_expires": true, "accepts_input_image": true,
+ "note": "The 3.69 Mpx floor is NOT family-wide — this one accepts 1024x1024.", "verification": "verified" },
+ { "model": "google/gemini-3-pro-image-preview", "provider": "tokenrouter", "shape": "gemini",
+ "params": ["prompt"],
+ "status": "excluded",
+ "error": "200 OK, parts:[], finishReason STOP — bills ~1356 tokens and returns nothing. Identical with responseModalities set.",
+ "excluded_reason": "Fails silently AND bills. Never selectable; kept in the file so nobody re-adds it.",
+ "measured": "e2e run 2026-08-15 confirmed it again, and this entry is why availability is asserted on a MEDIA PAYLOAD and never on a 200: a status code would read this model as working, on every call, for as long as it kept billing. read_submit enforces that for all five shapes, so a sibling cannot do the same quietly.",
+ "verification": "verified" }
+ ]
+ },
+
+ "image_to_image": {
+ "unit": "image",
+ "$warning": "NOTHING IN THIS CAPABILITY WAS VERIFIED — no image-input call was ever made. Ordering mirrors text_to_image. The build task for this tool is: verify each candidate with one call before the tool is enabled.",
+ "candidates": [
+ { "model": "google/gemini-3.1-flash-lite-image", "provider": "tokenrouter", "shape": "gemini",
+ "params": ["prompt", "image"], "in": ["text", "image"], "out": ["image", "text"],
+ "accepts_input_image": true, "output_mime": "image/jpeg",
+ "input_method": "an inlineData part beside the text part", "verification": "inferred" },
+ { "model": "bytedance-seed/seedream-4.5", "provider": "tokenrouter", "shape": "image-generation",
+ "params": ["prompt", "n", "size", "image"], "in": ["text", "image"], "out": ["image"],
+ "min_pixels": 3686400, "accepts_input_image": true, "output_url_expires": true,
+ "input_method": "an `image` field; the endpoint reports usage.input_images", "verification": "inferred" },
+ { "model": "google/gemini-3.1-flash-image-preview", "provider": "tokenrouter", "shape": "gemini",
+ "params": ["prompt", "image"], "in": ["text", "image"], "out": ["image", "text"],
+ "accepts_input_image": true, "output_mime": "image/png", "verification": "inferred" },
+ { "model": "microsoft/mai-image-2.5", "provider": "tokenrouter", "shape": "openai",
+ "params": ["prompt", "image"], "in": ["text", "image"], "out": ["image"],
+ "accepts_input_image": true,
+ "input_method": "an image_url content part in the user message", "verification": "inferred" },
+ { "model": "openai/gpt-5-image-mini", "provider": "tokenrouter", "shape": "openai",
+ "params": ["prompt", "image"], "in": ["text", "image"], "out": ["image"],
+ "accepts_input_image": true, "verification": "inferred" }
+ ]
+ },
+
+ "text_to_speech": {
+ "unit": "line",
+ "$warning": "These are CONVERSATIONAL models: they ANSWER the prompt rather than reading it. 'Say: hello.' returned 'Hello! It's great to talk with you.' No SSML, no voice cloning, no word timing.",
+ "candidates": [
+ { "model": "openai/gpt-audio-mini", "provider": "tokenrouter", "shape": "audio-chat",
+ "params": ["messages", "modalities", "audio"], "in": ["text"], "out": ["audio", "text"],
+ "voices": ["alloy"], "format": "wav", "latency_s": 3.03, "stream_required": false,
+ "verification": "verified" },
+ { "model": "openai/gpt-audio", "provider": "tokenrouter", "shape": "audio-chat",
+ "params": ["messages", "modalities", "audio", "stream"], "in": ["text"], "out": ["audio", "text"],
+ "voices": ["alloy"], "format": "wav", "latency_s": 2.6, "stream_required": true,
+ "note": "400 'Audio output requires stream: true' without it; audio arrives at choices[0].delta.audio and must be concatenated.",
+ "verification": "verified" }
+ ]
+ },
+
+ "text_to_music": {
+ "unit": "track",
+ "instead": "Do not use generate_speech instead — it produces conversation, not music.",
+ "$comment": "All 125 TokenRouter entries were searched by name (suno|udio|lyria|musicgen|music|song|melody) and by tag: the only audio-capable models there are the two conversational speech ones. The owner chose ElevenLabs Music direct. ONE candidate, stood down with the reason it is stood down for — an empty list produces 'no music model is connected', which is true and tells nobody what to do. No key is stored here: when the owner supplies a working one it goes in the integrations document as an ordinary provider entry, like every other.",
+ "candidates": [
+ { "model": "elevenlabs/music-v1", "provider": "elevenlabs", "shape": "elevenlabs-music",
+ "in": ["text"], "out": ["audio"],
+ "status": "unavailable", "reason_code": "paid_plan_required",
+ "reason": "Background music needs a paid ElevenLabs plan — the key measured on this account authenticates, but Music is not included in the free tier",
+ "measured": "e2e run 2026-08-15: POST /v1/music answered 402 Payment Required, NOT 401 — so the key is valid and the account is free-tier. The same key is scoped and cannot do speech either: GET /v1/voices answered 401 'missing the permission'. No adapter is written for this shape (see build_submit), so marking it available without writing one raises rather than silently sending nothing.",
+ "verification": "verified" }
+ ]
+ },
+
+ "export": {
+ "unit": "film",
+ "local": true,
+ "candidates": [],
+ "requires_binary": ["ffmpeg", "ffprobe"],
+ "$comment": "Not a provider capability. Reported unavailable when the image was built without ffmpeg.",
+ "max_shots": 40,
+ "max_total_s": 600
+ }
+ }
+}
diff --git a/gateway/media_plane.py b/gateway/media_plane.py
new file mode 100644
index 00000000..fdbaa9fc
--- /dev/null
+++ b/gateway/media_plane.py
@@ -0,0 +1,1290 @@
+"""Making a picture, a clip, a line of speech — and assembling them into one film.
+
+Two callers, one engine, one place the provider key is resolved:
+
+ * the `media` MCP server this gateway hosts, so an agent can ask for a CAPABILITY
+ (text_to_video, text_to_image, …) and be told which model actually ran;
+ * the routes a media app calls to read its canvas, poll its jobs and export a film.
+
+WHAT NEVER LEAVES THIS PROCESS. The provider key is resolved from the integrations document
+inside the gateway, at the moment of use. The runner never receives it (an agent gets a per-turn
+capability, never a key), and neither does the browser. Same shape the database server already
+uses, for the same reason: a sandbox runs a customer's agent with real bash and egress.
+
+THE AGENT NEVER NAMES A MODEL. It names a capability; this module walks that capability's ordered
+candidate list and returns the first one that can actually serve the request — provider connected,
+parameters honourable, not watermarked unless asked, not quarantined by a recent billable failure —
+and the caller reports which one it was. Four video models are listed and two of them are broken;
+that is the whole reason this exists rather than a model id in a tool argument.
+
+FIVE ENDPOINT SHAPES, all measured against the live account on 2026-08-15:
+
+ video-generation POST /video/generations -> task id; GET /video/generations/{id} to poll
+ image-generation POST /images/generations -> b64_json OR url (both occur)
+ openai POST /chat/completions -> choices[0].message.images[0].image_url.url
+ gemini POST /v1beta/models/{id}:generateContent -> inlineData parts
+ audio-chat POST /chat/completions with modalities -> message.audio.data (+ transcript)
+
+"200 OK" IS NOT SUCCESS. A candidate has only run once its response carries an actual media
+payload. google/gemini-3-pro-image-preview answers 200 with `parts: []` and bills ~1356 tokens;
+it is excluded from every chain, and this rule exists so its siblings cannot do the same quietly.
+
+NEVER FORWARD AN UNRECOGNISED PARAMETER. The relay ignores unknown fields and submits the job
+anyway, so a typo costs a full-price generation. Each candidate declares `params`, and the request
+builders emit nothing outside that set — see `build_submit`, which hands back exactly which
+tunables it used so a test can assert the subset rather than trust the code.
+"""
+from __future__ import annotations
+
+import asyncio
+import base64
+import binascii
+import contextlib
+import functools
+import json
+import os
+import pathlib
+import re
+import shutil
+import subprocess
+import tempfile
+import time
+import uuid
+
+# ── errors ────────────────────────────────────────────────────────────────────────
+class MediaError(Exception):
+ """A failure with a sentence the agent can act on."""
+
+
+class MediaRefused(MediaError):
+ """The provider refused before any billable work started — an HTTP error at submit, a
+ timeout before a task id existed. Retrying the candidate is free, so it is NOT quarantined."""
+
+
+class MediaEmpty(MediaError):
+ """The provider answered 200 and returned no media. Billable, and therefore a failure that
+ quarantines the candidate — this is the gemini-3-pro rule."""
+
+
+# ── the catalog ───────────────────────────────────────────────────────────────────
+_CATALOG_PATH = os.environ.get("HR_MEDIA_CATALOG") or str(
+ pathlib.Path(__file__).with_name("media_catalog.json"))
+
+# How long a candidate that failed AFTER a task id existed is left out of the chain. A submit
+# failure is free to retry and is never quarantined, which is exactly what lets the owner's
+# preferred model sit permanently at rank 1 and start working the day the relay is fixed.
+QUARANTINE_S = int(os.environ.get("HR_MEDIA_QUARANTINE_S", "1800"))
+# The one blocking provider call. A synchronous shape renders inside it, so the ceiling is the
+# slowest verified model (seedream-5.0-pro at 91 s) with room, not a round number.
+SUBMIT_TIMEOUT_S = float(os.environ.get("HR_MEDIA_SUBMIT_TIMEOUT_S", "180"))
+POLL_TIMEOUT_S = float(os.environ.get("HR_MEDIA_POLL_TIMEOUT_S", "30"))
+# A body larger than this is not a clip anyone asked for; it is a memory incident.
+MAX_BYTES = int(os.environ.get("HR_MEDIA_MAX_BYTES", str(128 * 1024 * 1024)))
+# Nothing terminal after this and the job is failed with a sentence, rather than polled forever.
+JOB_MAX_S = int(os.environ.get("HR_MEDIA_JOB_MAX_S", "1200"))
+# Summed MEASURED spend per session. Exceeded, generate_* refuses and names both numbers.
+SESSION_BUDGET_USD = float(os.environ.get("HR_MEDIA_SESSION_BUDGET_USD", "25"))
+
+# What a caller may ask for on each shape, beyond the structural fields the shape itself needs.
+# A candidate that declares none of its own is held to this — so "only whitelisted params are
+# forwarded" is true for every entry in the file, including one added later without a `params`.
+_SHAPE_TUNABLES = {
+ "video-generation": ("prompt", "duration", "image", "mode", "size"),
+ "image-generation": ("prompt", "n", "size", "image"),
+ "openai": ("prompt", "image"),
+ "gemini": ("prompt", "image"),
+ "audio-chat": ("messages", "modalities", "audio", "stream"),
+}
+
+
[email protected]_cache(maxsize=1)
+def catalog() -> dict:
+ """The capability catalog, read from disk at first use.
+
+ From disk rather than compiled in, for the same reason kits and skills are: a provider fixes
+ a model or breaks one, and a table in source goes stale with nothing to say so.
+ """
+ try:
+ doc = json.loads(pathlib.Path(_CATALOG_PATH).read_text())
+ except Exception as e: # noqa: BLE001
+ print(f"[media] catalog at {_CATALOG_PATH} is unreadable ({e}) — no capability is "
+ f"available until it is fixed", flush=True)
+ return {"providers": {}, "capabilities": {}}
+ caps = doc.get("capabilities") or {}
+ n = sum(len(c.get("candidates") or []) for c in caps.values() if isinstance(c, dict))
+ print(f"[media] catalog: {len(caps)} capabilities, {n} candidates", flush=True)
+ return doc
+
+
+def capability(name: str) -> dict:
+ c = (catalog().get("capabilities") or {}).get(name)
+ return c if isinstance(c, dict) else {}
+
+
+def capability_names() -> list[str]:
+ return [k for k in (catalog().get("capabilities") or {})]
+
+
+def provider_meta(provider: str) -> dict:
+ p = (catalog().get("providers") or {}).get(provider)
+ return p if isinstance(p, dict) else {}
+
+
+def declared_params(cand: dict) -> set[str]:
+ """The tunables this candidate accepts. Its own list when it names one, the shape's otherwise —
+ never "everything the caller sent"."""
+ own = [str(p) for p in (cand.get("params") or [])]
+ tunables = set(_SHAPE_TUNABLES.get(str(cand.get("shape") or ""), ()))
+ return ({p for p in own if p in tunables} or tunables) if own else tunables
+
+
+def estimated_usd(cand: dict) -> float | None:
+ """What one unit costs, or None. Present ONLY where it was measured — a guessed price is
+ worse than no price, because it is believed."""
+ if not cand.get("quota_measured"):
+ return None
+ usd = cand.get("usd")
+ return float(usd) if isinstance(usd, (int, float)) else None
+
+
+def limits_of(cand: dict) -> dict:
+ """What list_capabilities tells the agent about the model it would get. Only keys the
+ candidate actually declares — an absent limit is absent, not a default someone invented."""
+ out: dict = {}
+ for k in ("durations_s", "duration_min_s", "duration_max_s", "durations_rejected_s",
+ "duration_ignored", "duration_observed_s", "resolution", "min_pixels",
+ "sizes_verified", "voices", "format", "latency_s", "output_mime"):
+ if cand.get(k) is not None:
+ out[k] = cand[k]
+ if "accepts_input_image" in cand:
+ out["accepts_input_image"] = bool(cand["accepts_input_image"])
+ if cand.get("watermark"):
+ out["watermark"] = True
+ return out
+
+
+# ── chain selection ───────────────────────────────────────────────────────────────
+def _fmt_s(x: float) -> str:
+ return f"{int(x)}" if float(x).is_integer() else f"{x:g}"
+
+
+_STOOD_DOWN = ("excluded", "unavailable")
+
+
+def stood_down(cand: dict) -> str:
+ """"" unless this candidate is stood down by something MEASURED about the model itself, in
+ which case the sentence that says so.
+
+ Asked before anything about this deployment — which providers are connected, what was asked
+ for — because it is the more specific and more useful fact. "Background music needs a paid
+ plan" names a fix; "nobody has connected that provider" does not, and it is the sentence the
+ person reading it would have to get past first.
+
+ TWO statuses stand a candidate down and only two. `broken` is deliberately NOT one of them: a
+ model that fails at SUBMIT costs nothing to retry, and leaving it in the chain is precisely
+ what let the owner's preferred video model start working again the day the relay's mapping was
+ fixed — no code change, no cost, nobody watching. A rule that skipped everything marked broken
+ would have made that recovery impossible and nobody would ever have known.
+ """
+ status = str(cand.get("status") or "")
+ if status not in _STOOD_DOWN:
+ return ""
+ model = str(cand.get("model") or "?")
+ reason = str(cand.get("reason") or cand.get("excluded_reason") or cand.get("error") or "")
+ if status == "unavailable":
+ return reason or f"{model} is not available in this deployment"
+ return f"{model} is excluded: {reason or 'it fails silently'}"
+
+
+def can_serve(cand: dict, params: dict) -> str:
+ """"" when this candidate can honour the request, else the clause that says why not.
+
+ PARAMETER FIT IS CHECKED BEFORE HEALTH, because a model that cannot render 8 seconds is not
+ a fallback for one that can — it is a different film.
+ """
+ down = stood_down(cand)
+ if down:
+ return down
+ model = str(cand.get("model") or "?")
+
+ secs = params.get("seconds")
+ if secs is not None:
+ allowed = cand.get("durations_s")
+ if isinstance(allowed, list) and allowed:
+ if not any(abs(float(a) - float(secs)) < 1e-6 for a in allowed):
+ return (f"{model} renders "
+ f"{' and '.join(_fmt_s(a) for a in allowed)} s only")
+ # Durations this model was ASKED for and refused. A measured rejection, not a range
+ # somebody inferred around it: the catalog claimed a 1 s floor and both kling models
+ # answer 400 to a 1 s render, so the floor is gone and the measurement is here instead.
+ rejected = cand.get("durations_rejected_s")
+ if isinstance(rejected, list) and any(abs(float(a) - float(secs)) < 1e-6 for a in rejected):
+ return f"{model} refuses a {_fmt_s(secs)} s render"
+ lo, hi = cand.get("duration_min_s"), cand.get("duration_max_s")
+ if lo is not None and float(secs) < float(lo):
+ return f"{model} cannot render {_fmt_s(secs)} s (its shortest is {_fmt_s(lo)} s)"
+ if hi is not None and float(secs) > float(hi):
+ return f"{model} cannot render {_fmt_s(secs)} s (its longest is {_fmt_s(hi)} s)"
+
+ if params.get("image") is not None and not cand.get("accepts_input_image"):
+ # MiniMax and happyhorse IGNORE an input image and bill for a text-only clip. Skipping
+ # them here is what stops image_to_video quietly becoming text_to_video.
+ return f"{model} ignores an input image and would bill for a text-only render"
+
+ size = params.get("size")
+ if size and cand.get("min_pixels"):
+ w, h = parse_size(str(size))
+ if w and h and w * h < int(cand["min_pixels"]):
+ return (f"{model} rejects anything under "
+ f"{int(cand['min_pixels']):,} px and {size} is smaller")
+
+ if cand.get("watermark") and not params.get("allow_watermark"):
+ return f"{model} watermarks its output"
+
+ voice = params.get("voice")
+ if voice and cand.get("voices") and voice not in cand["voices"]:
+ return f"{model} has no voice called {voice!r}"
+ return ""
+
+
+def resolve(cap_name: str, params: dict, connected: set[str],
+ quarantined: dict[str, float] | None = None,
+ exclude: frozenset[str] | set[str] = frozenset()) -> tuple[dict | None, list[str]]:
+ """(candidate, skipped-clauses) — the first candidate that can actually serve this request.
+
+ Declaration order, never re-sorted: the file is the preference, and a run-time sort would make
+ "why did it pick that one" unanswerable. Nothing here issues a network call.
+
+ `exclude` is what a chain that is already running passes back in: a candidate this job has
+ ALREADY tried is not offered again, so advancing the chain is a loop over one function rather
+ than a second, parallel walk of the same list.
+ """
+ cap = capability(cap_name)
+ now = time.time()
+ q = quarantined or {}
+ skipped: list[str] = []
+ for cand in cap.get("candidates") or []:
+ if not isinstance(cand, dict):
+ continue
+ model = str(cand.get("model") or "?")
+ if model in exclude:
+ continue # already tried on this job; its error is in `attempts`
+ down = stood_down(cand)
+ if down:
+ skipped.append(down) # measured about the model; said before anything else
+ continue
+ provider = str(cand.get("provider") or "")
+ if provider and provider not in connected:
+ skipped.append(f"{model} needs a provider nobody has connected")
+ continue
+ why = can_serve(cand, params)
+ if why:
+ skipped.append(why)
+ continue
+ until = float(q.get(model) or 0)
+ if until > now:
+ mins = max(1, int((now - (until - QUARANTINE_S)) // 60) or 1)
+ skipped.append(f"{model} failed {mins} minute{'s' if mins != 1 else ''} ago")
+ continue
+ return cand, skipped
+ return None, skipped
+
+
+def refusal(cap_name: str, skipped: list[str]) -> str:
+ """The refusal, verbatim. The final clause is load-bearing: without it a model spends the
+ rest of the turn trying to connect a provider itself.
+
+ `instead` is the capability's own warning about the substitution a model would otherwise reach
+ for — declared in the catalog beside the candidates, so the refusal is built from ONE place
+ whatever the capability. It used to be a whole second refusal string that text_to_music alone
+ was special-cased to return, which meant an empty candidate list and a hard-coded sentence
+ could not disagree because only one of them was ever read.
+ """
+ cap = capability(cap_name)
+ reason = ("; ".join(skipped) + "." if skipped
+ else "No model is listed for it in this deployment.")
+ out = (f"No model is available for {cap_name} right now. {reason}\n"
+ f"Nothing was generated and nothing was charged.\n")
+ if cap.get("instead"):
+ out += f"{cap['instead']}\n"
+ return out + ("Ask the person to connect a provider that can do this — you cannot connect one "
+ "yourself.")
+
+
+_SIZE_RE = re.compile(r"^(\d{3,5})\s*[x*]\s*(\d{3,5})$", re.I)
+
+
+def parse_size(size: str) -> tuple[int, int]:
+ m = _SIZE_RE.match((size or "").strip())
+ return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
+
+
+# ── the five adapters: building a request ─────────────────────────────────────────
+class Submit:
+ """One outbound request, plus exactly which tunables it carried.
+
+ `tunables` is not decoration: it is how "only whitelisted params are forwarded" is asserted
+ rather than believed. Structural fields (model, messages, contents) are the shape's own and
+ are not tunables — a caller cannot influence them.
+ """
+
+ __slots__ = ("method", "url", "body", "tunables", "stream", "timeout")
+
+ def __init__(self, method: str, url: str, body: dict, tunables: dict,
+ stream: bool = False, timeout: float = SUBMIT_TIMEOUT_S):
+ self.method, self.url, self.body = method, url, body
+ self.tunables, self.stream, self.timeout = tunables, stream, timeout
+
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
+ return f"<Submit {self.method} {self.url} tunables={sorted(self.tunables)}>"
+
+
+def _timeout_for(cand: dict) -> float:
+ """A synchronous shape renders inside the submit, so its budget is its measured latency with
+ room — not one number for a 4-second model and a 91-second one."""
+ lat = cand.get("latency_s")
+ if str(cand.get("shape")) == "video-generation" or not isinstance(lat, (int, float)):
+ return min(SUBMIT_TIMEOUT_S, 120.0)
+ return min(SUBMIT_TIMEOUT_S, max(60.0, float(lat) * 3.0))
+
+
+def _api_root(base: str) -> str:
+ """The provider's API root, for the one shape whose path is not `/v1` relative.
+
+ The configured base carries the `/v1` every other shape needs, so it is right to keep it there
+ and strip it HERE rather than store a second base_url that could drift out of step with it.
+ """
+ return base[:-3].rstrip("/") if base.endswith("/v1") else base
+
+
+def build_submit(cand: dict, base_url: str, params: dict) -> Submit:
+ """The request that starts this generation. Nothing outside `declared_params(cand)` is sent."""
+ shape = str(cand.get("shape") or "")
+ model = str(cand.get("model") or "")
+ allow = declared_params(cand)
+ base = (base_url or "").rstrip("/")
+ tun: dict = {}
+
+ def take(name: str, value):
+ if value is None or name not in allow:
+ return None
+ tun[name] = value
+ return value
+
+ if shape == "video-generation":
+ body: dict = {"model": model, "extra_body": {}}
+ prompt = take("prompt", params.get("prompt"))
+ if prompt is not None:
+ body["prompt"] = prompt
+ secs = take("duration", params.get("seconds"))
+ if secs is not None:
+ # An integer where it is one: the relay round-trips 6.0 as "6.0" and one model reads
+ # that as a float it does not offer.
+ body["duration"] = int(secs) if float(secs).is_integer() else float(secs)
+ img = take("image", params.get("image"))
+ if img is not None:
+ body[str(cand.get("input_image_param") or "image")] = img
+ mode = take("mode", params.get("mode"))
+ if mode is not None:
+ body["mode"] = mode
+ size = take("size", params.get("size"))
+ if size is not None:
+ body["size"] = (size.replace("x", "*") if cand.get("size_format") == "W*H"
+ else size)
+ return Submit("POST", f"{base}/video/generations", body, tun, timeout=_timeout_for(cand))
+
+ if shape == "image-generation":
+ body = {"model": model}
+ prompt = take("prompt", params.get("prompt"))
+ if prompt is not None:
+ body["prompt"] = prompt
+ if "n" in allow:
+ tun["n"] = 1
+ body["n"] = 1
+ size = take("size", params.get("size"))
+ if size is not None:
+ body["size"] = size
+ img = take("image", params.get("image"))
+ if img is not None:
+ body["image"] = img
+ return Submit("POST", f"{base}/images/generations", body, tun, timeout=_timeout_for(cand))
+
+ if shape == "openai":
+ content: list = []
+ prompt = take("prompt", params.get("prompt"))
+ if prompt is not None:
+ content.append({"type": "text", "text": prompt})
+ img = take("image", params.get("image"))
+ if img is not None:
+ content.append({"type": "image_url",
+ "image_url": {"url": _data_uri(img, params.get("image_mime"))}})
+ body = {"model": model, "messages": [{"role": "user", "content": content}]}
+ return Submit("POST", f"{base}/chat/completions", body, tun, timeout=_timeout_for(cand))
+
+ if shape == "gemini":
+ parts: list = []
+ prompt = take("prompt", params.get("prompt"))
+ if prompt is not None:
+ parts.append({"text": prompt})
+ img = take("image", params.get("image"))
+ if img is not None:
+ parts.append({"inlineData": {"mimeType": params.get("image_mime") or "image/png",
+ "data": img}})
+ body = {"contents": [{"parts": parts}]}
+ # THE FULL ID, `google/` prefix and all: the bare name answers 503. Measured.
+ # `/v1beta` hangs off the API ROOT, not off `/v1` — the other four shapes are `/v1`
+ # relative, this one is not. Measured 2026-08-15 with a model id that does not exist, so
+ # the difference is the ROUTE and not the model:
+ # …/v1/v1beta/models/{id}:generateContent -> 404 "Invalid URL" (the path is wrong)
+ # …/v1beta/models/{id}:generateContent -> 503 model_not_found (the path is right)
+ # Concatenating onto the configured base silently killed both Gemini image models, and the
+ # chain fell through to a model 5x slower and priced per image — a failure that LOOKS like
+ # success because a picture still comes back.
+ return Submit("POST", f"{_api_root(base)}/v1beta/models/{model}:generateContent", body, tun,
+ timeout=_timeout_for(cand))
+
+ if shape == "audio-chat":
+ text = params.get("prompt") or ""
+ body = {"model": model,
+ "messages": [{"role": "user", "content": text}]}
+ if "modalities" in allow:
+ tun["modalities"] = ["text", "audio"]
+ body["modalities"] = ["text", "audio"]
+ if "audio" in allow:
+ aud = {"voice": params.get("voice") or "alloy",
+ "format": str(cand.get("format") or "wav")}
+ tun["audio"] = aud
+ body["audio"] = aud
+ stream = bool(cand.get("stream_required")) and "stream" in allow
+ if stream:
+ tun["stream"] = True
+ body["stream"] = True
+ tun["messages"] = body["messages"]
+ return Submit("POST", f"{base}/chat/completions", body, tun, stream=stream,
+ timeout=_timeout_for(cand))
+
+ raise MediaError(f"No adapter for endpoint shape {shape!r}.")
+
+
+def build_poll(cand: dict, base_url: str, task_id: str) -> tuple[str, str]:
+ if str(cand.get("shape")) != "video-generation":
+ raise MediaError("Only the video shape is polled; every other shape answers inline.")
+ return "GET", f"{(base_url or '').rstrip('/')}/video/generations/{task_id}"
+
+
+# ── the five adapters: reading a response ─────────────────────────────────────────
+class Payload:
+ """Media that actually arrived: bytes in hand, or a URL to fetch them from."""
+
+ __slots__ = ("data", "url", "mime", "transcript")
+
+ def __init__(self, data: bytes | None = None, url: str = "", mime: str = "",
+ transcript: str = ""):
+ self.data, self.url, self.mime, self.transcript = data, url, mime, transcript
+
+
+def _b64(s: str) -> bytes:
+ try:
+ return base64.b64decode(s, validate=False)
+ except (binascii.Error, ValueError) as e:
+ raise MediaEmpty("the provider returned something that is not base64") from e
+
+
+def _data_uri(b64_or_uri: str, mime: str | None) -> str:
+ s = b64_or_uri or ""
+ return s if s.startswith("data:") else f"data:{mime or 'image/png'};base64,{s}"
+
+
+def _from_data_uri(uri: str) -> tuple[bytes, str]:
+ head, _, tail = uri.partition(",")
+ mime = head[5:].split(";")[0] if head.startswith("data:") else "application/octet-stream"
+ return _b64(tail), mime
+
+
+def read_submit(cand: dict, status: int, doc) -> tuple[str, Payload | None]:
+ """(task_id, payload) for a submit response, with every credential the provider wrote into it
+ removed. The reading is `_read_submit`; the removal is `_clean`, which is the same one rule
+ every reader here is wrapped in."""
+ return _clean(_read_submit(cand, status, doc))
+
+
+def _read_submit(cand: dict, status: int, doc) -> tuple[str, Payload | None]:
+ """(task_id, payload) for a submit response.
+
+ A shape that answers with a task id returns ("task_…", None). A synchronous shape returns
+ ("", payload). Anything else raises — and WHICH exception decides whether the candidate is
+ quarantined, so the distinction is the point:
+ MediaRefused the provider said no before any billable work started; retry is free.
+ MediaEmpty it answered 200 and returned nothing; it billed, so stand it down.
+ """
+ if status >= 400:
+ raise MediaRefused(provider_message(doc, status))
+ if not isinstance(doc, dict):
+ raise MediaRefused("the provider returned a body that is not an object")
+ shape = str(cand.get("shape") or "")
+
+ if shape == "video-generation":
+ tid = str(doc.get("task_id") or doc.get("id") or "")
+ if not tid:
+ raise MediaRefused(provider_message(doc, status) or
+ "the provider accepted the request but returned no task id")
+ return tid, None
+
+ if shape == "image-generation":
+ items = doc.get("data")
+ first = items[0] if isinstance(items, list) and items and isinstance(items[0], dict) else {}
+ if first.get("b64_json"):
+ return "", Payload(data=_b64(str(first["b64_json"])), mime="image/png")
+ if first.get("url"):
+ return "", Payload(url=str(first["url"]))
+ raise MediaEmpty("the provider answered with no image")
+
+ if shape == "openai":
+ msg = _first_message(doc)
+ images = msg.get("images")
+ if isinstance(images, list):
+ for im in images:
+ url = ((im or {}).get("image_url") or {}).get("url") if isinstance(im, dict) else ""
+ if url and str(url).startswith("data:"):
+ data, mime = _from_data_uri(str(url))
+ return "", Payload(data=data, mime=mime)
+ if url:
+ return "", Payload(url=str(url))
+ raise MediaEmpty("the provider answered with text and no image")
+
+ if shape == "gemini":
+ cands = doc.get("candidates")
+ parts = []
+ if isinstance(cands, list) and cands and isinstance(cands[0], dict):
+ parts = ((cands[0].get("content") or {}).get("parts")) or []
+ for p in parts if isinstance(parts, list) else []:
+ # The ~1 MB thoughtSignature part sits beside the picture and is not one.
+ inline = (p or {}).get("inlineData") if isinstance(p, dict) else None
+ if isinstance(inline, dict) and inline.get("data"):
+ return "", Payload(data=_b64(str(inline["data"])),
+ mime=str(inline.get("mimeType") or "image/png"))
+ raise MediaEmpty("the provider answered 200 with no image part — it billed and returned "
+ "nothing")
+
+ if shape == "audio-chat":
+ msg = _first_message(doc)
+ audio = msg.get("audio") if isinstance(msg, dict) else None
+ if isinstance(audio, dict) and audio.get("data"):
+ fmt = str(cand.get("format") or "wav")
+ return "", Payload(data=_b64(str(audio["data"])), mime=f"audio/{fmt}",
+ transcript=str(audio.get("transcript") or ""))
+ raise MediaEmpty("the provider answered with no audio")
+
+ raise MediaError(f"No adapter for endpoint shape {shape!r}.")
+
+
+def read_stream_audio(cand: dict, chunks: list[str]) -> Payload:
+ """The streamed audio, scrubbed of credentials — see `_clean`."""
+ return _clean(_read_stream_audio(cand, chunks))
+
+
+def _read_stream_audio(cand: dict, chunks: list[str]) -> Payload:
+ """gpt-audio refuses without stream:true, and then delivers its audio in deltas that have to
+ be concatenated. Both halves are the model's, not ours."""
+ b64_parts: list[str] = []
+ transcript: list[str] = []
+ for raw in chunks:
+ line = raw.strip()
+ if not line.startswith("data:"):
+ continue
+ payload = line[5:].strip()
+ if not payload or payload == "[DONE]":
+ continue
+ try:
+ ev = json.loads(payload)
+ except Exception: # noqa: BLE001 — a keepalive or a partial frame is not an error
+ continue
+ for ch in (ev.get("choices") or []):
+ delta = (ch or {}).get("delta") or {}
+ aud = delta.get("audio") or {}
+ if isinstance(aud, dict):
+ if aud.get("data"):
+ b64_parts.append(str(aud["data"]))
+ if aud.get("transcript"):
+ transcript.append(str(aud["transcript"]))
+ if not b64_parts:
+ raise MediaEmpty("the provider streamed no audio")
+ fmt = str(cand.get("format") or "wav")
+ return Payload(data=_b64("".join(b64_parts)), mime=f"audio/{fmt}",
+ transcript="".join(transcript))
+
+
+# The provider's own vocabulary for a video job, plus everything that is not terminal.
+_VIDEO_RUNNING = {"NOT_START", "SUBMITTED", "IN_PROGRESS", "QUEUED", "PROCESSING", "RUNNING"}
+
+
+def read_poll(cand: dict, status: int, doc) -> tuple[str, Payload | None, str, str]:
+ """One poll, scrubbed of credentials — see `_clean`. `progress` is as much the provider's
+ prose as `error` is, and it is written to the job vertex and served to the browser."""
+ return _clean(_read_poll(cand, status, doc))
+
+
+def _read_poll(cand: dict, status: int, doc) -> tuple[str, Payload | None, str, str]:
+ """(status, payload, error, progress) for one poll.
+
+ Four statuses and no more: running | succeeded | failed | unknown. `unknown` IS NEVER
+ TERMINAL — an empty record is the known background-response race, and reading it as failure
+ is how a finished render gets thrown away.
+ """
+ if status >= 500 or not isinstance(doc, dict) or not doc:
+ return "unknown", None, "", ""
+ data = doc.get("data")
+ if not isinstance(data, dict) or not data:
+ if status >= 400:
+ return "failed", None, provider_message(doc, status), ""
+ return "unknown", None, "", ""
+ st = str(data.get("status") or "").upper()
+ progress = str(data.get("progress") or "")
+ if st == "SUCCESS":
+ url = str(data.get("result_url") or data.get("video_url") or data.get("url") or "")
+ if url:
+ return "succeeded", Payload(url=url), "", progress
+ # SUCCESS with nothing in it is a failure. Same rule as a 200 with no payload.
+ return "failed", None, "the provider reported success and returned no video", progress
+ if st == "FAILURE":
+ return "failed", None, scrub(str(data.get("message") or data.get("error") or "")
+ or "the render failed upstream"), progress
+ if st in _VIDEO_RUNNING or not st:
+ return "running", None, "", progress
+ return "unknown", None, "", progress
+
+
+def _first_message(doc: dict) -> dict:
+ ch = doc.get("choices")
+ if isinstance(ch, list) and ch and isinstance(ch[0], dict):
+ m = ch[0].get("message")
+ if isinstance(m, dict):
+ return m
+ return {}
+
+
+# ── the provider's own words, minus the credential in them ────────────────────────
+# A 401 is the one answer guaranteed to quote the key back at you: OpenAI's is literally
+# `Incorrect API key provided: sk-…`. That sentence is relayed to a sandbox, written onto a job
+# vertex and served to a browser, so it is scrubbed HERE — where a provider's words first become
+# one of our strings — and not at those three exits. An exit added later gets it for free; a
+# scrub at each exit is three places to remember and one to forget.
+_SECRETS: set[str] = set()
+_REDACTED = "[redacted]"
+
+
+def remember_secret(value: str) -> None:
+ """A credential this process sends out, and must therefore never relay back.
+
+ Registered where the key is resolved (one place), so scrubbing is an exact replacement and not
+ only a guess at what a credential looks like. Short strings are ignored: redacting those would
+ blank ordinary words out of a diagnosis.
+ """
+ s = (value or "").strip()
+ if len(s) >= 12:
+ _SECRETS.add(s)
+
+
+_SECRET_SHAPES = (
+ # A token with a recognisable prefix and a separator: sk-…, sk_live_…, ghp_…, xoxb-….
+ # The 8-character tail is what keeps "api-version", "key-value" and "secret-manager" intact.
+ (re.compile(r"(?i)\b(?:sk|pk|rk|ak|api|apikey|key|token|tok|secret|ghp|gho|ghs|xox[abprs])"
+ r"[-_][A-Za-z0-9][A-Za-z0-9\-_.]{7,}"), _REDACTED),
+ (re.compile(r"(?i)\bAIza[0-9A-Za-z\-_]{20,}"), _REDACTED),
+ (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), _REDACTED),
+ # A bearer the provider quoted back at us, in a sentence or in a curl line.
+ (re.compile(r"(?i)\b(bearer\s+)[A-Za-z0-9\-._~+/=]{12,}"), r"\1" + _REDACTED),
+ # Credentials in a URL: the userinfo, and the query parameters that carry a signature.
+ (re.compile(r"(?<=://)[^\s/@:]+:[^\s/@]+(?=@)"), _REDACTED),
+ (re.compile(r"(?i)([?&](?:api[-_]?key|key|token|access[-_]?token|sig|signature|password|"
+ r"secret)=)[^&\s\"']+"), r"\1" + _REDACTED),
+ # Not a credential, but it names the account being billed.
+ (re.compile(r"(?i)\borg[-_][A-Za-z0-9]{6,}"), _REDACTED),
+)
+
+
+def scrub(text: str) -> str:
+ """A provider sentence with every credential in it removed, and the diagnosis left standing.
+
+ Exact first — the keys this deployment actually sends — then by shape, because a provider also
+ says other people's tokens, its own bearer and an org id out loud, and a redaction that only
+ knows our own string only ever catches the leak we already found.
+ """
+ out = str(text or "")
+ for secret in _SECRETS:
+ if secret in out:
+ out = out.replace(secret, _REDACTED)
+ for pattern, replacement in _SECRET_SHAPES:
+ out = pattern.sub(replacement, out)
+ return out
+
+
+# The two Payload fields that are NOT the provider talking. `data` is the media itself. `url` is
+# the ADDRESS the media is fetched from, and a kling or seedream result_url is signed — its query
+# string is a credential, so redacting it would lose every render and protect nobody: that URL is
+# fetched once and is never persisted or relayed (see app._media_fetch, and the test that asserts
+# the provider URL never reaches disk).
+_PAYLOAD_VERBATIM = ("data", "url")
+
+
+def _clean(value):
+ """A value we have just made our own out of a provider's document, with every credential the
+ provider wrote into it removed — ONCE, here, rather than once per field.
+
+ The first round of this scrubbed `provider_message` and the FAILURE branch of a poll. The very
+ same document then walked out through `progress`, through the provider-chosen task id and
+ through an audio transcript — each of them written to the job vertex, served to the browser and
+ handed to the agent. Scrubbing a field at a time only ever covers the leak already found, so
+ every reader in this file returns through here instead: a field added to Payload, or a fifth
+ element added to a poll's tuple, is covered without anyone remembering.
+
+ A scrubbed task id is a task id that cannot be polled, and that is the deliberate trade: an
+ identifier shaped exactly like a credential is one we cannot tell from a credential, and a
+ render that fails loudly is better than a key on disk.
+ """
+ if isinstance(value, str):
+ return scrub(value)
+ if isinstance(value, tuple):
+ return tuple(_clean(v) for v in value)
+ if isinstance(value, list):
+ return [_clean(v) for v in value]
+ if isinstance(value, Payload):
+ for name in Payload.__slots__:
+ if name not in _PAYLOAD_VERBATIM:
+ setattr(value, name, _clean(getattr(value, name)))
+ return value
+
+
+def provider_message(doc, status: int) -> str:
+ """The provider's own sentence, which is what the agent needs — never our paraphrase of it.
+ Scrubbed of credentials, which is not a paraphrase: everything that diagnoses survives."""
+ if isinstance(doc, dict):
+ for key in ("message", "error", "detail", "msg"):
+ v = doc.get(key)
+ if isinstance(v, str) and v.strip():
+ return scrub(v.strip())
+ if isinstance(v, dict):
+ for k2 in ("message", "detail", "msg"):
+ if isinstance(v.get(k2), str) and v[k2].strip():
+ return scrub(str(v[k2]).strip())
+ if isinstance(doc.get("code"), str) and doc["code"] and doc["code"] != "success":
+ return scrub(str(doc["code"]))
+ return f"the provider answered HTTP {status}"
+
+
+def usage_usd(doc) -> float | None:
+ """A cost the provider reported inline (mai-image-2.5 does). Measured, so it may be believed;
+ absent otherwise, and never estimated."""
+ if not isinstance(doc, dict):
+ return None
+ u = doc.get("usage")
+ if isinstance(u, dict) and isinstance(u.get("cost"), (int, float)):
+ return float(u["cost"])
+ return None
+
+
+# ── verifying what came back is media ─────────────────────────────────────────────
+_MAGIC = (
+ (b"\x89PNG\r\n\x1a\n", "image/png", "png"),
+ (b"\xff\xd8\xff", "image/jpeg", "jpg"),
+ (b"GIF8", "image/gif", "gif"),
+ (b"RIFF", "", ""), # wav or webp — decided below
+ (b"OggS", "audio/ogg", "ogg"),
+ (b"ID3", "audio/mpeg", "mp3"),
+ (b"\xff\xfb", "audio/mpeg", "mp3"), # a bare MPEG frame, no ID3 tag in front of it
+ (b"\x1a\x45\xdf\xa3", "video/webm", "webm"),
+)
+
+
+def sniff(data: bytes) -> tuple[str, str]:
+ """(mime, extension) FROM THE BYTES, or ("", "") when they identify nothing.
+
+ The provider's content-type is a claim, not evidence, and it is never consulted here. That is
+ the whole point: an HTML error page served as `image/png` is exactly what a hint-trusting
+ sniffer stores as a picture, and the element then reads as ready and shows nothing.
+ """
+ head = data[:16]
+ if head[4:8] == b"ftyp":
+ brand = bytes(head[8:12])
+ return ("video/quicktime", "mov") if brand.startswith(b"qt") else ("video/mp4", "mp4")
+ for magic, mime, ext in _MAGIC:
+ if not head.startswith(magic):
+ continue
+ if magic == b"RIFF":
+ tag = data[8:12]
+ if tag == b"WEBP":
+ return "image/webp", "webp"
+ if tag == b"WAVE":
+ return "audio/wav", "wav"
+ continue
+ return mime, ext
+ return "", ""
+
+
+_KIND_FAMILY = {"video": "video", "image": "image", "audio": "audio", "film": "video"}
+
+
+def verify(kind: str, data: bytes) -> dict:
+ """{mime, ext, bytes, width, height, seconds} — or MediaEmpty when this is not that media.
+
+ A body that fails verification is a FAILURE, not a success. A relay that answers 200 with an
+ HTML error page is the case this catches, and storing it would make a broken element that
+ reads as ready.
+ """
+ if not data:
+ raise MediaEmpty("the provider returned an empty file")
+ if len(data) > MAX_BYTES:
+ raise MediaEmpty(f"the provider returned {len(data)} bytes, over the {MAX_BYTES} cap")
+ mime, ext = sniff(data)
+ want = _KIND_FAMILY.get(kind, kind)
+ if not mime:
+ raise MediaEmpty(f"the provider returned {len(data)} bytes this cannot identify as a "
+ f"{want}")
+ if not mime.startswith(want + "/"):
+ raise MediaEmpty(f"the provider returned {mime} where a {want} was expected")
+ out = {"mime": mime, "ext": ext, "bytes": len(data), "width": 0, "height": 0, "seconds": 0.0}
+ if want in ("video", "audio"):
+ probed = probe(data, ext)
+ if want == "video" and not probed.get("seconds"):
+ # A video whose duration cannot be read cannot be cut, timed or summed. Refusing is
+ # the honest answer; a zero-length shot in a timeline is not.
+ if have_ffmpeg():
+ raise MediaEmpty("the file came back unreadable — no duration in it")
+ out.update({k: v for k, v in probed.items() if v})
+ return out
+
+
+# ── ffmpeg: probing, and assembling a film ────────────────────────────────────────
[email protected]_cache(maxsize=1)
+def have_ffmpeg() -> bool:
+ """Both binaries or neither. Checked once at first use, so a deployment built without them
+ reports export unavailable rather than failing at the end of a four-minute render."""
+ return bool(shutil.which("ffmpeg") and shutil.which("ffprobe"))
+
+
+def _run(cmd: list[str], timeout: float) -> subprocess.CompletedProcess:
+ return subprocess.run(cmd, capture_output=True, timeout=timeout, check=False)
+
+
+def probe_file(path: str) -> dict:
+ """{seconds, width, height, has_audio} for a file on disk, or {} when it cannot be read."""
+ if not have_ffmpeg():
+ return {}
+ p = _run(["ffprobe", "-v", "error", "-print_format", "json", "-show_format", "-show_streams",
+ path], timeout=60)
+ if p.returncode != 0:
+ return {}
+ try:
+ doc = json.loads(p.stdout or b"{}")
+ except Exception: # noqa: BLE001
+ return {}
+ streams = doc.get("streams") or []
+ vid = next((s for s in streams if s.get("codec_type") == "video"), None)
+ aud = next((s for s in streams if s.get("codec_type") == "audio"), None)
+ dur = 0.0
+ for src in ((doc.get("format") or {}).get("duration"), (vid or {}).get("duration"),
+ (aud or {}).get("duration")):
+ try:
+ dur = float(src)
+ except (TypeError, ValueError):
+ continue
+ if dur > 0:
+ break
+ return {"seconds": round(dur, 3), "width": int((vid or {}).get("width") or 0),
+ "height": int((vid or {}).get("height") or 0), "has_audio": aud is not None}
+
+
+def probe(data: bytes, ext: str = "bin") -> dict:
+ with tempfile.NamedTemporaryFile(suffix=f".{ext or 'bin'}", delete=False) as f:
+ f.write(data)
+ path = f.name
+ try:
+ return probe_file(path)
+ finally:
+ with contextlib.suppress(OSError):
+ os.unlink(path)
+
+
+class ExportRefused(MediaError):
+ """The film cannot be assembled, and the sentence says what would fix it."""
+
+
+def assemble(shots: list[dict], audio: list[dict], *, fps: int, resolution: str,
+ out_path: str, on_progress=None) -> dict:
+ """Cut the shots together into one file. Returns {seconds, width, height, bytes}.
+
+ LETTERBOX, NEVER STRETCH. Every shot is scaled to fit inside the timeline's own declared
+ resolution and padded to it — not resized to whatever the first clip happened to be, which
+ distorts an entire film because one shot was shot in portrait.
+
+ THEN THE OUTPUT IS PROBED AND ITS DURATION COMPARED WITH THE PLAN. A mismatch fails the job
+ and reports both numbers. An assembled duration nobody checks is an assembled duration nobody
+ notices is wrong.
+ """
+ if not have_ffmpeg():
+ raise ExportRefused("This deployment cannot assemble video — ffmpeg is not installed. "
+ "The clips are all still here to download individually.")
+ if not shots:
+ raise ExportRefused("There is nothing in the timeline to export.")
+ W, H = parse_size(resolution)
+ if not W or not H:
+ raise ExportRefused(f"{resolution!r} is not a resolution this can render.")
+
+ inputs: list[str] = []
+ filters: list[str] = []
+ concat_in = ""
+ planned = 0.0
+ for i, shot in enumerate(shots):
+ path = shot["path"]
+ info = probe_file(path)
+ dur = float(info.get("seconds") or 0.0)
+ start = max(0.0, float(shot.get("in_s") or 0.0))
+ end = float(shot.get("out_s") or dur or 0.0) or dur
+ end = min(end, dur) if dur else end
+ if end <= start:
+ raise ExportRefused(f"Shot {i + 1} has no length between {start}s and {end}s.")
+ planned += end - start
+ if start:
+ inputs += ["-ss", f"{start:.3f}"]
+ inputs += ["-to", f"{end:.3f}", "-i", path]
+ filters.append(
+ f"[{i}:v]scale={W}:{H}:force_original_aspect_ratio=decrease,"
+ f"pad={W}:{H}:(ow-iw)/2:(oh-ih)/2:color=black,fps={fps},setsar=1,format=yuv420p[v{i}]")
+ if info.get("has_audio"):
+ filters.append(f"[{i}:a]aresample=async=1:first_pts=0,asetpts=PTS-STARTPTS[a{i}]")
+ else:
+ # A shot with no audio contributes silence of its exact length, so the concat's audio
+ # and video streams stay the same length and nothing drifts.
+ filters.append(f"anullsrc=r=48000:cl=stereo,atrim=0:{end - start:.3f},"
+ f"asetpts=PTS-STARTPTS[a{i}]")
+ concat_in += f"[v{i}][a{i}]"
+ if on_progress:
+ on_progress(i, len(shots))
+
+ filters.append(f"{concat_in}concat=n={len(shots)}:v=1:a=1[vout][acat]")
+ last_audio = "acat"
+ if audio:
+ mix_in = "[acat]"
+ for j, tr in enumerate(audio):
+ k = len(shots) + j
+ inputs += ["-i", tr["path"]]
+ delay = int(max(0.0, float(tr.get("start_s") or 0.0)) * 1000)
+ gain = float(tr.get("gain_db") or 0.0)
+ filters.append(f"[{k}:a]adelay={delay}|{delay},volume={gain}dB[m{j}]")
+ mix_in += f"[m{j}]"
+ filters.append(f"{mix_in}amix=inputs={len(audio) + 1}:duration=first:"
+ f"dropout_transition=0,alimiter=limit=0.95[aout]")
+ last_audio = "aout"
+
+ cmd = (["ffmpeg", "-nostdin", "-y"] + inputs +
+ ["-filter_complex", ";".join(filters), "-map", "[vout]", "-map", f"[{last_audio}]",
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", out_path])
+ p = _run(cmd, timeout=float(os.environ.get("HR_MEDIA_EXPORT_TIMEOUT_S", "1800")))
+ if p.returncode != 0 or not os.path.exists(out_path) or not os.path.getsize(out_path):
+ tail = (p.stderr or b"").decode("utf-8", "replace").strip().splitlines()[-3:]
+ raise ExportRefused("The assembly failed: " + (" ".join(tail) or "ffmpeg produced nothing"))
+
+ got = probe_file(out_path)
+ actual = float(got.get("seconds") or 0.0)
+ if abs(actual - planned) > 0.5:
+ raise ExportRefused(
+ f"The assembled film is {actual:.2f}s but the timeline plans {planned:.2f}s. "
+ f"Nothing was delivered — a film that is not the length it was cut to is not the film.")
+ return {"seconds": round(actual, 3), "width": int(got.get("width") or W),
+ "height": int(got.get("height") or H), "bytes": os.path.getsize(out_path),
+ "planned_seconds": round(planned, 3)}
+
+
+# ── the canvas: an Excalidraw scene we construct, never one an agent writes ───────
+# The agent gets narrow tools (place, move, arrange, remove) and those produce valid elements.
+# A large schema an agent writes freehand is a schema an agent gets wrong.
+SCENE_SOURCE = "harnessrouter/kits/media"
+
+# Default tile geometry. A 16:9 card wide enough to read a caption under.
+TILE_W, TILE_H, GUTTER = 480, 270, 24
+CAPTION_H = 24
+
+
+def new_scene(title: str = "") -> dict:
+ return {"type": "excalidraw", "version": 2, "source": SCENE_SOURCE,
+ "elements": [], "appState": {"viewBackgroundColor": "#ffffff", "gridSize": None},
+ "files": {},
+ "timeline": {"v": 1, "fps": 30, "resolution": "1920x1080", "shots": [], "audio": [],
+ "updatedAt": int(time.time() * 1000)},
+ "meta": {"title": title, "rev": 0}}
+
+
+def _eid() -> str:
+ return "el_" + uuid.uuid4().hex[:16]
+
+
+def _seed() -> int:
+ return int(uuid.uuid4().int % 2_000_000_000) + 1
+
+
+def _base_element(kind: str, x: float, y: float, w: float, h: float) -> dict:
+ now = int(time.time() * 1000)
+ return {"id": _eid(), "type": kind, "x": float(x), "y": float(y),
+ "width": float(w), "height": float(h), "angle": 0,
+ "strokeColor": "#1e1e1e", "backgroundColor": "transparent", "fillStyle": "solid",
+ "strokeWidth": 1, "strokeStyle": "solid", "roughness": 0, "opacity": 100,
+ "groupIds": [], "frameId": None, "roundness": None, "seed": _seed(),
+ "version": 1, "versionNonce": _seed(), "isDeleted": False,
+ "boundElements": None, "updated": now, "link": None, "locked": False}
+
+
+def media_element(kind: str, *, x: float, y: float, w: float = TILE_W, h: float = TILE_H,
+ media_id: str = "", job_id: str = "", status: str = "running",
+ model: str = "", cap: str = "", seconds: float = 0.0,
+ width: int = 0, height: int = 0, prompt: str = "", label: str = "",
+ media_url: str = "") -> dict:
+ """One element per clip, and one only.
+
+ Two elements per clip — a backing rectangle plus a captured frame with a hand-drawn play
+ triangle — doubles every move, every remove and every selection, and the two halves
+ desynchronise. A video is an `embeddable` the app renders itself; an image is an `image`
+ element whose file entry points at the same media.
+
+ NO PROVIDER URL IS EVER STORED. It expires; our copy does not. `link` is this gateway's own
+ media path, derived from the media id, so moving the deployment does not strand a scene.
+ """
+ el = _base_element("image" if kind == "image" else "embeddable", x, y, w, h)
+ el["customData"] = {"media": {
+ "v": 1, "kind": kind, "status": status, "jobId": job_id or None,
+ "mediaId": media_id or None, "posterMediaId": None,
+ "model": model or None, "capability": cap or None,
+ "seconds": float(seconds) or None, "width": int(width) or None,
+ "height": int(height) or None, "prompt": prompt or None, "label": label or None,
+ "createdAt": int(time.time() * 1000)}}
+ if kind == "image":
+ el.update({"status": "saved" if media_id else "pending",
+ "fileId": media_id or None, "scale": [1, 1], "crop": None})
+ else:
+ el["link"] = media_url or None
+ return el
+
+
+def text_element(text: str, *, x: float, y: float, w: float = TILE_W,
+ h: float = CAPTION_H) -> dict:
+ el = _base_element("text", x, y, w, h)
+ el.update({"text": text, "originalText": text, "fontSize": 16, "fontFamily": 5,
+ "textAlign": "left", "verticalAlign": "top", "containerId": None,
+ "lineHeight": 1.25, "autoResize": True, "strokeColor": "#1e1e1e"})
+ return el
+
+
+def file_entry(media_id: str, mime: str, url: str) -> dict:
+ """An Excalidraw files[] entry whose dataURL is a same-origin PATH rather than a data URI.
+
+ Verified: Excalidraw accepts a plain URL there. That is what keeps a ten-image board a few
+ kilobytes of document instead of forty megabytes of base64.
+ """
+ return {"id": media_id, "mimeType": mime or "image/png", "dataURL": url,
+ "created": int(time.time() * 1000), "lastRetrieved": int(time.time() * 1000)}
+
+
+def is_media(el: dict) -> bool:
+ return bool(((el or {}).get("customData") or {}).get("media"))
+
+
+def media_of(el: dict) -> dict:
+ return ((el or {}).get("customData") or {}).get("media") or {}
+
+
+def element_summary(el: dict) -> dict:
+ """What describe_canvas says about one element. Never raw scene JSON — the agent has no use
+ for `versionNonce` and every use for "Shot 2 is still rendering"."""
+ m = media_of(el)
+ kind = str(m.get("kind") or ("text" if el.get("type") == "text"
+ else "frame" if el.get("type") == "frame" else "shape"))
+ out = {"id": el.get("id"), "kind": kind,
+ "x": round(float(el.get("x") or 0), 1), "y": round(float(el.get("y") or 0), 1),
+ "w": round(float(el.get("width") or 0), 1), "h": round(float(el.get("height") or 0), 1)}
+ if el.get("type") == "text":
+ out["label"] = el.get("text") or ""
+ if m:
+ out["status"] = m.get("status")
+ for src, dst in (("label", "label"), ("seconds", "seconds"), ("model", "model"),
+ ("jobId", "job_id"), ("mediaId", "media_id")):
+ if m.get(src):
+ out[dst] = m[src]
+ if el.get("type") == "frame":
+ # Nothing here builds a frame; a person drawing one in the app is why this branch exists.
+ out["label"] = el.get("name") or ""
+ return out
+
+
+def next_free(elements: list[dict], columns: int = 4) -> tuple[float, float]:
+ """Where the next `place` with no coordinates lands. Returned by describe_canvas so the agent
+ can reason about layout without doing arithmetic and without guessing.
+
+ Packing is driven by the MEDIA TILES and nothing else. A caption sits under its clip, so
+ counting it as an occupant puts the next clip level with the caption instead of level with the
+ clip — a board that drifts down and to the right one shot at a time.
+ """
+ tiles = [e for e in elements if not e.get("isDeleted") and is_media(e)]
+ if not tiles:
+ return 40.0, 40.0
+ row_y = max(float(e.get("y") or 0) for e in tiles)
+ same_row = [e for e in tiles if abs(float(e.get("y") or 0) - row_y) < 1.0]
+ if len(same_row) >= columns:
+ # The row is full: drop below everything on the canvas, captions included, so the new row
+ # does not land on top of the last row's text.
+ live = [e for e in elements if not e.get("isDeleted")]
+ bottom = max(float(e.get("y") or 0) + float(e.get("height") or 0) for e in live)
+ return 40.0, bottom + GUTTER * 2
+ right = max(float(e.get("x") or 0) + float(e.get("width") or 0) for e in same_row)
+ return right + GUTTER, row_y
+
+
+def storyboard_items(els: list[dict], chosen: list[dict]) -> list[dict]:
+ """Group a flat element list into shots: each media element, then the elements PLACED WITH IT.
+
+ A media element's companions are the ones that follow it in document order until the next
+ media element, sharing its shot — because `place` appends a caption directly after the media
+ it captions, so document order already binds them and no new field is needed.
+
+ Selecting "every element with the same shot name" instead makes each element a child of every
+ clip in that shot, so a shot holding a still AND a clip emits every element twice and the
+ board is laid out on top of itself.
+ """
+ index = {id(e): i for i, e in enumerate(els)}
+ items: list[dict] = []
+ for e in chosen:
+ item = {"id": e.get("id"), "w": float(e.get("width") or TILE_W),
+ "h": float(e.get("height") or TILE_H)}
+ shot = (e.get("customData") or {}).get("shot")
+ kids: list[dict] = []
+ start = index.get(id(e))
+ if start is not None and shot:
+ for c in els[start + 1:]:
+ if is_media(c) or (c.get("customData") or {}).get("shot") != shot:
+ break # the next clip owns what follows it
+ kids.append({"id": c.get("id"), "w": float(c.get("width") or TILE_W),
+ "h": float(c.get("height") or CAPTION_H)})
+ item["children"] = kids
+ items.append(item)
+ return items
+
+
+def layout_positions(items: list[dict], layout: str, *, columns: int = 4, gutter: int = GUTTER,
+ origin: tuple[float, float] = (40.0, 40.0)) -> list[dict]:
+ """The row-packing every storyboard wants, on the server where the agent can ask for it.
+
+ `storyboard` is one row per shot — clip, then its caption, then its audio chip — because that
+ is what a person reads down a page, and computing it in a browser strands it there.
+ """
+ ox, oy = origin
+ out: list[dict] = []
+ if layout == "row":
+ x = ox
+ for it in items:
+ out.append({"element_id": it["id"], "x": x, "y": oy,
+ "w": it["w"], "h": it["h"]})
+ x += it["w"] + gutter
+ return out
+ if layout == "column":
+ y = oy
+ for it in items:
+ out.append({"element_id": it["id"], "x": ox, "y": y, "w": it["w"], "h": it["h"]})
+ y += it["h"] + gutter
+ return out
+ if layout == "storyboard":
+ y = oy
+ for it in items:
+ for band in [it] + list(it.get("children") or []):
+ out.append({"element_id": band["id"], "x": ox, "y": y,
+ "w": band["w"], "h": band["h"]})
+ y += band["h"] + gutter // 3
+ y += gutter * 2 # the gap between one shot and the next
+ return out
+ cols = max(1, int(columns))
+ col_w = max((it["w"] for it in items), default=TILE_W)
+ row_h = max((it["h"] for it in items), default=TILE_H)
+ for i, it in enumerate(items):
+ out.append({"element_id": it["id"],
+ "x": ox + (i % cols) * (col_w + gutter),
+ "y": oy + (i // cols) * (row_h + gutter),
+ "w": it["w"], "h": it["h"]})
+ return out
+
+
+def scene_bounds(elements: list[dict]) -> dict:
+ live = [e for e in elements if not e.get("isDeleted")]
+ if not live:
+ return {"x": 0, "y": 0, "w": 0, "h": 0}
+ xs = [float(e.get("x") or 0) for e in live]
+ ys = [float(e.get("y") or 0) for e in live]
+ x2 = [float(e.get("x") or 0) + float(e.get("width") or 0) for e in live]
+ y2 = [float(e.get("y") or 0) + float(e.get("height") or 0) for e in live]
+ return {"x": round(min(xs), 1), "y": round(min(ys), 1),
+ "w": round(max(x2) - min(xs), 1), "h": round(max(y2) - min(ys), 1)}
+
+
+def sanitize_scene(doc) -> dict:
+ """A document we will store, whatever a client sent.
+
+ `appState.collaborators` is a Map in the component and `{}` after a JSON round trip, and
+ Excalidraw crashes calling `.forEach` on it. Stripping it is not tidiness; it is the
+ difference between a canvas that opens and one that does not.
+ """
+ if not isinstance(doc, dict):
+ return new_scene()
+ out = dict(doc)
+ out.setdefault("type", "excalidraw")
+ out.setdefault("version", 2)
+ out.setdefault("source", SCENE_SOURCE)
+ els = out.get("elements")
+ out["elements"] = [e for e in els if isinstance(e, dict)] if isinstance(els, list) else []
+ st = out.get("appState")
+ st = dict(st) if isinstance(st, dict) else {}
+ st.pop("collaborators", None)
+ out["appState"] = st
+ out["files"] = out.get("files") if isinstance(out.get("files"), dict) else {}
+ tl = out.get("timeline")
+ out["timeline"] = tl if isinstance(tl, dict) else {"v": 1, "fps": 30,
+ "resolution": "1920x1080",
+ "shots": [], "audio": []}
+ meta = out.get("meta")
+ out["meta"] = meta if isinstance(meta, dict) else {"title": "", "rev": 0}
+ return out
+
+
+def timeline_total(scene: dict, ready_only: bool = False) -> float:
+ """Summed from the clips' REAL measured durations, never from the seconds someone asked for."""
+ by_id = {e.get("id"): e for e in scene.get("elements") or []}
+ total = 0.0
+ for shot in (scene.get("timeline") or {}).get("shots") or []:
+ el = by_id.get(shot.get("elementId")) or {}
+ m = media_of(el)
+ if ready_only and m.get("status") != "ready":
+ continue
+ dur = float(m.get("seconds") or 0.0)
+ a = float(shot.get("inS") or 0.0)
+ b = float(shot.get("outS") or dur or 0.0) or dur
+ total += max(0.0, min(b, dur or b) - a)
+ return round(total, 3)
+
+
+def levenshtein_ratio(a: str, b: str) -> float:
+ """How close what the model SAID is to what it was asked to say. Real data both sides — the
+ provider returns its own transcript, so `verbatim` is measured rather than assumed."""
+ a, b = re.sub(r"\W+", " ", (a or "").lower()).strip(), re.sub(r"\W+", " ", (b or "").lower()).strip()
+ if not a and not b:
+ return 1.0
+ if not a or not b:
+ return 0.0
+ prev = list(range(len(b) + 1))
+ for i, ca in enumerate(a, 1):
+ cur = [i]
+ for j, cb in enumerate(b, 1):
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
+ prev = cur
+ return 1.0 - prev[-1] / max(len(a), len(b))
+
+
+async def to_thread(fn, *a, **kw):
+ """Run a blocking ffmpeg/ffprobe call off the event loop. One helper, so no call site has to
+ remember that assembling a film blocks for minutes."""
+ return await asyncio.get_running_loop().run_in_executor(None, functools.partial(fn, *a, **kw))
diff --git a/gateway/tests/test_database_mcp.py b/gateway/tests/test_database_mcp.py
index 071077d1..49fa9645 100644
--- a/gateway/tests/test_database_mcp.py
+++ b/gateway/tests/test_database_mcp.py
@@ -173,6 +173,15 @@ def _record(hid: str) -> dict | None:
return asyncio.run(app._hosted_record(ORG, _key(hid)))
+def _secrets_root() -> Path:
+ """Where the running process's secret store actually is.
+
+ Read off the store rather than rebuilt from this module's own temp dir: `app` is imported once
+ per process, so whichever test module got there first decided HR_DATA_DIR — and an assertion
+ about "what is on disk" that looks in an empty directory passes for the wrong reason."""
+ return Path(app.BACKING.secrets._root)
+
+
def _save_config(api, hid: str, servers: list[dict], name="Dashboard"):
"""What the console does when someone presses Save: a whole-config PUT."""
return api.put(f"/v1/harnesses/{hid}",
@@ -243,7 +252,7 @@ def test_the_entry_carries_a_reference_and_not_a_connection_string(api, kit, har
def test_the_whole_connection_record_is_encrypted_on_disk(api, kit):
hid = _attach(api, kit)["harnessId"]
- files = list(Path(_DATA, "secrets").rglob(_key(hid)))
+ files = list(_secrets_root().rglob(_key(hid)))
assert files, "the record was not written to the secret store"
raw = files[0].read_text()
assert raw.startswith("hrenc1:")
@@ -329,7 +338,7 @@ def test_renaming_an_entry_is_not_a_removal(api, connected):
def test_deleting_the_harness_does_not_leave_the_credential_behind(api, connected):
"""The most decisive thing the UI offers must not leave a production password on disk."""
key = _key(connected)
- stored = next(iter(Path(_DATA, "secrets").rglob(key)))
+ stored = next(iter(_secrets_root().rglob(key)))
assert PG_DSN == (_record(connected) or {})["dsn"]
assert api.delete(f"/v1/harnesses/{connected}").json()["deleted"] is True
diff --git a/gateway/tests/test_media_attack.py b/gateway/tests/test_media_attack.py
new file mode 100644
index 00000000..b7221467
--- /dev/null
+++ b/gateway/tests/test_media_attack.py
@@ -0,0 +1,787 @@
+"""ADVERSARIAL REGRESSIONS for the media plane. Every test here is written so that PASSING means
+the attack was repelled; a failure is a finding.
+
+Three properties are held here, each of which was once false and each of which a narrow patch to
+the function a finding NAMED left open in the function beside it:
+
+ ONE TOOL CALL, AT MOST `_MEDIA_MAX_ADVANCES + 1` BILLABLE RENDERS. Two walks fall down the
+ chain — the SUBMIT walk in `_media_chain` and the POLL walk in `_media_job_billable_failure` —
+ and they share one budget, because "this request may buy one more render" is a fact about the
+ request and not about which of the two happened to notice.
+
+ A PROVIDER'S DOCUMENT IS SCRUBBED WHERE IT BECOMES OUR DATA. Not on the error channel only: the
+ poll's `progress`, the provider-chosen task id and an audio transcript are the same document,
+ one field over, and all three are persisted and relayed.
+
+ THIS SERVER FETCHES ONLY AN ADDRESS IT HAS CLASSIFIED. A name it could not resolve — because it
+ does not exist, or because the lookup did not answer — is not classified, and every poll is a
+ fresh roll of that dice.
+
+Zero generation endpoints are touched: every provider byte goes through httpx.MockTransport, the
+same seam tests/test_media_mcp.py uses. Nothing here spends anything.
+"""
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+import os
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+import httpx
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+# Set BEFORE importing app: the backing, the internal key and the encryption passphrase are all
+# read at import time, exactly as they are in a running container.
+_DATA = tempfile.mkdtemp(prefix="hr-mediaattack-")
+os.environ.update({
+ "HR_BACKING": "local", "HR_DATA_DIR": _DATA,
+ "HARNESS_WORKSPACE": os.path.join(_DATA, "workspaces"),
+ "HR_SECRET_KEY": "test-passphrase-not-a-real-one",
+ "HARNESS_INTERNAL_KEY": "test-internal-key",
+ "HARNESS_GLOBAL_TENANT": "global",
+ "HARNESS_PUBLIC_BASE_URL": "https://gateway.example",
+ "HR_POOL_AUTH": "none",
+ "HR_IDENTITY_MODE": "off",
+ "HR_MEDIA_SWEEP_S": "3600",
+})
+
+import app # noqa: E402
+import media_plane # noqa: E402
+from fastapi.testclient import TestClient # noqa: E402
+
+# The sweep interval is read when app is imported, and this file is not necessarily the module
+# that imported it. Set it directly, so the background sweeper cannot race an assertion about how
+# many renders one tool call bought.
+app._MEDIA_SWEEP_EVERY_S = 3600
+
+# The data root the app ACTUALLY writes to, which is the one `_disk_hits` has to walk. It is this
+# module's temp dir only when this module imported app first; when another test module did, the
+# env above arrived too late and a scan of it would find nothing and prove nothing.
+_DATA_ROOT = str(Path(getattr(app.BACKING.graph, "_path", os.path.join(_DATA, "graph.db"))).parent)
+
+# The sentinel. Every "the key never comes out" assertion is about this exact string.
+PROVIDER_KEY = "sk-tr-SENTINEL-do-not-leak-4f7a9b21"
+ORG = "testorg"
+HEADERS = {"x-harness-internal": "test-internal-key", "x-harness-org": ORG,
+ "x-harness-member": "[email protected]"}
+ENTRY_ID = "mcp.media"
+TR = "https://api.tokenrouter.com/v1"
+
+PNG_1PX = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")
+
+_KIT = {"id": "media", "title": "Videos", "app": {"route": "/kits/media"},
+ "harness": {"name": "Videos", "mcp_servers": [],
+ "launch": {"media": {"name": "media", "id": ENTRY_ID}},
+ "recommended": [{"base": "claude-code", "model": "claude-opus-5"}]}}
+
+needs_ffmpeg = pytest.mark.skipif(not media_plane.have_ffmpeg(), reason="no ffmpeg on this box")
+
+
+def _mp4(seconds: float = 1.0, size: str = "128x72") -> bytes:
+ """A real, tiny mp4: the gateway refuses a video it cannot measure, so a four-byte stub would
+ pass a test the product fails."""
+ with tempfile.TemporaryDirectory() as d:
+ out = os.path.join(d, "c.mp4")
+ subprocess.run(["ffmpeg", "-nostdin", "-y", "-f", "lavfi",
+ "-i", f"color=c=blue:s={size}:d={seconds}", "-f", "lavfi",
+ "-i", f"anullsrc=r=44100:cl=stereo:d={seconds}",
+ "-shortest", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac",
+ "-t", str(seconds), out], capture_output=True, check=True)
+ return Path(out).read_bytes()
+
+
+def _wav() -> bytes:
+ return (b"RIFF" + (36 + 8).to_bytes(4, "little") + b"WAVEfmt "
+ + (16).to_bytes(4, "little") + (1).to_bytes(2, "little") + (1).to_bytes(2, "little")
+ + (8000).to_bytes(4, "little") + (16000).to_bytes(4, "little")
+ + (2).to_bytes(2, "little") + (16).to_bytes(2, "little")
+ + b"data" + (8).to_bytes(4, "little") + b"\x00" * 8)
+
+
+# ── a hostile provider ────────────────────────────────────────────────────────────────────────
+class Hostile:
+ """A relay that behaves like a real one until told to misbehave. Records every outbound
+ request INCLUDING its Authorization header, which is the thing under test."""
+
+ def __init__(self):
+ self.calls: list[dict] = []
+ self.submit_error: tuple[int, dict] | None = None
+ self.poll_answer = None
+ self.task_id_override: str | None = None
+ self.result_url = "https://cdn.provider.example/out.mp4"
+ self.video_bytes = b""
+ self.tasks: dict[str, str] = {}
+
+ def handle(self, req: httpx.Request) -> httpx.Response:
+ body = json.loads(req.content or b"{}") if req.content else {}
+ self.calls.append({"method": req.method, "url": str(req.url), "body": body,
+ "auth": req.headers.get("authorization", ""),
+ "host": req.url.host})
+ url = str(req.url)
+
+ if url.endswith("/video/generations") and req.method == "POST":
+ if self.submit_error:
+ return httpx.Response(self.submit_error[0], json=self.submit_error[1])
+ tid = self.task_id_override or f"task_{len(self.tasks) + 1}"
+ self.tasks[tid] = body.get("model") or ""
+ return httpx.Response(200, json={"id": tid, "task_id": tid, "object": "video",
+ "model": body.get("model"), "status": "queued"})
+
+ if "/video/generations/" in url and req.method == "GET":
+ if self.poll_answer is not None:
+ return self.poll_answer
+ tid = url.rsplit("/", 1)[-1]
+ return httpx.Response(200, json={"code": "success", "message": "", "data": {
+ "id": tid, "task_id": tid, "platform": "mock", "status": "SUCCESS",
+ "result_url": self.result_url}})
+
+ if url.endswith("/images/generations"):
+ if self.submit_error:
+ return httpx.Response(self.submit_error[0], json=self.submit_error[1])
+ return httpx.Response(200, json={"created": 1, "data": [
+ {"b64_json": base64.b64encode(PNG_1PX).decode()}]})
+
+ if ":generateContent" in url:
+ if self.submit_error:
+ return httpx.Response(self.submit_error[0], json=self.submit_error[1])
+ return httpx.Response(200, json={"candidates": [{"content": {"parts": [
+ {"inlineData": {"mimeType": "image/png",
+ "data": base64.b64encode(PNG_1PX).decode()}}]}}]})
+
+ if url.endswith("/chat/completions"):
+ if self.submit_error:
+ return httpx.Response(self.submit_error[0], json=self.submit_error[1])
+ return httpx.Response(200, json={"choices": [{"message": {"content": None, "images": [
+ {"image_url": {"url": "data:image/png;base64,"
+ + base64.b64encode(PNG_1PX).decode()}}]}}]})
+
+ if url.startswith("https://cdn.provider.example/"):
+ data = self.video_bytes or PNG_1PX
+ return httpx.Response(200, content=data, headers={
+ "content-type": "video/mp4" if url.endswith(".mp4") else "image/png"})
+
+ # ANY other host — this is where an exfiltrated credential would land.
+ return httpx.Response(200, content=PNG_1PX, headers={"content-type": "image/png"})
+
+
+def hostile(monkeypatch):
+ h = Hostile()
+ cl = httpx.AsyncClient(transport=httpx.MockTransport(lambda r: h.handle(r)), timeout=30)
+ monkeypatch.setattr(app, "_media_client", lambda: cl)
+ app._media_quarantine.clear()
+ yield h
+ asyncio.run(cl.aclose())
+
+
[email protected](autouse=True)
+def resolvable_cdn(monkeypatch):
+ """The mock provider's CDN lives on a `.example` name, and `.example` resolves nowhere. This
+ server will not fetch a file from an address it could not classify, so the fake CDN has to
+ resolve the way a real one does — otherwise every landing test would be quietly asserting the
+ refusal instead of the thing it was written for.
+
+ Only `.example` is answered. Everything else falls through to the real resolver, which is what
+ lets the DNS tests below say "this name does not exist" and mean it.
+ """
+ real = socket.getaddrinfo
+
+ def fake(host, port, *a, **kw):
+ if str(host).endswith(".example"):
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "",
+ ("93.184.216.34", int(port or 443)))]
+ return real(host, port, *a, **kw)
+
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+
+
[email protected](scope="module")
+def client():
+ with TestClient(app.app) as c:
+ yield c
+
+
+def _connect_provider(key: str = PROVIDER_KEY) -> None:
+ asyncio.run(app._vault_put(app.GLOBAL_TENANT, app._INTEGRATIONS_KEY, json.dumps(
+ [{"name": "tr", "provider": "tokenrouter",
+ "config": {"api_key": key, "base_url": TR}}])))
+
+
[email protected](scope="module", autouse=True)
+def integration(client):
+ _connect_provider()
+ app.BACKING.workspace = app.backing.LocalWorkspaceFiles(os.path.join(_DATA, "workspaces"))
+ return True
+
+
+def kit(monkeypatch):
+ kid = f"mediaatk{int(time.time() * 1e6) % 10_000_000}"
+ monkeypatch.setattr(app, "_kits", lambda: {kid: {**_KIT, "id": kid}})
+ return kid
+
+
+# ── helpers ───────────────────────────────────────────────────────────────────────────────────
+def _launch(client, kit) -> str:
+ r = client.post(f"/v1/kits/{kit}/launch", json={}, headers=HEADERS)
+ assert r.status_code == 200, r.text
+ return r.json()["harnessId"]
+
+
+def _session(hid: str, org: str = ORG) -> str:
+ """A session vertex exactly as the session-create path writes one — `harness_id` and all. The
+ field name matters: the whole harness/session bind keys on it."""
+ sid = "sess_" + os.urandom(6).hex()
+ asyncio.run(app._vg_upsert("HarnessSession", sid,
+ {"tenant": org, "status": "idle", "turn_status": "idle",
+ "harness_id": hid}))
+ return sid
+
+
+def _stored(hid: str) -> list:
+ return json.loads(asyncio.run(
+ app.BACKING.graph.get(hid, label="Harness")).get("mcp_servers") or "[]")
+
+
+def _cred(hid: str, sid: str = "") -> str:
+ key = app._vault_key(next(s for s in _stored(hid) if s.get("id") == ENTRY_ID)["auth"])
+ return app._mint_hosted_cred(hid, sid, key)
+
+
+def _call(client, tok, name, args=None) -> dict:
+ r = client.post("/v1/mcp/media", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": name, "arguments": args or {}}},
+ headers={"authorization": f"Bearer {tok}"})
+ assert r.status_code == 200, r.text
+ return r.json()["result"]
+
+
+def _text(res: dict) -> str:
+ return res["content"][0]["text"]
+
+
+def _ok(res: dict) -> dict:
+ assert res.get("isError") is not True, _text(res)
+ return json.loads(_text(res))
+
+
+def _due(jid: str) -> None:
+ """Make a job due for the sweeper right now. Without this every _media_sweep() is a no-op
+ (next_poll_at is 20 s out) and every assertion after it is vacuous."""
+ job = asyncio.run(app._media_job_get(jid))
+ job["next_poll_at"] = 0
+ asyncio.run(app._media_job_save(job))
+
+
+def _sweep(jid: str | None = None) -> int:
+ if jid:
+ _due(jid)
+ return asyncio.run(app._media_sweep())
+
+
+def _vertex(jid: str) -> dict:
+ return asyncio.run(app.BACKING.graph.get(jid, label="MediaJob")) or {}
+
+
+def _disk_hits(needle: str) -> list[str]:
+ """Every file under the data root holding `needle` in the clear, minus the secret store (which
+ is allowed to — that is where the credential legitimately lives)."""
+ out = []
+ for p in Path(_DATA_ROOT).rglob("*"):
+ if not p.is_file() or p.stat().st_size > 8_000_000:
+ continue
+ try:
+ if needle in p.read_text(errors="ignore"):
+ if "/secrets/" in str(p) or "secret" in p.name:
+ continue
+ out.append(str(p))
+ except Exception: # noqa: BLE001
+ pass
+ return out
+
+
+def _assert_clean(needle, label, tool, vertex, browser):
+ bad = []
+ for where, hay in (("SANDBOX (tool result)", tool), ("VERTEX (durable)", vertex),
+ ("BROWSER (HTTP body)", browser)):
+ if needle in hay:
+ bad.append(f"{where}: …{hay[max(0, hay.find(needle) - 120):][:260]}")
+ bad += [f"DISK: {f}" for f in _disk_hits(needle)]
+ assert not bad, f"[{label}] the credential reached:\n" + "\n".join(bad)
+
+
+def _count_submits(hostile) -> list[str]:
+ """Every BILLABLE submit this test causes. Installed OUTSIDE any other handler override, so it
+ sees the ones an override answers too."""
+ submits: list[str] = []
+ real = hostile.handle
+
+ def counting(req):
+ u = str(req.url)
+ if req.method == "POST" and (u.endswith("/video/generations")
+ or u.endswith("/images/generations")
+ or u.endswith("/chat/completions")
+ or ":generateContent" in u):
+ try:
+ body = json.loads(req.content or b"{}")
+ except Exception: # noqa: BLE001
+ body = {}
+ submits.append(str(body.get("model") or u.rsplit("/", 2)[-2]))
+ return real(req)
+
+ hostile.handle = counting
+ return submits
+
+
+def _drive_to_terminal(jid: str) -> dict:
+ for _ in range(20):
+ job = asyncio.run(app._media_job_get(jid))
+ if job["status"] != "running":
+ return job
+ _sweep(jid)
+ return asyncio.run(app._media_job_get(jid))
+
+
+def _fetched_hosts(client, kit_id, hostile, url) -> list[str]:
+ """Every host this server opened a socket to while landing a render the provider said lives
+ at `url` — minus the provider's own submit/poll endpoint."""
+ hid = _launch(client, kit_id)
+ sid = _session(hid)
+ hostile.result_url = url
+ hostile.video_bytes = _mp4()
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "r", "seconds": 6}))["job_id"]
+ _due(jid)
+ hostile.calls.clear()
+ asyncio.run(app._media_sweep())
+ return [c["host"] for c in hostile.calls if "/video/generations" not in c["url"]]
+
+
+def _five_routes(hid, sid, jid=None, med=None):
+ return [
+ ("GET scene", "get", f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/sessions/{sid}/scene",
+ None),
+ ("PUT scene", "put", f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/sessions/{sid}/scene",
+ {"scene": {"type": "excalidraw", "version": 2, "elements": [], "appState": {}}}),
+ ("GET jobs", "get", f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/sessions/{sid}/jobs", None),
+ ("POST export", "post",
+ f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/sessions/{sid}/export", {}),
+ ("GET bytes", "get",
+ f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/sessions/{sid}/media/{med or 'med_x'}", None),
+ ]
+
+
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+# ONE TOOL CALL, ONE BUDGET — the submit walk, the poll walk, and the fact that they share it
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+
+def test_v32_a_billable_empty_answer_does_not_walk_the_whole_image_chain(client, kit, hostile):
+ """THE SUBMIT WALK. `_media_chain`, not `_media_job_billable_failure`.
+
+ media_plane raises MediaEmpty for "200 with nothing in it", and the catalog's own words for
+ that case are "it billed and returned nothing". The chain caught MediaEmpty and continued to
+ the next candidate with no cap at all, so one generate_image where every candidate answers
+ 200-with-no-image paid for the whole eleven-model chain inside a single tool call — and
+ `_MEDIA_MAX_ADVANCES`, which caps the poll walk, never saw it.
+ """
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ real = hostile.handle
+
+ def empty200(req):
+ u = str(req.url)
+ if u.endswith("/images/generations"):
+ return httpx.Response(200, json={"created": 1, "data": []})
+ if ":generateContent" in u:
+ return httpx.Response(200, json={"candidates": [{"content": {"parts": []}}]})
+ if u.endswith("/chat/completions"):
+ return httpx.Response(200, json={"choices": [{"message": {"content": "sorry"}}]})
+ return real(req)
+
+ hostile.handle = empty200
+ submits = _count_submits(hostile)
+ res = _call(client, _cred(hid, sid), "generate_image", {"prompt": "a cat"})
+ assert res.get("isError") is True, res
+ assert len(submits) <= app._MEDIA_MAX_ADVANCES + 1, (
+ f"ONE generate_image CALL BOUGHT {len(submits)} BILLABLE RENDERS: {submits}")
+ # and the agent is TOLD what its one call bought, rather than being handed a bare "no model".
+ assert "billed" in _text(res).lower(), _text(res)
+
+
+def test_v32b_the_speech_chain_is_governed_by_the_same_cap(client, kit, hostile, monkeypatch):
+ """Same walk, second capability — so this is a fact about `_media_chain` and not about one
+ catalog entry.
+
+ The speech chain is two candidates long, which the shipped cap already bounds at both of them;
+ what would still be vacuous is "two is fewer than the whole chain". So the cap itself is moved
+ to zero: the walk must be GOVERNED by it and not merely shorter than the chain. Before the
+ fix, moving the cap changed nothing here, because the submit walk did not consult it.
+ """
+ monkeypatch.setattr(app, "_MEDIA_MAX_ADVANCES", 0)
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ real = hostile.handle
+
+ def empty_audio(req):
+ if str(req.url).endswith("/chat/completions"):
+ return httpx.Response(200, json={"choices": [{"message": {"content": "sorry"}}]})
+ return real(req)
+
+ hostile.handle = empty_audio
+ submits = _count_submits(hostile)
+ res = _call(client, _cred(hid, sid), "generate_speech", {"text": "hello"})
+ assert res.get("isError") is True, res
+ assert len(submits) <= 1, (
+ f"ONE generate_speech CALL BOUGHT {len(submits)} BILLABLE RENDERS with the advance "
+ f"budget set to zero: {submits}")
+
+
+def test_the_two_walks_share_one_budget(client, kit, hostile):
+ """THE SIBLING PATH, which is how the last cap was reported closed while costing money.
+
+ One tool call, both walks: candidate 1 answers 200-with-no-image (billable — the SUBMIT walk
+ advances), candidate 2 hands back a URL that then 503s (billable — the POLL walk would
+ advance). If each walk keeps its own count, one call buys four renders. The count belongs to
+ the REQUEST, so it must buy two.
+ """
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ real = hostile.handle
+
+ def empty_then_dead_url(req):
+ u = str(req.url)
+ if ":generateContent" in u: # candidate 1: billed, gave nothing
+ return httpx.Response(200, json={"candidates": [{"content": {"parts": []}}]})
+ if u.endswith("/images/generations"): # candidate 2: billed, url is dead
+ return httpx.Response(200, json={"created": 1, "data": [
+ {"url": "https://cdn.provider.example/gone.png"}]})
+ if u.startswith("https://cdn.provider.example/gone.png"):
+ return httpx.Response(503, content=b"upstream unavailable")
+ if u.endswith("/chat/completions"):
+ return httpx.Response(200, json={"choices": [{"message": {"content": "sorry"}}]})
+ return real(req)
+
+ hostile.handle = empty_then_dead_url
+ submits = _count_submits(hostile)
+ res = _call(client, _cred(hid, sid), "generate_image", {"prompt": "a cat"})
+ if not res.get("isError"):
+ _drive_to_terminal(_ok(res)["job_id"])
+ assert len(submits) <= app._MEDIA_MAX_ADVANCES + 1, (
+ f"ONE generate_image CALL BOUGHT {len(submits)} BILLABLE RENDERS ACROSS THE TWO WALKS: "
+ f"{submits}")
+
+
+def test_a_render_that_billed_at_submit_is_not_forgotten_by_the_job(client, kit, hostile):
+ """The mechanism the test above rests on: what the submit walk spent is written ONTO the job,
+ which is the only thing that outlives the tool call and the only place the poll walk can read
+ it from."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ real = hostile.handle
+
+ spent: list[str] = []
+
+ def empty_first(req):
+ """Only the FIRST candidate bills and returns nothing; the next one works. So the request
+ succeeds — and the job it produced has to remember that one render was already bought."""
+ u = str(req.url)
+ if ":generateContent" in u and not spent:
+ spent.append(u)
+ return httpx.Response(200, json={"candidates": [{"content": {"parts": []}}]})
+ return real(req)
+
+ hostile.handle = empty_first
+ job = _ok(_call(client, _cred(hid, sid), "generate_image", {"prompt": "a cat"}))
+ v = _vertex(job["job_id"])
+ assert int(float(v.get("advances") or 0)) >= 1, (
+ f"a candidate billed inside the submit walk and the job records no advance: {v}")
+
+
+def test_a_second_render_bought_by_the_same_request_is_also_stood_down(client, kit, hostile):
+ """The sibling of the sibling. `_media_job_resubmit` is the one place a billable failure was
+ recorded by hand rather than by the function that records billable failures: a candidate it
+ reached that billed and gave nothing was neither written down, nor stood down, nor counted —
+ so the very next request picked the same broken model and paid again."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ # Leave only the shape that hands back a URL, so BOTH candidates this request reaches are ones
+ # that bill and then fail to deliver.
+ for c in media_plane.capability("text_to_image")["candidates"]:
+ if str(c.get("shape")) != "image-generation":
+ app._media_quarantine[str(c["model"])] = time.time() + 9999
+ real = hostile.handle
+
+ def dead_url(req):
+ u = str(req.url)
+ if u.endswith("/images/generations"):
+ return httpx.Response(200, json={"created": 1, "data": [
+ {"url": "https://cdn.provider.example/gone.png"}]})
+ if u.startswith("https://cdn.provider.example/gone.png"):
+ return httpx.Response(503, content=b"upstream unavailable")
+ return real(req)
+
+ hostile.handle = dead_url
+ jid = _ok(_call(client, _cred(hid, sid), "generate_image", {"prompt": "a cat"}))["job_id"]
+ attempts = json.loads(_vertex(jid).get("attempts_json") or "[]")
+ billed = [a for a in attempts if a.get("billed")]
+ assert len(billed) == 2, f"a request bought two renders and wrote down {len(billed)}: {attempts}"
+ for a in billed:
+ assert app._media_quarantine.get(a["model"], 0) > time.time(), (
+ f"{a['model']} billed for nothing and is still first in the chain")
+
+
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+# A PROVIDER DOCUMENT IS SCRUBBED WHERE IT BECOMES OUR DATA — not on the error channel only
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+
+@needs_ffmpeg
+def test_v35_the_progress_string_is_a_provider_string_too(client, kit, hostile):
+ """read_poll scrubbed the FAILURE branch and returned `progress` — from the SAME document —
+ untouched. It is stored on the vertex, served to the browser and handed to the agent: the
+ same three sinks the error text reaches, one field over."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ hostile.video_bytes = _mp4()
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "r", "seconds": 6}))["job_id"]
+ hostile.poll_answer = httpx.Response(200, json={"code": "success", "data": {
+ "status": "IN_PROGRESS", "progress": f"30% (worker auth: {PROVIDER_KEY})"}})
+ _due(jid)
+ tool = _text(_call(client, _cred(hid, sid), "check_jobs", {"job_ids": [jid]}))
+ vertex = json.dumps(_vertex(jid))
+ browser = client.get(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/sessions/{sid}/jobs",
+ headers=HEADERS).text
+ assert "30%" in tool or "30%" in browser, (tool[:300], browser[:300]) # not vacuous
+ _assert_clean(PROVIDER_KEY, "poll `progress` field", tool, vertex, browser)
+
+
+@needs_ffmpeg
+def test_v36_a_provider_chosen_task_id_is_not_written_to_disk_in_the_clear(client, kit, hostile):
+ """The provider also chooses the task id, and it is persisted verbatim on the job vertex."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ hostile.task_id_override = f"task_{PROVIDER_KEY}"
+ hostile.video_bytes = _mp4()
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "r", "seconds": 6}))["job_id"]
+ _assert_clean(PROVIDER_KEY, "provider-chosen task id", "", json.dumps(_vertex(jid)), "")
+
+
+def test_v37_a_provider_transcript_is_a_provider_string_too(client, kit, hostile):
+ """gpt-audio's transcript arrives in the same body as the audio, is stored beside the bytes and
+ is handed to the agent as `spoken_text`."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ real = hostile.handle
+
+ def audio(req):
+ if str(req.url).endswith("/chat/completions"):
+ return httpx.Response(200, json={"choices": [{"message": {"audio": {
+ "data": base64.b64encode(_wav()).decode(),
+ "transcript": f"hello (billed to {PROVIDER_KEY})"}}}]})
+ return real(req)
+
+ hostile.handle = audio
+ res = _call(client, _cred(hid, sid), "generate_speech", {"text": "hello"})
+ body = _text(res)
+ assert res.get("isError") is not True, body
+ assert "hello" in body # not vacuous
+ _assert_clean(PROVIDER_KEY, "provider transcript", body, json.dumps(_vertex("")), "")
+
+
+@needs_ffmpeg
+def test_a_signed_result_url_is_still_fetched_verbatim(client, kit, hostile):
+ """The other half, and the one an over-broad scrub fails: a result_url IS a credential-bearing
+ string — every kling and seedream URL is signed — and it is the address of the file. Redacting
+ the signature would repel nothing and lose every render."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ signed = "https://cdn.provider.example/out.mp4?signature=abcdef0123456789&key=zyxwvu987654321"
+ hostile.result_url = signed
+ hostile.video_bytes = _mp4()
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "r", "seconds": 6}))["job_id"]
+ _sweep(jid)
+ fetched = [c["url"] for c in hostile.calls if c["host"] == "cdn.provider.example"]
+ assert signed in fetched, f"the signed address was not fetched as given: {fetched}"
+ assert asyncio.run(app._media_job_get(jid))["status"] == "succeeded"
+
+
+def test_the_scrub_leaves_our_own_vocabulary_standing(client):
+ """A redaction that eats model names, refusal sentences or a task id is a redaction nobody can
+ diagnose against — and a mangled task id is a render that can never be polled."""
+ for name in media_plane.capability_names():
+ for cand in media_plane.capability(name).get("candidates") or []:
+ model = str(cand.get("model") or "")
+ assert media_plane.scrub(model) == model, model
+ reason = str(cand.get("reason") or "")
+ assert media_plane.scrub(reason) == reason, reason
+ for tid in ("task_1", "cgt-2026081512345678", "9f8a7b6c-1234-4f5e-8a9b-0c1d2e3f4a5b",
+ "7529431068442312704"):
+ assert media_plane.scrub(tid) == tid, tid
+
+
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+# THIS SERVER FETCHES ONLY AN ADDRESS IT HAS CLASSIFIED
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+
+@needs_ffmpeg
[email protected]("url,host", [
+ ("http://169.254.169.254/latest/meta-data/iam/security-credentials/", "169.254.169.254"),
+ ("http://127.0.0.1:8080/admin", "127.0.0.1"),
+ ("http://[::1]:9000/x.mp4", "::1"),
+ ("http://10.1.2.3/internal.mp4", "10.1.2.3"),
+ ("http://192.168.0.7/x.mp4", "192.168.0.7"),
+ ("http://172.16.9.9/x.mp4", "172.16.9.9"),
+ ("http://0.0.0.0/x.mp4", "0.0.0.0"),
+ ("http://2130706433/x.mp4", "2130706433"), # decimal 127.0.0.1
+ ("http://127.1/x.mp4", "127.1"),
+])
+def test_v24_internal_addresses_are_refused(client, kit, hostile, url, host):
+ assert host not in _fetched_hosts(client, kit, hostile, url), f"THE GATEWAY FETCHED {url}"
+
+
+@needs_ffmpeg
[email protected]("url", ["file:///etc/passwd", "gopher://127.0.0.1:11211/_x",
+ "ftp://10.0.0.1/x", "//169.254.169.254/x"])
+def test_v25_non_http_schemes_are_refused(client, kit, hostile, url):
+ hosts = _fetched_hosts(client, kit, hostile, url)
+ assert not hosts, f"{url} produced outbound calls to {hosts}"
+
+
+@needs_ffmpeg
+def test_v26_an_unresolvable_internal_name_is_refused(client, kit, hostile):
+ """The finding named TWO addresses that were reached: 169.254.169.254 and
+ http://internal.svc/admin. This is the second one, and it is the one an "it does not resolve,
+ so it is not internal" rule lets straight through: our lookup failing says nothing about what
+ the socket will do a millisecond later, in a cluster where `.svc` is a search domain.
+ """
+ hosts = _fetched_hosts(client, kit, hostile, "http://internal.svc/admin")
+ assert "internal.svc" not in hosts, (
+ f"THE GATEWAY STILL FETCHES http://internal.svc/admin. hosts touched = {hosts}")
+
+
+@needs_ffmpeg
+def test_v27_a_public_url_that_redirects_to_metadata_is_not_followed(client, kit, hostile):
+ """A check on the URL the provider names is worthless if a 302 moves the socket afterwards."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ real = hostile.handle
+
+ def redirecting(req):
+ if req.url.host == "cdn.provider.example" and str(req.url).endswith("hop.mp4"):
+ return httpx.Response(302, headers={
+ "location": "http://169.254.169.254/latest/meta-data/"})
+ return real(req)
+
+ hostile.handle = redirecting
+ hostile.result_url = "https://cdn.provider.example/hop.mp4"
+ hostile.video_bytes = _mp4()
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "r", "seconds": 6}))["job_id"]
+ _due(jid)
+ hostile.calls.clear()
+ asyncio.run(app._media_sweep())
+ hit = [c["url"] for c in hostile.calls if c["host"] == "169.254.169.254"]
+ assert not hit, f"A REDIRECT MOVED THE FETCH TO LINK-LOCAL METADATA: {hit}"
+
+
+def test_v28_the_shared_classifier_still_refuses_what_it_could_not_classify(client, monkeypatch):
+ """One rule, one answer: a host that does not resolve is refused for the MCP and database
+ callers too, and that is their whole contract."""
+ bad_name = "this-name-does-not-exist-hr-test.invalid"
+ assert app._internal_target(bad_name, 443) is not None
+ monkeypatch.setattr(app, "_pool_is_local", lambda: False)
+ assert app._ssrf_check(f"https://{bad_name}/x") is not None
+ assert app._ssrf_check("https://169.254.169.254/") is not None
+ assert app._ssrf_check("https://10.0.0.9/mcp") is not None
+
+
+def test_v28b_a_transient_dns_failure_does_not_open_the_provider_url_check(client, monkeypatch):
+ """`except Exception: return None` does not only mean NXDOMAIN. A resolver timeout, a
+ momentarily unreachable resolver, an EAI_AGAIN under load — each one made the provider-URL
+ check answer "fine" about an address it had NOT classified. The one caller whose URL is chosen
+ by a remote party was the one caller that failed open, and every poll is a fresh roll.
+ """
+ real = socket.getaddrinfo
+
+ def flaky(host, port, *a, **kw):
+ if host == "rebind.attacker.example":
+ raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")
+ return real(host, port, *a, **kw)
+
+ monkeypatch.setattr(socket, "getaddrinfo", flaky)
+ assert app._provider_url_check("http://rebind.attacker.example/x.mp4") is not None, (
+ "a name whose lookup merely TIMED OUT was accepted as an address to fetch; the same name "
+ "resolving to 10.0.0.5 on the next lookup is the whole SSRF")
+
+
+def test_a_name_that_does_not_exist_and_one_we_could_not_look_up_are_told_apart(monkeypatch):
+ """Both are refused — an address this server cannot classify is one it does not open a socket
+ to — but they are DIFFERENT facts, and the operator reading the log is the one who needs them
+ apart: one is a bad URL, the other is a broken resolver."""
+ real = socket.getaddrinfo
+
+ def flaky(host, port, *a, **kw):
+ if host == "flaky.attacker.example":
+ raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")
+ return real(host, port, *a, **kw)
+
+ monkeypatch.setattr(socket, "getaddrinfo", flaky)
+ gone = app._internal_target("this-name-does-not-exist-hr-test.invalid", 443)
+ unknown = app._internal_target("flaky.attacker.example", 443)
+ assert gone and unknown and gone != unknown, (gone, unknown)
+
+
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+# THE CANARY — every rule above must leave the rightful owner working
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+
+@needs_ffmpeg
+def test_v12_the_rightful_harness_is_still_served_on_all_five_routes(client, kit, hostile):
+ """The half an over-broad patch fails: a fix that 404s everything repels every attack in this
+ file and ships a dead canvas."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ hostile.video_bytes = _mp4()
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "r", "seconds": 6}))["job_id"]
+ _call(client, _cred(hid, sid), "place", {"items": [{"job_id": jid}]})
+ _sweep(jid)
+ med = asyncio.run(app._media_job_get(jid))["media_id"]
+ assert med, "the render never landed; this test would prove nothing"
+ codes = {}
+ for label, verb, path, body in _five_routes(hid, sid, jid, med):
+ r = getattr(client, verb)(path, headers=HEADERS, **({"json": body} if body else {}))
+ codes[label] = r.status_code
+ assert codes["GET scene"] == 200, codes
+ assert codes["GET jobs"] == 200, codes
+ assert codes["GET bytes"] == 200, codes
+ # PUT scene may legitimately 412/422 (revision / media-element rules); it must NOT 404.
+ assert codes["PUT scene"] != 404, codes
+ # export may legitimately 400 (nothing on the timeline); it must NOT 404.
+ assert codes["POST export"] != 404, codes
+
+
+@needs_ffmpeg
+def test_an_ordinary_render_still_lands(client, kit, hostile):
+ """The plainest thing the product does, asserted after every rule above — because each of them
+ sits directly on this path."""
+ hid = _launch(client, kit)
+ sid = _session(hid)
+ hostile.video_bytes = _mp4()
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "r", "seconds": 6}))["job_id"]
+ _sweep(jid)
+ job = asyncio.run(app._media_job_get(jid))
+ assert job["status"] == "succeeded", job
+ assert job["media_id"], job
diff --git a/gateway/tests/test_media_mcp.py b/gateway/tests/test_media_mcp.py
new file mode 100644
index 00000000..7c1b5928
--- /dev/null
+++ b/gateway/tests/test_media_mcp.py
@@ -0,0 +1,2092 @@
+"""Making media as an ORDINARY MCP server on a harness — the chain that picks a model and says
+which one it picked, the jobs that outlive the turn, the canvas, the export, and the one rule that
+matters more than any of them: the provider key never comes back out.
+
+Every request in this file goes through the real app with local backing (SQLite + encrypted files
+in a temp dir), so what is asserted is what a caller would actually receive. Every PROVIDER call
+goes through an httpx MockTransport, so the five adapters are genuinely exercised — the URL, the
+body, the parsing — and nothing is spent doing it.
+
+THE CREDENTIAL CHECK IS NOT ONE TEST. `_seen` records every response body and every line the
+gateway printed, and the last tests assert the provider key appears in none of them — so a route
+added later that leaks it fails this file even if nobody writes a test for that route.
+
+Tests that need a REAL generation are skipped unless HR_TEST_TOKENROUTER_KEY is set, and when it is
+they use the shortest duration and the smallest size the model allows, one call each, reusing task
+ids rather than resubmitting. No generation is ever looped.
+"""
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+import httpx
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+# Set BEFORE importing app: the backing, the internal key and the encryption passphrase are all
+# read at import time, exactly as they are in a running container.
+_DATA = tempfile.mkdtemp(prefix="hr-mediatest-")
+os.environ.update({
+ "HR_BACKING": "local", "HR_DATA_DIR": _DATA,
+ # Self-hosted, a workspace is a live directory. The default is /data/workspaces, which does
+ # not exist on a laptop — so the projection would silently not happen and this file would be
+ # asserting nothing.
+ "HARNESS_WORKSPACE": os.path.join(_DATA, "workspaces"),
+ "HR_SECRET_KEY": "test-passphrase-not-a-real-one",
+ "HARNESS_INTERNAL_KEY": "test-internal-key",
+ "HARNESS_GLOBAL_TENANT": "global",
+ # A base URL, so the MCP server is offered to a turn the way it would be in production — and
+ # so it is an address this gateway recognises as its own.
+ "HARNESS_PUBLIC_BASE_URL": "https://gateway.example",
+ "HR_POOL_AUTH": "none",
+ # Self-hosted: the one operator is the administrator, which is what lets this file connect the
+ # provider integration the media server resolves its key from.
+ "HR_IDENTITY_MODE": "off",
+ # The sweeper must not race the assertions; every test drives _media_sweep itself.
+ "HR_MEDIA_SWEEP_S": "3600",
+})
+
+import app # noqa: E402
+import media_plane # noqa: E402
+from fastapi.testclient import TestClient # noqa: E402
+
+# The sentinel. Every assertion about "the key never comes out" is about this exact string.
+PROVIDER_KEY = "sk-tr-SENTINEL-do-not-leak-4f7a9b21"
+
+ORG = "testorg"
+HEADERS = {"x-harness-internal": "test-internal-key", "x-harness-org": ORG,
+ "x-harness-member": "[email protected]"}
+
+MCP_URL = "https://gateway.example/v1/mcp/media"
+ENTRY_ID = "mcp.media"
+TR = "https://api.tokenrouter.com/v1"
+
+# The kit that provisions the media server. Attaching it is something the kit that uses it drives,
+# so every attach in this file goes through launch — there is no other way in.
+_KIT = {"id": "media", "title": "Videos", "app": {"route": "/kits/media"},
+ "harness": {"name": "Videos", "mcp_servers": [],
+ "launch": {"media": {"name": "media", "id": ENTRY_ID}},
+ "recommended": [{"base": "claude-code", "model": "claude-opus-5"}]}}
+
+LIVE_KEY = os.environ.get("HR_TEST_TOKENROUTER_KEY", "").strip()
+needs_live = pytest.mark.skipif(not LIVE_KEY,
+ reason="no HR_TEST_TOKENROUTER_KEY — a real generation costs money")
+needs_ffmpeg = pytest.mark.skipif(not media_plane.have_ffmpeg(), reason="no ffmpeg on this box")
+
+# Every response body and every printed line this file produced. See the module docstring.
+_seen: list[str] = []
+# Every provider request the mock transport saw, for the test currently running.
+_calls: list[dict] = []
+# The same, for the whole file and never cleared — so "the key DID reach the provider" is not an
+# assertion about whichever test happened to run last.
+_all_calls: list[dict] = []
+
+
+# ── tiny real media, so verification is exercised on bytes and not on a stub ──────
+PNG_1PX = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")
+WAV_SILENCE = (b"RIFF$\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x40\x1f\x00\x00"
+ b"\x80>\x00\x00\x02\x00\x10\x00data\x00\x00\x00\x00")
+
+
+def _mp4(seconds: float = 1.0, size: str = "128x72") -> bytes:
+ """A real, tiny mp4. ffprobe has to be able to read a duration out of it, because the gateway
+ refuses a video it cannot measure — a stub of four bytes would pass a test the product fails."""
+ with tempfile.TemporaryDirectory() as d:
+ out = os.path.join(d, "c.mp4")
+ subprocess.run(["ffmpeg", "-nostdin", "-y", "-f", "lavfi",
+ "-i", f"color=c=blue:s={size}:d={seconds}", "-f", "lavfi",
+ "-i", f"anullsrc=r=44100:cl=stereo:d={seconds}",
+ "-shortest", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac",
+ "-t", str(seconds), out], capture_output=True, check=True)
+ return Path(out).read_bytes()
+
+
+# ── the provider, mocked at the transport ────────────────────────────────────────
+class Provider:
+ """A stand-in for TokenRouter that answers per model, records every request, and can be told
+ to fail a specific one. The adapters run for real against it."""
+
+ def __init__(self):
+ self.fail: dict[str, tuple[int, dict]] = {} # model -> (status, body)
+ self.tasks: dict[str, dict] = {} # task id -> poll record
+ self.video_bytes = b""
+ self.polls: dict[str, list] = {} # task id -> queued poll answers
+ # Where a finished render says it lives, and how that address answers. Both are the
+ # PROVIDER's to choose, which is the whole reason they are knobs here.
+ self.result_url = "https://cdn.provider.example/out.mp4"
+ self.cdn_status = 200
+
+ def queue_poll(self, task_id: str, *answers) -> None:
+ self.polls.setdefault(task_id, []).extend(answers)
+
+ def handle(self, req: httpx.Request) -> httpx.Response:
+ body = json.loads(req.content or b"{}") if req.content else {}
+ call = {"method": req.method, "url": str(req.url), "body": body,
+ "auth": req.headers.get("authorization", "")}
+ _calls.append(call)
+ _all_calls.append(call)
+ url = str(req.url)
+
+ if url.endswith("/video/generations") and req.method == "POST":
+ model = body.get("model") or ""
+ if model in self.fail:
+ st, b = self.fail[model]
+ return httpx.Response(st, json=b)
+ tid = f"task_{len(self.tasks) + 1}"
+ self.tasks[tid] = {"model": model}
+ return httpx.Response(200, json={"id": tid, "task_id": tid, "object": "video",
+ "model": model, "status": "queued"})
+
+ if "/video/generations/" in url and req.method == "GET":
+ tid = url.rsplit("/", 1)[-1]
+ queued = self.polls.get(tid)
+ if queued:
+ return queued.pop(0)
+ return httpx.Response(200, json={"code": "success", "message": "", "data": {
+ "id": tid, "task_id": tid, "platform": "mock", "status": "SUCCESS",
+ "result_url": self.result_url}})
+
+ if url.endswith("/images/generations"):
+ model = body.get("model") or ""
+ if model in self.fail:
+ st, b = self.fail[model]
+ return httpx.Response(st, json=b)
+ return httpx.Response(200, json={"created": 1, "background": "opaque",
+ "data": [{"b64_json": base64.b64encode(PNG_1PX).decode()}]})
+
+ if ":generateContent" in url:
+ model = url.split("/models/")[-1].split(":")[0]
+ if model in self.fail:
+ st, b = self.fail[model]
+ return httpx.Response(st, json=b)
+ if model == "google/gemini-3-pro-image-preview":
+ # 200 OK, no parts, and it bills. Kept honest here because it is the exact shape
+ # the "a 200 is not a success" rule exists for.
+ return httpx.Response(200, json={"candidates": [{"content": {"parts": []},
+ "finishReason": "STOP"}]})
+ return httpx.Response(200, json={"candidates": [{"content": {"parts": [
+ {"thoughtSignature": "x" * 64},
+ {"inlineData": {"mimeType": "image/png",
+ "data": base64.b64encode(PNG_1PX).decode()}}]}}]})
+
+ if url.endswith("/chat/completions"):
+ model = body.get("model") or ""
+ if model in self.fail:
+ st, b = self.fail[model]
+ return httpx.Response(st, json=b)
+ if body.get("modalities"):
+ if body.get("stream"):
+ frames = [
+ 'data: ' + json.dumps({"choices": [{"delta": {"audio": {
+ "data": base64.b64encode(WAV_SILENCE[:22]).decode(),
+ "transcript": "Hello "}}}]}),
+ 'data: ' + json.dumps({"choices": [{"delta": {"audio": {
+ "data": base64.b64encode(WAV_SILENCE[22:]).decode(),
+ "transcript": "there."}}}]}),
+ "data: [DONE]"]
+ return httpx.Response(200, text="\n\n".join(frames) + "\n\n",
+ headers={"content-type": "text/event-stream"})
+ return httpx.Response(200, json={"choices": [{"message": {"audio": {
+ "data": base64.b64encode(WAV_SILENCE).decode(),
+ "transcript": "Hello! It's great to talk with you."}}}]})
+ return httpx.Response(200, json={"choices": [{"message": {"content": None, "images": [
+ {"image_url": {"url": "data:image/png;base64,"
+ + base64.b64encode(PNG_1PX).decode()}}]}}],
+ "usage": {"cost": 0.048188}})
+
+ if url.startswith("https://cdn.provider.example/"):
+ data = self.video_bytes or PNG_1PX
+ ctype = "video/mp4" if url.endswith(".mp4") else "image/png"
+ return httpx.Response(self.cdn_status, content=data,
+ headers={"content-type": ctype})
+
+ # ANY other host. A relay that names one has moved the gateway somewhere it chose, so
+ # this answers rather than 404s — a refusal here would hide the fetch under a failure.
+ return httpx.Response(200, content=b'{"SecretAccessKey":"AWSSECRET"}',
+ headers={"content-type": "application/json"})
+
+
[email protected](autouse=True)
+def resolvable_cdn(monkeypatch):
+ """The mock provider's CDN lives on a `.example` name, and `.example` resolves nowhere. This
+ server will not fetch a finished render from an address it could not classify (see
+ _provider_url_check), so the fake CDN has to resolve the way a real one does — otherwise every
+ test that lands a file would quietly be asserting the refusal instead.
+
+ Only `.example` is answered here, to a public address. Everything else falls through to the
+ real resolver, so the SSRF assertions still mean what they say.
+ """
+ import socket
+ real = socket.getaddrinfo
+
+ def fake(host, port, *a, **kw):
+ if str(host).endswith(".example"):
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "",
+ ("93.184.216.34", int(port or 443)))]
+ return real(host, port, *a, **kw)
+
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+
+
+def provider(monkeypatch):
+ p = Provider()
+ _calls.clear()
+ client = httpx.AsyncClient(transport=httpx.MockTransport(lambda r: p.handle(r)),
+ timeout=30)
+ monkeypatch.setattr(app, "_media_client", lambda: client)
+ app._media_quarantine.clear()
+ yield p
+ asyncio.run(client.aclose())
+
+
+# ── the harness under test ───────────────────────────────────────────────────────
[email protected](scope="module")
+def client():
+ with TestClient(app.app) as c:
+ yield c
+
+
+class Rec:
+ """A client whose every response body is recorded before it is returned."""
+
+ def __init__(self, c: TestClient):
+ self.c = c
+
+ def _do(self, method: str, path: str, **kw):
+ r = getattr(self.c, method)(path, headers={**HEADERS, **(kw.pop("headers", None) or {})},
+ **kw)
+ _seen.append(r.text)
+ return r
+
+ def get(self, path, **kw):
+ return self._do("get", path, **kw)
+
+ def post(self, path, **kw):
+ return self._do("post", path, **kw)
+
+ def put(self, path, **kw):
+ return self._do("put", path, **kw)
+
+ def delete(self, path, **kw):
+ return self._do("delete", path, **kw)
+
+
[email protected](scope="module")
+def api(client):
+ return Rec(client)
+
+
+def _connect_provider(key: str = PROVIDER_KEY) -> None:
+ """One TokenRouter integration holding the key — the deployment's own credential, which is
+ what every media call resolves and what nothing may ever return.
+
+ Written straight into the document the media server reads, rather than through the admin
+ route: how a key got connected is another surface's business, and going through that route
+ would make this file depend on the identity mode whichever test module imported `app` first
+ happened to set."""
+ asyncio.run(app._vault_put(app.GLOBAL_TENANT, app._INTEGRATIONS_KEY, json.dumps(
+ [{"name": "tr", "provider": "tokenrouter",
+ "config": {"api_key": key, "base_url": TR}}])))
+
+
[email protected](scope="module", autouse=True)
+def integration(api):
+ _connect_provider()
+ # Self-hosted, a workspace is a live directory, and its root is read at import time from
+ # HARNESS_WORKSPACE. Bound here to THIS file's temp dir so the projection is real wherever the
+ # process happened to start — a projection that silently lands nowhere asserts nothing.
+ app.BACKING.workspace = app.backing.LocalWorkspaceFiles(os.path.join(_DATA, "workspaces"))
+ return True
+
+
+def kit(monkeypatch):
+ """This kit, with a fresh id per test so launch's idempotence isn't a shared fixture."""
+ kid = f"media{int(time.time() * 1e6) % 10_000_000}"
+ monkeypatch.setattr(app, "_kits", lambda: {kid: {**_KIT, "id": kid}})
+ return kid
+
+
+def _launch(api, kit) -> dict:
+ r = api.post(f"/v1/kits/{kit}/launch", json={})
+ assert r.status_code == 200, r.text
+ return r.json()
+
+
+def harness(api, kit):
+ return _launch(api, kit)["harnessId"]
+
+
+def session(api, harness):
+ """A session that belongs to this org AND to this harness, so both ownership checks on every
+ app route are real.
+
+ `harness_id` is the field the product's own session-create path stamps (_start_session), and
+ therefore the field the media routes read. Writing anything else here would make the bind
+ testable and absent.
+ """
+ return _session_of(harness)
+
+
+def _session_of(hid: str, org: str = ORG) -> str:
+ sid = "sess_" + os.urandom(6).hex()
+ asyncio.run(app._vg_upsert("HarnessSession", sid,
+ {"tenant": org, "status": "idle", "turn_status": "idle",
+ "harness_id": hid}))
+ return sid
+
+
+def _due(jid: str) -> None:
+ """Make a job due for its next poll right now.
+
+ Without this every advance is a no-op — next_poll_at is 20 s out — and every assertion after
+ it is vacuous. Real time is the only other way to get there.
+ """
+ job = asyncio.run(app._media_job_get(jid))
+ job["next_poll_at"] = 0
+ asyncio.run(app._media_job_save(job))
+
+
+def _vertex(hid: str) -> dict:
+ return asyncio.run(app.BACKING.graph.get(hid, label="Harness"))
+
+
+def _stored(hid: str) -> list:
+ return json.loads(_vertex(hid).get("mcp_servers") or "[]")
+
+
+def _entry_of(hid: str) -> dict:
+ return next(s for s in _stored(hid) if s.get("id") == ENTRY_ID)
+
+
+def _key(hid: str) -> str:
+ return app._vault_key(_entry_of(hid)["auth"])
+
+
+def _cred(hid: str, sid: str = "") -> str:
+ return app._mint_hosted_cred(hid, sid, _key(hid))
+
+
+def _rpc(client, token, method, params=None, rid=1):
+ body = {"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}}
+ r = client.post("/v1/mcp/media", json=body,
+ headers={"authorization": f"Bearer {token}"} if token else {})
+ _seen.append(r.text)
+ return r
+
+
+def _call(client, tok, name, args=None) -> dict:
+ r = _rpc(client, tok, "tools/call", {"name": name, "arguments": args or {}})
+ assert r.status_code == 200, r.text
+ return r.json()["result"]
+
+
+def _ok(res: dict) -> dict:
+ assert res.get("isError") is not True, res["content"][0]["text"]
+ return json.loads(res["content"][0]["text"])
+
+
+def _err(res: dict) -> str:
+ assert res.get("isError") is True, res
+ return res["content"][0]["text"]
+
+
+def _save_config(api, hid: str, servers: list, name="Videos"):
+ return api.put(f"/v1/harnesses/{hid}",
+ json={"name": name, "base": "claude-code", "mcp_servers": servers})
+
+
+# ══ the entry, and where the credential is not ═══════════════════════════════════
+
+def test_launching_provisions_an_entry_indistinguishable_from_a_third_party_one(api, kit):
+ out = _launch(api, kit)
+ hid = out["harnessId"]
+ entry = _entry_of(hid)
+ assert entry["url"] == MCP_URL and entry["transport"] == "http"
+ assert entry["auth"].startswith("vault:" + app._HOSTED_SECRET_PREFIX)
+ # THE WHOLE POINT: its key set is a third-party entry's key set. Nothing stored distinguishes
+ # them, so nothing can branch on the difference.
+ assert set(entry) == {"id", "name", "url", "transport", "auth", "enabled"}
+ assert PROVIDER_KEY not in json.dumps(_vertex(hid))
+
+
+def test_the_record_holds_a_binding_and_no_secret_at_all(api, kit):
+ """A database record holds a customer's connection string. This one holds who it is for and
+ nothing else — the provider credential is the deployment's, and must never become a
+ per-harness secret."""
+ hid = _launch(api, kit)["harnessId"]
+ rec = asyncio.run(app._hosted_record(ORG, _key(hid)))
+ assert rec["server"] == "media" and rec["harness"] == hid
+ assert set(rec) == {"server", "harness", "updated_at"}
+ assert PROVIDER_KEY not in json.dumps(rec)
+
+
+def test_launching_needs_no_encryption_passphrase(api, kit, monkeypatch):
+ """The database's record holds a customer's connection string, so an instance that cannot
+ encrypt must refuse it. This record holds a binding and no credential at all, and refusing
+ would block a feature with nothing to protect."""
+ real = app.BACKING.secrets.put
+
+ async def no_passphrase(tenant, name, value, *, require_encryption=False):
+ if require_encryption:
+ raise app.backing.SecretsNotConfigured("set HR_SECRET_KEY")
+ return await real(tenant, name, value)
+
+ monkeypatch.setattr(app.BACKING.secrets, "put", no_passphrase)
+ out = _launch(api, kit)
+ assert out["created"] is True
+ rec = asyncio.run(app._hosted_record(ORG, _key(out["harnessId"])))
+ assert rec == {"server": "media", "harness": out["harnessId"],
+ "updated_at": rec["updated_at"]}
+
+
+def test_launch_is_idempotent(api, kit):
+ first = _launch(api, kit)
+ key_before = _key(first["harnessId"])
+ again = _launch(api, kit)
+ assert again["harnessId"] == first["harnessId"] and again["created"] is False
+ assert len([e for e in _stored(first["harnessId"]) if e.get("id") == ENTRY_ID]) == 1
+ assert _key(first["harnessId"]) == key_before
+
+
+def test_a_turn_is_handed_a_capability_and_never_the_provider_key(harness):
+ """Invariant 1, at the funnel every plugin passes through: grep the WHOLE resolved plugin list
+ for the sentinel and find nothing, then confirm what the sandbox actually got."""
+ v = asyncio.run(app._harness_vertex(harness))
+ mcp, *_ = asyncio.run(app._harness_plugins(harness, ORG, hv=v, sid="sess-42"))
+ entry = next(m for m in mcp if m["name"] == "media")
+ assert entry["url"] == MCP_URL
+ assert entry["auth"].startswith("hrs_")
+ assert app._verify_hosted_cred(entry["auth"]) == (harness, "sess-42", _key(harness))
+ assert PROVIDER_KEY not in json.dumps(mcp)
+
+
+def test_the_hosted_namespace_never_resolves_as_a_bearer_token(harness, capsys):
+ """The refusal at the funnel every outbound credential passes through, so it holds for callers
+ that do not exist yet."""
+ capsys.readouterr()
+ assert asyncio.run(app._resolve_mcp_auth(ORG, f"vault:{_key(harness)}")) == ""
+ assert "refusing to resolve" in capsys.readouterr().out
+
+
+def test_an_entry_here_that_names_no_record_is_not_offered(api, kit):
+ """A url of ours with a third-party auth is not a server we can serve: minting for it would
+ hand out a capability to a record this harness does not have."""
+ hid = api.post("/v1/harnesses", json={"name": "Bare", "base": "claude-code"}).json()["id"]
+ assert _save_config(api, hid, [{"id": "mcp.fake", "name": "media", "url": MCP_URL,
+ "transport": "http", "auth": "vault:harness-mcp-theirs",
+ "enabled": True}]).status_code == 200
+ v = asyncio.run(app._harness_vertex(hid))
+ mcp, *_ = asyncio.run(app._harness_plugins(hid, ORG, hv=v, sid="s"))
+ assert mcp == []
+
+
+def test_one_harness_cannot_read_anothers_canvas(client, api, kit, harness):
+ """The binding: `auth` is a client-writable field on an ordinary entry and harness ids are
+ public, so a caller can write someone else's ref onto their own entry."""
+ thief = api.post("/v1/harnesses", json={"name": "Thief", "base": "claude-code"}).json()["id"]
+ stolen = _key(harness)
+ assert _save_config(api, thief, [{"id": ENTRY_ID, "name": "media", "url": MCP_URL,
+ "transport": "http", "auth": f"vault:{stolen}",
+ "enabled": True}], name="Thief").status_code == 200
+ tok = app._mint_hosted_cred(thief, "sess1", stolen)
+ assert "no media tools are connected" in _err(_call(client, tok, "describe_canvas")).lower()
+
+
+def test_the_session_comes_from_the_credential_and_never_from_arguments():
+ """Invariant 5: no tool has a `session` property and every schema is closed, so a call naming
+ another session is rejected by the schema rather than by a check someone has to remember."""
+ for tool in app._MEDIA_MCP_TOOLS:
+ schema = tool["inputSchema"]
+ assert schema.get("additionalProperties") is False, tool["name"]
+ assert "session" not in (schema.get("properties") or {}), tool["name"]
+ assert "harness" not in (schema.get("properties") or {}), tool["name"]
+
+
+def test_a_credential_with_no_session_is_told_so_rather_than_generating(client, harness,
+ provider):
+ res = _call(client, _cred(harness, ""), "generate_video",
+ {"prompt": "rain on a window", "seconds": 6})
+ assert "no workspace" in _err(res)
+ assert _calls == [], "a generation was submitted for a session that does not exist"
+
+
+def test_the_endpoint_refuses_without_a_valid_credential(client, harness):
+ assert _rpc(client, None, "tools/list").status_code == 401
+ assert _rpc(client, "hrs_not-a-real-token", "tools/list").status_code == 401
+ good = _cred(harness, "s1")
+ forged = good[:-1] + ("a" if good[-1] != "a" else "b")
+ assert _rpc(client, forged, "tools/list").status_code == 401
+
+
+def test_a_deleted_harness_stops_answering_its_own_credential(client, api, kit):
+ hid = _launch(api, kit)["harnessId"]
+ tok = _cred(hid, "s1")
+ api.delete(f"/v1/harnesses/{hid}")
+ assert "cannot make media" in _err(_call(client, tok, "describe_canvas"))
+
+
+def test_a_disabled_entry_is_not_handed_to_a_turn_and_its_endpoint_refuses(client, api, kit):
+ """A token minted before the switch is valid for hours, so the refusal has to be at the
+ endpoint too and not only where turns are built."""
+ hid = _launch(api, kit)["harnessId"]
+ tok = _cred(hid, "s1")
+ assert _save_config(api, hid, [{**_entry_of(hid), "enabled": False}]).status_code == 200
+ v = asyncio.run(app._harness_vertex(hid))
+ mcp, *_ = asyncio.run(app._harness_plugins(hid, ORG, hv=v, sid="s1"))
+ assert [m for m in mcp if m["name"] == "media"] == []
+ assert "cannot make media" in _err(_call(client, tok, "describe_canvas"))
+
+
+# ══ the protocol ═════════════════════════════════════════════════════════════════
+
+def test_initialize_echoes_the_protocol_version_and_a_notification_is_a_202(client, harness):
+ tok = _cred(harness, "s1")
+ res = _rpc(client, tok, "initialize", {"protocolVersion": "2025-06-18"}).json()["result"]
+ assert res["protocolVersion"] == "2025-06-18" and res["capabilities"]["tools"] == {}
+ assert res["serverInfo"]["name"] == "media"
+ n = client.post("/v1/mcp/media", headers={"authorization": f"Bearer {tok}"},
+ json={"jsonrpc": "2.0", "method": "notifications/initialized"})
+ assert n.status_code == 202
+
+
+def test_the_tool_list_is_thirteen_tools(client, harness):
+ tools = _rpc(client, _cred(harness, "s1"), "tools/list").json()["result"]["tools"]
+ assert [t["name"] for t in tools] == [
+ "list_capabilities", "generate_video", "generate_image", "generate_speech",
+ "generate_music", "check_jobs", "describe_canvas", "place", "move", "arrange",
+ "remove", "set_timeline", "export_timeline"]
+ assert all(t["inputSchema"]["type"] == "object" for t in tools)
+
+
+def test_an_unknown_tool_and_an_unknown_method_are_answered_not_crashed(client, harness):
+ tok = _cred(harness, "s1")
+ assert "No tool named" in _err(_call(client, tok, "make_a_feature_film"))
+ assert _rpc(client, tok, "resources/list").json()["error"]["code"] == -32601
+
+
+# ══ the chain ════════════════════════════════════════════════════════════════════
+
+def test_the_chain_reports_the_model_that_actually_ran(client, harness, session, provider):
+ """The owner's preferred model is rank 1 and broken. It is tried, it fails at submit, and the
+ model reported is the one that took the job."""
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "unknown model 'eva-video-2.5'"})
+ out = _ok(_call(client, _cred(harness, session), "generate_video",
+ {"prompt": "rain on a window at night", "seconds": 6}))
+ assert out["model"] == "MiniMax-Hailuo-2.3"
+ assert out["capability"] == "text_to_video" and out["status"] == "running"
+ assert out["attempts"][0]["model"] == "dreamina-seedance-2-5-hc"
+ assert "eva-video-2.5" in out["attempts"][0]["error"]
+ assert out["estimated_usd"] == 0.28
+
+
+def test_a_submit_failure_is_never_quarantined_so_the_broken_model_self_heals(
+ client, harness, session, provider):
+ """A candidate that fails BEFORE a task id exists costs nothing to retry, which is exactly what
+ lets rank 1 sit there permanently and start working the day the relay is fixed."""
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "unknown model 'eva-video-2.5'"})
+ tok = _cred(harness, session)
+ _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))
+ assert "dreamina-seedance-2-5-hc" not in app._media_quarantine
+
+ provider.fail.clear() # the relay is fixed
+ out = _ok(_call(client, tok, "generate_video", {"prompt": "b", "seconds": 6}))
+ assert out["model"] == "dreamina-seedance-2-5-hc", "the preferred model did not self-heal"
+
+
+def test_a_two_hundred_with_no_media_is_a_failure_and_the_model_is_stood_down(
+ client, harness, session, provider):
+ """Invariant 7, with gemini-3-pro's exact response. It is excluded from the chain, so the
+ assertion is that a candidate behaving that way is treated as failed AND quarantined."""
+ empty = (200, {"candidates": [{"content": {"parts": []}, "finishReason": "STOP"}]})
+ provider.fail["google/gemini-3.1-flash-lite-image"] = empty
+ out = _ok(_call(client, _cred(harness, session), "generate_image", {"prompt": "a frame"}))
+ assert out["model"] != "google/gemini-3.1-flash-lite-image"
+ assert app._media_quarantine.get("google/gemini-3.1-flash-lite-image", 0) > time.time()
+ assert "returned nothing" in out["attempts"][0]["error"]
+
+
+def test_the_excluded_model_can_never_be_selected(client, harness, session, provider):
+ """It is in the file so nobody re-adds it, and it must be unreachable from every chain."""
+ for cand in media_plane.capability("text_to_image")["candidates"]:
+ if cand["model"] == "google/gemini-3-pro-image-preview":
+ assert cand["status"] == "excluded"
+ assert media_plane.can_serve({"model": "x", "status": "excluded"}, {})
+ for _ in range(3):
+ out = _ok(_call(client, _cred(harness, session), "generate_image", {"prompt": "a"}))
+ assert out["model"] != "google/gemini-3-pro-image-preview"
+
+
+def test_image_to_video_never_degrades_to_text_to_video(client, harness, session, provider):
+ """Invariant 9. MiniMax and happyhorse IGNORE an input image and bill for a text-only clip, so
+ if no image-capable model works this capability has NO substitute and must refuse."""
+ img = _ok(_call(client, _cred(harness, session), "generate_image", {"prompt": "a face"}))
+ _calls.clear()
+ for m in ("dreamina-seedance-2-5-hc", "kling-v3", "kling-v2-6"):
+ app._media_quarantine[m] = time.time() + 900
+ res = _call(client, _cred(harness, session), "generate_video",
+ {"prompt": "the face turns", "seconds": 6, "from_image": img["job_id"]})
+ text = _err(res)
+ assert "No model is available for image_to_video" in text
+ assert "you cannot connect one yourself" in text
+ assert [c for c in _calls if "generations" in c["url"]] == [], "it submitted anyway"
+
+
+def test_an_input_frame_is_sent_to_the_provider_and_never_written_onto_the_job(
+ client, harness, session, provider):
+ """Continuity is `from_image`, so this path carries a base64 frame on every call. A graph
+ property has a size cap and a frame is megabytes, so what is WRITTEN DOWN is the media id and
+ the bytes are re-read from our own store if the chain has to advance."""
+ tok = _cred(harness, session)
+ face = _ok(_call(client, tok, "generate_image", {"prompt": "a face"}))
+ out = _ok(_call(client, tok, "generate_image",
+ {"prompt": "the same face, smiling", "from_image": face["media_id"]}))
+ assert out["capability"] == "image_to_image"
+
+ sent = _calls[-1]["body"]
+ assert "inlineData" in json.dumps(sent), "the frame never reached the provider"
+
+ raw = asyncio.run(app.BACKING.graph.get(out["job_id"], label="MediaJob"))
+ stored = json.loads(raw["params_json"])
+ assert "image" not in stored and "image_mime" not in stored
+ assert stored["from_media"] == face["media_id"]
+ assert len(raw["params_json"]) < 2000, "a frame was written onto the vertex"
+ # And a job read back off the vertex can still advance, because the frame is re-readable.
+ job = asyncio.run(app._media_job_get(out["job_id"]))
+ assert job["params"]["from_media"] == face["media_id"]
+ assert asyncio.run(app._media_read_image(session, face["media_id"]))[1]
+
+
+def test_a_missing_input_frame_is_named_rather_than_generated_around(client, harness, session,
+ provider):
+ tok = _cred(harness, session)
+ assert "No job with the id mjob_nope" in _err(
+ _call(client, tok, "generate_video", {"prompt": "a", "seconds": 6,
+ "from_image": "mjob_nope"}))
+ assert "no media with the id med_nope" in _err(
+ _call(client, tok, "generate_image", {"prompt": "a", "from_image": "med_nope"})).lower()
+
+
+def test_the_watermarked_model_is_never_chosen_by_default(client, harness, session, provider):
+ """Invariant 13: every other video candidate down, allow_watermark unset → the refusal, not
+ a stamped clip nobody asked for."""
+ for c in media_plane.capability("text_to_video")["candidates"]:
+ if c["model"] != "happyhorse-1.0-t2v":
+ app._media_quarantine[c["model"]] = time.time() + 900
+ res = _call(client, _cred(harness, session), "generate_video", {"prompt": "a", "seconds": 6})
+ assert "watermarks its output" in _err(res)
+
+ out = _ok(_call(client, _cred(harness, session), "generate_video",
+ {"prompt": "a", "seconds": 6, "allow_watermark": True}))
+ assert out["model"] == "happyhorse-1.0-t2v"
+
+
+def test_parameter_fit_is_checked_before_health(client, harness, session, provider):
+ """A model that cannot render 8 seconds is not a fallback for one that can — it is a different
+ film. MiniMax does 6 and 10 only, so 8 must go past it rather than be rounded onto it."""
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "unknown model"})
+ out = _ok(_call(client, _cred(harness, session), "generate_video",
+ {"prompt": "a", "seconds": 8}))
+ assert out["model"] == "kling-v3", "8 s was silently rounded onto a 6/10 s model"
+ body = next(c["body"] for c in _calls
+ if c["url"].endswith("/video/generations") and c["body"].get("model") == "kling-v3")
+ assert body["duration"] == 8
+
+
+def test_a_video_submit_without_a_duration_is_impossible(client, harness, session, provider):
+ """Invariant 11: kling's own default is 15.041 s at ~$1.68, six times a 6 s MiniMax clip. The
+ schema requires it, and every builder emits it."""
+ assert app._MEDIA_MCP_TOOLS[1]["name"] == "generate_video"
+ assert app._MEDIA_MCP_TOOLS[1]["inputSchema"]["required"] == ["prompt", "seconds"]
+ _ok(_call(client, _cred(harness, session), "generate_video", {"prompt": "a", "seconds": 6}))
+ for c in _calls:
+ if c["url"].endswith("/video/generations"):
+ assert c["body"].get("duration"), f"a clip was submitted with no duration: {c['body']}"
+
+
[email protected]("cap,args,shape", [
+ ("text_to_video", {"prompt": "p", "seconds": 6}, "video-generation"),
+ ("text_to_image", {"prompt": "p", "size": "1920x1920"}, "image-generation"),
+ ("text_to_image", {"prompt": "p"}, "gemini"),
+ ("text_to_image", {"prompt": "p"}, "openai"),
+ ("text_to_speech", {"prompt": "p", "voice": "alloy"}, "audio-chat"),
+])
+def test_only_whitelisted_params_are_forwarded(cap, args, shape):
+ """Invariant 12, one case per shape. The relay silently ignores unknown params and submits the
+ job anyway, so a typo would cost a full-price generation."""
+ cand = next(c for c in media_plane.capability(cap)["candidates"]
+ if c.get("shape") == shape and c.get("status") != "excluded")
+ sub = media_plane.build_submit(cand, TR, {**args, "not_a_real_param": "boom",
+ "resolution": "4k"})
+ assert set(sub.tunables) <= media_plane.declared_params(cand), sub.tunables
+ assert "not_a_real_param" not in json.dumps(sub.body)
+ assert "4k" not in json.dumps(sub.body)
+
+
+def test_the_gemini_shape_keeps_the_google_prefix():
+ """The bare name answers 503. Measured, and the kind of thing a tidy-up would break."""
+ cand = next(c for c in media_plane.capability("text_to_image")["candidates"]
+ if c["shape"] == "gemini")
+ sub = media_plane.build_submit(cand, TR, {"prompt": "p"})
+ assert "google/" in sub.url
+
+
+def test_the_gemini_shape_posts_to_the_api_root_not_under_v1():
+ """`/v1beta` hangs off the ROOT. Measured live 2026-08-15 against a model id that does not
+ exist, so the two answers differ by ROUTE and not by model:
+
+ …/v1/v1beta/models/{id}:generateContent -> 404 "Invalid URL"
+ …/v1beta/models/{id}:generateContent -> 503 model_not_found
+
+ This assertion used to read `f"{TR}/v1beta/..."`, which is the bug written down as the
+ expectation: every Gemini call 404'd, the chain fell through to a slower per-image model, and
+ a picture still came back — so the suite stayed green while the two fastest models in the
+ chain were dead in every deployment. Pin the negative too; that is the half that was wrong.
+ """
+ for cap in ("text_to_image", "image_to_image"):
+ for cand in media_plane.capability(cap)["candidates"]:
+ if cand.get("shape") != "gemini":
+ continue
+ for base in (TR, TR.rstrip("/") + "/", "https://api.tokenrouter.com"):
+ url = media_plane.build_submit(cand, base, {"prompt": "p"}).url
+ assert "/v1/v1beta/" not in url, url
+ assert url == (f"https://api.tokenrouter.com/v1beta/models/"
+ f"{cand['model']}:generateContent"), url
+
+
+def test_arrange_positions_every_element_exactly_once():
+ """A shot holding a still AND a clip laid the board out on top of itself.
+
+ Each media element's companions were "everything sharing the shot name", which includes the
+ OTHER media in that shot and its caption — so four elements produced eight positions, the
+ second pass overwrote the first, and the clip landed under its own caption. The agent noticed
+ before any test did: "the arrange returned duplicate positions… arrange lumped all four into
+ one shot group and stacked them."
+ """
+ def media(eid, shot):
+ return {"id": eid, "width": 480, "height": 270,
+ "customData": {"shot": shot, "media": {"v": 1, "kind": "video",
+ "status": "ready"}}}
+
+ def caption(eid, shot):
+ return {"id": eid, "type": "text", "width": 480, "height": 24,
+ "customData": {"shot": shot}}
+
+ els = [media("A", "Shot 1"), caption("a", "Shot 1"),
+ media("B", "Shot 1"), caption("b", "Shot 1"),
+ media("C", "Shot 2"), caption("c", "Shot 2")]
+ chosen = [e for e in els if media_plane.is_media(e)]
+ pos = media_plane.layout_positions(media_plane.storyboard_items(els, chosen), "storyboard")
+ ids = [p["element_id"] for p in pos]
+ assert sorted(ids) == sorted(e["id"] for e in els), ids
+ assert len(ids) == len(set(ids)), f"an element was positioned twice: {ids}"
+ # And nothing overlaps anything else.
+ boxes = {p["element_id"]: p for p in pos}
+ for i, p in enumerate(pos):
+ for q in pos[i + 1:]:
+ apart = (p["y"] + p["h"] <= q["y"] or q["y"] + q["h"] <= p["y"]
+ or p["x"] + p["w"] <= q["x"] or q["x"] + q["w"] <= p["x"])
+ assert apart, f"{p['element_id']} overlaps {q['element_id']}"
+ # A caption sits directly under the media it was placed with, not under the other clip's.
+ assert boxes["a"]["y"] > boxes["A"]["y"] and boxes["a"]["y"] < boxes["B"]["y"]
+ assert boxes["b"]["y"] > boxes["B"]["y"]
+
+
+def test_every_refusal_ends_with_you_cannot_connect_it_yourself(client, harness, session,
+ provider):
+ """Invariant 25, over every no-model path there is."""
+ for m in [c["model"] for c in media_plane.capability("text_to_video")["candidates"]]:
+ app._media_quarantine[m] = time.time() + 900
+ for m in [c["model"] for c in media_plane.capability("text_to_speech")["candidates"]]:
+ app._media_quarantine[m] = time.time() + 900
+ tok = _cred(harness, session)
+ for name, args in (("generate_video", {"prompt": "a", "seconds": 6}),
+ ("generate_speech", {"text": "hello"}),
+ ("generate_music", {"prompt": "a warm score"})):
+ assert "you cannot connect" in _err(_call(client, tok, name, args)).lower(), name
+
+
+def test_music_never_becomes_speech(client, harness, session, provider):
+ """Invariant 10: with text_to_speech fully available, generate_music still refuses, and no
+ provider call is made.
+
+ And the refusal NAMES THE FIX. One candidate stood down with the reason it is stood down for
+ beats an empty list: "no music model is connected" is true and leaves the reader nowhere,
+ while "needs a paid ElevenLabs plan" is a thing a person can go and do.
+ """
+ _calls.clear()
+ text = _err(_call(client, _cred(harness, session), "generate_music",
+ {"prompt": "a warm orchestral score"}))
+ assert "paid ElevenLabs plan" in text, text
+ assert "not music" in text
+ assert _calls == []
+ # And speech is genuinely available right now, so this is not passing on an empty deployment.
+ assert _ok(_call(client, _cred(harness, session), "generate_speech",
+ {"text": "hello"}))["model"].startswith("openai/gpt-audio")
+
+
+def test_list_capabilities_is_free_and_names_what_is_broken(client, harness, session, provider):
+ _calls.clear()
+ out = _ok(_call(client, _cred(harness, session), "list_capabilities"))
+ by = {c["name"]: c for c in out["capabilities"]}
+ assert _calls == [], "list_capabilities issued a provider call"
+ assert by["text_to_video"]["available"] is True
+ assert by["text_to_video"]["model"] == "dreamina-seedance-2-5-hc"
+ # Every limit reported is one that was MEASURED on this model, and nothing else is reported.
+ # It ignores the duration it is sent — asked 1 s, returned 6.08 s — so the agent is told that
+ # rather than left to believe the number it asked for.
+ assert by["text_to_video"]["limits"] == {"duration_ignored": True,
+ "duration_observed_s": 6.08,
+ "resolution": "1280x720",
+ "accepts_input_image": False}
+ assert by["text_to_music"]["available"] is False
+ assert "paid ElevenLabs plan" in by["text_to_music"]["reason"]
+ assert by["export"]["available"] is media_plane.have_ffmpeg()
+ # A cost is present only where it was measured.
+ assert "estimated_usd_per_unit" not in by["text_to_video"]
+ for m in ("dreamina-seedance-2-5-hc",):
+ app._media_quarantine[m] = time.time() + 900
+ again = {c["name"]: c for c in _ok(_call(client, _cred(harness, session),
+ "list_capabilities"))["capabilities"]}
+ assert again["text_to_video"]["model"] == "MiniMax-Hailuo-2.3"
+ assert again["text_to_video"]["estimated_usd_per_unit"] == 0.28
+ assert again["text_to_video"]["limits"]["durations_s"] == [6, 10]
+
+
+def test_the_session_budget_stops_generation_rather_than_throttling_it(
+ client, harness, session, provider, monkeypatch):
+ monkeypatch.setattr(media_plane, "SESSION_BUDGET_USD", 0.10)
+ provider.video_bytes = b""
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "unknown model"})
+ first = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))
+ job = asyncio.run(app._media_job_get(first["job_id"]))
+ job["status"] = "succeeded"
+ asyncio.run(app._media_job_save(job))
+ text = _err(_call(client, tok, "generate_video", {"prompt": "b", "seconds": 6}))
+ assert "$0.28" in text and "$0.10" in text and "cannot raise the limit" in text
+
+
+# ══ jobs ═════════════════════════════════════════════════════════════════════════
+
+def test_a_video_job_polls_then_lands_as_our_own_file(client, harness, session, provider):
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ out = _ok(_call(client, tok, "generate_video", {"prompt": "rain", "seconds": 6}))
+ jid = out["job_id"]
+
+ tid = next(t for t in provider.tasks)
+ provider.queue_poll(tid, httpx.Response(200, json={"code": "success", "message": "", "data": {
+ "id": tid, "task_id": tid, "status": "IN_PROGRESS", "progress": "40%"}}))
+ # Poll #1 — still rendering. The job must not be advanced past its own next_poll_at, so drop
+ # the gate the way real time would.
+ _due(jid)
+ running = _ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0]
+ assert running["status"] == "running" and running["progress"] == "40%"
+
+ _due(jid)
+ done = _ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0]
+ assert done["status"] == "succeeded" and done["kind"] == "video"
+ assert done["media_id"].startswith("med_")
+ assert done["seconds"] > 0 and done["bytes"] > 0
+ assert done["model"] == "MiniMax-Hailuo-2.3" and done["usd"] == 0.28
+
+
+def test_an_empty_poll_is_never_terminal(client, harness, session, provider):
+ """Invariant 8. An empty record is the known background-response race; reading it as failure
+ is how a finished render gets thrown away."""
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+ tid = next(iter(provider.tasks))
+ provider.queue_poll(tid, httpx.Response(200, json={}))
+
+ rows = []
+ for _ in range(2):
+ _due(jid)
+ rows.append(_ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0])
+ assert [r["status"] for r in rows] == ["unknown", "succeeded"], rows
+ assert "ask again" in rows[0]["note"]
+ # And `unknown` is never what the job IS — only what one answer was.
+ assert asyncio.run(app._media_job_get(jid))["status"] == "succeeded"
+
+
+def test_an_unknown_job_id_is_a_row_and_never_an_omission(client, harness, session, provider):
+ """A missing row reads as 'still running', which is the worst possible answer."""
+ rows = _ok(_call(client, _cred(harness, session), "check_jobs",
+ {"job_ids": ["mjob_nope", "mjob_also_nope"]}))["jobs"]
+ assert [r["job_id"] for r in rows] == ["mjob_nope", "mjob_also_nope"]
+ assert all(r["status"] == "failed" and "No job with that id" in r["error"] for r in rows)
+
+
+def test_a_failed_render_advances_the_chain_exactly_once(client, harness, session, provider):
+ """The render was billable, so the chain advances once — not in a loop."""
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+ tid = next(iter(provider.tasks))
+ provider.queue_poll(tid, httpx.Response(200, json={"code": "success", "data": {
+ "id": tid, "task_id": tid, "status": "FAILURE", "message": "the render failed upstream"}}))
+ _due(jid)
+ row = _ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0]
+ assert row["status"] == "running", "a billable failure did not advance the chain"
+ assert row["model"] == "kling-v3"
+ assert app._media_quarantine["MiniMax-Hailuo-2.3"] > time.time()
+
+
+def test_one_finished_render_is_downloaded_and_stored_exactly_once(client, harness, session,
+ provider):
+ """The sweeper, check_jobs and the app's poll route advance jobs CONCURRENTLY by design.
+
+ Without a per-job lock each of them saw the same SUCCESS, each fetched the same clip and each
+ stored it under a fresh media id. Measured live on the VM: one 6 s clip landed three times,
+ 3,974,388 bytes apiece (byte-identical, md5 2aeae1f1…), two orphaned the instant the third
+ won the vertex. The `next_poll_at` gate does not help — every racer reads the same past value.
+ """
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+
+ async def race():
+ job = await app._media_job_get(jid)
+ job["next_poll_at"] = 0
+ await app._media_job_save(job)
+ fresh = await app._media_job_get(jid)
+ # Five callers, all holding the same pre-landing snapshot — the real shape of the race.
+ return await asyncio.gather(*[app._media_job_advance(dict(fresh)) for _ in range(5)])
+
+ out = asyncio.run(race())
+ assert all(j["status"] == "succeeded" for j in out), [j["status"] for j in out]
+ ids = {j["media_id"] for j in out}
+ assert len(ids) == 1, f"the same render landed under {len(ids)} media ids: {ids}"
+
+ stored = [c for c in _calls if "cdn.provider.example" in c["url"]]
+ assert len(stored) == 1, f"the clip was downloaded {len(stored)} times"
+ assert asyncio.run(app._media_job_get(jid))["media_id"] == ids.pop()
+
+
+def test_a_job_outlives_its_turn(client, harness, session, provider):
+ """Invariant 21. The sweeper is not an optimisation: without it a job whose turn ended and
+ whose tab is closed never completes, and its provider URL expires."""
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+ place = _ok(_call(client, tok, "place", {"items": [{"job_id": jid, "shot": "Shot 1"}]}))
+ eid = place["placed"][0]["element_id"]
+ rev_before = place["scene_rev"]
+
+ _due(jid)
+ assert asyncio.run(app._media_sweep()) >= 1 # no turn, no agent, no tab
+
+ scene = asyncio.run(app._media_scene_read(session))
+ el = next(e for e in scene["elements"] if e["id"] == eid)
+ assert el["customData"]["media"]["status"] == "ready"
+ assert el["customData"]["media"]["mediaId"].startswith("med_")
+ assert int(scene["meta"]["rev"]) > rev_before
+
+
+def test_a_job_that_never_finishes_is_failed_with_a_sentence(client, harness, session, provider,
+ monkeypatch):
+ monkeypatch.setattr(media_plane, "JOB_MAX_S", 0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+ tid = next(iter(provider.tasks))
+ provider.queue_poll(tid, httpx.Response(200, json={"code": "success", "data": {
+ "id": tid, "task_id": tid, "status": "IN_PROGRESS"}}))
+ _due(jid)
+ row = _ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0]
+ assert row["status"] == "failed" and "never finished" in row["error"]
+
+
+def test_the_provider_url_is_never_persisted(client, harness, session, provider):
+ """Invariant 14. Every provider URL is signed or short-lived — happyhorse's lasts a day — so a
+ scene holding one is a scene that stops working tomorrow."""
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+ _ok(_call(client, tok, "place", {"items": [{"job_id": jid}]}))
+ _due(jid)
+ asyncio.run(app._media_sweep())
+
+ med = asyncio.run(app._media_job_get(jid))["media_id"]
+ scene = json.dumps(asyncio.run(app._media_scene_read(session)))
+ vertex = json.dumps(asyncio.run(app._media_job_get(jid)))
+ meta = json.dumps(asyncio.run(app._media_meta(session, med)))
+ for blob in (scene, vertex, meta):
+ assert "cdn.provider.example" not in blob
+ assert med in scene, "the scene does not point at our own copy either"
+
+
+# ══ the synchronous shapes ═══════════════════════════════════════════════════════
+
+def test_an_image_lands_inline_and_says_so(client, harness, session, provider):
+ """A synchronous shape renders inside the submit. Reporting it as 'running' would be a lie the
+ very next call exposes."""
+ out = _ok(_call(client, _cred(harness, session), "generate_image",
+ {"prompt": "a rainy window", "size": "1024x1024"}))
+ assert out["status"] == "succeeded" and out["media_id"].startswith("med_")
+ assert out["model"] == "google/gemini-3.1-flash-lite-image"
+ assert out["size"] == "1024x1024"
+
+
+def test_a_size_below_a_models_floor_skips_it(client, harness, session, provider):
+ """seedream-4.5 rejects anything under 3,686,400 px with a 400. Skipping it is cheaper than
+ finding out."""
+ for c in media_plane.capability("text_to_image")["candidates"]:
+ if c["shape"] == "gemini":
+ app._media_quarantine[c["model"]] = time.time() + 900
+ out = _ok(_call(client, _cred(harness, session), "generate_image",
+ {"prompt": "a", "size": "1024x1024"}))
+ assert out["model"] != "bytedance-seed/seedream-4.5"
+ big = _ok(_call(client, _cred(harness, session), "generate_image",
+ {"prompt": "a", "size": "1920x1920"}))
+ assert big["model"] == "bytedance-seed/seedream-4.5"
+
+
+def test_speech_reports_what_the_model_actually_said(client, harness, session, provider):
+ """These models ANSWER the prompt rather than reading it, and the transcript the provider
+ returns is real data — so `verbatim` is measured, not assumed."""
+ out = _ok(_call(client, _cred(harness, session), "generate_speech", {"text": "Say: hello."}))
+ assert out["model"] == "openai/gpt-audio-mini"
+ assert "answers prompts rather than reading them" in out["warning"]
+ assert out["spoken_text"] == "Hello! It's great to talk with you."
+ assert out["verbatim"] is False
+
+
+def test_the_streaming_audio_model_is_driven_the_way_it_demands(client, harness, session,
+ provider):
+ """gpt-audio answers 400 without stream:true and then delivers audio in deltas that have to be
+ concatenated."""
+ app._media_quarantine["openai/gpt-audio-mini"] = time.time() + 900
+ out = _ok(_call(client, _cred(harness, session), "generate_speech", {"text": "hello"}))
+ assert out["model"] == "openai/gpt-audio" and out["status"] == "succeeded"
+ body = next(c["body"] for c in _calls if c["body"].get("model") == "openai/gpt-audio")
+ assert body["stream"] is True and body["modalities"] == ["text", "audio"]
+ assert out["spoken_text"] == "Hello there."
+
+
+def test_the_openai_shape_reads_the_image_out_of_a_message_with_no_content(client, harness,
+ session, provider):
+ """`message.content` is null on image turns; the picture is in `message.images`."""
+ for c in media_plane.capability("text_to_image")["candidates"]:
+ if c["shape"] in ("gemini", "image-generation"):
+ app._media_quarantine[c["model"]] = time.time() + 900
+ out = _ok(_call(client, _cred(harness, session), "generate_image", {"prompt": "a"}))
+ assert out["model"] == "microsoft/mai-image-2.5" and out["status"] == "succeeded"
+ # And a cost the provider reported INLINE is used, because it was measured.
+ assert out["estimated_usd"] == 0.0482
+
+
+def test_a_body_that_is_not_media_is_a_failure_and_not_a_success(client, harness, session,
+ provider):
+ """A relay answering 200 with an HTML error page is the case this catches. Storing it would
+ make an element that reads as ready and plays nothing."""
+ provider.fail["google/gemini-3.1-flash-lite-image"] = (
+ 200, {"candidates": [{"content": {"parts": [
+ {"inlineData": {"mimeType": "image/png",
+ "data": base64.b64encode(b"<html>gateway timeout</html>").decode()}}]}}]})
+ out = _ok(_call(client, _cred(harness, session), "generate_image", {"prompt": "a"}))
+ # It answered, and it billed, so the chain advances exactly once — and the reason is recorded
+ # rather than an HTML page being stored as a picture.
+ assert out["model"] != "google/gemini-3.1-flash-lite-image"
+ assert "cannot identify as a image" in json.dumps(out["attempts"])
+ assert app._media_quarantine["google/gemini-3.1-flash-lite-image"] > time.time()
+ assert media_plane.sniff(b"<html>gateway timeout</html>") == ("", "")
+
+
+def test_a_billable_render_that_cannot_be_fetched_leaves_a_visible_failure(client, harness,
+ session, provider):
+ """It already billed by the time the fetch is attempted, so an untraceable charge is worse
+ than a job that says what went wrong. With no candidate left to advance to, the job is failed
+ and readable — not absent."""
+ only = "openai/gpt-5.4-image-2"
+ for c in media_plane.capability("text_to_image")["candidates"]:
+ if c["model"] != only:
+ app._media_quarantine[c["model"]] = time.time() + 900
+ provider.fail[only] = (200, {"data": [{"url": "https://cdn.provider.example/gone.png"}]})
+ inner = provider.handle
+
+ def gone(req):
+ return (httpx.Response(404, text="expired") if req.url.path.endswith("gone.png")
+ else inner(req))
+
+ provider.handle = gone
+ out = _ok(_call(client, _cred(harness, session), "generate_image",
+ {"prompt": "a", "size": "1024x1024"}))
+ assert out["status"] == "failed" and out["model"] == only
+ job = asyncio.run(app._media_job_get(out["job_id"]))
+ assert job is not None and job["status"] == "failed"
+ assert "could not be fetched" in job["error"]
+ assert job["attempts"][-1]["model"] == only
+
+
+def test_a_poll_that_reports_success_with_no_video_is_a_failure():
+ """The same rule the submit side holds, on the poll side: SUCCESS with nothing in it is not a
+ success — it is the shape that lets a job sit 'done' with no file."""
+ cand = {"shape": "video-generation", "model": "x"}
+ status, payload, err, _p = media_plane.read_poll(cand, 200, {"code": "success", "data": {
+ "id": "t", "status": "SUCCESS", "result_url": ""}})
+ assert status == "failed" and payload is None and "returned no video" in err
+
+
+def test_the_gemini_reader_walks_past_the_thought_signature_part(client, harness, session,
+ provider):
+ """The ~1 MB thoughtSignature part sits beside the picture and is not one."""
+ out = _ok(_call(client, _cred(harness, session), "generate_image", {"prompt": "a"}))
+ assert out["model"] == "google/gemini-3.1-flash-lite-image"
+ meta = asyncio.run(app._media_meta(session, out["media_id"]))
+ assert meta["mime"] == "image/png" and meta["bytes"] == len(PNG_1PX)
+
+
+def test_the_catalog_is_read_from_disk_and_not_compiled_in(tmp_path, monkeypatch):
+ """A table in source goes stale the moment a provider fixes a model or breaks one, and nothing
+ says so. Same rule as kits and skills."""
+ assert Path(media_plane._CATALOG_PATH).name == "media_catalog.json"
+ doc = json.loads(Path(media_plane._CATALOG_PATH).read_text())
+ assert doc["capabilities"]["text_to_video"]["candidates"][0]["model"] == \
+ "dreamina-seedance-2-5-hc", "the owner's preferred model is no longer rank 1"
+ swapped = tmp_path / "cat.json"
+ swapped.write_text(json.dumps({"providers": {}, "capabilities": {}}))
+ monkeypatch.setattr(media_plane, "_CATALOG_PATH", str(swapped))
+ media_plane.catalog.cache_clear()
+ try:
+ assert media_plane.capability_names() == []
+ finally:
+ monkeypatch.undo()
+ media_plane.catalog.cache_clear()
+
+
+# ══ the catalog is measurement, and corrections are measurement too ══════════════
+# Four things were measured AFTER the sweep that wrote this file, and each is a fact the code has
+# to keep honouring. They are asserted here rather than trusted to a comment.
+
+def test_nothing_is_skipped_for_being_marked_broken(client, harness, session, provider):
+ """The rule that must never be added.
+
+ `dreamina-seedance-2-5-hc` was marked broken for the whole outage and stayed at rank 1,
+ because a candidate that fails at SUBMIT costs nothing to retry. That is the only reason it
+ started working again the day the relay's mapping was fixed — no code change, nobody watching.
+ A tidy-up that skipped everything marked `status: broken` would have made the recovery
+ impossible and left the file looking correct.
+ """
+ broken = [c for c in media_plane.capability("text_to_video")["candidates"]
+ if str(c.get("status") or "") == "broken"]
+ assert broken, "nothing is marked broken any more — this test is asserting against nothing"
+ for cand in broken:
+ assert media_plane.can_serve(cand, {"seconds": 6}) == "", cand["model"]
+ # and the corrected rank 1 is now selected and really renders
+ out = _ok(_call(client, _cred(harness, session), "generate_video",
+ {"prompt": "rain", "seconds": 6}))
+ assert out["model"] == "dreamina-seedance-2-5-hc"
+
+
+def test_the_model_that_ignores_a_duration_says_so_rather_than_being_believed(client, harness,
+ session, provider):
+ """Measured: 1 s was asked for and a 6.08 s clip came back. It stays rank 1 — it renders, and
+ it renders well — but nothing downstream may assume the length it was asked for."""
+ cand = media_plane.capability("text_to_video")["candidates"][0]
+ assert cand["model"] == "dreamina-seedance-2-5-hc" and cand["duration_ignored"] is True
+ assert "duration_min_s" not in cand and "durations_s" not in cand, (
+ "an ignored duration must not be written down as a limit — that would skip the model")
+ out = _ok(_call(client, _cred(harness, session), "generate_video",
+ {"prompt": "rain", "seconds": 1}))
+ assert out["model"] == cand["model"], "a 1 s ask must still reach it, not skip it"
+ assert "does not honour a requested duration" in out["note"]
+ assert "6.08" in out["note"], "the note quotes what was measured, not a guess"
+ # And the duration is still SENT: a video submit that carries none lets the model choose.
+ body = next(c["body"] for c in _calls if c["url"].endswith("/video/generations"))
+ assert body["duration"] == 1
+
+
+def test_the_model_that_rejects_an_input_image_is_not_in_the_image_chain():
+ """It rejects an input image url outright. Listing it in image_to_video would spend the rank-1
+ slot of a capability with NO substitute on a model that cannot do it at all."""
+ assert [c["model"] for c in media_plane.capability("image_to_video")["candidates"]] == [
+ "kling-v3", "kling-v2-6"]
+ t2v = media_plane.capability("text_to_video")["candidates"][0]
+ assert t2v["model"] == "dreamina-seedance-2-5-hc"
+ assert t2v["accepts_input_image"] is False
+ assert media_plane.can_serve(t2v, {"image": "…"}), "it would have taken an image job"
+
+
[email protected]("cap", ["text_to_video", "image_to_video"])
+def test_a_duration_a_model_measurably_refuses_is_not_offered_to_it(cap):
+ """Both kling models answer 400 to a 1 s render, and this file used to claim 1 s was their
+ floor. The claim is gone; what replaced it is the measurement and nothing wider — the shortest
+ duration they DO accept was never measured, and a number nobody measured is worse than none.
+ """
+ klings = [c for c in media_plane.capability(cap)["candidates"]
+ if c["model"] in ("kling-v3", "kling-v2-6")]
+ assert len(klings) == 2
+ for cand in klings:
+ assert "duration_min_s" not in cand, f"{cand['model']} still claims a floor nobody measured"
+ assert cand["durations_rejected_s"] == [1]
+ assert media_plane.can_serve(cand, {"seconds": 1}) == f"{cand['model']} refuses a 1 s render"
+ assert media_plane.can_serve(cand, {"seconds": 6}) == ""
+
+
+def test_music_is_one_stood_down_candidate_and_not_an_empty_list():
+ """A capability with no candidates can only say "nothing is connected". One candidate carrying
+ the reason it is stood down says what to do instead — and holds no credential to say it."""
+ cap = media_plane.capability("text_to_music")
+ cand, skipped = media_plane.resolve("text_to_music", {}, {"tokenrouter"}, {})
+ assert cand is None
+ assert len(cap["candidates"]) == 1
+ only = cap["candidates"][0]
+ assert only["model"] == "elevenlabs/music-v1" and only["status"] == "unavailable"
+ assert only["reason_code"] == "paid_plan_required"
+ # The measured reason is what the agent is told — NOT "nobody has connected that provider",
+ # which is the sentence an unconnected provider would otherwise produce first.
+ assert skipped == [only["reason"]]
+ assert "paid ElevenLabs plan" in media_plane.refusal("text_to_music", skipped)
+ assert not [k for k in json.dumps(cap).lower().split('"') if k.startswith("sk_")], \
+ "a key was written into the catalog; it belongs in the integration document"
+
+
+# ══ the canvas ═══════════════════════════════════════════════════════════════════
+
+def test_placing_a_running_job_is_the_intended_path(client, harness, session, provider):
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ tok = _cred(harness, session)
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "rain", "seconds": 6}))["job_id"]
+ out = _ok(_call(client, tok, "place",
+ {"items": [{"job_id": jid, "shot": "Shot 1", "caption": "Rain on the window"}]}))
+ assert out["placed"][0]["status"] == "running"
+ seen = _ok(_call(client, tok, "describe_canvas"))
+ kinds = [e["kind"] for e in seen["elements"]]
+ assert kinds == ["video", "text"]
+ assert seen["elements"][0]["status"] == "running"
+ assert seen["shots"] == [{"name": "Shot 1", "element_ids": [e["id"] for e in seen["elements"]]}]
+ assert seen["free_space"]["x"] > 0
+ # And the job knows its element, so the agent can move it without another read.
+ assert _ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0]["element_id"]
+
+
+def test_packing_is_driven_by_the_tiles_and_not_by_the_captions(client, harness, session,
+ provider):
+ """A caption sits under its clip. Counting it as an occupant puts the next clip level with the
+ caption instead of level with the clip, and a board drifts down and right one shot at a time."""
+ tok = _cred(harness, session)
+ ids = [_ok(_call(client, tok, "generate_image", {"prompt": f"f{i}"}))["media_id"]
+ for i in range(2)]
+ first = _ok(_call(client, tok, "place",
+ {"items": [{"media_id": ids[0], "caption": "under it"}]}))["placed"]
+ assert (first[0]["x"], first[0]["y"]) == (40.0, 40.0)
+ assert first[1]["y"] > first[0]["y"], "the caption is not under the clip"
+ second = _ok(_call(client, tok, "place",
+ {"items": [{"media_id": ids[1]}]}))["placed"][0]
+ assert second["y"] == 40.0, "the second tile drifted down past a caption"
+ assert second["x"] == first[0]["x"] + first[0]["w"] + 24
+
+
+def test_the_arrange_flag_on_place_has_two_different_behaviours(client, harness, session,
+ provider):
+ """A parameter whose two values behave identically is a lie in a schema."""
+ tok = _cred(harness, session)
+ a = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ b = _ok(_call(client, tok, "generate_image", {"prompt": "b"}))
+ packed = _ok(_call(client, tok, "place", {"items": [{"media_id": a["media_id"]}]}))
+ assert (packed["placed"][0]["x"], packed["placed"][0]["y"]) == (40.0, 40.0)
+ loose = _ok(_call(client, tok, "place", {"items": [{"media_id": b["media_id"]}],
+ "arrange": "none"}))
+ assert (loose["placed"][0]["x"], loose["placed"][0]["y"]) == (0.0, 0.0)
+
+
+def test_describe_canvas_never_returns_raw_scene_json(client, harness, session, provider):
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"]}]}))
+ out = _ok(_call(client, tok, "describe_canvas"))
+ el = out["elements"][0]
+ assert set(el) <= {"id", "kind", "x", "y", "w", "h", "label", "status", "seconds", "model",
+ "job_id", "media_id"}
+ assert "versionNonce" not in json.dumps(out) and "seed" not in json.dumps(out)
+
+
+def test_an_item_must_name_exactly_one_thing(client, harness, session, provider):
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ both = _err(_call(client, tok, "place",
+ {"items": [{"text": "hi"}, {"media_id": img["media_id"], "text": "also"}]}))
+ assert "item 2 named both" in both
+ assert "item 1 named neither" in _err(_call(client, tok, "place", {"items": [{"x": 0}]}))
+
+
+def test_moving_one_element_of_a_shot_moves_the_shot(client, harness, session, provider):
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ placed = _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"],
+ "shot": "Shot 1", "caption": "under it",
+ "x": 0, "y": 0}]}))
+ clip, cap = placed["placed"][0]["element_id"], placed["placed"][1]["element_id"]
+ before = {e["id"]: e for e in _ok(_call(client, tok, "describe_canvas"))["elements"]}
+ out = _ok(_call(client, tok, "move", {"moves": [{"element_id": clip, "x": 500, "y": 300}]}))
+ assert out["moved"] == [clip] and out["not_found"] == []
+ after = {e["id"]: e for e in _ok(_call(client, tok, "describe_canvas"))["elements"]}
+ assert after[clip]["x"] == 500
+ assert after[cap]["x"] == before[cap]["x"] + 500
+ assert after[cap]["y"] == before[cap]["y"] + 300
+
+
+def test_arrange_packs_a_grid_and_a_storyboard(client, harness, session, provider):
+ tok = _cred(harness, session)
+ for i in range(3):
+ img = _ok(_call(client, tok, "generate_image", {"prompt": f"frame {i}"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"],
+ "shot": f"Shot {i + 1}",
+ "caption": f"caption {i}"}]}))
+ grid = _ok(_call(client, tok, "arrange", {"layout": "grid", "columns": 2}))
+ xs = {p["x"] for p in grid["positions"]}
+ assert len(grid["positions"]) == 3 and len(xs) == 2
+
+ story = _ok(_call(client, tok, "arrange", {"layout": "storyboard"}))
+ ys = [p["y"] for p in story["positions"]]
+ assert ys == sorted(ys) and len(story["positions"]) == 6, "captions are not in the rows"
+
+
+def test_remove_never_deletes_media(client, harness, session, provider):
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ eid = _ok(_call(client, tok, "place",
+ {"items": [{"media_id": img["media_id"]}]}))["placed"][0]["element_id"]
+ out = _ok(_call(client, tok, "remove", {"element_ids": [eid, "el_nope"]}))
+ assert out["removed"] == [eid] and out["not_found"] == ["el_nope"]
+ assert out["media_kept"] is True
+ # And it can be placed again, which is the whole reason to say so.
+ again = _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"]}]}))
+ assert again["placed"][0]["element_id"] != eid
+
+
+def test_a_finished_image_gets_a_new_file_id_equal_to_its_media_id(client, harness, session,
+ provider):
+ """Excalidraw's addFiles will not update a fileId that already exists, so a placeholder swapped
+ onto the same id stays a placeholder forever."""
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"]}]}))
+ scene = asyncio.run(app._media_scene_read(session))
+ el = next(e for e in scene["elements"] if e["type"] == "image")
+ assert el["fileId"] == img["media_id"]
+ assert scene["files"][img["media_id"]]["id"] == img["media_id"]
+ assert scene["files"][img["media_id"]]["dataURL"].endswith(img["media_id"])
+
+
+def test_the_scene_stays_a_valid_excalidraw_scene(client, harness, session, provider):
+ """Invariant 15, as far as Python can assert it: the top-level shape Excalidraw's restore()
+ reads, plus our two additions surviving a round trip."""
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"], "shot": "Shot 1"}]}))
+ scene = asyncio.run(app._media_scene_read(session))
+ assert scene["type"] == "excalidraw" and scene["version"] == 2
+ assert set(scene) >= {"type", "version", "source", "elements", "appState", "files",
+ "timeline", "meta"}
+ el = scene["elements"][0]
+ for k in ("id", "type", "x", "y", "width", "height", "angle", "strokeColor",
+ "backgroundColor", "seed", "version", "versionNonce", "isDeleted", "groupIds"):
+ assert k in el, k
+ # The Map that becomes {} on a round trip and crashes .forEach is never stored.
+ assert "collaborators" not in scene["appState"]
+ round_tripped = media_plane.sanitize_scene(json.loads(json.dumps(scene)))
+ assert round_tripped["timeline"] == scene["timeline"]
+ assert round_tripped["elements"][0]["customData"] == el["customData"]
+
+
+# ══ the timeline and the export ══════════════════════════════════════════════════
+
+def _two_ready_clips(client, tok, provider, session) -> list[str]:
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ ids = []
+ for i, (secs, size) in enumerate(((1.0, "128x72"), (1.0, "72x128"))):
+ provider.video_bytes = _mp4(secs, size)
+ jid = _ok(_call(client, tok, "generate_video",
+ {"prompt": f"shot {i}", "seconds": 6}))["job_id"]
+ eid = _ok(_call(client, tok, "place",
+ {"items": [{"job_id": jid, "shot": f"Shot {i + 1}"}]}
+ ))["placed"][0]["element_id"]
+ _due(jid)
+ asyncio.run(app._media_sweep())
+ ids.append(eid)
+ return ids
+
+
+@needs_ffmpeg
+def test_the_timeline_is_explicit_order_and_warns_honestly(client, harness, session, provider):
+ tok = _cred(harness, session)
+ a, b = _two_ready_clips(client, tok, provider, session)
+ out = _ok(_call(client, tok, "set_timeline",
+ {"shots": [{"element_id": b}, {"element_id": a}], "fps": 30,
+ "resolution": "1920x1080"}))
+ assert out["ready"] is True and out["timeline"]["shots"] == 2
+ assert out["total_seconds"] > 0
+ assert any("letterboxed" in w for w in out["warnings"]), out
+ scene = asyncio.run(app._media_scene_read(session))
+ # ARRAY ORDER IS THE CUT ORDER — never re-derived from where things sit on the canvas.
+ assert [s["elementId"] for s in scene["timeline"]["shots"]] == [b, a]
+
+
+@needs_ffmpeg
+def test_export_letterboxes_and_validates_its_own_duration(client, harness, session, provider):
+ """Invariants 22 and 23. One 9:16 shot in position 1 must not distort the film, and an
+ assembled duration nobody checks is one nobody notices is wrong."""
+ tok = _cred(harness, session)
+ a, b = _two_ready_clips(client, tok, provider, session)
+ _ok(_call(client, tok, "set_timeline", {"shots": [{"element_id": a}, {"element_id": b}],
+ "resolution": "1920x1080", "fps": 24}))
+ out = _ok(_call(client, tok, "export_timeline", {}))
+ assert out["shots"] == 2 and out["status"] == "running"
+ assert "eta" not in json.dumps(out).lower()
+
+ for _ in range(120):
+ job = asyncio.run(app._media_job_get(out["job_id"]))
+ if job["status"] != "running":
+ break
+ time.sleep(0.5)
+ assert job["status"] == "succeeded", job.get("error")
+ assert job["width"] == 1920 and job["height"] == 1080
+ assert abs(job["seconds"] - 2.0) < 0.5
+
+ # LETTERBOXED, NOT STRETCHED — read off the actual pixels. Shot 2 is 72x128 (portrait); in a
+ # 1920x1080 frame its picture is a centred column with black either side. A film that resized
+ # every clip to the first one's shape would paint the whole row blue.
+ film = asyncio.run(app._blob_get(app._media_blob(session, job["media_id"], "mp4"),
+ kb=app.BLOB_KB))
+ frame = _frame_at(film, 1.5)
+ def px(x, y):
+ i = (y * 1920 + x) * 3
+ return frame[i], frame[i + 1], frame[i + 2]
+ assert max(px(10, 540)) < 40, "the padding is not black — the shot was stretched"
+ assert px(960, 540)[2] > 120, "the middle of the frame is not the shot"
+ # And shot 1 is 16:9, so it fills the frame edge to edge with no bars.
+ first = _frame_at(film, 0.5)
+ assert first[(540 * 1920 + 10) * 3 + 2] > 120, "a 16:9 shot was letterboxed anyway"
+
+
+def _frame_at(mp4: bytes, t: float) -> bytes:
+ """One decoded RGB frame of a film, so 'letterboxed, never stretched' is read off pixels
+ rather than off a duration nobody looked at."""
+ with tempfile.TemporaryDirectory() as d:
+ src = os.path.join(d, "film.mp4")
+ Path(src).write_bytes(mp4)
+ out = subprocess.run(["ffmpeg", "-nostdin", "-ss", str(t), "-i", src, "-frames:v", "1",
+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
+ capture_output=True, check=True)
+ return out.stdout
+
+
+@needs_ffmpeg
+def test_export_fails_when_the_assembled_length_is_not_the_planned_length(monkeypatch):
+ """Invariant 23, at the guard itself. An assembled duration nobody checks is an assembled
+ duration nobody notices is wrong — which is exactly how a two-second-short film ships."""
+ real = media_plane.probe_file
+ with tempfile.TemporaryDirectory() as d:
+ clip = os.path.join(d, "a.mp4")
+ Path(clip).write_bytes(_mp4(2.0))
+ out = os.path.join(d, "out.mp4")
+
+ def short(path):
+ got = real(path)
+ return {**got, "seconds": 0.2} if path == out else got
+
+ monkeypatch.setattr(media_plane, "probe_file", short)
+ with pytest.raises(media_plane.ExportRefused) as e:
+ media_plane.assemble([{"path": clip, "in_s": 0.0, "out_s": 2.0}], [], fps=24,
+ resolution="1920x1080", out_path=out)
+ msg = str(e.value)
+ assert "0.20s" in msg and "2.00s" in msg, msg
+ assert "Nothing was delivered" in msg
+
+
+@needs_ffmpeg
+def test_export_refuses_while_a_shot_is_still_rendering(client, harness, session, provider):
+ tok = _cred(harness, session)
+ a, _b = _two_ready_clips(client, tok, provider, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ pending = _ok(_call(client, tok, "generate_video", {"prompt": "c", "seconds": 6}))["job_id"]
+ eid = _ok(_call(client, tok, "place",
+ {"items": [{"job_id": pending}]}))["placed"][0]["element_id"]
+ tl = _ok(_call(client, tok, "set_timeline",
+ {"shots": [{"element_id": a}, {"element_id": eid}]}))
+ assert tl["ready"] is False
+ assert any("still rendering" in w for w in tl["warnings"])
+ assert "still rendering" in _err(_call(client, tok, "export_timeline", {}))
+
+
+def test_export_refuses_honestly_without_ffmpeg(client, harness, session, provider, monkeypatch):
+ """Invariant 24. No silent degradation and no partial file."""
+ monkeypatch.setattr(media_plane, "have_ffmpeg", lambda: False)
+ tok = _cred(harness, session)
+ text = _err(_call(client, tok, "export_timeline", {}))
+ assert "ffmpeg is not installed" in text and "still here to download" in text
+ caps = {c["name"]: c for c in _ok(_call(client, tok, "list_capabilities"))["capabilities"]}
+ assert caps["export"]["available"] is False
+ assert "ffmpeg is not installed" in caps["export"]["reason"]
+
+
+def test_export_with_an_empty_timeline_refuses(client, harness, session, provider):
+ assert "nothing in the timeline" in _err(
+ _call(client, _cred(harness, session), "export_timeline", {})).lower()
+
+
+# ══ the app's data plane ═════════════════════════════════════════════════════════
+
+def test_the_app_reads_the_scene_and_the_server_describes_itself(api, harness, session, client,
+ provider):
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"]}]}))
+
+ got = api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}/scene").json()
+ assert got["rev"] >= 1 and got["scene"]["type"] == "excalidraw"
+
+ desc = api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}").json()
+ assert desc["id"] == ENTRY_ID and desc["name"] == "media"
+ by = {c["name"]: c for c in desc["capabilities"]}
+ assert by["text_to_video"]["available"] is True
+ assert by["text_to_music"]["available"] is False
+ assert desc["export"]["available"] is media_plane.have_ffmpeg()
+ assert "connection" not in desc
+
+
+def test_the_app_cannot_add_or_delete_a_media_element(api, harness, session, client, provider):
+ """Invariant 17: a browser bug must not be able to orphan a rendered clip or resurrect a
+ deleted one."""
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"], "caption": "hi"}]}))
+ base = f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}/scene"
+ got = api.get(base).json()
+ scene = got["scene"]
+
+ stripped = {**scene, "elements": [e for e in scene["elements"]
+ if not media_plane.is_media(e)]}
+ r = api.put(base, json={"scene": stripped}, headers={"if-match": str(got["rev"])})
+ assert r.status_code == 422 and r.json()["error"]["code"] == "media_elements_are_the_agents"
+ assert api.get(base).json()["rev"] == got["rev"], "the store moved on a refused write"
+
+ # Moving what the person drew, and what they may move, is fine.
+ moved = {**scene, "elements": [{**e, "x": 999} for e in scene["elements"]]}
+ ok = api.put(base, json={"scene": moved}, headers={"if-match": str(got["rev"])})
+ assert ok.status_code == 200 and ok.json()["rev"] == got["rev"] + 1
+
+
+def test_the_app_write_is_409_while_a_turn_runs_and_412_when_the_revision_moved(
+ api, harness, session, client, provider):
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"]}]}))
+ base = f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}/scene"
+ got = api.get(base).json()
+
+ stale = api.put(base, json={"scene": got["scene"]}, headers={"if-match": "0"})
+ assert stale.status_code == 412 and stale.json()["error"]["code"] == "scene_moved"
+ assert stale.json()["error"]["detail"]["rev"] == got["rev"]
+
+ asyncio.run(app._vg_upsert("HarnessSession", session, {"turn_status": "running"}))
+ busy = api.put(base, json={"scene": got["scene"]}, headers={"if-match": str(got["rev"])})
+ assert busy.status_code == 409 and busy.json()["error"]["code"] == "session_busy"
+ asyncio.run(app._vg_upsert("HarnessSession", session, {"turn_status": "idle"}))
+
+
+def test_the_media_route_serves_ranges(api, harness, session, client, provider):
+ """Without Range, Safari refuses to play at all and a timeline cannot scrub."""
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ url = (f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}"
+ f"/media/{img['media_id']}")
+ whole = api.get(url)
+ assert whole.status_code == 200 and whole.headers["accept-ranges"] == "bytes"
+ assert whole.headers["etag"] == f'"{img["media_id"]}"'
+ assert "immutable" in whole.headers["cache-control"]
+ assert whole.content == PNG_1PX
+
+ part = api.get(url, headers={"range": "bytes=0-9"})
+ assert part.status_code == 206 and len(part.content) == 10
+ assert part.headers["content-range"] == f"bytes 0-9/{len(PNG_1PX)}"
+ tail = api.get(url, headers={"range": "bytes=-4"})
+ assert tail.status_code == 206 and tail.content == PNG_1PX[-4:]
+ assert api.get(url, headers={"range": "bytes=999999-"}).status_code == 416
+
+
+def test_the_apps_job_poll_is_the_same_path_the_agent_takes(api, harness, session, client,
+ provider):
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "no"})
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+ _due(jid)
+ out = api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}/jobs"
+ f"?ids={jid}").json()
+ assert out["jobs"][0]["job_id"] == jid and out["jobs"][0]["status"] == "succeeded"
+ assert out["spend_usd"] == 0.28
+
+
+def test_the_spend_figure_is_measured_and_absent_when_it_is_not(api, harness, session, client,
+ provider):
+ """Invariant 30: a session whose jobs reported no cost shows nothing at all, not $0.00."""
+ tok = _cred(harness, session)
+ _ok(_call(client, tok, "generate_image", {"prompt": "a"})) # gemini reports no cost
+ out = api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}/jobs").json()
+ assert out["spend_usd"] == 0
+ assert out["jobs"][0].get("usd") is None, "a cost nobody measured was reported"
+
+
+def test_another_org_cannot_reach_any_of_it(client, api, harness, session, provider):
+ other = {**HEADERS, "x-harness-org": "someone-else"}
+ base = f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}"
+ for r in (client.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}", headers=other),
+ client.get(f"{base}/scene", headers=other),
+ client.get(f"{base}/jobs", headers=other),
+ client.get(f"{base}/media/med_anything", headers=other),
+ client.post(f"{base}/export", headers=other)):
+ _seen.append(r.text)
+ assert r.status_code == 404, r.text
+
+
+def test_deleting_the_session_takes_its_media_with_it(api, harness, session, client, provider):
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ assert asyncio.run(app._media_meta(session, img["media_id"]))
+ api.delete(f"/v1/traces/{session}")
+ assert asyncio.run(app._media_meta(session, img["media_id"])) is None
+ assert asyncio.run(app._media_jobs_of(session)) == []
+
+
+# ══ the workspace projection ═════════════════════════════════════════════════════
+
+def test_the_scene_is_projected_into_the_workspace_as_an_ordinary_artifact(client, harness,
+ session, provider):
+ """The canvas lives in the store because the gateway cannot durably write a live sandbox's
+ workspace mid-turn — but `scene.excalidraw` still has to be a file the console can list."""
+ tok = _cred(harness, session)
+ img = _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ _ok(_call(client, tok, "place", {"items": [{"media_id": img["media_id"]}]}))
+ raw = asyncio.run(app.BACKING.workspace.read(session, "scene.excalidraw"))
+ assert raw, "nothing was projected"
+ doc = json.loads(raw)
+ assert doc["type"] == "excalidraw" and doc["elements"]
+ assert doc["meta"]["rev"] == asyncio.run(app._media_scene_read(session))["meta"]["rev"]
+
+
+# ══ attacked ═════════════════════════════════════════════════════════════════════
+# Findings from an adversarial pass, each written so that PASSING means the attack was repelled.
+# They are here rather than in a scratch file because a hole closed once and left untested is a
+# hole that comes back the next time someone tidies the code that closed it.
+
+_KEY_IN_A_401 = (f"Incorrect API key provided: {PROVIDER_KEY}. You can find your API key at "
+ f"https://tokenrouter.example/keys")
+
+
+def _fail_every_candidate(provider, cap: str, status: int, body: dict) -> None:
+ """Every model this capability could reach answers the same way — which is what turns one
+ provider sentence into the refusal that enumerates all of them."""
+ for cand in media_plane.capability(cap)["candidates"]:
+ provider.fail[str(cand["model"])] = (status, body)
+
+
+def test_a_provider_sentence_that_names_the_key_never_reaches_the_agent(client, harness, session,
+ provider):
+ """Every major provider echoes the offending credential in its 401 — OpenAI's is literally
+ `Incorrect API key provided: sk-…`. The refusal names every candidate it skipped, so one
+ un-redacted sentence is the key handed to the sandbox once per candidate in a single tool
+ result. The sandbox runs a customer's agent with real bash and real egress."""
+ _fail_every_candidate(provider, "text_to_image", 401, {"message": _KEY_IN_A_401})
+ body = _err(_call(client, _cred(harness, session), "generate_image", {"prompt": "a cat"}))
+ assert PROVIDER_KEY not in body, body[:500]
+ # Redacted, not swallowed: the diagnosis is the whole point of relaying the sentence at all.
+ assert "Incorrect API key provided" in body
+
+
+def test_a_credential_shaped_string_is_redacted_even_when_it_is_not_our_key(client, harness,
+ session, provider):
+ """A provider says more than our own key out loud: the account it bills, a token it wants us
+ to use instead, a signed URL. Matching only the string we configured catches only the leak we
+ already knew about."""
+ other = "sk-live-9f2b7c41d0e8a35b6c7d8e9f0a1b"
+ _fail_every_candidate(provider, "text_to_image", 401, {"message":
+ f"key {other} for org-9f2b7c41d0 is revoked; retry as "
+ f"https://api.example/v1/x?api_key={other} with Bearer {other}"})
+ body = _err(_call(client, _cred(harness, session), "generate_image", {"prompt": "a cat"}))
+ for secret in (other, "org-9f2b7c41d0"):
+ assert secret not in body, body[:500]
+ assert "is revoked" in body
+
+
[email protected]("sentence", [
+ "400 unknown model 'eva-video-2.5' (relay maps it to a name the upstream rejects)",
+ "Audio output requires stream: true",
+ "InvalidParameter: image size must be at least 3686400 pixels, got 1024x1024",
+ "fail_to_fetch_task — upstream 'model is not supported'",
+ "api_panic: assignment to entry in nil map",
+ "code 1201: the image is not valid base64",
+ "Your account does not have access to gpt-5-image-mini; api-version 2026-01-01 is required",
+ "the render failed upstream after 240s",
+])
+def test_redaction_leaves_the_diagnosis_completely_intact(sentence):
+ """The point of relaying a provider's own sentence is that it diagnoses. A scrubber that eats
+ model ids, parameter names, error codes or version strings turns every failure into 'something
+ went wrong' — which is the paraphrase this deliberately does not do."""
+ assert media_plane.scrub(sentence) == sentence
+
+
+def _a_job_that_fails_naming_the_key(client, tok, provider) -> str:
+ """One video job whose render fails upstream with the key in the failure message, and whose
+ fallback is refused the same way. Returns the job id, failed."""
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "rain", "seconds": 6}))["job_id"]
+ tid = next(iter(provider.tasks))
+ provider.queue_poll(tid, httpx.Response(200, json={"code": "success", "data": {
+ "id": tid, "task_id": tid, "status": "FAILURE",
+ "message": f"auth rejected for key {PROVIDER_KEY}"}}))
+ _fail_every_candidate(provider, "text_to_video", 500,
+ {"message": f"auth rejected for key {PROVIDER_KEY}"})
+ _due(jid)
+ return jid
+
+
+def test_a_provider_sentence_that_names_the_key_is_not_written_onto_the_job(client, harness,
+ session, provider):
+ """Worse than a transient echo: a billable failure writes the sentence into `attempts` on a
+ vertex, where it outlives the turn, the tab and a restart."""
+ tok = _cred(harness, session)
+ jid = _a_job_that_fails_naming_the_key(client, tok, provider)
+ row = _ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0]
+ assert row["status"] == "failed", row # the advance really ran
+ vertex = asyncio.run(app.BACKING.graph.get(jid, label="MediaJob"))
+ assert PROVIDER_KEY not in json.dumps(vertex), json.dumps(vertex.get("attempts_json"))[:500]
+ assert PROVIDER_KEY not in json.dumps(row)
+ assert "auth rejected" in json.dumps(row) # and the diagnosis survived
+
+
+def test_a_provider_sentence_that_names_the_key_is_not_served_to_the_browser(api, client, harness,
+ session, provider):
+ """The app's jobs route returns `error`, straight from the same string."""
+ tok = _cred(harness, session)
+ _a_job_that_fails_naming_the_key(client, tok, provider)
+ r = api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}/jobs")
+ assert '"failed"' in r.text, r.text[:300] # the advance really ran
+ assert PROVIDER_KEY not in r.text, r.text[:500]
+
+
+def test_a_provider_chosen_task_id_cannot_move_the_poll_to_another_host(client, harness, session,
+ provider):
+ """`build_poll` interpolates the provider's OWN task id into a URL, and that poll carries this
+ deployment's key. A relay that answers a submit with a task id containing `@` or `../` would
+ otherwise choose where the key goes."""
+ cand = next(c for c in media_plane.capability("text_to_video")["candidates"]
+ if c.get("shape") == "video-generation")
+ for hostile in ("[email protected]", "../../../../evil.example/x", "..%2f..%2fevil.example",
+ "x#@evil.example", "[email protected]"):
+ _method, url = media_plane.build_poll(cand, TR, hostile)
+ assert httpx.URL(url).host == "api.tokenrouter.com", url
+
+
+def test_the_finished_file_is_fetched_without_the_credential(client, harness, session, provider):
+ """A result_url is an address the PROVIDER chose. Fetching it must not carry our key."""
+ provider.video_bytes = _mp4(1.0)
+ jid = _ok(_call(client, _cred(harness, session), "generate_video",
+ {"prompt": "a", "seconds": 6}))["job_id"]
+ _due(jid)
+ asyncio.run(app._media_sweep())
+ fetches = [c for c in _calls if "cdn.provider.example" in c["url"]]
+ assert fetches, "the fetch never happened — the assertion below would be vacuous"
+ assert all(not c["auth"] for c in fetches), fetches
+
+
+def test_a_result_url_inside_our_own_network_is_not_fetched(client, harness, session, provider):
+ """A result_url is attacker-influenced, and nothing checked it: the gateway reached
+ 169.254.169.254 — where cloud metadata lives — because a relay named it."""
+ provider.video_bytes = _mp4(1.0)
+ provider.result_url = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
+ tok = _cred(harness, session)
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "a", "seconds": 6}))["job_id"]
+ for _ in range(4):
+ if asyncio.run(app._media_job_get(jid))["status"] != "running":
+ break
+ _due(jid)
+ asyncio.run(app._media_sweep())
+ inside = [c for c in _calls if "169.254.169.254" in c["url"]]
+ assert not inside, [c["url"] for c in inside]
+ row = _ok(_call(client, tok, "check_jobs", {"job_ids": [jid]}))["jobs"][0]
+ assert row["status"] == "failed" and "AWSSECRET" not in json.dumps(row)
+
+
+# ── the job model ────────────────────────────────────────────────────────────────
+
+def test_another_agent_cannot_read_this_agents_session_through_the_app(api, client, kit, harness,
+ session, provider,
+ monkeypatch):
+ """The app's data plane binds the ENTRY to the harness and the SESSION to the org — and, until
+ this, never the session to the harness. So a second agent's own media entry plus this
+ session's id read its jobs, its canvas, and the BYTES of its render."""
+ provider.video_bytes = _mp4(1.0)
+ tok = _cred(harness, session)
+ jid = _ok(_call(client, tok, "generate_video",
+ {"prompt": "secret storyboard", "seconds": 6}))["job_id"]
+ _ok(_call(client, tok, "place", {"items": [{"text": "CONFIDENTIAL SHOT LIST"}]}))
+ _due(jid)
+ asyncio.run(app._media_sweep())
+ med = asyncio.run(app._media_job_get(jid))["media_id"]
+ assert med, "nothing landed — the assertions below would be vacuous"
+
+ kid_b = f"mediab{int(time.time() * 1e6) % 10_000_000}"
+ monkeypatch.setattr(app, "_kits", lambda: {kid_b: {**_KIT, "id": kid_b}})
+ hid_b = _launch(api, kid_b)["harnessId"]
+ base = f"/v1/harnesses/{hid_b}/servers/{ENTRY_ID}/sessions/{session}"
+ for path in (f"{base}/jobs", f"{base}/scene", f"{base}/media/{med}"):
+ r = api.get(path)
+ assert r.status_code >= 400, f"{path} served another agent's session: {r.text[:200]}"
+ assert jid not in r.text and "CONFIDENTIAL" not in r.text
+ assert api.put(f"{base}/scene", json={"scene": {}}).status_code >= 400
+ # and the same session on its OWN agent still works, so this is not passing by refusing
+ # everything.
+ assert api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{session}"
+ f"/media/{med}").status_code == 200
+
+
+def test_a_session_that_names_no_agent_is_refused_rather_than_assumed(api, harness):
+ """A session that names no agent cannot be proved to belong to this one. Fail closed."""
+ sid = "sess_" + os.urandom(6).hex()
+ asyncio.run(app._vg_upsert("HarnessSession", sid, {"tenant": ORG, "status": "idle"}))
+ r = api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{sid}/scene")
+ assert r.status_code == 404, r.text[:200]
+
+
+def test_deleting_the_agent_stops_and_buries_its_jobs(api, client, kit, provider):
+ """DELETE returned 200 and the sweeper carried on: two more provider calls carrying the key,
+ and a finished file written into the store — for an agent the owner had deleted."""
+ hid = _launch(api, kit)["harnessId"]
+ sid = _session_of(hid)
+ provider.video_bytes = _mp4(1.0)
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "a", "seconds": 6}))["job_id"]
+ assert api.delete(f"/v1/harnesses/{hid}").status_code == 200
+
+ _due(jid)
+ _calls.clear()
+ asyncio.run(app._media_sweep())
+ assert [c["url"] for c in _calls if "/video/generations/" in c["url"]] == []
+ job = asyncio.run(app._media_job_get(jid))
+ assert job["status"] != "succeeded" and not job.get("media_id")
+ assert asyncio.run(app._blob_list_all(f"media/{sid}/", kb=app.BLOB_KB)) == []
+ # Nothing addressed to a deleted agent is still readable, by either door.
+ assert _call(client, _cred(hid, sid), "check_jobs",
+ {"job_ids": [jid]}).get("isError") is True
+ assert api.get(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/sessions/{sid}/jobs").status_code >= 400
+
+
+def test_switching_the_media_server_off_stops_its_jobs_and_switching_it_on_resumes_them(
+ api, client, kit, provider):
+ """`check_enabled` refuses a TURN; the sweeper never asked, so a server the owner had switched
+ off carried on spending. Off is a pause, not a death — the same job finishes when it is back
+ on, which is what makes this different from deleting the agent."""
+ hid = _launch(api, kit)["harnessId"]
+ sid = _session_of(hid)
+ provider.video_bytes = _mp4(1.0)
+ jid = _ok(_call(client, _cred(hid, sid), "generate_video",
+ {"prompt": "a", "seconds": 6}))["job_id"]
+
+ assert _save_config(api, hid, [{**_entry_of(hid), "enabled": False}]).status_code == 200
+ _due(jid)
+ _calls.clear()
+ asyncio.run(app._media_sweep())
+ assert [c["url"] for c in _calls if "/video/generations/" in c["url"]] == []
+ assert asyncio.run(app._media_job_get(jid))["status"] == "running"
+
+ assert _save_config(api, hid, [{**_entry_of(hid), "enabled": True}]).status_code == 200
+ _due(jid)
+ asyncio.run(app._media_sweep())
+ assert asyncio.run(app._media_job_get(jid))["status"] == "succeeded"
+
+
+def test_one_tool_call_buys_at_most_one_fallback_render(client, harness, session, provider):
+ """A transient failure fetching the FINISHED file is not a reason to render the whole chain.
+
+ `_media_job_billable_failure` promised to advance EXACTLY ONCE; it advanced once per POLL, and
+ there is a poll after every advance. Measured with the CDN 503ing on an otherwise-fine render:
+ one generate_video walked all six models, $1.96 of list price, and the agent was told nothing.
+ """
+ provider.video_bytes = _mp4(1.0)
+ provider.cdn_status = 503
+ tok = _cred(harness, session)
+ jid = _ok(_call(client, tok, "generate_video", {"prompt": "one shot", "seconds": 6}))["job_id"]
+ for _ in range(10):
+ if asyncio.run(app._media_job_get(jid))["status"] != "running":
+ break
+ _due(jid)
+ asyncio.run(app._media_sweep())
+ submits = [c for c in _calls if c["url"].endswith("/video/generations")]
+ assert len(submits) <= 2, ("one call bought "
+ f"{len(submits)} renders: {[c['body'].get('model') for c in submits]}")
+ job = asyncio.run(app._media_job_get(jid))
+ assert job["status"] == "failed"
+ # And the money is counted. The budget guard summed only SUCCEEDED jobs, so a session that
+ # burned the whole chain read as $0.00 and the cap never fired.
+ assert asyncio.run(app._media_spend(session)) >= 0.28
+
+
+def test_a_media_id_cannot_walk_out_of_its_session(api, client, harness, provider):
+ """`med` is agent- and URL-supplied and is interpolated straight into a storage key."""
+ sid_a, sid_b = _session_of(harness), _session_of(harness)
+ _ok(_call(client, _cred(harness, sid_b), "place",
+ {"items": [{"text": "OTHER SESSION SECRET"}]}))
+ ref = f"../../sessions/{sid_b}/scene"
+ r = api.get(f"/v1/harnesses/{harness}/servers/{ENTRY_ID}/sessions/{sid_a}/media/{ref}")
+ assert "OTHER SESSION SECRET" not in r.text
+ res = _call(client, _cred(harness, sid_a), "generate_image", {"prompt": "x",
+ "from_image": ref})
+ assert "OTHER SESSION" not in json.dumps(res)
+
+
+# ══ a real generation, only when a key is configured ═════════════════════════════
+
+@needs_live
+def test_one_real_image_end_to_end(api, kit, client):
+ """The cheapest, fastest verified model, one call, the smallest size it takes. Skipped
+ entirely unless HR_TEST_TOKENROUTER_KEY is set."""
+ _connect_provider(LIVE_KEY)
+ try:
+ hid = _launch(api, kit)["harnessId"]
+ sid = "sess_" + os.urandom(6).hex()
+ asyncio.run(app._vg_upsert("HarnessSession", sid, {"tenant": ORG, "status": "idle"}))
+ out = _ok(_call(client, _cred(hid, sid), "generate_image",
+ {"prompt": "a single grey square", "size": "1024x1024"}))
+ assert out["status"] == "succeeded", out
+ meta = asyncio.run(app._media_meta(sid, out["media_id"]))
+ assert meta["bytes"] > 0 and meta["mime"].startswith("image/")
+ print(f"[live] {out['model']} produced {meta['bytes']}B", flush=True)
+ finally:
+ _connect_provider()
+
+
+@needs_live
+def test_the_two_untested_video_models_are_probed_once_each(api, kit, client):
+ """MiniMax-Hailuo-2.3 and happyhorse-1.0-t2v were never submitted. ONE submit each, at the
+ shortest duration each allows, and the task id is NOT polled to completion — a submit that
+ returns a task id is the fact under test.
+
+ A TASK ID, not a status code. `google/gemini-3-pro-image-preview` answers 200 with an empty
+ parts list and bills ~1356 tokens for it, so a probe that reads HTTP < 500 as "this model
+ works" would record that model as available on every call, for as long as it kept charging.
+ Availability is a media payload — read_submit is the one place that decides, and this probe
+ goes through it rather than around it.
+ """
+ _connect_provider(LIVE_KEY)
+ try:
+ results = {}
+ for model, secs in (("MiniMax-Hailuo-2.3", 6), ("happyhorse-1.0-t2v", 3)):
+ cand = next(c for c in media_plane.capability("text_to_video")["candidates"]
+ if c["model"] == model)
+ sub = media_plane.build_submit(cand, TR, {"prompt": "a grey wall", "seconds": secs})
+ r = httpx.post(sub.url, json=sub.body,
+ headers={"authorization": f"Bearer {LIVE_KEY}"}, timeout=60)
+ doc = r.json() if r.content else {}
+ print(f"[live] {model}: HTTP {r.status_code} {json.dumps(doc)[:200]}", flush=True)
+ results[model] = media_plane.read_submit(cand, r.status_code, doc)
+ for model, (task_id, payload) in results.items():
+ assert task_id or payload is not None, f"{model} answered with no task and no media"
+ finally:
+ _connect_provider()
+
+
+# ══ the whole file, checked at once ═══════════════════════════════════════════════
+
+def test_the_provider_key_appears_in_no_response_this_file_produced():
+ """Every body recorded above, in one assertion. A new route that leaks the key fails here even
+ if nobody thought to test that route."""
+ assert _seen, "nothing was recorded — the recording client stopped being used"
+ leaked = [t for t in _seen if PROVIDER_KEY in t]
+ assert not leaked, f"{len(leaked)} response(s) contained the provider key: {leaked[:1]}"
+
+
+def test_the_provider_key_reaches_the_provider_and_nothing_else():
+ """The other half: it DID go out on the wire to the provider, so this is not passing because
+ nothing was ever called."""
+ assert _all_calls, "no provider call was made — this file would pass on an empty mock"
+ outbound = [c for c in _all_calls if "cdn.provider.example" not in c["url"]]
+ assert outbound and all(c["auth"] == f"Bearer {PROVIDER_KEY}" for c in outbound)
+ assert all(c["url"].startswith(TR) for c in outbound), "a call went somewhere unexpected"
+
+
+def test_the_provider_key_appears_in_nothing_the_gateway_printed(api, kit, client, provider,
+ capsys):
+ """Launch, generate, fail, sweep, delete — then read the logs the container would have written."""
+ capsys.readouterr()
+ hid = _launch(api, kit)["harnessId"]
+ sid = "sess_" + os.urandom(6).hex()
+ asyncio.run(app._vg_upsert("HarnessSession", sid, {"tenant": ORG, "status": "idle"}))
+ tok = _cred(hid, sid)
+ provider.fail["dreamina-seedance-2-5-hc"] = (400, {"message": "unknown model"})
+ _call(client, tok, "generate_image", {"prompt": "a"})
+ _call(client, tok, "generate_video", {"prompt": "a", "seconds": 6})
+ _call(client, tok, "generate_music", {"prompt": "a"})
+ asyncio.run(app._media_sweep())
+ api.delete(f"/v1/traces/{sid}")
+ out = capsys.readouterr()
+ assert PROVIDER_KEY not in out.out and PROVIDER_KEY not in out.err
+ # And it did log something identifying, so this is not passing on an empty string.
+ assert "[media]" in out.out
+
+
+def test_the_provider_key_is_on_no_vertex_and_in_no_scene(api, kit, client, provider, session):
+ hid = _launch(api, kit)["harnessId"]
+ tok = _cred(hid, session)
+ _ok(_call(client, tok, "generate_image", {"prompt": "a"}))
+ dump = json.dumps(_vertex(hid)) + json.dumps(asyncio.run(app._media_jobs_of(session)))
+ dump += json.dumps(asyncio.run(app._media_scene_read(session)))
+ assert PROVIDER_KEY not in dump
+ # The secret store holds the integration document, and only the integration document.
+ root = Path(app.BACKING.secrets._root)
+ hits = [p for p in root.rglob("*")
+ if p.is_file() and PROVIDER_KEY in p.read_text(errors="ignore")
+ and app._INTEGRATIONS_KEY not in p.name]
+ assert hits == [], f"the key was written somewhere it should not be: {hits}"
+
+
+def test_the_provider_key_is_in_nothing_this_file_wrote_down():
+ """The other half of the recording client, and the half a response-only sweep cannot see.
+
+ `_seen` covers what was RETURNED. This covers what was KEPT: every vertex, every job, every
+ scene, every stored file and every projected workspace this file produced — the whole data
+ directory, which is the entire durable state of a deployment. A key that never appears in a
+ response but sits on a graph vertex is the same leak with a much longer half-life, and it is
+ exactly the one that shipped.
+
+ Written as a walk of the storage root rather than a list of places to look, so a NEW place to
+ write things down is covered on the day it is added rather than on the day someone remembers.
+ """
+ # This deployment really is holding the sentinel as its credential — otherwise the walk below
+ # would pass on a store that never had a key in it.
+ doc = json.dumps(asyncio.run(app._integrations_doc()))
+ assert PROVIDER_KEY in doc, "the integration is gone — this test is asserting against nothing"
+
+ leaked = []
+ for p in Path(_DATA).rglob("*"):
+ if not p.is_file() or p.stat().st_size > 64_000_000:
+ continue
+ try:
+ if PROVIDER_KEY in p.read_text(errors="ignore"):
+ leaked.append(str(p))
+ except OSError:
+ continue
+ # Nowhere, not even the secret store: the one place it is allowed to live keeps it encrypted.
+ assert leaked == [], f"the provider key was written to disk in the clear: {leaked}"