Skip to content

The agent that grows with you

feat(video): add OpenRouter Hailuo 3 Max provider

cedanoagent387ac50d850d
diff --git a/agent/provider_media.py b/agent/provider_media.py
index 72b77c03e26..1db99e9f9a7 100644
--- a/agent/provider_media.py
+++ b/agent/provider_media.py
@@ -13,7 +13,7 @@ import base64
import datetime
import uuid
from pathlib import Path
-from typing import Dict, Tuple
+from typing import Dict, Optional, Tuple
def cache_dir(kind: str) -> Path:
@@ -45,7 +45,8 @@ def save_b64(kind: str, b64_data: str, *, prefix: str, extension: str) -> Path:
def save_url(
kind: str, url: str, *, prefix: str, timeout: float, max_bytes: int, chunk_size: int,
content_types: Dict[str, str], url_extensions: Tuple[str, ...], default_extension: str,
- label: str, empty_error: str,
+ label: str, empty_error: str, headers: Optional[Dict[str, str]] = None,
+ require_known_content_type: bool = False,
) -> Path:
"""Stream-download *url* into the cache with a size cap.
@@ -56,11 +57,15 @@ def save_url(
callers can fall back to the bare URL; a partial file is never left behind.
"""
import requests
- response = requests.get(url, timeout=timeout, stream=True)
+ response = requests.get(url, headers=headers, timeout=timeout, stream=True)
response.raise_for_status()
content_type = (response.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()
extension = content_types.get(content_type)
+ if require_known_content_type and extension is None:
+ raise ValueError(
+ f"{label} download returned unexpected Content-Type {content_type or '(missing)'}"
+ )
if extension is None:
url_path = url.split("?", 1)[0].lower()
extension = next(
diff --git a/agent/video_gen_provider.py b/agent/video_gen_provider.py
index 31ec67e105d..45a03c829b2 100644
--- a/agent/video_gen_provider.py
+++ b/agent/video_gen_provider.py
@@ -30,10 +30,12 @@ logger = logging.getLogger(__name__)
# Advertised as an enum hint in the tool schema; providers may accept a narrower
# or wider set and are responsible for clamping.
-COMMON_ASPECT_RATIOS: Tuple[str, ...] = ("16:9", "9:16", "1:1", "4:3", "3:4", "3:2", "2:3")
+COMMON_ASPECT_RATIOS: Tuple[str, ...] = (
+ "16:9", "9:16", "1:1", "4:3", "3:4", "3:2", "2:3", "21:9"
+)
DEFAULT_ASPECT_RATIO = "16:9"
-COMMON_RESOLUTIONS: Tuple[str, ...] = ("480p", "540p", "720p", "1080p")
+COMMON_RESOLUTIONS: Tuple[str, ...] = ("480p", "540p", "720p", "768p", "1080p")
DEFAULT_RESOLUTION = "720p"
@@ -83,7 +85,13 @@ _URL_VIDEO_CONTENT_TYPES = {
def save_url_video(
- url: str, *, prefix: str = "video", timeout: float = 180.0, max_bytes: int = 200 * 1024 * 1024
+ url: str,
+ *,
+ prefix: str = "video",
+ timeout: float = 180.0,
+ max_bytes: int = 200 * 1024 * 1024,
+ headers: Optional[Dict[str, str]] = None,
+ require_video_content_type: bool = False,
) -> Path:
"""Download an (often ephemeral) video URL into ``$HERMES_HOME/cache/videos/``;
raises on network / HTTP / oversize / empty errors so callers can fall back to the URL."""
@@ -92,6 +100,7 @@ def save_url_video(
chunk_size=256 * 1024, content_types=_URL_VIDEO_CONTENT_TYPES,
url_extensions=("mp4", "webm", "mov", "mkv"), default_extension="mp4",
label="Video", empty_error="Video at {url} was empty (0 bytes).",
+ headers=headers, require_known_content_type=require_video_content_type,
)
diff --git a/plugins/video_gen/openrouter/__init__.py b/plugins/video_gen/openrouter/__init__.py
new file mode 100644
index 00000000000..9f436b3d770
--- /dev/null
+++ b/plugins/video_gen/openrouter/__init__.py
@@ -0,0 +1,340 @@
+"""OpenRouter MiniMax H3 Max video generation backend.
+
+Uses OpenRouter's dedicated asynchronous video API rather than the chat
+completions API: submit ``POST /api/v1/videos``, poll the returned job, then
+materialize the completed clip under Hermes' video cache.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import logging
+import os
+import time
+from typing import Any, Dict, List, Optional
+from urllib.parse import urlsplit
+
+from agent.video_gen_provider import (
+ VideoGenProvider,
+ error_response,
+ save_url_video,
+ success_response,
+)
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_MODEL = "minimax/hailuo-3-max"
+DEFAULT_BASE_URL = "https://openrouter.ai/api/v1"
+DEFAULT_DURATION = 5
+DEFAULT_RESOLUTION = "768p"
+DEFAULT_ASPECT_RATIO = "16:9"
+SUPPORTED_DURATIONS = tuple(range(5, 16))
+SUPPORTED_RESOLUTIONS = ("480p", "768p")
+SUPPORTED_ASPECT_RATIOS = ("21:9", "16:9", "4:3", "1:1", "3:4", "9:16")
+_TERMINAL_STATUSES = frozenset({"completed", "failed", "cancelled", "canceled", "expired"})
+
+
+def _is_public_first_frame_url(value: str) -> bool:
+ """Accept provider-fetchable HTTPS URLs, never local/private inputs."""
+ try:
+ parsed = urlsplit(value)
+ host = (parsed.hostname or "").strip().lower().rstrip(".")
+ if parsed.scheme.lower() != "https" or not host:
+ return False
+ if host == "localhost" or host.endswith((".localhost", ".local", ".lan", ".internal")):
+ return False
+ try:
+ return ipaddress.ip_address(host).is_global
+ except ValueError:
+ return True
+ except (TypeError, ValueError):
+ return False
+
+
+def _nearest(value: int, supported: tuple[int, ...]) -> int:
+ return min(supported, key=lambda candidate: (abs(candidate - value), candidate))
+
+
+def _build_payload(
+ *,
+ prompt: str,
+ image_url: Optional[str],
+ duration: Optional[int],
+ aspect_ratio: str,
+ resolution: str,
+) -> Dict[str, Any]:
+ """Translate the unified Hermes inputs to OpenRouter's video API."""
+ requested_duration = duration if duration is not None else DEFAULT_DURATION
+ try:
+ requested_duration = int(requested_duration)
+ except (TypeError, ValueError):
+ requested_duration = DEFAULT_DURATION
+
+ payload: Dict[str, Any] = {
+ "model": DEFAULT_MODEL,
+ "prompt": prompt,
+ "duration": _nearest(requested_duration, SUPPORTED_DURATIONS),
+ "resolution": resolution if resolution in SUPPORTED_RESOLUTIONS else DEFAULT_RESOLUTION,
+ "aspect_ratio": (
+ aspect_ratio if aspect_ratio in SUPPORTED_ASPECT_RATIOS else DEFAULT_ASPECT_RATIO
+ ),
+ }
+ if image_url:
+ payload["frame_images"] = [
+ {
+ "type": "image_url",
+ "image_url": {"url": image_url},
+ "frame_type": "first_frame",
+ }
+ ]
+ return payload
+
+
+class OpenRouterVideoGenProvider(VideoGenProvider):
+ """MiniMax H3 Max text-to-video and first-frame image-to-video."""
+
+ _IGNORES_SEED = True # Unified ABC input; H3 Max's OpenRouter SKU rejects it.
+ _poll_interval_s = 5.0
+ _poll_deadline_s = 900.0
+ _request_timeout_s = 60.0
+
+
+ @property
+ def name(self) -> str:
+ return "openrouter"
+
+ @property
+ def display_name(self) -> str:
+ return "OpenRouter"
+
+ def _api_key(self) -> str:
+ return os.getenv("OPENROUTER_API_KEY", "").strip()
+
+ def _base_url(self) -> str:
+ return os.getenv("OPENROUTER_BASE_URL", DEFAULT_BASE_URL).strip().rstrip("/")
+
+ def _session(self):
+ import requests
+
+ return requests.Session()
+
+ def _headers(self) -> Dict[str, str]:
+ return {
+ "Authorization": f"Bearer {self._api_key()}",
+ "Content-Type": "application/json",
+ "User-Agent": "hermes-agent/video_gen",
+ }
+
+ def is_available(self) -> bool:
+ return bool(self._api_key())
+
+ def list_models(self) -> List[Dict[str, Any]]:
+ return [
+ {
+ "id": DEFAULT_MODEL,
+ "display": "MiniMax H3 Max",
+ "speed": "~20-60s",
+ "strengths": "Fast text-to-video and first-frame image-to-video.",
+ "price": "$0.05/s (480p), $0.08/s (768p)",
+ "modalities": ["text", "image"],
+ }
+ ]
+
+ def default_model(self) -> Optional[str]:
+ return DEFAULT_MODEL
+
+ def capabilities(self) -> Dict[str, Any]:
+ return {
+ "modalities": ["text", "image"],
+ "aspect_ratios": list(SUPPORTED_ASPECT_RATIOS),
+ "resolutions": list(SUPPORTED_RESOLUTIONS),
+ "max_duration": max(SUPPORTED_DURATIONS),
+ "min_duration": min(SUPPORTED_DURATIONS),
+ "supports_audio": False,
+ "supports_negative_prompt": False,
+ "supports_seed": False,
+ "supports_upscale": False,
+ "max_reference_images": 0,
+ }
+
+ def get_setup_schema(self) -> Dict[str, Any]:
+ return {
+ "name": "OpenRouter",
+ "badge": "paid",
+ "tag": "MiniMax H3 Max — text-to-video and first-frame image-to-video",
+ "env_vars": [
+ {
+ "key": "OPENROUTER_API_KEY",
+ "prompt": "OpenRouter API key",
+ "url": "https://openrouter.ai/settings/keys",
+ }
+ ],
+ }
+
+ def _poll(self, session: Any, job_id: str) -> Dict[str, Any]:
+ deadline = time.monotonic() + self._poll_deadline_s
+ url = f"{self._base_url()}/videos/{job_id}"
+ last_status = "unknown"
+
+ def raise_timeout() -> None:
+ raise TimeoutError(
+ f"video job {job_id} did not finish within {int(self._poll_deadline_s)}s "
+ f"(last status={last_status})"
+ )
+
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise_timeout()
+ response = session.get(
+ url,
+ headers=self._headers(),
+ timeout=max(0.001, min(self._request_timeout_s, remaining)),
+ )
+ response.raise_for_status()
+ payload = response.json()
+ last_status = str(payload.get("status") or "").lower() or "unknown"
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise_timeout()
+ if last_status in _TERMINAL_STATUSES:
+ return payload
+ time.sleep(min(self._poll_interval_s, remaining))
+
+ def _save_completed_video(self, job_id: str) -> str:
+ """Stream the authenticated content endpoint through the shared size cap.
+
+ Do not follow a provider-supplied ``unsigned_urls`` destination: deriving
+ the endpoint from the configured API origin keeps the bearer request on
+ the same operator-selected host and avoids a second unbounded code path.
+ """
+ return str(
+ save_url_video(
+ f"{self._base_url()}/videos/{job_id}/content",
+ prefix="openrouter-hailuo",
+ headers=self._headers(),
+ require_video_content_type=True,
+ )
+ )
+
+ def generate(
+ self,
+ prompt: str,
+ *,
+ model: Optional[str] = None,
+ image_url: Optional[str] = None,
+ reference_image_urls: Optional[List[str]] = None,
+ duration: Optional[int] = None,
+ aspect_ratio: str = DEFAULT_ASPECT_RATIO,
+ resolution: str = DEFAULT_RESOLUTION,
+ negative_prompt: Optional[str] = None,
+ audio: Optional[bool] = None,
+ seed: Optional[int] = None,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ del negative_prompt, audio, seed, kwargs
+ cleaned_prompt = (prompt or "").strip()
+ if not cleaned_prompt:
+ return error_response(
+ error="prompt is required",
+ error_type="invalid_request",
+ provider=self.name,
+ )
+ model_id = (model or DEFAULT_MODEL).strip()
+ if model_id != DEFAULT_MODEL:
+ return error_response(
+ error=f"OpenRouter video currently supports only {DEFAULT_MODEL}",
+ error_type="invalid_model",
+ provider=self.name,
+ model=model_id,
+ prompt=cleaned_prompt,
+ )
+ if reference_image_urls:
+ return error_response(
+ error=f"{DEFAULT_MODEL} does not support reference_image_urls",
+ error_type="unsupported_input",
+ provider=self.name,
+ model=model_id,
+ prompt=cleaned_prompt,
+ )
+ cleaned_image_url = (image_url or "").strip() or None
+ if cleaned_image_url and not _is_public_first_frame_url(cleaned_image_url):
+ return error_response(
+ error="image_url must be a public HTTPS URL",
+ error_type="invalid_request",
+ provider=self.name,
+ model=model_id,
+ prompt=cleaned_prompt,
+ )
+ if not self._api_key():
+ return error_response(
+ error="OPENROUTER_API_KEY is not set",
+ error_type="missing_credentials",
+ provider=self.name,
+ model=model_id,
+ prompt=cleaned_prompt,
+ )
+
+ payload = _build_payload(
+ prompt=cleaned_prompt,
+ image_url=cleaned_image_url,
+ duration=duration,
+ aspect_ratio=aspect_ratio,
+ resolution=resolution,
+ )
+ session = self._session()
+ try:
+ submitted = session.post(
+ f"{self._base_url()}/videos",
+ headers=self._headers(),
+ json=payload,
+ timeout=self._request_timeout_s,
+ )
+ submitted.raise_for_status()
+ submission = submitted.json()
+ job_id = str(submission.get("id") or "").strip()
+ if not job_id:
+ raise ValueError("OpenRouter submit response did not contain a job id")
+ job = self._poll(session, job_id)
+ status = str(job.get("status") or "").lower()
+ if status != "completed":
+ return error_response(
+ error=str(job.get("error") or f"video job ended with status={status!r}"),
+ error_type="job_failed",
+ provider=self.name,
+ model=model_id,
+ prompt=cleaned_prompt,
+ aspect_ratio=payload["aspect_ratio"],
+ )
+ video_path = self._save_completed_video(job_id)
+ except Exception as exc: # noqa: BLE001 - normalize transport/API failures for tool callers
+ logger.debug("OpenRouter H3 Max video generation failed", exc_info=True)
+ return error_response(
+ error=f"OpenRouter video generation failed: {exc}",
+ error_type="api_error",
+ provider=self.name,
+ model=model_id,
+ prompt=cleaned_prompt,
+ aspect_ratio=payload["aspect_ratio"],
+ )
+
+ raw_usage = job.get("usage")
+ usage: Dict[str, Any] = raw_usage if isinstance(raw_usage, dict) else {}
+ extra: Dict[str, Any] = {"job_id": job_id}
+ if usage.get("cost") is not None:
+ extra["cost"] = usage["cost"]
+ return success_response(
+ video=video_path,
+ model=model_id,
+ prompt=cleaned_prompt,
+ modality="image" if cleaned_image_url else "text",
+ aspect_ratio=payload["aspect_ratio"],
+ duration=payload["duration"],
+ provider=self.name,
+ extra=extra,
+ )
+
+
+def register(ctx) -> None:
+ """Plugin entry point."""
+ ctx.register_video_gen_provider(OpenRouterVideoGenProvider())
diff --git a/plugins/video_gen/openrouter/plugin.yaml b/plugins/video_gen/openrouter/plugin.yaml
new file mode 100644
index 00000000000..a7aa96932ca
--- /dev/null
+++ b/plugins/video_gen/openrouter/plugin.yaml
@@ -0,0 +1,7 @@
+name: openrouter
+version: 1.0.0
+description: "OpenRouter MiniMax H3 Max video generation via the asynchronous /api/v1/videos API."
+author: Nous Research
+kind: backend
+requires_env:
+ - OPENROUTER_API_KEY
diff --git a/tests/agent/test_provider_media.py b/tests/agent/test_provider_media.py
new file mode 100644
index 00000000000..47f517c78d8
--- /dev/null
+++ b/tests/agent/test_provider_media.py
@@ -0,0 +1,81 @@
+from __future__ import annotations
+
+import pytest
+
+from agent import provider_media
+
+
+class _Response:
+ def __init__(self, content_type: str, chunks: list[bytes]):
+ self.headers = {"Content-Type": content_type}
+ self._chunks = chunks
+
+ def raise_for_status(self):
+ return None
+
+ def iter_content(self, chunk_size: int):
+ del chunk_size
+ return iter(self._chunks)
+
+
+def _save_video(url: str, **kwargs):
+ return provider_media.save_url(
+ "videos",
+ url,
+ prefix="provider-test",
+ timeout=30,
+ max_bytes=1024,
+ chunk_size=64,
+ content_types={"video/mp4": "mp4"},
+ url_extensions=("mp4",),
+ default_extension="mp4",
+ label="Video",
+ empty_error="empty: {url}",
+ **kwargs,
+ )
+
+
+def test_save_url_forwards_headers_and_streams_to_cache(monkeypatch, tmp_path):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ calls = []
+
+ def fake_get(url, **kwargs):
+ calls.append((url, kwargs))
+ return _Response("video/mp4", [b"clip"])
+
+ monkeypatch.setattr("requests.get", fake_get)
+
+ path = _save_video(
+ "https://api.example/videos/job/content",
+ headers={"Authorization": "Bearer test"},
+ require_known_content_type=True,
+ )
+
+ assert path.read_bytes() == b"clip"
+ assert path.suffix == ".mp4"
+ assert calls == [
+ (
+ "https://api.example/videos/job/content",
+ {
+ "headers": {"Authorization": "Bearer test"},
+ "timeout": 30,
+ "stream": True,
+ },
+ )
+ ]
+
+
+def test_save_url_strict_content_type_rejects_non_video(monkeypatch, tmp_path):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ monkeypatch.setattr(
+ "requests.get",
+ lambda *_args, **_kwargs: _Response("text/html", [b"not a video"]),
+ )
+
+ with pytest.raises(ValueError, match="unexpected Content-Type text/html"):
+ _save_video(
+ "https://api.example/videos/job/content",
+ require_known_content_type=True,
+ )
+
+ assert not list(provider_media.cache_dir("videos").iterdir())
diff --git a/tests/plugins/video_gen/test_openrouter.py b/tests/plugins/video_gen/test_openrouter.py
new file mode 100644
index 00000000000..59f4dec8598
--- /dev/null
+++ b/tests/plugins/video_gen/test_openrouter.py
@@ -0,0 +1,286 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pytest
+
+from tools.video_generation_tool import VIDEO_GENERATE_SCHEMA
+from agent import video_gen_registry
+from plugins.video_gen.openrouter import (
+ DEFAULT_MODEL,
+ OpenRouterVideoGenProvider,
+ _build_payload,
+)
+
+
+@dataclass
+class _Response:
+ payload: dict
+ status_code: int = 200
+ content: bytes = b""
+
+ def json(self):
+ return self.payload
+
+ def raise_for_status(self):
+ if self.status_code >= 400:
+ raise RuntimeError(f"HTTP {self.status_code}: {self.payload}")
+
+
+class _Session:
+ def __init__(self):
+ self.posts = []
+ self.gets = []
+ self.polls = [
+ _Response({"id": "job-1", "status": "in_progress"}),
+ _Response(
+ {
+ "id": "job-1",
+ "status": "completed",
+ "unsigned_urls": ["https://cdn.example/video.mp4"],
+ "usage": {"cost": 0.4},
+ }
+ ),
+ ]
+
+ def post(self, url, **kwargs):
+ self.posts.append((url, kwargs))
+ return _Response(
+ {
+ "id": "job-1",
+ "polling_url": "https://openrouter.ai/api/v1/videos/job-1",
+ "status": "pending",
+ },
+ status_code=202,
+ )
+
+ def get(self, url, **kwargs):
+ self.gets.append((url, kwargs))
+ return self.polls.pop(0)
+
+
+def test_poll_caps_request_timeout_and_rejects_late_terminal_response(monkeypatch):
+ provider = OpenRouterVideoGenProvider()
+ provider._poll_deadline_s = 10
+ provider._request_timeout_s = 60
+ session = _Session()
+ session.polls = [_Response({"id": "job-1", "status": "completed"})]
+ ticks = iter([100.0, 109.0, 111.0])
+ monkeypatch.setattr("plugins.video_gen.openrouter.time.monotonic", lambda: next(ticks))
+
+ with pytest.raises(TimeoutError, match="did not finish within 10s"):
+ provider._poll(session, "job-1")
+
+ assert session.gets[0][1]["timeout"] == 1.0
+
+
+def test_unified_video_schema_exposes_hailuo_resolution_and_aspect_ratio():
+ properties = VIDEO_GENERATE_SCHEMA["parameters"]["properties"]
+
+ assert "768p" in properties["resolution"]["enum"]
+ assert "21:9" in properties["aspect_ratio"]["enum"]
+
+
+def test_hailuo_catalog_and_capabilities_are_pinned_to_openrouter_contract():
+ provider = OpenRouterVideoGenProvider()
+
+ assert DEFAULT_MODEL == "minimax/hailuo-3-max"
+ assert provider.default_model() == DEFAULT_MODEL
+ assert provider.list_models() == [
+ {
+ "id": DEFAULT_MODEL,
+ "display": "MiniMax H3 Max",
+ "speed": "~20-60s",
+ "strengths": "Fast text-to-video and first-frame image-to-video.",
+ "price": "$0.05/s (480p), $0.08/s (768p)",
+ "modalities": ["text", "image"],
+ }
+ ]
+ assert provider.capabilities() == {
+ "modalities": ["text", "image"],
+ "aspect_ratios": ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"],
+ "resolutions": ["480p", "768p"],
+ "max_duration": 15,
+ "min_duration": 5,
+ "supports_audio": False,
+ "supports_negative_prompt": False,
+ "supports_seed": False,
+ "supports_upscale": False,
+ "max_reference_images": 0,
+ }
+
+
+def test_build_payload_uses_openrouter_video_fields_and_clamps_values():
+ payload = _build_payload(
+ prompt="A lighthouse in a storm",
+ image_url="https://example.com/start.png",
+ duration=99,
+ aspect_ratio="2:3",
+ resolution="720p",
+ )
+
+ assert payload == {
+ "model": DEFAULT_MODEL,
+ "prompt": "A lighthouse in a storm",
+ "duration": 15,
+ "resolution": "768p",
+ "aspect_ratio": "16:9",
+ "frame_images": [
+ {
+ "type": "image_url",
+ "image_url": {"url": "https://example.com/start.png"},
+ "frame_type": "first_frame",
+ }
+ ],
+ }
+
+
+def test_generate_submits_polls_and_materializes_completed_video(monkeypatch, tmp_path):
+ provider = OpenRouterVideoGenProvider()
+ session = _Session()
+ saved = []
+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
+ monkeypatch.setattr(provider, "_session", lambda: session)
+ monkeypatch.setattr("plugins.video_gen.openrouter.time.sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ "plugins.video_gen.openrouter.save_url_video",
+ lambda url, prefix, headers, require_video_content_type: saved.append(
+ (url, prefix, headers, require_video_content_type)
+ )
+ or tmp_path / "hailuo.mp4",
+ )
+
+ result = provider.generate(
+ "A slow cinematic push-in",
+ duration=5,
+ aspect_ratio="9:16",
+ resolution="480p",
+ )
+
+ assert result["success"] is True
+ assert result["video"] == str(tmp_path / "hailuo.mp4")
+ assert result["provider"] == "openrouter"
+ assert result["model"] == DEFAULT_MODEL
+ assert result["modality"] == "text"
+ assert result["duration"] == 5
+ assert result["cost"] == 0.4
+ assert session.posts[0][0] == "https://openrouter.ai/api/v1/videos"
+ assert session.posts[0][1]["json"]["resolution"] == "480p"
+ assert [url for url, _kwargs in session.gets] == [
+ "https://openrouter.ai/api/v1/videos/job-1",
+ "https://openrouter.ai/api/v1/videos/job-1",
+ ]
+ assert saved == [
+ (
+ "https://openrouter.ai/api/v1/videos/job-1/content",
+ "openrouter-hailuo",
+ {
+ "Authorization": "Bearer test-key",
+ "Content-Type": "application/json",
+ "User-Agent": "hermes-agent/video_gen",
+ },
+ True,
+ )
+ ]
+
+
+def test_generate_rejects_non_http_image_input_without_calling_api(monkeypatch):
+ provider = OpenRouterVideoGenProvider()
+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
+
+ result = provider.generate("animate this", image_url="/private/start.png")
+
+ assert result["success"] is False
+ assert result["error_type"] == "invalid_request"
+ assert "public HTTP" in result["error"]
+
+
+def test_generate_rejects_private_first_frame_without_calling_api(monkeypatch):
+ provider = OpenRouterVideoGenProvider()
+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
+ monkeypatch.setattr(
+ provider,
+ "_session",
+ lambda: (_ for _ in ()).throw(AssertionError("API must not be called")),
+ )
+
+ result = provider.generate("animate this", image_url="https://127.0.0.1/start.png")
+
+ assert result["success"] is False
+ assert result["error_type"] == "invalid_request"
+
+
+def test_reference_images_are_rejected_before_session_creation(monkeypatch):
+ provider = OpenRouterVideoGenProvider()
+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
+ monkeypatch.setattr(
+ provider,
+ "_session",
+ lambda: (_ for _ in ()).throw(AssertionError("API must not be called")),
+ )
+
+ result = provider.generate(
+ "use these references",
+ reference_image_urls=["https://example.com/reference.png"],
+ )
+
+ assert result["success"] is False
+ assert result["error_type"] == "unsupported_input"
+
+
+def test_generate_rejects_unknown_model_without_calling_api(monkeypatch):
+ provider = OpenRouterVideoGenProvider()
+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
+
+ result = provider.generate("test", model="other/video-model")
+
+ assert result["success"] is False
+ assert result["error_type"] == "invalid_model"
+ assert DEFAULT_MODEL in result["error"]
+
+
+def test_register_and_picker_discovery_expose_openrouter(monkeypatch):
+ from hermes_cli import tools_config
+ from hermes_cli import plugins as plugin_loader
+ from plugins.video_gen.openrouter import register
+
+ class _Context:
+ def register_video_gen_provider(self, provider):
+ video_gen_registry.register_provider(provider)
+
+ video_gen_registry._reset_for_tests()
+ try:
+ register(_Context())
+ monkeypatch.setattr(plugin_loader, "_ensure_plugins_discovered", lambda: None)
+
+ registered = video_gen_registry.get_provider("openrouter")
+ rows = tools_config._plugin_video_gen_providers()
+
+ assert isinstance(registered, OpenRouterVideoGenProvider)
+ row = next(item for item in rows if item["video_gen_plugin_name"] == "openrouter")
+ assert row["name"] == "OpenRouter"
+ assert row["env_vars"][0]["key"] == "OPENROUTER_API_KEY"
+ finally:
+ video_gen_registry._reset_for_tests()
+
+
+def test_dynamic_schema_is_capability_scoped(monkeypatch):
+ from tools import video_generation_tool
+
+ provider = OpenRouterVideoGenProvider()
+ monkeypatch.setattr(video_generation_tool, "_resolve_active_provider", lambda: provider)
+ monkeypatch.setattr(video_generation_tool, "_read_configured_video_model", lambda: DEFAULT_MODEL)
+
+ schema = video_generation_tool._build_dynamic_video_schema()
+ properties = schema["parameters"]["properties"]
+
+ assert properties["duration"]["minimum"] == 5
+ assert properties["duration"]["maximum"] == 15
+ assert properties["resolution"]["enum"] == ["480p", "768p"]
+ assert properties["aspect_ratio"]["enum"] == [
+ "21:9", "16:9", "4:3", "1:1", "3:4", "9:16",
+ ]
+ assert "image_url" in properties
+ assert "reference_image_urls" not in properties
+ assert "audio" not in properties
+ assert "seed" not in properties
diff --git a/tests/tools/test_video_generate_schema.py b/tests/tools/test_video_generate_schema.py
index 390a4eb2c89..f07e938eb19 100644
--- a/tests/tools/test_video_generate_schema.py
+++ b/tests/tools/test_video_generate_schema.py
@@ -82,7 +82,14 @@ class TestFleetCapabilityCoverage(unittest.TestCase):
for axis in CAPABILITY_AXES:
self.assertIn(axis, caps, f"deepinfra missing {axis}")
checked += 1
- self.assertGreaterEqual(checked, 3)
+ # openrouter
+ from plugins.video_gen.openrouter import OpenRouterVideoGenProvider
+
+ caps = OpenRouterVideoGenProvider().capabilities()
+ for axis in CAPABILITY_AXES:
+ self.assertIn(axis, caps, f"openrouter missing {axis}")
+ checked += 1
+ self.assertGreaterEqual(checked, 4)
def test_abc_default_fails_closed(self):
from agent.video_gen_provider import VideoGenProvider
@@ -161,10 +168,13 @@ class TestFleetCapabilityCoverage(unittest.TestCase):
f"({implements_upscale})",
)
declares_seed = '"supports_seed": True' in src
- implements_seed = ("seed" in impl_src
- and ("payload[\"seed\"]" in impl_src
- or "seed: Optional[int]" in impl_src
- or "\"seed\": seed" in impl_src))
+ # Merely accepting ``seed`` in generate() is part of the ABC
+ # contract, not proof that the backend implements it. Providers
+ # can mark that contract-only parameter explicitly.
+ implements_seed = ("payload[\"seed\"]" in impl_src
+ or "\"seed\": seed" in impl_src
+ or ("seed: Optional[int]" in impl_src
+ and "_IGNORES_SEED = True" not in impl_src))
self.assertEqual(
declares_seed, implements_seed,
f"{name}: supports_seed declaration ({declares_seed}) "