The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(video_gen): resolve OpenRouter and DeepInfra credentials per profile, not from os.environ
John Paul Solivabb3011a2022b
diff --git a/agent/video_gen_provider.py b/agent/video_gen_provider.pyindex 4b1644ba1b3..56b3bd8e6c0 100644--- a/agent/video_gen_provider.py+++ b/agent/video_gen_provider.py@@ -17,13 +17,13 @@ from __future__ import annotationsimport abcimport logging-import osimport timefrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuplefrom agent import provider_mediafrom agent.provider_base import CatalogProviderBase+from agent.secret_scope import get_secret_strlogger = logging.getLogger(__name__)@@ -153,7 +153,8 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):_poll_deadline_s: float = 900.0def _api_key(self) -> str:- return os.environ.get(self._env_key, "").strip()+ # Through the profile secret scope: under multiplexing os.environ holds another profile's key.+ return get_secret_str(self._env_key).strip()def is_available(self) -> bool:return bool(self._api_key())@@ -176,7 +177,7 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):return videodef _base_url(self) -> str:- return os.environ.get(f"{self.name.upper()}_BASE_URL", "").strip() or self._default_base_url+ return get_secret_str(f"{self.name.upper()}_BASE_URL").strip() or self._default_base_urldef generate(self, prompt: str, *, model: Optional[str] = None, image_url: Optional[str] = None,diff --git a/plugins/video_gen/openrouter/__init__.py b/plugins/video_gen/openrouter/__init__.pyindex c89b16473a3..6c8c8180168 100644--- a/plugins/video_gen/openrouter/__init__.py+++ b/plugins/video_gen/openrouter/__init__.py@@ -14,7 +14,6 @@ Docs: https://openrouter.ai/docs/guides/overview/multimodal/video-generationfrom __future__ import annotationsimport logging-import osimport timefrom typing import Any, Dict, List, Optional, Tuple@@ -162,14 +161,17 @@ class OpenRouterVideoGenProvider(VideoGenProvider):self._catalog_cache: Optional[Tuple[List[Dict[str, Any]], float]] = None# ---- credentials / transport -------------------------------------------------------------- def _api_key(self) -> str:- return os.environ.get("OPENROUTER_API_KEY", "").strip()+ def _credentials(self) -> Tuple[str, str]:+ """``(api_key, base_url)`` from the runtime resolver chat uses, so a pooled or OAuth credential counts+ and a multiplexed profile never spends the launch profile's ``os.environ`` key; raises on failure."""+ from hermes_cli.runtime_provider import resolve_runtime_provider- def _base_url(self) -> str:- return (os.environ.get("OPENROUTER_BASE_URL", "").strip() or DEFAULT_BASE_URL).rstrip("/")+ runtime = resolve_runtime_provider(requested="openrouter")+ return (str(runtime.get("api_key") or "").strip(),+ (str(runtime.get("base_url") or "").strip() or DEFAULT_BASE_URL).rstrip("/"))- def _headers(self) -> Dict[str, str]:- return {"Authorization": f"Bearer {self._api_key()}", "Content-Type": "application/json",+ def _headers(self, api_key: str) -> Dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json","HTTP-Referer": "https://github.com/NousResearch/hermes-agent", "X-Title": "Hermes Agent"}def _session(self) -> Any:@@ -177,7 +179,11 @@ class OpenRouterVideoGenProvider(VideoGenProvider):return requests.Session()def is_available(self) -> bool:- return bool(self._api_key())+ try:+ return bool(self._credentials()[0])+ except Exception as exc: # noqa: BLE001 — a resolution failure is "unavailable", never a picker crash+ logger.debug("OpenRouter video credential resolution failed: %s", exc)+ return False# ---- catalog -------------------------------------------------------------------------------def _catalog(self) -> List[Dict[str, Any]]:@@ -187,7 +193,7 @@ class OpenRouterVideoGenProvider(VideoGenProvider):entries: List[Dict[str, Any]] = []try:import requests- response = requests.get(f"{self._base_url()}/videos/models", timeout=_CATALOG_TIMEOUT_S)+ response = requests.get(f"{self._credentials()[1]}/videos/models", timeout=_CATALOG_TIMEOUT_S)response.raise_for_status()data = response.json().get("data")entries = [e for e in (data if isinstance(data, list) else []) if isinstance(e, dict) and e.get("id")]@@ -247,15 +253,15 @@ class OpenRouterVideoGenProvider(VideoGenProvider):"env_vars": [{"key": "OPENROUTER_API_KEY", "prompt": "OpenRouter API key", "url": "https://openrouter.ai/settings/keys"}]}# ---- generation ----------------------------------------------------------------------------- def _poll(self, session: Any, job_id: str) -> Dict[str, Any]:+ def _poll(self, session: Any, job_id: str, base_url: str, headers: Dict[str, str]) -> Dict[str, Any]:deadline = time.monotonic() + self._poll_deadline_s- url = f"{self._base_url()}/videos/{job_id}"+ url = f"{base_url}/videos/{job_id}"last_status = "unknown"while True:remaining = deadline - time.monotonic()if remaining <= 0:raise TimeoutError(f"video job {job_id} did not finish within {int(self._poll_deadline_s)}s (last status={last_status})")- response = session.get(url, headers=self._headers(), timeout=max(0.001, min(self._request_timeout_s, remaining)))+ response = session.get(url, headers=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"@@ -263,12 +269,12 @@ class OpenRouterVideoGenProvider(VideoGenProvider):return payloadtime.sleep(min(self._poll_interval_s, max(0.0, deadline - time.monotonic())))- def _save_completed_video(self, job_id: str) -> str:+ def _save_completed_video(self, job_id: str, base_url: str, headers: Dict[str, str]) -> str:# The content endpoint is derived from our configured origin, never from ``unsigned_urls``: the# bearer key must only ever be sent to the host the operator selected. That origin is operator# chosen (a LAN relay is legitimate), so the first hop is trusted for the private-address check.- return str(save_url_video(f"{self._base_url()}/videos/{job_id}/content", prefix="openrouter",- headers=self._headers(), require_video_content_type=True,+ return str(save_url_video(f"{base_url}/videos/{job_id}/content", prefix="openrouter",+ headers=headers, require_video_content_type=True,trusted_origin=True))def generate(@@ -287,8 +293,15 @@ class OpenRouterVideoGenProvider(VideoGenProvider):if not prompt:return fail("prompt is required", "invalid_request")- if not self._api_key():- return fail("OPENROUTER_API_KEY is not set", "missing_credentials")+ try:+ api_key, base_url = self._credentials()+ except Exception as exc: # noqa: BLE001+ return fail(f"Could not resolve OpenRouter credentials: {exc}", "missing_credentials")+ if not api_key:+ return fail("No OpenRouter credential: set OPENROUTER_API_KEY or run `hermes auth add openrouter`",+ "missing_credentials")+ # Resolved once: a rotating pool must not submit under one key and poll or download under another.+ headers = self._headers(api_key)image_url = (image_url or "").strip() or Nonerefs = [r.strip() for r in (reference_image_urls or []) if isinstance(r, str) and r.strip()]for ref in ([image_url] if image_url else []) + refs:@@ -301,7 +314,7 @@ class OpenRouterVideoGenProvider(VideoGenProvider):duration=duration, aspect_ratio=aspect_ratio, resolution=resolution, audio=audio, seed=seed)session = self._session()try:- submitted = session.post(f"{self._base_url()}/videos", headers=self._headers(), json=payload,+ submitted = session.post(f"{base_url}/videos", headers=headers, json=payload,timeout=self._request_timeout_s)if submitted.status_code >= 400:detail = ""@@ -314,11 +327,11 @@ class OpenRouterVideoGenProvider(VideoGenProvider):job_id = str(submitted.json().get("id") or "").strip()if not job_id:return fail("OpenRouter submit response did not contain a job id", "api_error")- job = self._poll(session, job_id)+ job = self._poll(session, job_id, base_url, headers)status = str(job.get("status") or "").lower()if status != "completed":return fail(str(job.get("error") or f"video job ended with status={status!r}"), "job_failed")- video_path = self._save_completed_video(job_id)+ video_path = self._save_completed_video(job_id, base_url, headers)except Exception as exc: # noqa: BLE001 — normalize transport/timeout failures for tool callerslogger.debug("OpenRouter video generation failed", exc_info=True)return fail(f"OpenRouter video generation failed: {exc}", "api_error")diff --git a/tests/plugins/video_gen/test_deepinfra_provider.py b/tests/plugins/video_gen/test_deepinfra_provider.pyindex 35019317784..0acdc2a2578 100644--- a/tests/plugins/video_gen/test_deepinfra_provider.py+++ b/tests/plugins/video_gen/test_deepinfra_provider.py@@ -134,3 +134,31 @@ def test_generate_text_to_video_downloads_url_and_saves_locally():assert "image_url" not in captured["kwargs"].get("extra_body", {})+def test_credentials_follow_the_profile_secret_scope(monkeypatch):+ """On a multiplexed gateway os.environ is the launch profile's .env: the key and base URL come from the+ routed profile's scope, and a profile without a key is unavailable instead of borrowing the launch key."""+ from agent.secret_scope import reset_secret_scope, set_multiplex_active, set_secret_scope++ monkeypatch.setenv("DEEPINFRA_BASE_URL", "https://launch.example/v1")+ provider = deepinfra_plugin.DeepInfraVideoGenProvider()+ captured: dict = {}+ set_multiplex_active(True)+ try:+ token = set_secret_scope({"DEEPINFRA_API_KEY": "profile-b-key", "DEEPINFRA_BASE_URL": "https://profile-b.example/v1"})+ try:+ with patch.dict("sys.modules", {"openai": _fake_openai_with_capture(captured)}), \+ _mock_url_download(captured):+ assert provider.generate(prompt="a cube", model="vendor/x")["success"]+ finally:+ reset_secret_scope(token)+ token = set_secret_scope({})+ try:+ assert provider.is_available() is False+ finally:+ reset_secret_scope(token)+ finally:+ set_multiplex_active(False)+ if captured.get("http_client") is not None:+ captured["http_client"].close()+ assert captured["api_key"] == "profile-b-key"+ assert captured["base_url"] == "https://profile-b.example/v1"diff --git a/tests/plugins/video_gen/test_openrouter.py b/tests/plugins/video_gen/test_openrouter.pyindex 9b662ef70da..2d9f6b2fa02 100644--- a/tests/plugins/video_gen/test_openrouter.py+++ b/tests/plugins/video_gen/test_openrouter.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field+from types import SimpleNamespacefrom agent import video_gen_registryfrom plugins.video_gen.openrouter import OpenRouterVideoGenProvider, _build_payload@@ -121,6 +122,78 @@ def test_generate_submits_polls_and_downloads_from_configured_origin(monkeypatchassert saved[0][1]["trusted_origin"] is True+def _generate_capturing(monkeypatch, tmp_path, provider):+ """``generate()`` over the fake transport; returns the result and every Authorization header sent."""+ session = _Session()+ monkeypatch.setattr(provider, "_session", lambda: session)+ monkeypatch.setattr("plugins.video_gen.openrouter.time.sleep", lambda s: None)+ saved = []++ def fake_save(url, **kwargs):+ saved.append((url, kwargs))+ return tmp_path / "clip.mp4"+ monkeypatch.setattr("plugins.video_gen.openrouter.save_url_video", fake_save)+ result = provider.generate("a fox")+ bearers = [kwargs["headers"]["Authorization"] for _, kwargs in session.posts + session.gets + saved]+ return result, session, bearers+++def _add_pooled_key(key, label):+ from hermes_cli.auth_commands import auth_add_command+ auth_add_command(SimpleNamespace(provider="openrouter", auth_type="api-key", api_key=key, label=label))+++def test_pooled_credential_enables_the_backend(monkeypatch, tmp_path):+ """A key added only with ``hermes auth add openrouter`` serves chat and image_gen; video must use it too."""+ _add_pooled_key("sk-or-pool", "pool")+ provider = _provider(monkeypatch, [_VEO])+ assert provider.is_available() is True+ result, _, bearers = _generate_capturing(monkeypatch, tmp_path, provider)+ assert result["success"], result+ assert bearers == ["Bearer sk-or-pool"] * 4 # submit, two polls, download+++def test_one_job_keeps_one_credential_while_the_pool_rotates(monkeypatch, tmp_path):+ """A job created under one account is only visible to that account: poll and download must reuse the+ submit key even when a round-robin pool would hand out the other one next."""+ from hermes_constants import get_hermes_home+ (get_hermes_home() / "config.yaml").write_text("credential_pool_strategies:\n openrouter: round_robin\n")+ _add_pooled_key("sk-or-one", "one")+ _add_pooled_key("sk-or-two", "two")+ result, _, bearers = _generate_capturing(monkeypatch, tmp_path, _provider(monkeypatch, [_VEO]))+ assert result["success"], result+ assert len(bearers) == 4 and len(set(bearers)) == 1 and bearers[0] in {"Bearer sk-or-one", "Bearer sk-or-two"}+++def test_multiplexed_profile_spends_its_own_key_not_the_launch_profiles(monkeypatch, tmp_path):+ """On a multiplexed gateway os.environ is the launch profile's .env; a routed turn must sign every request+ with its own profile's key and send it only to its own profile's base URL."""+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_multiplex_active, set_secret_scope+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-launch-profile")+ monkeypatch.setenv("OPENROUTER_BASE_URL", "https://launch.example/api/v1")+ profile_home = tmp_path / "profile-b"+ profile_home.mkdir()+ (profile_home / ".env").write_text("OPENROUTER_API_KEY=sk-or-profile-b\n"+ "OPENROUTER_BASE_URL=https://profile-b.example/api/v1\n")+ provider = _provider(monkeypatch, [_VEO])++ set_multiplex_active(True)+ home_token = set_hermes_home_override(str(profile_home))+ secret_token = set_secret_scope(build_profile_secret_scope(profile_home))+ try:+ result, session, bearers = _generate_capturing(monkeypatch, tmp_path, provider)+ finally:+ reset_secret_scope(secret_token)+ reset_hermes_home_override(home_token)+ set_multiplex_active(False)++ assert result["success"], result+ assert bearers == ["Bearer sk-or-profile-b"] * 4+ assert session.posts[0][0] == "https://profile-b.example/api/v1/videos"++def test_generate_rejects_local_image_paths_before_spending(monkeypatch):monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")provider = _provider(monkeypatch, [_VEO])diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 1e07b5486ef..357ab37c050 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -331,7 +331,7 @@ Backends ship as plugins under `plugins/video_gen/<name>/`:- **xAI Grok-Imagine** — text-to-video and image-to-video (SuperGrok OAuth or `XAI_API_KEY`).- **FAL.ai** — Veo 3.1, Pixverse v6, Kling 3.0 / O3 (requires `FAL_KEY`).-- **OpenRouter** — every generative model on OpenRouter's video API (Veo 3.1, Sora 2 Pro, Kling 3, Seedance 2, Wan 3, Hailuo 3, Grok Imagine, FLUX 3 Video, …); text-to-video, image-to-video and reference-to-video; catalog and per-model limits fetched live (requires `OPENROUTER_API_KEY`, billed to your OpenRouter credit).+- **OpenRouter** — every generative model on OpenRouter's video API (Veo 3.1, Sora 2 Pro, Kling 3, Seedance 2, Wan 3, Hailuo 3, Grok Imagine, FLUX 3 Video, …); text-to-video, image-to-video and reference-to-video; catalog and per-model limits fetched live (requires `OPENROUTER_API_KEY` or a credential added with `hermes auth add openrouter`, billed to your OpenRouter credit).- **DeepInfra** — live `video-gen` catalog over the OpenAI-compatible videos endpoint (requires `DEEPINFRA_API_KEY`).The single `video_generate` tool covers both modalities — pass `image_url` to animate a still, omit it to generate from text alone. The active backend auto-routes to the right endpoint. As with `image_generate`, the model is user-configured (`video_gen.model`) and not selectable by the agent — none of the video tools take a `model` argument. The tool's description is rebuilt at session start to reflect the active backend's actual capabilities (modalities, aspect ratios, resolutions, duration range, max reference images, audio support). See [Video Generation Provider Plugins](../developer-guide/video-gen-provider-plugin.md) for backend authoring.