Skip to content

The agent that grows with you

feat(image_gen): route the managed selection by model id across FAL, Krea and Portal

teknium1294421fdfbba
diff --git a/tests/tools/test_image_generation.py b/tests/tools/test_image_generation.py
index bbbbfe86161..bf9c808ec70 100644
--- a/tests/tools/test_image_generation.py
+++ b/tests/tools/test_image_generation.py
@@ -571,14 +571,14 @@ class TestKreaModelNormalization:
class TestManagedKreaRouting:
- """`_maybe_route_managed_krea` only fires for Krea models in managed mode."""
+ """`_maybe_route_managed_model` only fires for Krea / Portal models in managed mode."""
def test_no_route_when_model_not_krea(self, image_tool, monkeypatch):
monkeypatch.setattr(image_tool, "_read_configured_image_provider", lambda: None)
monkeypatch.setattr(
image_tool, "_read_configured_image_model", lambda: "fal-ai/flux-2/klein/9b"
)
- assert image_tool._maybe_route_managed_krea("p", "square") is None
+ assert image_tool._maybe_route_managed_model("p", "square") is None
def test_routes_native_krea_model_to_krea_plugin_in_managed_mode(
@@ -616,7 +616,7 @@ class TestManagedKreaRouting:
"hermes_cli.plugins._ensure_plugins_discovered", lambda *a, **k: None
)
- out = image_tool._maybe_route_managed_krea("a cat", "portrait")
+ out = image_tool._maybe_route_managed_model("a cat", "portrait")
assert out is not None
assert _json.loads(out)["success"] is True
kwargs = fake_provider.generate.call_args.kwargs
@@ -625,6 +625,40 @@ class TestManagedKreaRouting:
assert kwargs["aspect_ratio"] == "portrait"
+class TestManagedPortalRouting:
+ """A Portal model under the managed selection reaches the Portal plugin — never FAL."""
+
+ def _fake_registry(self, monkeypatch, fake_provider):
+ monkeypatch.setattr("agent.image_gen_registry.get_provider", lambda name: fake_provider)
+ monkeypatch.setattr("hermes_cli.plugins._ensure_plugins_discovered", lambda *a, **k: None)
+
+ def test_routes_portal_model_to_nous_plugin(self, image_tool, monkeypatch):
+ import json as _json
+ from unittest.mock import MagicMock
+
+ monkeypatch.setattr(image_tool, "_read_configured_image_provider", lambda: "nous")
+ monkeypatch.setattr(image_tool, "_read_configured_image_model", lambda: "openai/gpt-5.4-image-2")
+ fake_provider = MagicMock(display_name="Nous Portal")
+ fake_provider.generate.return_value = {"success": True, "image": "/tmp/x.png"}
+ self._fake_registry(monkeypatch, fake_provider)
+
+ out = image_tool._maybe_route_managed_model("a cat", "square")
+
+ assert _json.loads(out)["success"] is True
+ assert fake_provider.generate.call_args.kwargs["model"] == "openai/gpt-5.4-image-2"
+
+ def test_portal_model_without_plugin_errors_instead_of_billing_fal(self, image_tool, monkeypatch):
+ import json as _json
+
+ monkeypatch.setattr(image_tool, "_read_configured_image_provider", lambda: "nous")
+ monkeypatch.setattr(image_tool, "_read_configured_image_model", lambda: "openai/gpt-5.4-image-2")
+ self._fake_registry(monkeypatch, None)
+
+ out = image_tool._maybe_route_managed_model("a cat", "square")
+
+ assert out is not None and _json.loads(out)["success"] is False
+
+
class TestFalKreaCatalog:
"""Krea 2 on FAL remains in the FAL picker for FAL-billed users."""
diff --git a/tests/tools/test_image_generation_managed.py b/tests/tools/test_image_generation_managed.py
new file mode 100644
index 00000000000..ebb165b5ad0
--- /dev/null
+++ b/tests/tools/test_image_generation_managed.py
@@ -0,0 +1,36 @@
+"""The single managed image row: model id → gateway, and a de-duplicated union catalog."""
+
+from unittest.mock import patch
+
+import tools.image_generation_managed as managed
+from plugins.image_gen.krea import KREA_MODEL_IDS
+from tools.image_generation_catalog import DEFAULT_MODEL, FAL_MODELS
+
+
+def test_every_fal_and_krea_model_resolves_to_its_own_gateway_and_the_rest_to_portal():
+ assert managed.managed_backend_for_model(None) == managed.FAL
+ assert {managed.managed_backend_for_model(m) for m in FAL_MODELS} == {managed.FAL}
+ assert {managed.managed_backend_for_model(m) for m in KREA_MODEL_IDS} == {managed.KREA}
+ assert managed.managed_backend_for_model("vendor/some-portal-only-model") == managed.PORTAL
+
+
+def test_union_catalog_lists_each_model_once():
+ def rows(name):
+ return {
+ "krea": [{"id": m, "display": m} for m in KREA_MODEL_IDS],
+ "nous": [
+ {"id": "microsoft/mai-image-2.5-pro"}, # same id as a FAL entry
+ {"id": "krea/krea-2-medium"}, # Krea 2 under its Portal id
+ {"id": "google/gemini-3-pro-image"}, # Nano Banana Pro under its Portal id
+ {"id": "vendor/portal-only"},
+ ],
+ }[name]
+
+ with patch.object(managed, "_plugin_rows", side_effect=rows):
+ catalog, default = managed.managed_image_catalog()
+
+ assert default == DEFAULT_MODEL
+ portal = {m for m, meta in catalog.items() if meta["backend"] == managed.PORTAL}
+ assert portal == {"vendor/portal-only"}
+ assert catalog["microsoft/mai-image-2.5-pro"]["backend"] == managed.FAL
+ assert KREA_MODEL_IDS <= set(catalog) and not any(m.startswith("fal-ai/krea/") for m in catalog)
diff --git a/tools/image_generation_managed.py b/tools/image_generation_managed.py
new file mode 100644
index 00000000000..cdf36135cfc
--- /dev/null
+++ b/tools/image_generation_managed.py
@@ -0,0 +1,84 @@
+"""Managed ("Nous Subscription") image generation: one picker row, one model catalog.
+
+Three gateways sit behind the single stored selection ``image_gen.provider: nous``; the stored
+``image_gen.model`` decides which one serves a request:
+
+* ``fal`` — the FAL managed gateway, every id in the in-tree ``FAL_MODELS`` catalog;
+* ``krea`` — the Krea managed gateway, the ``plugins/image_gen/krea`` model ids;
+* ``portal`` — Nous Portal chat-completions image models (``plugins/image_gen/openrouter``'s
+ ``nous`` provider), anything else.
+
+Before this module the second and third gateways each had their own picker row that also
+wrote ``provider: nous`` — every managed row read "active" at once and picking the Portal row
+silently generated on FAL.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, Optional, Tuple
+
+FAL, KREA, PORTAL = "fal", "krea", "portal"
+
+# Portal ids that are the same model as a FAL or Krea catalog entry. FAL wins (it is the
+# gateway the free tool pool funds); Krea 2 goes through its native gateway, never FAL or the
+# Portal. Only cross-id duplicates live here — identical ids collapse by key.
+_PORTAL_DUPLICATE_OF = {
+ "openai/gpt-image-2": "fal-ai/gpt-image-2",
+ "google/gemini-3-pro-image": "fal-ai/nano-banana-pro",
+ "google/gemini-3.1-flash-image": "fal-ai/nano-banana-2",
+ "google/gemini-3.1-flash-lite-image": "google/nano-banana-2-lite",
+ "krea/krea-2-medium": "krea-2-medium",
+ "krea/krea-2-medium-turbo": "krea-2-medium-turbo",
+ "krea/krea-2-large": "krea-2-large",
+}
+_FAL_KREA_PREFIX = "fal-ai/krea/"
+
+
+def managed_backend_for_model(model_id: Optional[str]) -> str:
+ """Gateway that serves ``model_id`` under the managed selection (unset → FAL default)."""
+ from plugins.image_gen.krea import KREA_MODEL_IDS
+ from tools.image_generation_catalog import FAL_MODELS
+
+ candidate = model_id.strip() if isinstance(model_id, str) else ""
+ if not candidate or candidate in FAL_MODELS:
+ return FAL
+ if candidate in KREA_MODEL_IDS:
+ return KREA
+ return PORTAL
+
+
+def _plugin_rows(name: str) -> list:
+ """``list_models()`` of a registered image gen plugin; ``[]`` when unavailable."""
+ from tools.image_generation_tool import _get_plugin_provider
+
+ try:
+ provider = _get_plugin_provider(name)
+ return list(provider.list_models() or []) if provider is not None else []
+ except Exception: # noqa: BLE001 - a broken plugin must not empty the whole picker
+ return []
+
+
+def managed_image_catalog(
+ *, include_krea: bool = True, include_portal: bool = True,
+) -> Tuple[Dict[str, Dict[str, Any]], str]:
+ """``({model_id: metadata}, default_model)`` for the managed row's model picker.
+
+ FAL catalog first (minus the Krea-on-FAL entries), then native Krea, then Portal models
+ that are not another entry in disguise. Every row carries ``backend`` so callers can hide
+ the gateways an account is not entitled to.
+ """
+ from tools.image_generation_catalog import DEFAULT_MODEL, FAL_MODELS
+
+ catalog: Dict[str, Dict[str, Any]] = {
+ mid: {**meta, "backend": FAL} for mid, meta in FAL_MODELS.items()
+ if not mid.startswith(_FAL_KREA_PREFIX)}
+ if include_krea:
+ for row in _plugin_rows("krea"):
+ catalog[row["id"]] = {**row, "backend": KREA}
+ if include_portal:
+ for row in _plugin_rows("nous"):
+ mid = row["id"]
+ if mid in catalog or _PORTAL_DUPLICATE_OF.get(mid) in catalog:
+ continue
+ catalog[mid] = {**row, "backend": PORTAL}
+ return catalog, DEFAULT_MODEL
diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.py
index 2aeed20104f..6d00b89fcd2 100644
--- a/tools/image_generation_tool.py
+++ b/tools/image_generation_tool.py
@@ -660,8 +660,6 @@ def _dispatch_to_plugin_provider(
return _provider_result(result, "Provider returned a non-dict result")
-# Native Krea model ids are served by the Krea managed gateway (managed mode only —
-# direct/BYO users keep their pipeline).
def _normalize_krea_model(model_id: Optional[str]) -> Optional[str]:
"""Return ``model_id`` when it is one of the Krea plugin's model ids, else ``None``."""
from plugins.image_gen.krea import KREA_MODEL_IDS
@@ -670,38 +668,63 @@ def _normalize_krea_model(model_id: Optional[str]) -> Optional[str]:
return candidate if candidate in KREA_MODEL_IDS else None
-def _maybe_route_managed_krea(
- prompt: str, aspect_ratio: str, image_url: Optional[str] = None,
- reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> Optional[str]:
- """JSON result from the managed Krea gateway, or ``None`` to fall through.
+def _managed_model_plugin() -> Optional[tuple]:
+ """``(plugin_name, model_id)`` when the managed selection stores a Krea or Portal model, else ``None``.
- Fires only for a native Krea model with no ``image_gen.provider`` other than
- ``"nous"`` stored (a picker choice dispatches normally) and a resolvable Krea gateway.
+ The managed row writes ``provider: nous`` for three gateways; the model id says which. FAL
+ models (and an unset model) return ``None`` so the in-tree FAL path handles them. Only the
+ ``nous``/unset selection qualifies — a direct/BYO provider pick dispatches normally.
"""
+ from tools.image_generation_managed import KREA, PORTAL, managed_backend_for_model
+
configured_provider = _read_configured_image_provider()
if configured_provider is not None and configured_provider != NOUS_MANAGED_PROVIDER:
return None
- normalized = _normalize_krea_model(_read_configured_image_model())
- if normalized is None:
+ model_id = _read_configured_image_model()
+ backend = managed_backend_for_model(model_id)
+ if backend == KREA:
+ return "krea", model_id
+ if backend == PORTAL and configured_provider == NOUS_MANAGED_PROVIDER:
+ return "nous", model_id
+ return None
+
+
+def _maybe_route_managed_model(
+ prompt: str, aspect_ratio: str, image_url: Optional[str] = None,
+ reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> Optional[str]:
+ """JSON result from the Krea or Portal gateway the stored model belongs to, or ``None`` to fall
+ through to FAL.
+
+ A Krea model with no reachable Krea gateway falls through (direct/BYO users keep their
+ pipeline); a Portal model never does — falling through would silently bill a FAL default.
+ """
+ target = _managed_model_plugin()
+ if target is None:
return None
+ plugin_name, model_id = target
try:
- from plugins.image_gen.krea import _resolve_managed_krea_gateway
- if _resolve_managed_krea_gateway() is None:
- return None
- provider = _get_plugin_provider("krea")
+ if plugin_name == "krea":
+ from plugins.image_gen.krea import _resolve_managed_krea_gateway
+ if _resolve_managed_krea_gateway() is None:
+ return None
+ provider = _get_plugin_provider(plugin_name)
except Exception as exc: # noqa: BLE001
- logger.debug("Managed Krea routing unavailable: %s", exc)
- return None
+ logger.debug("Managed %s routing unavailable: %s", plugin_name, exc)
+ provider = None
if provider is None:
- return None
- kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio, "model": normalized}
+ if plugin_name == "krea":
+ return None
+ return _provider_error(
+ f"image_gen.model='{model_id}' is a Nous Portal model but the Portal image backend is not "
+ f"available. Pick another model via `hermes tools` → Image Generation.", "provider_not_registered")
+ kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio, "model": model_id}
try:
_add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale)
result = provider.generate(**kwargs)
except Exception as exc: # noqa: BLE001
- logger.warning("Managed Krea routing failed: %s", exc)
- return _provider_error(f"Managed Krea generation error: {exc}", "provider_exception")
- return _provider_result(result, "Krea provider returned a non-dict result")
+ logger.warning("Managed %s routing failed: %s", plugin_name, exc)
+ return _provider_error(f"Managed {provider.display_name} generation error: {exc}", "provider_exception")
+ return _provider_result(result, f"{provider.display_name} provider returned a non-dict result")
def _confine_source_images(image_url, reference_image_urls, task_id, *, permitted: tuple = ("image",)):
@@ -742,12 +765,12 @@ def _handle_image_generate(args, **kw):
args.get("image_url"), args.get("reference_image_urls"), task_id)
if confine_error is not None:
return confine_error
- # Order matters: explicit plugin provider (incl. "krea"), then model-driven managed Krea
- # interception (only when no provider is set, so BYO/direct FAL stays untouched), then FAL.
+ # Order matters: explicit plugin provider, then the model-driven managed gateways (Krea /
+ # Portal — only under the "nous"/unset selection, so BYO/direct FAL stays untouched), then FAL.
sources = dict(image_url=image_url, reference_image_urls=reference_image_urls,
upscale=upscale if isinstance(upscale, bool) else None)
raw = None
- for route in (_dispatch_to_plugin_provider, _maybe_route_managed_krea, image_generate_tool):
+ for route in (_dispatch_to_plugin_provider, _maybe_route_managed_model, image_generate_tool):
raw = route(prompt, aspect_ratio, **sources)
if raw is not None:
break
@@ -763,15 +786,15 @@ _NO_CAPABILITIES = {"modalities": ["text"], "max_reference_images": 0, "supports
def _active_image_capabilities() -> Dict[str, Any]:
"""Best-effort capabilities of the active backend/model; never raises.
- Mirrors runtime dispatch: a Krea model id under the managed selection asks the Krea
+ Mirrors runtime dispatch: a Krea or Portal model id under the managed selection asks that
plugin, a set ``image_gen.provider`` asks that plugin, else the FAL catalog.
Fail-closed: an undeclared capability is advertised as absent.
"""
info: Dict[str, Any] = dict(_NO_CAPABILITIES)
configured_provider = _read_configured_image_provider()
- managed_selection = configured_provider in (None, NOUS_MANAGED_PROVIDER)
- if managed_selection and _normalize_krea_model(_read_configured_image_model()) is not None:
- plugin_name = "krea"
+ managed = _managed_model_plugin()
+ if managed is not None:
+ plugin_name = managed[0]
elif configured_provider and configured_provider != "fal":
plugin_name = configured_provider
else: