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(integrations): show and control how video, speech and music are routed

richard-epsilla96ef290460cf
diff --git a/gateway/app.py b/gateway/app.py
index 245a54ff..9e630400 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -888,6 +888,13 @@ _MODEL_MAP_PREV_KEY = "harness-model-map.prev"
# where picking one is a broken choice; and the two route independently — the integration that
# serves your chat models is often not the one that serves images.
_IMAGE_MODEL_MAP_KEY = "harness-image-model-map"
+# Video, speech and music are NOT routed by a model map. They are routed by the media
+# chain: an ordered list of candidates per capability, each carrying what it measurably
+# does, and the first one whose provider is connected wins. This document is the operator's
+# preference over that order — which to try first, which to switch off — and it is kept
+# apart from the catalog for the reason media_plane.set_policy explains: the catalog is
+# measurement, this is policy, and one must not overwrite the other.
+_MEDIA_POLICY_KEY = "harness-media-policy"
_IMAGE_MODEL_MAP_PREV_KEY = "harness-image-model-map.prev"
_INTEGRATION_SECRET_FIELDS = ("api_key", "aws_bearer_token", "aws_secret_access_key", "aws_session_token")
# integration provider type × runner backend -> the runner-side provider that carries it.
@@ -928,6 +935,23 @@ async def _model_map_doc() -> dict:
return {}
+async def _media_policy_doc() -> dict:
+ v = await _vault_get(GLOBAL_TENANT, _MEDIA_POLICY_KEY)
+ try:
+ doc = json.loads(v) if v else {}
+ return doc if isinstance(doc, dict) else {}
+ except Exception: # noqa: BLE001
+ return {}
+
+
+async def _media_policy_load() -> dict:
+ """Read it and hand it to the media plane. The plane holds one cached copy because it is read
+ on every resolve; this is the only thing that sets it."""
+ doc = await _media_policy_doc()
+ media_plane.set_policy(doc)
+ return doc
+
+
async def _image_model_map_doc() -> dict:
v = await _vault_get(GLOBAL_TENANT, _IMAGE_MODEL_MAP_KEY)
try:
@@ -2161,6 +2185,17 @@ async def _reconcile_sweep() -> int:
return fixed
[email protected]_event("startup")
+async def _start_media_policy() -> None:
+ """The operator's media preference, published to the plane before the first turn can arrive.
+ Without this the order they chose applies only after something else happens to write it."""
+ try:
+ await _media_policy_load()
+ except Exception as e: # noqa: BLE001 — a missing preference is not a reason not to start
+ print(f"[media] could not read the routing preference ({e}); using the catalog order",
+ flush=True)
+
+
@app.on_event("startup")
async def _start_bus() -> None:
global _redis_out
@@ -3443,6 +3478,45 @@ def _integration_public(integ: dict) -> dict:
for c, v in _integration_image_models(integ).items()]}
+async def _media_chains_public() -> list[dict]:
+ """Every media capability's chain, in the order it will actually be walked.
+
+ Read through media_plane.capability(), which is where the operator's preference is applied —
+ so what the console draws is the list the router uses, not a second reading of the file that
+ could drift from it.
+
+ The measured facts travel with each candidate because they are the reason for the order. An
+ operator moving a model to the top is choosing between "honours the duration you ask for" and
+ "ignores it and returns 6 s", and that choice cannot be made from a model name.
+ """
+ connected = set((await _media_providers()).keys())
+ out: list[dict] = []
+ for name in media_plane.capability_names():
+ cap = media_plane.capability(name)
+ cands = [c for c in (cap.get("candidates") or []) if isinstance(c, dict)]
+ rows = []
+ for c in cands:
+ model = str(c.get("model") or "")
+ provider = str(c.get("provider") or "")
+ rows.append({
+ "model": model,
+ "provider": provider,
+ "connected": provider in connected,
+ "off": bool(c.get("policy_off")),
+ # Why it is where it is, in the words the file recorded when it was called.
+ "resolution": c.get("resolution") or "",
+ "seconds": c.get("duration_observed_s"),
+ "duration_ignored": bool(c.get("duration_ignored")),
+ "accepts_input_image": c.get("accepts_input_image"),
+ "usd": c.get("usd"),
+ "verification": c.get("verification") or "",
+ # The clause the chain would use if this one were asked for right now.
+ "unavailable": media_plane.stood_down(c),
+ })
+ out.append({"capability": name, "unit": cap.get("unit") or "", "candidates": rows})
+ return out
+
+
@app.get("/v1/admin/integrations")
async def admin_integrations_get(request: Request) -> dict:
await _require_integrations_admin(request)
@@ -3450,7 +3524,9 @@ async def admin_integrations_get(request: Request) -> dict:
"model_map": await _effective_model_map(),
"image_model_map": await _effective_image_model_map(),
"providers": sorted({p for p, _ in _INTEGRATION_WIRING}),
- "catalog": _provider_catalog_public()}
+ "catalog": _provider_catalog_public(),
+ "media_chains": await _media_chains_public(),
+ "media_policy": await _media_policy_doc()}
class IntegrationsBody(BaseModel):
@@ -3459,6 +3535,9 @@ class IntegrationsBody(BaseModel):
# Optional: a console that predates image routing still saves without wiping the image map.
# Absent means "leave it alone", which is not the same as an empty dict meaning "clear it".
image_model_map: dict | None = None
+ # Same rule: absent leaves the media preference alone, {} clears it back to the catalog's own
+ # order. A console that does not know about media routing must not silently reset it.
+ media_policy: dict | None = None
@app.put("/v1/admin/integrations")
@@ -3539,6 +3618,26 @@ async def admin_integrations_put(body: IntegrationsBody, request: Request) -> di
await _vault_put(GLOBAL_TENANT, _MODEL_MAP_KEY, json.dumps(mm))
if imm is not None:
await _vault_put(GLOBAL_TENANT, _IMAGE_MODEL_MAP_KEY, json.dumps(imm))
+ if body.media_policy is not None:
+ # Only models this deployment actually HAS. A preference naming a model the catalog does
+ # not carry is silent dead weight: it survives every write, explains nothing, and reorders
+ # nothing — and the day that name appears in an upgraded catalog it takes effect without
+ # anyone choosing it.
+ known = {str(c.get("model")) for n in media_plane.capability_names()
+ for c in (media_plane.capability(n).get("candidates") or [])
+ if isinstance(c, dict)}
+ clean: dict = {}
+ for cap, pref in (body.media_policy or {}).items():
+ if not isinstance(pref, dict):
+ continue
+ order = [str(m) for m in (pref.get("order") or []) if str(m) in known]
+ off = [str(m) for m in (pref.get("disabled") or []) if str(m) in known]
+ if order or off:
+ clean[str(cap)] = {"order": order, "disabled": off}
+ await _vault_put(GLOBAL_TENANT, _MEDIA_POLICY_KEY, json.dumps(clean))
+ # The plane caches it, so the write must publish it. Otherwise the order takes effect on
+ # the next restart, which is indistinguishable from the control not working.
+ media_plane.set_policy(clean)
# Answer with what will actually route, not with what was just filed away — the two differ by
# every model claimed on read, and the console renders this straight into the picker.
return {"ok": True, "integrations": [_integration_public(i) for i in out],
diff --git a/gateway/media_plane.py b/gateway/media_plane.py
index 67c49367..81a235ad 100644
--- a/gateway/media_plane.py
+++ b/gateway/media_plane.py
@@ -169,9 +169,58 @@ def catalog() -> dict:
return doc
+# ── the operator's preference, as a LAYER over the measured catalog ───────────────────────────
+# THE CATALOG IS FACT AND THIS IS POLICY, and they are kept apart on purpose. The file records
+# what each model DID when it was called — the duration it honoured, the frame it returned, what
+# it cost. An operator saying "prefer this one, switch that one off" is a different kind of
+# statement, and writing it into the catalog would overwrite a measurement with an opinion and
+# lose the reason the ranking was what it was.
+#
+# It is applied in `capability()` — the ONE place candidates are read — so the chain that runs, the
+# chain the console draws and the chain an agent is told about are the same list. Applying it at
+# the two call sites instead is how a console comes to show an order the router does not use.
+_policy: dict = {}
+
+
+def set_policy(doc: dict | None) -> None:
+ """Replace the operator's preference. Called at startup and after every write."""
+ global _policy # noqa: PLW0603 — one module-level cache
+ _policy = doc if isinstance(doc, dict) else {}
+
+
+def policy() -> dict:
+ return _policy
+
+
+def _apply_policy(cap_name: str, cands: list) -> list:
+ """Candidates in the operator's order, with switched-off ones MARKED rather than removed.
+
+ Marked, not filtered: a model that vanishes from the chain produces a refusal that cannot
+ explain itself. `stood_down` turns the mark into a sentence, so an agent that finds nothing
+ available is told "X is switched off on this instance" instead of "no model can do this".
+ """
+ p = (_policy.get(cap_name) or {}) if isinstance(_policy.get(cap_name), dict) else {}
+ order = [str(m) for m in (p.get("order") or [])]
+ off = {str(m) for m in (p.get("disabled") or [])}
+ if not order and not off:
+ return cands
+ marked = [({**c, "policy_off": True} if str(c.get("model")) in off else c) for c in cands]
+ if not order:
+ return marked
+ rank = {m: i for i, m in enumerate(order)}
+ # A candidate the preference does not mention keeps its catalog position, AFTER the ones it
+ # does: a model added by an upgrade must not silently outrank what an operator chose.
+ return sorted(marked, key=lambda c: (rank.get(str(c.get("model")), len(order)),))
+
+
def capability(name: str) -> dict:
c = (catalog().get("capabilities") or {}).get(name)
- return c if isinstance(c, dict) else {}
+ if not isinstance(c, dict):
+ return {}
+ cands = c.get("candidates")
+ if not isinstance(cands, list) or not _policy:
+ return c
+ return {**c, "candidates": _apply_policy(name, cands)}
def capability_names() -> list[str]:
@@ -348,6 +397,10 @@ def stood_down(cand: dict) -> str:
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.
"""
+ model_off = str(cand.get("model") or "?")
+ if cand.get("policy_off"):
+ # The operator's own decision, said in their terms: this is not a fault and not a limit.
+ return f"{model_off} is switched off on this instance"
status = str(cand.get("status") or "")
if status not in _STOOD_DOWN:
return ""
diff --git a/gateway/tests/test_media_mcp.py b/gateway/tests/test_media_mcp.py
index de13cdf8..08e7eccb 100644
--- a/gateway/tests/test_media_mcp.py
+++ b/gateway/tests/test_media_mcp.py
@@ -2746,3 +2746,53 @@ def test_the_provider_key_is_in_nothing_this_file_wrote_down():
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}"
+
+
+# ══ the operator's routing preference ════════════════════════════════════════════
+# The catalog is what each model DID. This is what the operator WANTS. They are separate
+# documents for a reason, and these assert the seam holds in both directions.
+
+def test_the_preference_reorders_the_chain_without_touching_the_catalog():
+ """Promotion is a policy edit, not a catalog edit: the file still says what it measured."""
+ before = [c["model"] for c in media_plane.capability("text_to_video")["candidates"]]
+ assert len(before) > 1
+ last = before[-1]
+ try:
+ media_plane.set_policy({"text_to_video": {"order": [last]}})
+ after = [c["model"] for c in media_plane.capability("text_to_video")["candidates"]]
+ assert after[0] == last, "the promoted model is not first"
+ assert sorted(after) == sorted(before), "the preference added or dropped a candidate"
+ # And the file on disk is untouched — the measurement outlives the opinion.
+ doc = json.loads(Path(media_plane._CATALOG_PATH).read_text())
+ assert [c["model"] for c in doc["capabilities"]["text_to_video"]["candidates"]] == before
+ finally:
+ media_plane.set_policy({})
+
+
+def test_a_switched_off_model_says_so_instead_of_vanishing():
+ """A candidate removed from the list produces a refusal that cannot explain itself. Switched
+ off, it is still in the chain and still has a sentence — which is what an agent relays."""
+ first = media_plane.capability("text_to_video")["candidates"][0]["model"]
+ try:
+ media_plane.set_policy({"text_to_video": {"disabled": [first]}})
+ cands = media_plane.capability("text_to_video")["candidates"]
+ assert first in [c["model"] for c in cands], "it was dropped rather than marked"
+ off = next(c for c in cands if c["model"] == first)
+ assert media_plane.stood_down(off) == f"{first} is switched off on this instance"
+ # resolve skips it and SAYS why, then serves the next one that can.
+ cand, skipped = media_plane.resolve(
+ "text_to_video", {}, connected={"tokenrouter", "vercel", "elevenlabs"})
+ assert any("switched off" in s for s in skipped)
+ assert cand is None or cand["model"] != first
+ finally:
+ media_plane.set_policy({})
+
+
+def test_a_preference_naming_an_unknown_model_orders_nothing():
+ """Dead weight that would take effect the day an upgrade adds that name."""
+ before = [c["model"] for c in media_plane.capability("text_to_video")["candidates"]]
+ try:
+ media_plane.set_policy({"text_to_video": {"order": ["not-a-model-anyone-has"]}})
+ assert [c["model"] for c in media_plane.capability("text_to_video")["candidates"]] == before
+ finally:
+ media_plane.set_policy({})
diff --git a/ui/src/app/(app)/integrations/page.tsx b/ui/src/app/(app)/integrations/page.tsx
index a8d033c8..74fb0cf0 100644
--- a/ui/src/app/(app)/integrations/page.tsx
+++ b/ui/src/app/(app)/integrations/page.tsx
@@ -48,7 +48,26 @@ interface Doc {
image_model_map?: Record<string, string>;
providers: string[];
catalog: ProviderMeta[];
+ /** Video, speech and music are NOT routed by a model map. They are routed by an ordered chain
+ * per capability, and the first candidate whose provider is connected wins. */
+ media_chains?: MediaChain[];
+ media_policy?: Record<string, { order?: string[]; disabled?: string[] }>;
}
+interface MediaCandidate {
+ model: string;
+ provider: string;
+ connected: boolean;
+ off: boolean;
+ resolution?: string;
+ seconds?: number | null;
+ duration_ignored?: boolean;
+ accepts_input_image?: boolean | null;
+ usd?: number | null;
+ verification?: string;
+ /** The clause the chain would use if this one were asked for right now. */
+ unavailable?: string;
+}
+interface MediaChain { capability: string; unit: string; candidates: MediaCandidate[] }
const SECRET = '__secret__';
@@ -77,10 +96,12 @@ export default function IntegrationsPage() {
useEffect(() => { if (allowed) reload(); }, [allowed, reload]);
async function persist(next: { integrations: Integration[]; model_map: Record<string, string>;
- image_model_map?: Record<string, string> }) {
- // Always send both maps. The write replaces the whole document, so posting one of them alone
- // would silently clear the other.
- const body = { image_model_map: doc?.image_model_map || {}, ...next };
+ image_model_map?: Record<string, string>;
+ media_policy?: Record<string, { order?: string[]; disabled?: string[] }> }) {
+ // Always send every map. The write replaces the whole document, so posting one of them alone
+ // would silently clear the others.
+ const body = { image_model_map: doc?.image_model_map || {},
+ media_policy: doc?.media_policy || {}, ...next };
setBusy(true); setErr('');
try {
const r = await harnessFetch('/api/harness/v1/admin/integrations', {
@@ -192,6 +213,22 @@ export default function IntegrationsPage() {
model_map: doc.model_map, image_model_map: next })}
emptyHint="None of your integrations serve an image model." />
+ {/* Video, speech and music. NOT a map: a chain, in order, with the measurements that
+ justify the order. Flattening it to one row per model would throw away both the
+ ranking and the facts, which are the two things that make a fallback safe. */}
+ {(doc.media_chains || []).filter((c) => c.candidates.length > 0).map((chain) => (
+ <MediaChainTable
+ key={chain.capability}
+ chain={chain}
+ busy={busy}
+ policy={doc.media_policy || {}}
+ onChange={(next) => void persist({ integrations: doc.integrations,
+ model_map: doc.model_map,
+ image_model_map: doc.image_model_map || {},
+ media_policy: next })}
+ />
+ ))}
+
</>
)}
</div>
@@ -400,3 +437,98 @@ function AddMappingRow({ map, allCanonicals, integrations, servedBy, busy, onAdd
</div>
);
}
+
+/* ── one media capability's chain ────────────────────────────────────────────────────────────
+ Order is the routing rule: the first candidate whose provider is connected and that can serve
+ the request is the one that runs. So the control is Move up / Move down, not a dropdown — the
+ list IS the policy, and showing it any other way would be showing something that is not what
+ happens.
+
+ Every measured fact travels with its row because those facts are the reason to prefer one over
+ another. "Ignores the duration you ask for" is the difference between a 5-second shot and a
+ 6-second one, and nobody can weigh that from a model name. */
+const CAP_TITLE: Record<string, string> = {
+ text_to_video: 'Video, from text',
+ image_to_video: 'Video, from an image',
+ text_to_image: 'Images',
+ image_to_image: 'Images, from an image',
+ text_to_speech: 'Speech',
+ text_to_music: 'Music',
+ export: 'Film assembly',
+};
+
+function MediaChainTable({ chain, policy, busy, onChange }: {
+ chain: MediaChain;
+ policy: Record<string, { order?: string[]; disabled?: string[] }>;
+ busy: boolean;
+ onChange: (next: Record<string, { order?: string[]; disabled?: string[] }>) => void;
+}) {
+ const models = chain.candidates.map((c) => c.model);
+ const cur = policy[chain.capability] || {};
+ const off = new Set(cur.disabled || []);
+
+ /** The order as it stands, with one model moved. Written whole: a preference that lists only
+ * the models somebody touched leaves the rest to the catalog, and the two disagree the moment
+ * the catalog changes. */
+ const move = (from: number, to: number) => {
+ if (to < 0 || to >= models.length) return;
+ const next = [...models];
+ const [row] = next.splice(from, 1);
+ next.splice(to, 0, row);
+ onChange({ ...policy, [chain.capability]: { order: next, disabled: [...off] } });
+ };
+ const toggle = (model: string) => {
+ const d = new Set(off);
+ if (d.has(model)) d.delete(model); else d.add(model);
+ onChange({ ...policy, [chain.capability]: { order: models, disabled: [...d] } });
+ };
+
+ const facts = (c: MediaCandidate) => {
+ const out: string[] = [];
+ if (c.resolution) out.push(c.resolution);
+ if (typeof c.seconds === 'number') out.push(`${c.seconds}s measured`);
+ if (c.duration_ignored) out.push('ignores the duration you ask for');
+ if (c.accepts_input_image === false) out.push('text only');
+ if (typeof c.usd === 'number') out.push(`$${c.usd.toFixed(2)} a ${chain.unit || 'run'}`);
+ return out;
+ };
+
+ return (
+ <div className="itg-section">
+ <div className="itg-section-head">
+ <div>
+ <h2>{CAP_TITLE[chain.capability] || chain.capability}</h2>
+ <p>Tried in this order. The first one whose provider is connected, and that can do what
+ was asked, is the one that runs.</p>
+ </div>
+ </div>
+ <table className="table">
+ <thead><tr><th>Order</th><th>Model</th><th>Provider</th><th>What it does</th><th /></tr></thead>
+ <tbody>
+ {chain.candidates.map((c, i) => (
+ <tr key={c.model} className={c.off || !c.connected ? 'is-dim' : undefined}>
+ <td>{i + 1}</td>
+ <td>
+ <span className="mono">{c.model}</span>
+ {/* Never colour alone: the state is a word. */}
+ {c.off && <span className="chip"> switched off</span>}
+ {!c.off && !c.connected && <span className="chip"> no key</span>}
+ {!c.off && c.connected && c.unavailable && <span className="chip"> unavailable</span>}
+ </td>
+ <td>{c.provider}</td>
+ <td className="muted">{facts(c).join(' · ') || '—'}</td>
+ <td className="right">
+ <button className="button ghost" type="button" disabled={busy || i === 0}
+ onClick={() => move(i, i - 1)} aria-label={`Move ${c.model} up`}>Up</button>
+ <button className="button ghost" type="button" disabled={busy || i === chain.candidates.length - 1}
+ onClick={() => move(i, i + 1)} aria-label={`Move ${c.model} down`}>Down</button>
+ <button className="button ghost" type="button" disabled={busy}
+ onClick={() => toggle(c.model)}>{c.off ? 'Switch on' : 'Switch off'}</button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}