The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(plugins/image_gen): shared _common (config/key/save/error/picker helpers), convert all 8 providers, per-model tables
Tekniumb5b62aa83d8a
diff --git a/plugins/image_gen/_common.py b/plugins/image_gen/_common.pynew file mode 100644index 00000000000..a09cd541619--- /dev/null+++ b/plugins/image_gen/_common.py@@ -0,0 +1,322 @@+"""Shared helpers for the bundled ``image_gen`` provider plugins.++Every provider under ``plugins/image_gen/`` is loaded by path (module name+``hermes_plugins.image_gen__<name>``) and resolves this module through the+repo root on ``sys.path`` — the same way they import ``agent.image_gen_provider``.+Nothing here is a plugin: the scanner only looks at directories.+"""++from __future__ import annotations++import logging+import os+from dataclasses import dataclass+from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple++from agent.image_gen_provider import (+ error_response,+ normalize_reference_images,+ save_b64_image,+ save_url_image,+)++logger = logging.getLogger(__name__)++# OpenAI-style ``size`` strings for the three semantic aspect ratios. Shared by+# every OpenAI-compatible ``images.generations`` backend so aspect_ratio means+# the same thing across providers.+OPENAI_SIZES: Dict[str, str] = {+ "landscape": "1536x1024",+ "square": "1024x1024",+ "portrait": "1024x1536",+}++# gpt-image-2 quality tiers, exposed as three virtual model ids so the picker+# and ``image_gen.model`` behave like any other multi-model backend. All three+# hit the same API model with a different ``quality`` knob.+GPT_IMAGE_2_API_MODEL = "gpt-image-2"+GPT_IMAGE_2_DEFAULT = "gpt-image-2-medium"+GPT_IMAGE_2_TIERS: Dict[str, Dict[str, Any]] = {+ "gpt-image-2-low": {+ "display": "GPT Image 2 (Low)",+ "speed": "~15s",+ "strengths": "Fast iteration, lowest cost",+ "quality": "low",+ },+ "gpt-image-2-medium": {+ "display": "GPT Image 2 (Medium)",+ "speed": "~40s",+ "strengths": "Balanced — default",+ "quality": "medium",+ },+ "gpt-image-2-high": {+ "display": "GPT Image 2 (High)",+ "speed": "~2min",+ "strengths": "Highest fidelity, strongest prompt adherence",+ "quality": "high",+ },+}++PROMPT_REQUIRED = "Prompt is required and must be a non-empty string"+OPENAI_MISSING = "openai Python package not installed (pip install openai)"++ErrorFn = Callable[..., Dict[str, Any]]+++def size_for(aspect: str) -> str:+ """OpenAI ``size`` string for a semantic aspect (square when unknown)."""+ return OPENAI_SIZES.get(aspect, OPENAI_SIZES["square"])+++def load_image_gen_config(sub: Optional[str] = None) -> Dict[str, Any]:+ """Read ``image_gen`` (or ``image_gen.<sub>``) from config.yaml; ``{}`` on any failure."""+ label = "image_gen" if sub is None else f"image_gen.{sub}"+ try:+ from hermes_cli.config import load_config++ cfg = load_config()+ section = cfg.get("image_gen") if isinstance(cfg, dict) else None+ if sub is not None:+ section = section.get(sub) if isinstance(section, dict) else None+ return section if isinstance(section, dict) else {}+ except Exception as exc: # noqa: BLE001 - config is best-effort+ logger.debug("Could not load %s config: %s", label, exc)+ return {}+++def resolve_static_model(+ models: Dict[str, Dict[str, Any]],+ default: str,+ *,+ env_var: str,+ config_key: str,+ explicit: Optional[str] = None,+ include_top_level: bool = True,+ config: Optional[Dict[str, Any]] = None,+) -> Tuple[str, Dict[str, Any]]:+ """Pick ``(model_id, meta)`` from a fixed catalog.++ Precedence (first *known* id wins; unknown ids fall through rather than+ error): explicit caller override → ``env_var`` → ``image_gen.<config_key>.model``+ → top-level ``image_gen.model`` (when ``include_top_level``) → ``default``.+ """+ if isinstance(explicit, str) and explicit.strip() in models:+ return explicit.strip(), models[explicit.strip()]++ env_override = os.environ.get(env_var)+ if env_override and env_override in models:+ return env_override, models[env_override]++ cfg = load_image_gen_config() if config is None else config+ scoped = cfg.get(config_key)+ candidates = [scoped.get("model") if isinstance(scoped, dict) else None]+ if include_top_level:+ candidates.append(cfg.get("model"))+ for candidate in candidates:+ if isinstance(candidate, str) and candidate in models:+ return candidate, models[candidate]++ return default, models[default]+++def collect_source_images(+ image_url: Optional[str],+ reference_image_urls: Optional[List[str]],+ limit: Optional[int] = None,+) -> List[str]:+ """Primary ``image_url`` first, then normalized references, clamped to ``limit``."""+ sources: List[str] = []+ if isinstance(image_url, str) and image_url.strip():+ sources.append(image_url.strip())+ sources.extend(normalize_reference_images(reference_image_urls) or [])+ return sources[:limit] if limit is not None else sources+++def catalog_rows(+ models: Dict[str, Dict[str, Any]],+ fields: Iterable[str] = ("display", "speed", "strengths", "price"),+ *,+ price: Optional[str] = None,+) -> List[Dict[str, Any]]:+ """Picker rows for a catalog: ``id`` plus ``fields`` read from each meta.++ A missing ``display`` falls back to the model id, other missing fields to+ ``""``; ``price`` (when given) overrides the per-model value.+ """+ rows = []+ for model_id, meta in models.items():+ row: Dict[str, Any] = {"id": model_id}+ for field in fields:+ row[field] = meta.get(field, model_id if field == "display" else "")+ if price is not None:+ row["price"] = price+ rows.append(row)+ return rows+++def api_key_setup_schema(+ name: str, badge: str, tag: str, *, key: str, prompt: str, url: str+) -> Dict[str, Any]:+ """``get_setup_schema()`` dict for a provider authenticated by one env var."""+ return {+ "name": name,+ "badge": badge,+ "tag": tag,+ "env_vars": [{"key": key, "prompt": prompt, "url": url}],+ }+++def error_factory(provider: str, aspect: str, *, model: str = "", prompt: str = "") -> ErrorFn:+ """Return ``fail(error, error_type, **override)`` pre-bound to this call's context."""++ def fail(error: str, error_type: str, **override: Any) -> Dict[str, Any]:+ kwargs = dict(provider=provider, model=model, prompt=prompt, aspect_ratio=aspect)+ kwargs.update(override)+ return error_response(error=error, error_type=error_type, **kwargs)++ return fail+++def prompt_required_error(provider: str, aspect: str) -> Dict[str, Any]:+ return error_response(+ error=PROMPT_REQUIRED,+ error_type="invalid_argument",+ provider=provider,+ aspect_ratio=aspect,+ )+++def openai_importable() -> bool:+ try:+ import openai # noqa: F401+ except ImportError:+ return False+ return True+++def import_openai(provider: str, aspect: str) -> Tuple[Any, Optional[Dict[str, Any]]]:+ """Return ``(openai_module, None)`` or ``(None, missing_dependency error)``."""+ try:+ import openai+ except ImportError:+ return None, error_response(+ error=OPENAI_MISSING,+ error_type="missing_dependency",+ provider=provider,+ aspect_ratio=aspect,+ )+ return openai, None+++def materialize_image(+ b64: Optional[str],+ url: Optional[str],+ *,+ prefix: str,+ label: str,+ provider: str,+ model: str,+ prompt: str,+ aspect: str,+ log: logging.Logger = logger,+) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:+ """Turn a ``(b64_json, url)`` result pair into a local image reference.++ Returns ``(image_ref, None)`` or ``(None, error_dict)``. Base64 is always+ cached (a write failure is an ``io_error``); a URL is cached best-effort+ because provider URLs are often ephemeral, falling back to the bare URL so+ a cache hiccup never destroys a successful generation.+ """+ fail = error_factory(provider, aspect, model=model, prompt=prompt)+ if b64:+ try:+ return str(save_b64_image(b64, prefix=prefix)), None+ except Exception as exc: # noqa: BLE001+ return None, fail(f"Could not save image to cache: {exc}", "io_error")+ if url:+ return cache_url_best_effort(url, prefix=prefix, label=label, log=log), None+ return None, fail(f"{label} response contained neither b64_json nor URL", "empty_response")+++def cache_url_best_effort(url: str, *, prefix: str, label: str, log: logging.Logger = logger) -> str:+ """Cache ``url`` locally; on failure warn and return the bare URL."""+ try:+ return str(save_url_image(url, prefix=prefix))+ except Exception as exc: # noqa: BLE001+ log.warning(+ "%s image URL %s could not be cached (%s); falling back to bare URL.", label, url, exc,+ )+ return url+++def requests_error_message(response: Any, exc: Exception) -> str:+ """``error.message`` from an HTTP error body, else the first 300 chars of it."""+ try:+ return response.json().get("error", {}).get("message", response.text[:300])+ except Exception: # noqa: BLE001 - non-JSON / non-dict body+ return response.text[:300] if response is not None else str(exc)+++@dataclass+class HttpFailure:+ """One failed ``post_json`` attempt, pre-shaped as ``(error, error_type)``.++ ``kind`` is ``http`` / ``timeout`` / ``connection`` / ``request`` /+ ``invalid_json``; ``status`` and ``response`` are set for ``http`` only.+ """++ kind: str+ error: str+ error_type: str+ status: int = 0+ message: str = ""+ response: Any = None+++def post_json(+ url: str,+ *,+ headers: Dict[str, str],+ payload: Dict[str, Any],+ timeout: Any,+ label: str,+ error_message: Callable[[Any, Exception], str] = requests_error_message,+ catch_request_exception: bool = False,+) -> Tuple[Optional[Any], Optional[HttpFailure]]:+ """POST ``payload`` and parse the JSON body: ``(body, None)`` or ``(None, failure)``.++ ``timeout`` is passed to ``requests`` verbatim; the timeout message reports+ its read component. ``error_message(response, exc)`` extracts the HTTP error+ text so each backend can keep its own body shape.+ """+ import requests++ read_timeout = timeout[1] if isinstance(timeout, tuple) else timeout+ try:+ response = requests.post(url, headers=headers, json=payload, timeout=timeout)+ response.raise_for_status()+ except requests.HTTPError as exc:+ resp = exc.response+ status = resp.status_code if resp is not None else 0+ message = error_message(resp, exc)+ return None, HttpFailure(+ "http", f"{label} image generation failed ({status}): {message}", "api_error",+ status=status, message=message, response=resp,+ )+ except requests.Timeout:+ return None, HttpFailure(+ "timeout", f"{label} image generation timed out ({int(read_timeout)}s)", "timeout"+ )+ except requests.ConnectionError as exc:+ return None, HttpFailure("connection", f"{label} connection error: {exc}", "connection_error")+ except requests.RequestException as exc:+ if not catch_request_exception:+ raise+ return None, HttpFailure("request", f"{label} request failed: {exc}", "api_error")++ try:+ return response.json(), None+ except Exception as exc: # noqa: BLE001+ return None, HttpFailure(+ "invalid_json", f"{label} returned invalid JSON: {exc}", "invalid_response"+ )diff --git a/plugins/image_gen/deepinfra/__init__.py b/plugins/image_gen/deepinfra/__init__.pyindex 90754b369f7..a2027010dff 100644--- a/plugins/image_gen/deepinfra/__init__.py+++ b/plugins/image_gen/deepinfra/__init__.py@@ -1,28 +1,19 @@"""DeepInfra image generation backend.-Exposes DeepInfra's image-gen catalog (FLUX, Qwen-Image-Edit, …) through-the OpenAI-compatible ``/v1/openai/images/generations`` endpoint as an-:class:`ImageGenProvider` implementation.+Exposes DeepInfra's image-gen catalog (FLUX, Qwen-Image-Edit, …) through the+OpenAI-compatible ``/v1/openai/images/generations`` endpoint.-**Fully dynamic model discovery.** Unlike the other image-gen plugins in-this tree (which ship a hardcoded ``_MODELS`` dict), DeepInfra publishes-a single tagged catalog at+**Fully dynamic model discovery.** DeepInfra publishes one tagged catalog at``https://api.deepinfra.com/v1/openai/models?filter=true&sort_by=hermes``where each entry's ``metadata.tags`` declares its surface (``image-gen``-here). ``list_models()`` filters that catalog via-:func:`hermes_cli.models._fetch_deepinfra_models_by_tag` so newly added-models show up in ``hermes tools`` automatically. No model ids are-hardcoded in this file — if a model is retired upstream, it disappears-from hermes the next time the catalog is fetched, no patch required.--Model selection (first hit wins):--1. ``DEEPINFRA_IMAGE_MODEL`` env var-2. ``image_gen.deepinfra.model`` in ``config.yaml``-3. First model from the live catalog--When all three are absent (catalog unreachable, nothing configured),-``generate()`` returns an :func:`error_response` rather than guessing.+here). ``list_models()`` filters it via+:func:`hermes_cli.models._fetch_deepinfra_models_by_tag`, so no model ids are+hardcoded here: new models appear in ``hermes tools`` automatically and+retired ones disappear on the next fetch.++Model selection (first hit wins): ``DEEPINFRA_IMAGE_MODEL`` env →+``image_gen.deepinfra.model`` → first model from the live catalog. When all+three are absent ``generate()`` returns an error rather than guessing."""from __future__ import annotations@@ -35,40 +26,23 @@ from agent.secret_scope import get_secretfrom agent.image_gen_provider import (DEFAULT_ASPECT_RATIO,ImageGenProvider,- error_response,resolve_aspect_ratio,save_b64_image,save_url_image,success_response,)+from plugins.image_gen._common import (+ api_key_setup_schema,+ error_factory,+ import_openai,+ load_image_gen_config,+ prompt_required_error,+ size_for,+)logger = logging.getLogger(__name__)-# DeepInfra accepts standard OpenAI ``size`` strings. Mirrors the-# OpenAI plugin's mapping so aspect_ratio semantics stay consistent-# across the agent's image_generate tool surface.-_SIZES = {- "landscape": "1536x1024",- "square": "1024x1024",- "portrait": "1024x1536",-}---def _load_deepinfra_image_config() -> Dict[str, Any]:- """Read ``image_gen.deepinfra`` from config.yaml."""- try:- from hermes_cli.config import load_config-- cfg = load_config()- section = cfg.get("image_gen") if isinstance(cfg, dict) else None- di_section = section.get("deepinfra") if isinstance(section, dict) else None- return di_section if isinstance(di_section, dict) else {}- except Exception as exc:- logger.debug("Could not load image_gen.deepinfra config: %s", exc)- return {}--def _live_models() -> Optional[List[Dict[str, Any]]]:"""Fetch ``image-gen``-tagged models from the DeepInfra catalog."""try:@@ -83,24 +57,22 @@ def _format_catalog_row(item: Dict[str, Any]) -> Dict[str, Any]:"""Format a catalog item into the picker row shape."""mid = item.get("id", "")metadata = item.get("metadata") or {}- pricing = metadata.get("pricing") if isinstance(metadata, dict) else None- price = ""- if isinstance(pricing, dict) and pricing.get("per_image_unit") is not None:- try:- price = f"${float(pricing['per_image_unit']):.4f}/image"- except (TypeError, ValueError):- price = ""+ if not isinstance(metadata, dict):+ metadata = {}row: Dict[str, Any] = {"id": mid,"display": mid.split("/", 1)[-1] if "/" in mid else mid,- "strengths": metadata.get("description", "") if isinstance(metadata, dict) else "",+ "strengths": metadata.get("description", ""),}- if price:- row["price"] = price- if isinstance(metadata, dict):- for key in ("default_width", "default_height", "default_iterations"):- if metadata.get(key) is not None:- row[key] = metadata[key]+ pricing = metadata.get("pricing")+ if isinstance(pricing, dict) and pricing.get("per_image_unit") is not None:+ try:+ row["price"] = f"${float(pricing['per_image_unit']):.4f}/image"+ except (TypeError, ValueError):+ pass+ for key in ("default_width", "default_height", "default_iterations"):+ if metadata.get(key) is not None:+ row[key] = metadata[key]return row@@ -124,11 +96,7 @@ def _resolve_model(catalog: List[Dict[str, Any]], cfg: Dict[str, Any]) -> Optionclass DeepInfraImageGenProvider(ImageGenProvider):- """DeepInfra ``images.generations`` backend.-- Catalog is discovered live from the DeepInfra ``/models`` endpoint- filtered by the ``image-gen`` surface tag.- """+ """DeepInfra ``images.generations`` backend; catalog discovered live by the ``image-gen`` tag."""@propertydef name(self) -> str:@@ -142,34 +110,22 @@ class DeepInfraImageGenProvider(ImageGenProvider):return bool((get_secret("DEEPINFRA_API_KEY", "") or "").strip())def list_models(self) -> List[Dict[str, Any]]:- live = _live_models()- if not live:- return []- return [_format_catalog_row(item) for item in live]+ return [_format_catalog_row(item) for item in _live_models() or []]def default_model(self) -> Optional[str]:rows = self.list_models()- if rows:- return rows[0].get("id")- return None+ return rows[0].get("id") if rows else Nonedef capabilities(self) -> Dict[str, Any]:"""DeepInfra's OpenAI-compatible generation surface is text-only."""return {"modalities": ["text"], "max_reference_images": 0}def get_setup_schema(self) -> Dict[str, Any]:- return {- "name": "DeepInfra",- "badge": "paid",- "tag": "FLUX, Qwen-Image, … — live catalog from api.deepinfra.com",- "env_vars": [- {- "key": "DEEPINFRA_API_KEY",- "prompt": "DeepInfra API key",- "url": "https://deepinfra.com/dash/api_keys",- },- ],- }+ return api_key_setup_schema(+ "DeepInfra", "paid", "FLUX, Qwen-Image, … — live catalog from api.deepinfra.com",+ key="DEEPINFRA_API_KEY", prompt="DeepInfra API key",+ url="https://deepinfra.com/dash/api_keys",+ )def generate(self,@@ -179,91 +135,53 @@ class DeepInfraImageGenProvider(ImageGenProvider):) -> Dict[str, Any]:prompt = (prompt or "").strip()aspect = resolve_aspect_ratio(aspect_ratio)+ fail = error_factory("deepinfra", aspect)if kwargs.get("image_url") or kwargs.get("reference_image_urls"):- return error_response(- error=(- "DeepInfra image generation is text-to-image only in this "- "backend; image_url and reference_image_urls are unsupported."- ),- error_type="modality_unsupported",- provider="deepinfra",- prompt=prompt,- aspect_ratio=aspect,+ return fail(+ "DeepInfra image generation is text-to-image only in this "+ "backend; image_url and reference_image_urls are unsupported.",+ "modality_unsupported", prompt=prompt,)if not prompt:- return error_response(- error="Prompt is required and must be a non-empty string",- error_type="invalid_argument",- provider="deepinfra",- aspect_ratio=aspect,- )+ return prompt_required_error("deepinfra", aspect)api_key = (get_secret("DEEPINFRA_API_KEY", "") or "").strip()if not api_key:- return error_response(- error=(- "DEEPINFRA_API_KEY not set. Run `hermes tools` → Image "- "Generation → DeepInfra to configure, or `hermes setup` "- "to add the key."- ),- error_type="auth_required",- provider="deepinfra",- aspect_ratio=aspect,+ return fail(+ "DEEPINFRA_API_KEY not set. Run `hermes tools` → Image "+ "Generation → DeepInfra to configure, or `hermes setup` "+ "to add the key.",+ "auth_required",)- di_cfg = _load_deepinfra_image_config()- catalog = _live_models() or []- model_id = _resolve_model(catalog, di_cfg)+ di_cfg = load_image_gen_config("deepinfra")+ model_id = _resolve_model(_live_models() or [], di_cfg)if not model_id:- return error_response(- error=(- "No DeepInfra image-gen model available. Pin one in "- "config.yaml under image_gen.deepinfra.model, set "- "DEEPINFRA_IMAGE_MODEL, or check connectivity to "- "api.deepinfra.com so the live catalog can be fetched."- ),- error_type="no_model_available",- provider="deepinfra",- prompt=prompt,- aspect_ratio=aspect,+ return fail(+ "No DeepInfra image-gen model available. Pin one in "+ "config.yaml under image_gen.deepinfra.model, set "+ "DEEPINFRA_IMAGE_MODEL, or check connectivity to "+ "api.deepinfra.com so the live catalog can be fetched.",+ "no_model_available", prompt=prompt,)- size = _SIZES.get(aspect, _SIZES["square"])+ size = size_for(aspect)from hermes_cli.models import deepinfra_base_url- base_url = deepinfra_base_url(di_cfg)- # DeepInfra's /images/generations is OpenAI-compatible — use the- # openai SDK so we inherit its retry, timeout, and error mapping- # (mirrors the existing OpenAI image-gen plugin).- try:- import openai- except ImportError:- return error_response(- error="openai Python package not installed (pip install openai)",- error_type="missing_dependency",- provider="deepinfra",- aspect_ratio=aspect,- )+ # OpenAI-compatible endpoint — the openai SDK supplies retry, timeout+ # and error mapping (mirrors the OpenAI image-gen plugin).+ openai, err = import_openai("deepinfra", aspect)+ if err:+ return err- client = openai.OpenAI(api_key=api_key, base_url=base_url)+ fail = error_factory("deepinfra", aspect, model=model_id, prompt=prompt)+ client = openai.OpenAI(api_key=api_key, base_url=deepinfra_base_url(di_cfg))try:- response = client.images.generate(- model=model_id,- prompt=prompt,- size=size,- n=1,- )+ response = client.images.generate(model=model_id, prompt=prompt, size=size, n=1)except Exception as exc:logger.debug("DeepInfra image generation failed", exc_info=True)- return error_response(- error=f"DeepInfra image generation failed: {exc}",- error_type="api_error",- provider="deepinfra",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"DeepInfra image generation failed: {exc}", "api_error")finally:close = getattr(client, "close", None)if callable(close):@@ -271,55 +189,31 @@ class DeepInfraImageGenProvider(ImageGenProvider):data = getattr(response, "data", None) or []if not data:- return error_response(- error="DeepInfra returned no image data",- error_type="empty_response",- provider="deepinfra",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("DeepInfra returned no image data", "empty_response")first = data[0]b64 = getattr(first, "b64_json", None)url = getattr(first, "url", None)-# Drop the ``vendor/`` prefix and any colons so the saved filename# stays a single path component on every OS.- short = model_id.split("/", 1)[-1].replace(":", "_")+ prefix = f"deepinfra_{model_id.split('/', 1)[-1].replace(':', '_')}"if b64:try:- saved_path = save_b64_image(b64, prefix=f"deepinfra_{short}")+ image_ref = str(save_b64_image(b64, prefix=prefix))except Exception as exc:- return error_response(- error=f"Could not save image to cache: {exc}",- error_type="io_error",- provider="deepinfra",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- image_ref = str(saved_path)+ return fail(f"Could not save image to cache: {exc}", "io_error")elif url:- # Materialise the (often short-lived) delivery URL locally so a- # downstream consumer (Telegram send_photo, browser fetch) doesn't- # get a dead link — mirrors the openai/xai/krea image plugins.+ # Delivery URLs are often short-lived; materialise locally so downstream+ # consumers (Telegram send_photo, browser fetch) don't get a dead link.# Best-effort: fall back to the bare URL if the download fails.try:- image_ref = str(save_url_image(url, prefix=f"deepinfra_{short}"))+ image_ref = str(save_url_image(url, prefix=prefix))except Exception as exc:logger.debug("DeepInfra: caching delivery URL failed (%s); returning URL", exc)image_ref = urlelse:- return error_response(- error="DeepInfra response contained neither b64_json nor URL",- error_type="empty_response",- provider="deepinfra",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("DeepInfra response contained neither b64_json nor URL", "empty_response")return success_response(image=image_ref,diff --git a/plugins/image_gen/fal/__init__.py b/plugins/image_gen/fal/__init__.pyindex 6acd54c1905..611a20bcb4a 100644--- a/plugins/image_gen/fal/__init__.py+++ b/plugins/image_gen/fal/__init__.py@@ -1,31 +1,20 @@"""FAL.ai image generation backend.-Wraps the 18-model FAL catalog (FLUX 2, Z-Image, Nano Banana, GPT-Image 1.5, Recraft, Imagen 4, Qwen, Ideogram, …) as an-:class:`ImageGenProvider` implementation.--The heavy lifting — model catalog, payload construction, request-submission, managed-Nous-gateway selection, Clarity Upscaler chaining-— lives in :mod:`tools.image_generation_tool`. This plugin reaches into-that module via call-time indirection (``import tools.image_generation_tool as _it``)-so:--* the existing test suite (``tests/tools/test_image_generation.py``,- ``tests/tools/test_managed_media_gateways.py``) keeps patching- ``image_tool._submit_fal_request`` / ``image_tool.fal_client`` /- ``image_tool._managed_fal_client`` without modification, and-* there's exactly one canonical FAL code path on disk — the plugin is a- registration adapter, not a parallel implementation.--See issue #26241 for the migration plan and the-``plugin-extraction-test-patch-compatibility.md`` rules this follows.+Wraps the FAL catalog (FLUX 2, Z-Image, Nano Banana, GPT Image 1.5, Recraft,+Imagen 4, Qwen, Ideogram, …) as an :class:`ImageGenProvider`.++The heavy lifting — model catalog, payload construction, request submission,+managed-Nous-gateway selection, Clarity Upscaler chaining — lives in+:mod:`tools.image_generation_tool`. This plugin reaches into that module via+call-time indirection (``import tools.image_generation_tool as _it``) so the+existing tests keep patching ``image_tool.*`` unchanged, and there is exactly+one canonical FAL code path on disk — the plugin is a registration adapter."""from __future__ import annotationsimport jsonimport logging-import osfrom typing import Any, Dict, List, Optionalfrom agent.image_gen_provider import (@@ -33,19 +22,17 @@ from agent.image_gen_provider import (ImageGenProvider,resolve_aspect_ratio,)+from plugins.image_gen._common import api_key_setup_schema, catalog_rowslogger = logging.getLogger(__name__)+_PASSTHROUGH_KWARGS = (+ "num_inference_steps", "guidance_scale", "num_images", "output_format", "seed", "upscale",+)-class FalImageGenProvider(ImageGenProvider):- """FAL.ai image generation backend.- Delegates to ``tools.image_generation_tool.image_generate_tool`` so- the in-tree FAL implementation (model catalog, payload builder,- managed-gateway selection, Clarity Upscaler chaining) is the single- source of truth. Everything is resolved at call time via the- ``_it`` indirection so tests can monkey-patch the legacy module.- """+class FalImageGenProvider(ImageGenProvider):+ """FAL.ai backend delegating to ``tools.image_generation_tool`` at call time."""@propertydef name(self) -> str:@@ -56,70 +43,46 @@ class FalImageGenProvider(ImageGenProvider):return "FAL.ai"def is_available(self) -> bool:- # Available when direct FAL_KEY is set OR the managed Nous- # gateway resolves a fal-queue origin. Both checks come from the- # legacy module so this provider tracks whatever logic ships- # there.+ # Direct FAL_KEY or a managed Nous fal-queue origin; both checks live in+ # the legacy module so this provider tracks whatever logic ships there.import tools.image_generation_tool as _ittry:return bool(_it.check_fal_api_key())- except Exception: # noqa: BLE001 — defensive; never break the picker+ except Exception: # noqa: BLE001 — never break the pickerreturn Falsedef list_models(self) -> List[Dict[str, Any]]:import tools.image_generation_tool as _it- return [- {- "id": model_id,- "display": meta.get("display", model_id),- "speed": meta.get("speed", ""),- "strengths": meta.get("strengths", ""),- "price": meta.get("price", ""),- }- for model_id, meta in _it.FAL_MODELS.items()- ]+ return catalog_rows(_it.FAL_MODELS)def default_model(self) -> Optional[str]:import tools.image_generation_tool as _itreturn _it.DEFAULT_MODELdef get_setup_schema(self) -> Dict[str, Any]:- return {- "name": "FAL.ai",- "badge": "paid",- "tag": "Pick from flux-2-klein, flux-2-pro, gpt-image, nano-banana-2, nano-banana-pro, etc. — text-to-image & image editing",- "env_vars": [- {- "key": "FAL_KEY",- "prompt": "FAL API key",- "url": "https://fal.ai/dashboard/keys",- },- ],- }+ return api_key_setup_schema(+ "FAL.ai", "paid",+ "Pick from flux-2-klein, flux-2-pro, gpt-image, nano-banana-2, nano-banana-pro, etc. — text-to-image & image editing",+ key="FAL_KEY", prompt="FAL API key", url="https://fal.ai/dashboard/keys",+ )def capabilities(self) -> Dict[str, Any]:- # Whether image-to-image is available depends on the currently-- # selected FAL model (each model entry declares an edit_endpoint or- # not). Report the active model's actual surface so the dynamic tool- # schema is accurate.+ # Image-to-image depends on the currently selected FAL model (each entry+ # declares an edit_endpoint or not); Clarity Upscaler chains on request+ # for any model.import tools.image_generation_tool as _ittry:_model_id, meta = _it._resolve_fal_model()except Exception: # noqa: BLE001return {"modalities": ["text"], "max_reference_images": 0}- # Clarity Upscaler chains on explicit request for any FAL model.if meta.get("edit_endpoint"):return {"modalities": ["text", "image"],"max_reference_images": int(meta.get("max_reference_images") or 1),"supports_upscale": True,}- return {- "modalities": ["text"],- "max_reference_images": 0,- "supports_upscale": True,- }+ return {"modalities": ["text"], "max_reference_images": 0, "supports_upscale": True}def generate(self,@@ -130,43 +93,24 @@ class FalImageGenProvider(ImageGenProvider):reference_image_urls: Optional[List[str]] = None,**kwargs: Any,) -> Dict[str, Any]:- """Generate or edit an image via the legacy FAL pipeline.-- Forwards prompt + aspect_ratio + image_url/reference_image_urls (and- any forward-compat extras the schema supports) into- :func:`tools.image_generation_tool.image_generate_tool`, then reshapes- its JSON-string response into the provider-ABC dict format consumed by- ``_dispatch_to_plugin_provider``.- """+ """Forward to :func:`tools.image_generation_tool.image_generate_tool` and+ reshape its JSON-string response into the provider-ABC dict."""import tools.image_generation_tool as _itaspect = resolve_aspect_ratio(aspect_ratio)passthrough = {- key: kwargs[key]- for key in (- "num_inference_steps",- "guidance_scale",- "num_images",- "output_format",- "seed",- "upscale",- )+ key: kwargs[key] for key in _PASSTHROUGH_KWARGSif key in kwargs and kwargs[key] is not None}- # Only forward the image-to-image inputs when actually supplied, so a- # plain text-to-image call delegates exactly as it did before (no- # noisy None kwargs).+ # Only forward image-to-image inputs when supplied, so a plain+ # text-to-image call delegates exactly as before (no noisy None kwargs).if image_url is not None:passthrough["image_url"] = image_urlif reference_image_urls is not None:passthrough["reference_image_urls"] = reference_image_urlstry:- raw = _it.image_generate_tool(- prompt=prompt,- aspect_ratio=aspect,- **passthrough,- )+ raw = _it.image_generate_tool(prompt=prompt, aspect_ratio=aspect, **passthrough)except Exception as exc: # noqa: BLE001 — never raise out of generatelogger.warning("FAL image_generate_tool raised: %s", exc, exc_info=True)return {@@ -192,27 +136,19 @@ class FalImageGenProvider(ImageGenProvider):"error_type": "provider_contract",}- # Stamp provider/prompt/aspect_ratio so downstream consumers see- # the uniform shape declared in ``agent.image_gen_provider``.+ # Stamp the uniform shape declared in ``agent.image_gen_provider``; the+ # legacy pipeline resolves the model internally, so query it after the fact.response.setdefault("provider", "fal")response.setdefault("prompt", prompt)response.setdefault("aspect_ratio", aspect)- # Annotate model best-effort — the legacy pipeline resolves it- # internally, so query it after the fact for the response shape.if "model" not in response:try:- model_id, _meta = _it._resolve_fal_model()- response["model"] = model_id+ response["model"] = _it._resolve_fal_model()[0]except Exception: # noqa: BLE001passreturn response-# ----------------------------------------------------------------------------# Plugin entry point-# -----------------------------------------------------------------------------def register(ctx) -> None:"""Plugin entry point — wire ``FalImageGenProvider`` into the registry."""ctx.register_image_gen_provider(FalImageGenProvider())diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.pyindex bbaded47b05..7a36a30e12b 100644--- a/plugins/image_gen/krea/__init__.py+++ b/plugins/image_gen/krea/__init__.py@@ -1,20 +1,16 @@"""Krea image generation backend.-Exposes Krea's `Krea 2` foundation image model family — Krea 2 Medium and-Krea 2 Large — as an :class:`ImageGenProvider` implementation.+Exposes Krea's ``Krea 2`` foundation image model family (Medium, Large,+Medium Turbo) as an :class:`ImageGenProvider`.-Krea's API is asynchronous: the generate endpoint returns a ``job_id``-that you poll at ``GET /jobs/{job_id}``. This provider hides that-roundtrip behind the synchronous ``generate()`` contract: submit, poll-every 2s with light backoff, materialise the result URL to local cache,-return the success/error dict like every other backend.+Krea's API is asynchronous: the generate endpoint returns a ``job_id`` polled+at ``GET /jobs/{job_id}``. This provider hides that roundtrip behind the+synchronous ``generate()`` contract: submit, poll every 2s with light backoff,+materialise the result URL to local cache, return the usual dict.-Selection precedence (first hit wins):--1. ``KREA_IMAGE_MODEL`` env var (escape hatch for scripts / tests)-2. ``image_gen.krea.model`` in ``config.yaml``-3. ``image_gen.model`` in ``config.yaml`` (when it's one of our IDs)-4. :data:`DEFAULT_MODEL` — ``krea-2-medium`` (Krea's "start here" recommendation)+Selection precedence (first hit wins): ``model`` kwarg → ``KREA_IMAGE_MODEL``+env → ``image_gen.krea.model`` → ``image_gen.model`` (when it's one of our+IDs) → :data:`DEFAULT_MODEL` (``krea-2-medium``, Krea's "start here" pick).Docs: https://docs.krea.ai/developers/krea-2/overviewAPI: https://docs.krea.ai/api-reference/krea/krea-2-large@@ -23,7 +19,6 @@ API: https://docs.krea.ai/api-reference/krea/krea-2-largefrom __future__ import annotationsimport logging-import osimport timeimport uuidfrom typing import Any, Dict, List, Optional, Tuple@@ -34,22 +29,27 @@ from agent.secret_scope import get_secretfrom agent.image_gen_provider import (DEFAULT_ASPECT_RATIO,ImageGenProvider,- error_response,- normalize_reference_images,resolve_aspect_ratio,save_url_image,success_response,)+from plugins.image_gen._common import (+ api_key_setup_schema,+ catalog_rows,+ collect_source_images,+ error_factory,+ load_image_gen_config,+ prompt_required_error,+ resolve_static_model,+)logger = logging.getLogger(__name__)-# ----------------------------------------------------------------------------# Constants-# ----------------------------------------------------------------------------BASE_URL = "https://api.krea.ai"-# Map our short model IDs to Krea's URL path segment.+# ``path`` is Krea's URL segment. ``upscale`` (the Enhance pass) is opt-in for+# every tier: default-on enhance passes degraded output quality, and Large is+# 2K native anyway._MODELS: Dict[str, Dict[str, Any]] = {"krea-2-medium": {"display": "Krea 2 Medium",@@ -57,8 +57,6 @@ _MODELS: Dict[str, Dict[str, Any]] = {"strengths": "Illustration, anime, painting, expressive styles. Faster + cheaper.","price": "$0.030 (text) / $0.035 (style refs) / $0.040 (moodboards)","path": "medium",- # Upscaling is opt-in everywhere (Aug 2026 policy: default-on- # enhance passes degraded output quality)."upscale": False,},"krea-2-large": {@@ -67,7 +65,6 @@ _MODELS: Dict[str, Dict[str, Any]] = {"strengths": "Photorealism, raw textured looks (motion blur, grain), expressive styles.","price": "$0.060 (text) / $0.065 (style refs) / $0.070 (moodboards)","path": "large",- # 2K native — high-res enough out of the box."upscale": False,},"krea-2-medium-turbo": {@@ -76,121 +73,78 @@ _MODELS: Dict[str, Dict[str, Any]] = {"strengths": "Fastest Krea 2 — medium quality at lower latency / cost.","price": "$0.015 (text) / $0.0175 (style refs)","path": "medium-turbo",- # Opt-in only (Aug 2026 policy)."upscale": False,},}DEFAULT_MODEL = "krea-2-medium"-# Hermes uses 3 abstract aspect ratios. Map to Krea's enum (which is wider).-# Krea accepts: 1:1, 4:3, 3:2, 16:9, 2.35:1, 4:5, 2:3, 9:16-_ASPECT_MAP = {- "landscape": "16:9",- "square": "1:1",- "portrait": "9:16",-}+# Hermes' 3 abstract ratios → Krea's enum (1:1, 4:3, 3:2, 16:9, 2.35:1, 4:5, 2:3, 9:16).+_ASPECT_MAP = {"landscape": "16:9", "square": "1:1", "portrait": "9:16"}# Only resolution Krea currently supports.DEFAULT_RESOLUTION = "1K"-# Krea's image_style_references entries are objects ({"url", "strength"}), not-# bare URL strings. When the caller supplies a URL without an explicit strength-# we apply Krea's recommended starting value. Range per Krea docs is -2..2.+# image_style_references entries are objects ({"url", "strength"}), not bare+# strings; a URL without explicit strength gets Krea's recommended start (range -2..2)._DEFAULT_STYLE_REFERENCE_STRENGTH = 0.6+_MAX_STYLE_REFERENCES = 10-# Valid creativity levels per Krea docs. Default is "medium"._VALID_CREATIVITY = {"raw", "low", "medium", "high"}-# Polling cadence. Krea recommends 2-5s; we start at 2s and back off to 5s-# for long jobs (Large can take ~1min). Total ceiling matches Krea's-# hosted-tool timeout of 3 minutes.+# Polling: Krea recommends 2-5s; start at 2s, back off to 5s for long jobs+# (Large can take ~1min). Ceiling matches Krea's hosted-tool timeout of 3 min._POLL_INITIAL_INTERVAL = 2.0_POLL_MAX_INTERVAL = 5.0_POLL_BACKOFF = 1.3_POLL_TIMEOUT_SECONDS = 180.0-# HTTP statuses worth retrying during the poll loop. Everything else (401,-# 402, 403, 404, other 4xx) is a permanent failure — surface it immediately-# instead of burning the 180s deadline retrying a request that will never-# succeed.+# Statuses worth retrying while polling. Everything else (401/402/403/404,+# other 4xx) is permanent — surface it immediately instead of burning the+# 180s deadline on a request that will never succeed._RETRYABLE_POLL_STATUSES = frozenset({408, 409, 425, 429, 500, 502, 503, 504})_TERMINAL_STATES = {"completed", "failed", "cancelled"}-# Krea Enhance — the upscale/enhancer endpoint used for the optional-# ``upscale`` pass after generation ("1.5K native, 4K via Enhancer" is-# Krea's own pipeline shape). Cheap creative enhancer, max 8K.+# Krea Enhance — the optional ``upscale`` pass after generation ("1.5K native,+# 4K via Enhancer" is Krea's own pipeline shape). Cheap creative enhancer, max 8K._ENHANCE_PATH = "/generate/enhance/krea/enhance"_ENHANCE_SCALE_FACTOR = 2--# ----------------------------------------------------------------------------# Config-# ---------------------------------------------------------------------------+_USER_AGENT = "Hermes-Agent/1.0 (krea-image-gen)"def _load_krea_config() -> Dict[str, Any]:- """Read ``image_gen.krea`` (with fallthrough to ``image_gen``) from config.yaml."""- try:- from hermes_cli.config import load_config+ """Read ``image_gen`` (the krea section lives under ``image_gen.krea``)."""+ return load_image_gen_config()- cfg = load_config()- section = cfg.get("image_gen") if isinstance(cfg, dict) else None- return section if isinstance(section, dict) else {}- except Exception as exc: # noqa: BLE001- logger.debug("Could not load image_gen config: %s", exc)- return {}+def _krea_section() -> Dict[str, Any]:+ section = _load_krea_config().get("krea")+ return section if isinstance(section, dict) else {}-def _resolve_model(explicit: Optional[str] = None) -> Tuple[str, Dict[str, Any]]:- """Decide which model to use and return ``(model_id, meta)``.- Precedence: explicit caller override (e.g. managed-mode routing or a direct- ``model`` kwarg) → ``KREA_IMAGE_MODEL`` env → ``image_gen.krea.model`` →- ``image_gen.model`` → :data:`DEFAULT_MODEL`.- """- if isinstance(explicit, str) and explicit.strip() in _MODELS:- return explicit.strip(), _MODELS[explicit.strip()]-- env_override = os.environ.get("KREA_IMAGE_MODEL")- if env_override and env_override in _MODELS:- return env_override, _MODELS[env_override]-- cfg = _load_krea_config()- krea_cfg = cfg.get("krea") if isinstance(cfg.get("krea"), dict) else {}- candidate: Optional[str] = None- if isinstance(krea_cfg, dict):- value = krea_cfg.get("model")- if isinstance(value, str) and value in _MODELS:- candidate = value- if candidate is None:- top = cfg.get("model")- if isinstance(top, str) and top in _MODELS:- candidate = top-- if candidate is not None:- return candidate, _MODELS[candidate]-- return DEFAULT_MODEL, _MODELS[DEFAULT_MODEL]+def _resolve_model(explicit: Optional[str] = None) -> Tuple[str, Dict[str, Any]]:+ """``(model_id, meta)``: explicit → ``KREA_IMAGE_MODEL`` → ``image_gen.krea.model``+ → ``image_gen.model`` → :data:`DEFAULT_MODEL`."""+ return resolve_static_model(+ _MODELS, DEFAULT_MODEL, env_var="KREA_IMAGE_MODEL", config_key="krea",+ explicit=explicit, config=_load_krea_config(),+ )def _resolve_managed_krea_gateway():- """Return managed Krea gateway config when the user is on the managed path.-- Strict selection model: the managed Krea gateway is used when the stored- ``image_gen`` selection is ``nous`` (or legacy ``use_gateway: true``), or- on a never-configured install when no direct ``KREA_API_KEY`` exists.- An explicit vendor selection (``krea``, ``fal``, ...) pins the direct- path. Returns ``None`` (direct/BYO path) otherwise, and never raises —- plugin discovery and availability scans must stay robust.+ """Managed Krea gateway config when the user is on the managed path, else ``None``.++ Strict selection: managed when the stored ``image_gen`` selection is+ ``nous`` (or legacy ``use_gateway: true``), or on a never-configured install+ with no direct ``KREA_API_KEY``. An explicit vendor selection (``krea``,+ ``fal``, ...) pins the direct path. Never raises — plugin discovery and+ availability scans must stay robust."""try:from tools.managed_tool_gateway import resolve_managed_tool_gateway- from tools.tool_backend_helpers import (- NOUS_MANAGED_PROVIDER,- read_selection,- )+ from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER, read_selectionexcept Exception as exc: # noqa: BLE001logger.debug("Managed Krea gateway resolution unavailable: %s", exc)return None@@ -200,7 +154,6 @@ def _resolve_managed_krea_gateway():except Exception: # noqa: BLE001selected = Noneif selected is not None and selected != NOUS_MANAGED_PROVIDER:- # Explicit vendor selection: direct credentials only.return Noneif selected is None and get_secret("KREA_API_KEY"):return None@@ -216,91 +169,140 @@ def _managed_krea_gateway_ready() -> bool:"""Cheap, offline-friendly probe for managed Krea availability."""try:from tools.managed_tool_gateway import is_managed_tool_gateway_ready- except Exception: # noqa: BLE001- return False- try:+return bool(is_managed_tool_gateway_ready("krea"))except Exception: # noqa: BLE001return Falsedef _resolve_creativity(value: Optional[str]) -> str:- """Coerce ``creativity`` kwarg to a valid Krea value (default ``medium``)."""- if isinstance(value, str):- v = value.strip().lower()- if v in _VALID_CREATIVITY:- return v- cfg = _load_krea_config()- krea_cfg = cfg.get("krea") if isinstance(cfg.get("krea"), dict) else {}- cfg_value = krea_cfg.get("creativity") if isinstance(krea_cfg, dict) else None- if isinstance(cfg_value, str) and cfg_value.strip().lower() in _VALID_CREATIVITY:- return cfg_value.strip().lower()+ """Coerce ``creativity`` kwarg (then config) to a valid Krea value; default ``medium``."""+ for candidate in (value, _krea_section().get("creativity")):+ if isinstance(candidate, str) and candidate.strip().lower() in _VALID_CREATIVITY:+ return candidate.strip().lower()return "medium"+def _headers(auth_token: str, *, managed: bool, json_body: bool) -> Dict[str, str]:+ headers = {"Authorization": f"Bearer {auth_token}", "User-Agent": _USER_AGENT}+ if json_body:+ headers["Content-Type"] = "application/json"+ if managed:+ # The gateway derives the per-generation billing idempotency boundary+ # from this header (else a body fingerprint); a fresh key per submit+ # keeps each generation a distinct billable execution.+ headers["x-idempotency-key"] = str(uuid.uuid4())+ return headers+++def _submit_error_message(resp: Any, exc: Exception) -> str:+ try:+ body = resp.json() if resp is not None else {}+ return (+ body.get("error", {}).get("message")+ if isinstance(body.get("error"), dict)+ else body.get("message") or body.get("detail")+ ) or (resp.text[:300] if resp is not None else str(exc))+ except Exception: # noqa: BLE001+ return resp.text[:300] if resp is not None else str(exc)+++def _is_terminal(job: Any) -> bool:+ """``completed_at`` is a backstop terminal marker even when ``status`` is an+ unfamiliar enum (Krea adds pending states — backlogged/scheduled/sampling — over time)."""+ return isinstance(job, dict) and (+ job.get("status") in _TERMINAL_STATES or bool(job.get("completed_at"))+ )++def _poll_krea_job(base_url: str,auth_token: str,job_id: str,*,timeout_seconds: float = _POLL_TIMEOUT_SECONDS,-) -> Optional[Dict[str, Any]]:- """Poll ``/jobs/{job_id}`` until terminal; return the job dict or None.-- Best-effort variant of the main generate() poll loop used for secondary- jobs (the Enhance upscale pass): any failure returns ``None`` so the- caller can fall back instead of failing the whole generation.+ on_error: Optional[Any] = None,+) -> Any:+ """Poll ``/jobs/{job_id}`` until terminal.++ Returns the terminal job dict, or ``None`` when the poll gave up. With+ ``on_error(kind, detail)`` supplied (the main generation path), a fatal+ poll failure returns whatever that callback returns instead of ``None``;+ without it (the best-effort Enhance pass) failures only log.+ ``kind`` ∈ ``http`` (detail = status) / ``timeout`` / ``invalid_json`` /+ ``deadline`` (detail = last status seen)."""job_url = f"{base_url}/jobs/{job_id}"- headers = {- "Authorization": f"Bearer {auth_token}",- "User-Agent": "Hermes-Agent/1.0 (krea-image-gen)",- }+ headers = _headers(auth_token, managed=False, json_body=False)interval = _POLL_INITIAL_INTERVALdeadline = time.monotonic() + timeout_seconds+ last_status: Optional[str] = None+ enhance = on_error is None++ def give_up(kind: str, detail: Any, warning: str, *warn_args: Any) -> Any:+ if on_error is None:+ logger.warning(warning, *warn_args)+ return None+ return on_error(kind, detail)+while True:time.sleep(interval)interval = min(interval * _POLL_BACKOFF, _POLL_MAX_INTERVAL)try:resp = requests.get(job_url, headers=headers, timeout=30)resp.raise_for_status()- job = resp.json()except requests.HTTPError as exc:status = exc.response.status_code if exc.response is not None else 0+ if not enhance:+ logger.error("Krea poll failed (%d) for job %s", status, job_id)+ # Fail fast on permanent statuses; retry transient ones.if status not in _RETRYABLE_POLL_STATUSES or time.monotonic() >= deadline:- logger.warning("Krea enhance poll failed (%d) for job %s", status, job_id)- return None+ return give_up("http", status, "Krea enhance poll failed (%d) for job %s", status, job_id)+ continue+ except (requests.Timeout, requests.ConnectionError) as exc:+ if not enhance:+ logger.warning("Krea poll transient error for job %s: %s", job_id, exc)+ if time.monotonic() >= deadline:+ return give_up("timeout", exc, "Krea enhance poll gave up for job %s: %s", job_id, exc)continue- except Exception as exc: # noqa: BLE001 — timeout/connection/JSON+ except Exception as exc: # noqa: BLE001 — enhance-only: any other failure is best-effort+ if not enhance:+ raiseif time.monotonic() >= deadline:logger.warning("Krea enhance poll gave up for job %s: %s", job_id, exc)return Nonecontinue- if isinstance(job, dict):- status_str = job.get("status")- if status_str in _TERMINAL_STATES or job.get("completed_at"):- return job+ try:+ job = resp.json()+ except Exception as exc: # noqa: BLE001+ if not enhance:+ logger.warning("Krea poll returned invalid JSON for job %s: %s", job_id, exc)+ if time.monotonic() >= deadline:+ return give_up("invalid_json", exc, "Krea enhance poll gave up for job %s: %s", job_id, exc)+ continue++ if isinstance(job, dict) and isinstance(job.get("status"), str):+ last_status = job["status"]+ if _is_terminal(job):+ return jobif time.monotonic() >= deadline:- logger.warning("Krea enhance job %s did not finish in %ds", job_id, int(timeout_seconds))- return None+ return give_up(+ "deadline", last_status,+ "Krea enhance job %s did not finish in %ds", job_id, int(timeout_seconds),+ )def _extract_result_url(job: Optional[Dict[str, Any]]) -> Optional[str]:- """Pull the first result URL out of a terminal Krea job dict."""- if not isinstance(job, dict):- return None- result = job.get("result")+ """First result URL from a terminal Krea job: ``result.urls[]`` per Krea's+ job-lifecycle docs, falling back to a single ``result.url``."""+ result = job.get("result") if isinstance(job, dict) else Noneif not isinstance(result, dict):return Noneurls = result.get("urls")- if isinstance(urls, list):- for candidate in urls:- if isinstance(candidate, str) and candidate.strip():- return candidate.strip()- single = result.get("url")- if isinstance(single, str) and single.strip():- return single.strip()+ for candidate in [*(urls if isinstance(urls, list) else []), result.get("url")]:+ if isinstance(candidate, str) and candidate.strip():+ return candidate.strip()return None@@ -315,27 +317,21 @@ def _enhance_image("""Run Krea Enhance on ``image_url``; return the enhanced URL or None.Best-effort: any submit/poll/result failure logs and returns ``None`` so- the caller falls back to the original (un-upscaled) image — an upscale- failure must never destroy an already-successful generation.+ the caller falls back to the original image — an upscale failure must+ never destroy an already-successful generation."""- headers = {- "Authorization": f"Bearer {auth_token}",- "Content-Type": "application/json",- "User-Agent": "Hermes-Agent/1.0 (krea-image-gen)",- }- if managed:- headers["x-idempotency-key"] = str(uuid.uuid4())payload: Dict[str, Any] = {"image_url": image_url,"image_scaling_factor": _ENHANCE_SCALE_FACTOR,- # Keep the enhancer faithful to the generated composition: the- # original prompt guides detail, and default ai_strength stays- # conservative (Krea default 0.4 adds detail without redrawing).+ # The original prompt guides detail; default ai_strength (0.4) adds+ # detail without redrawing the composition."prompt": prompt,}try:resp = requests.post(- f"{base_url}{_ENHANCE_PATH}", headers=headers, json=payload, timeout=30,+ f"{base_url}{_ENHANCE_PATH}",+ headers=_headers(auth_token, managed=managed, json_body=True),+ json=payload, timeout=30,)resp.raise_for_status()job_id = (resp.json() or {}).get("job_id")@@ -353,9 +349,30 @@ def _enhance_image(return _extract_result_url(job)-# ----------------------------------------------------------------------------# Provider-# ---------------------------------------------------------------------------+def _collect_style_refs(+ image_url: Optional[str], reference_image_urls: Optional[List[str]], legacy_refs: Any+) -> List[Any]:+ """Reference images for style transfer: unified ``image_url`` ++ ``reference_image_urls`` first, then the legacy ``image_style_references``+ kwarg, whose entries may be URL strings or Krea ref objects (passed through+ verbatim). Strings are deduped in order; capped at Krea's limit of 10."""+ refs: List[Any] = collect_source_images(image_url, reference_image_urls)+ if isinstance(legacy_refs, list):+ for ref in legacy_refs:+ if isinstance(ref, str):+ if ref.strip():+ refs.append(ref.strip())+ elif ref:+ refs.append(ref)+ seen: set = set()+ deduped: List[Any] = []+ for r in refs:+ if isinstance(r, str):+ if r in seen:+ continue+ seen.add(r)+ deduped.append(r)+ return deduped[:_MAX_STYLE_REFERENCES]class KreaImageGenProvider(ImageGenProvider):@@ -370,54 +387,32 @@ class KreaImageGenProvider(ImageGenProvider):return "Krea"def is_available(self) -> bool:- # Available with a direct Krea key OR via the managed Nous gateway- # (Nous Subscription), so portal users with no Krea key can still- # reach Krea 2 through the gateway.+ # Direct key OR the managed Nous gateway (Nous Subscription), so portal+ # users without a Krea key can still reach Krea 2.return bool(get_secret("KREA_API_KEY")) or _managed_krea_gateway_ready()def list_models(self) -> List[Dict[str, Any]]:- return [- {- "id": model_id,- "display": meta["display"],- "speed": meta["speed"],- "strengths": meta["strengths"],- "price": meta["price"],- }- for model_id, meta in _MODELS.items()- ]+ return catalog_rows(_MODELS)def default_model(self) -> Optional[str]:return DEFAULT_MODELdef get_setup_schema(self) -> Dict[str, Any]:- return {- "name": "Krea",- "badge": "paid",- "tag": "Krea 2 foundation model — Medium ($0.03), Large ($0.06), Medium Turbo ($0.015). Style transfer, moodboards, reference-guided generation. Direct key or managed Nous Subscription gateway.",- "env_vars": [- {- "key": "KREA_API_KEY",- "prompt": "Krea API key",- "url": "https://www.krea.ai/settings/api-tokens",- },- ],- }+ return api_key_setup_schema(+ "Krea", "paid",+ "Krea 2 foundation model — Medium ($0.03), Large ($0.06), Medium Turbo ($0.015). Style transfer, moodboards, reference-guided generation. Direct key or managed Nous Subscription gateway.",+ key="KREA_API_KEY", prompt="Krea API key", url="https://www.krea.ai/settings/api-tokens",+ )def capabilities(self) -> Dict[str, Any]:- # Krea supports reference-guided generation (image-to-image style- # transfer) via image_style_references — up to 10 refs — and an- # opt-in Enhance upscale pass (see generate()'s upscale_requested).+ # Reference-guided generation via image_style_references (up to 10) plus+ # the opt-in Enhance upscale pass.return {"modalities": ["text", "image"],- "max_reference_images": 10,+ "max_reference_images": _MAX_STYLE_REFERENCES,"supports_upscale": True,}- # ------------------------------------------------------------------- # generate()- # -------------------------------------------------------------------def generate(self,prompt: str,@@ -431,52 +426,17 @@ class KreaImageGenProvider(ImageGenProvider):aspect = resolve_aspect_ratio(aspect_ratio)krea_ar = _ASPECT_MAP.get(aspect, "1:1")- # Collect reference images for reference-guided generation (image-to-- # image style transfer). Sources, in order:- # 1. unified image_url (primary source) + reference_image_urls (strings)- # 2. legacy image_style_references kwarg — may be plain URL strings OR- # Krea's richer ref objects (e.g. {"url": ..., "strength": ...}),- # which are passed through verbatim for backward compatibility.- style_refs: List[Any] = []- if isinstance(image_url, str) and image_url.strip():- style_refs.append(image_url.strip())- for ref in (normalize_reference_images(reference_image_urls) or []):- style_refs.append(ref)- legacy_refs = kwargs.get("image_style_references")- if isinstance(legacy_refs, list):- for ref in legacy_refs:- if isinstance(ref, str):- if ref.strip():- style_refs.append(ref.strip())- elif ref:- # Non-string ref object (dict, etc.) — pass through as-is.- style_refs.append(ref)- # Dedupe string entries while preserving order (dict refs aren't- # hashable, so they're kept verbatim); Krea caps at 10.- seen: set = set()- deduped: List[Any] = []- for r in style_refs:- if isinstance(r, str):- if r in seen:- continue- seen.add(r)- deduped.append(r)- style_refs = deduped[:10]+ style_refs = _collect_style_refs(+ image_url, reference_image_urls, kwargs.get("image_style_references")+ )modality = "image" if style_refs else "text"if not prompt:- return error_response(- error="Prompt is required and must be a non-empty string",- error_type="invalid_argument",- provider="krea",- aspect_ratio=aspect,- )+ return prompt_required_error("krea", aspect)- # Route through the managed Nous gateway (Nous Subscription) when the- # user is on the managed path; otherwise use the direct Krea API with a- # BYO ``KREA_API_KEY``. The gateway owns the shared Krea credential and- # meters/bills per generation, so the caller token is the Nous access- # token, not a Krea key.+ # Managed Nous gateway (Nous Subscription) owns the shared Krea+ # credential and meters per generation, so the caller token is the Nous+ # access token; otherwise the direct Krea API with a BYO ``KREA_API_KEY``.managed = _resolve_managed_krea_gateway()if managed is not None:base_url = managed.gateway_origin.rstrip("/")@@ -485,53 +445,38 @@ class KreaImageGenProvider(ImageGenProvider):base_url = BASE_URLauth_token = get_secret("KREA_API_KEY")if not auth_token:- return error_response(- error=(- "KREA_API_KEY not set. Run `hermes tools` → Image "- "Generation → Krea to configure, get a key at "- "https://www.krea.ai/settings/api-tokens, or sign in to "- "a Nous account with the managed Krea gateway enabled "- "(`hermes setup`)."- ),- error_type="auth_required",- provider="krea",- aspect_ratio=aspect,+ return error_factory("krea", aspect)(+ "KREA_API_KEY not set. Run `hermes tools` → Image "+ "Generation → Krea to configure, get a key at "+ "https://www.krea.ai/settings/api-tokens, or sign in to "+ "a Nous account with the managed Krea gateway enabled "+ "(`hermes setup`).",+ "auth_required",)model_id, meta = _resolve_model(kwargs.get("model"))creativity = _resolve_creativity(kwargs.get("creativity"))+ fail = error_factory("krea", aspect, model=model_id, prompt=prompt)++ styles = kwargs.get("styles")+ moodboards = kwargs.get("moodboards")+ styles = styles if isinstance(styles, list) and styles else None+ moodboards = moodboards if isinstance(moodboards, list) and moodboards else None- # The managed gateway only prices base text-to-image and URL- # ``image_style_references`` tiers. Trained styles (LoRAs) and- # moodboards have no managed price and are rejected at the gateway, so- # fail fast here with actionable guidance instead of a raw 400.+ # The managed gateway only prices base text-to-image and URL style+ # references; LoRAs and moodboards are rejected there, so fail fast+ # with guidance instead of a raw 400.if managed is not None:- if isinstance(kwargs.get("styles"), list) and kwargs.get("styles"):- return error_response(- error=(- "Managed Krea (Nous Subscription) does not support "- "trained styles (LoRAs). Set KREA_API_KEY to use Krea "- "directly, or omit `styles`."- ),- error_type="unsupported_argument",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- if isinstance(kwargs.get("moodboards"), list) and kwargs.get("moodboards"):- return error_response(- error=(- "Managed Krea (Nous Subscription) does not support "- "moodboards. Set KREA_API_KEY to use Krea directly, or "- "omit `moodboards`."- ),- error_type="unsupported_argument",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ for present, what, arg in (+ (styles, "trained styles (LoRAs)", "styles"),+ (moodboards, "moodboards", "moodboards"),+ ):+ if present:+ return fail(+ f"Managed Krea (Nous Subscription) does not support {what}. "+ f"Set KREA_API_KEY to use Krea directly, or omit `{arg}`.",+ "unsupported_argument",+ )payload: Dict[str, Any] = {"prompt": prompt,@@ -539,77 +484,39 @@ class KreaImageGenProvider(ImageGenProvider):"resolution": DEFAULT_RESOLUTION,"creativity": creativity,}-- # Optional forward-compat passthroughs — the Krea API accepts these- # but they're not required and most agent calls won't supply them.seed = kwargs.get("seed")if isinstance(seed, int):payload["seed"] = seed-- styles = kwargs.get("styles")- if isinstance(styles, list) and styles:+ if styles:payload["styles"] = styles-if style_refs:- # Reference-guided generation (image-to-image style transfer).- # Krea requires each entry to be an object ({"url", "strength"}),- # NOT a bare URL string — a string yields a 422 "Expected object,- # received string". Convert URL strings to the object form and pass- # already-object refs through verbatim (clamped to 10 above).- normalized_refs: List[Any] = []- for ref in style_refs:- if isinstance(ref, str):- normalized_refs.append(- {"url": ref, "strength": _DEFAULT_STYLE_REFERENCE_STRENGTH}- )- else:- normalized_refs.append(ref)- payload["image_style_references"] = normalized_refs-- moodboards = kwargs.get("moodboards")- if isinstance(moodboards, list) and moodboards:+ # Krea requires objects ({"url", "strength"}) — a bare string yields+ # a 422 "Expected object, received string". Object refs pass through.+ payload["image_style_references"] = [+ {"url": ref, "strength": _DEFAULT_STYLE_REFERENCE_STRENGTH}+ if isinstance(ref, str) else ref+ for ref in style_refs+ ]+ if moodboards:# Krea currently caps at 1 moodboard per request.payload["moodboards"] = moodboards[:1]- headers = {- "Authorization": f"Bearer {auth_token}",- "Content-Type": "application/json",- "User-Agent": "Hermes-Agent/1.0 (krea-image-gen)",- }- if managed is not None:- # The gateway derives the per-generation billing idempotency- # boundary from this header (else it falls back to a body- # fingerprint). A fresh key per submit keeps each generation a- # distinct billable execution.- headers["x-idempotency-key"] = str(uuid.uuid4())-# 1. Submit job.submit_url = f"{base_url}/generate/image/krea/krea-2/{meta['path']}"try:response = requests.post(submit_url,- headers=headers,- json=payload,- timeout=30,+ headers=_headers(auth_token, managed=managed is not None, json_body=True),+ json=payload, timeout=30,)response.raise_for_status()except requests.HTTPError as exc:resp = exc.responsestatus = resp.status_code if resp is not None else 0- try:- body = resp.json() if resp is not None else {}- err_msg = (- body.get("error", {}).get("message")- if isinstance(body.get("error"), dict)- else body.get("message") or body.get("detail")- ) or (resp.text[:300] if resp is not None else str(exc))- except Exception: # noqa: BLE001- err_msg = resp.text[:300] if resp is not None else str(exc)+ err_msg = _submit_error_message(resp, exc)logger.error("Krea submit failed (%d): %s", status, err_msg)- # On a managed 4xx, surface actionable remediation mirroring the- # FAL managed gateway path: the model may not be enabled/priced on- # the Nous Portal, or the gateway's shared Krea key hit its- # concurrency cap (429).+ # Managed 4xx: the model may not be enabled/priced on the Nous+ # Portal, or the gateway's shared key hit its concurrency cap (429).if managed is not None and 400 <= status < 500:hint = ("Krea's shared-key concurrency cap was hit — retry shortly."@@ -621,272 +528,96 @@ class KreaImageGenProvider(ImageGenProvider):"`hermes tools` → Image Generation."))- return error_response(- error=(- f"Nous Subscription Krea gateway rejected '{model_id}' "- f"(HTTP {status}): {err_msg}. {hint}"- ),- error_type="api_error",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,+ return fail(+ f"Nous Subscription Krea gateway rejected '{model_id}' "+ f"(HTTP {status}): {err_msg}. {hint}",+ "api_error",)- return error_response(- error=f"Krea image generation failed ({status}): {err_msg}",- error_type="api_error",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Krea image generation failed ({status}): {err_msg}", "api_error")except requests.Timeout:- return error_response(- error="Krea submit timed out (30s)",- error_type="timeout",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("Krea submit timed out (30s)", "timeout")except requests.ConnectionError as exc:- return error_response(- error=f"Krea connection error: {exc}",- error_type="connection_error",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Krea connection error: {exc}", "connection_error")try:submit_body = response.json()except Exception as exc: # noqa: BLE001- return error_response(- error=f"Krea returned invalid JSON on submit: {exc}",- error_type="invalid_response",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Krea returned invalid JSON on submit: {exc}", "invalid_response")job_id = submit_body.get("job_id")if not isinstance(job_id, str) or not job_id:- return error_response(- error="Krea submit response missing job_id",- error_type="invalid_response",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )-- # 2. Poll for completion. Status/result polling is bound to the same- # principal at the gateway, so the managed path polls the gateway's- # ``/jobs/{id}`` with the Nous token (404 on cross-user/unknown jobs).- job_url = f"{base_url}/jobs/{job_id}"- poll_headers = {- "Authorization": f"Bearer {auth_token}",- "User-Agent": "Hermes-Agent/1.0 (krea-image-gen)",- }- interval = _POLL_INITIAL_INTERVAL- deadline = time.monotonic() + _POLL_TIMEOUT_SECONDS- last_status: Optional[str] = None-- while True:- time.sleep(interval)- interval = min(interval * _POLL_BACKOFF, _POLL_MAX_INTERVAL)-- try:- poll_resp = requests.get(job_url, headers=poll_headers, timeout=30)- poll_resp.raise_for_status()- except requests.HTTPError as exc:- resp = exc.response- status = resp.status_code if resp is not None else 0- logger.error("Krea poll failed (%d) for job %s", status, job_id)- # Fail fast for non-retryable statuses (auth/billing/not-found,- # other permanent 4xx) so callers don't wait the full 180s- # deadline on a request that will never succeed. Only retry- # transient statuses such as 408/409/425/429/5xx.- if status not in _RETRYABLE_POLL_STATUSES or time.monotonic() >= deadline:- return error_response(- error=f"Krea poll failed ({status}) for job {job_id}",- error_type="api_error",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- # Otherwise keep trying — transient 5xx (and a few retryable- # 4xx like 408/409/425/429) are common on async jobs.- continue- except (requests.Timeout, requests.ConnectionError) as exc:- logger.warning("Krea poll transient error for job %s: %s", job_id, exc)- if time.monotonic() >= deadline:- return error_response(- error=f"Krea poll timed out for job {job_id}: {exc}",- error_type="timeout",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- continue-- try:- job = poll_resp.json()- except Exception as exc: # noqa: BLE001- logger.warning("Krea poll returned invalid JSON for job %s: %s", job_id, exc)- if time.monotonic() >= deadline:- return error_response(- error=f"Krea poll returned invalid JSON: {exc}",- error_type="invalid_response",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- continue-- status_str = job.get("status") if isinstance(job, dict) else None- if isinstance(status_str, str):- last_status = status_str- if status_str in _TERMINAL_STATES:- break-- # ``completed_at`` is a backstop terminal marker even when the- # ``status`` enum is unfamiliar (Krea adds new pending states- # over time — backlogged/scheduled/sampling — and we don't- # want to mis-handle a future one).- if isinstance(job, dict) and job.get("completed_at"):- break-- if time.monotonic() >= deadline:- return error_response(- error=(- f"Krea job {job_id} did not complete within "- f"{int(_POLL_TIMEOUT_SECONDS)}s (last status: {last_status or 'unknown'})"- ),- error_type="timeout",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,+ return fail("Krea submit response missing job_id", "invalid_response")++ # 2. Poll for completion. Polling is bound to the same principal at the+ # gateway, so the managed path polls the gateway's ``/jobs/{id}`` with+ # the Nous token (404 on cross-user/unknown jobs).+ poll_errors: List[Dict[str, Any]] = []++ def poll_error(kind: str, detail: Any) -> Dict[str, Any]:+ if kind == "http":+ err = fail(f"Krea poll failed ({detail}) for job {job_id}", "api_error")+ elif kind == "timeout":+ err = fail(f"Krea poll timed out for job {job_id}: {detail}", "timeout")+ elif kind == "invalid_json":+ err = fail(f"Krea poll returned invalid JSON: {detail}", "invalid_response")+ else:+ err = fail(+ f"Krea job {job_id} did not complete within "+ f"{int(_POLL_TIMEOUT_SECONDS)}s (last status: {detail or 'unknown'})",+ "timeout",)+ poll_errors.append(err)+ return err- # 3. Terminal — extract result.+ job = _poll_krea_job(base_url, auth_token, job_id, on_error=poll_error)+ if poll_errors:+ return poll_errors[0]if not isinstance(job, dict):- return error_response(- error="Krea returned non-dict job body",- error_type="invalid_response",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("Krea returned non-dict job body", "invalid_response")+ # 3. Terminal — extract result.+ last_status = job.get("status")if last_status == "failed":err = (job.get("result") or {}).get("error") if isinstance(job.get("result"), dict) else None- return error_response(- error=f"Krea job {job_id} failed: {err or 'unknown error'}",- error_type="api_error",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )-+ return fail(f"Krea job {job_id} failed: {err or 'unknown error'}", "api_error")if last_status == "cancelled":- return error_response(- error=f"Krea job {job_id} was cancelled",- error_type="cancelled",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )-- # Successful path — pull URL out of the result.- result = job.get("result")- if not isinstance(result, dict):- return error_response(- error="Krea job completed but result was missing",- error_type="empty_response",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )-- # Per Krea's job-lifecycle docs the completed payload exposes- # ``result.urls`` (an array). Fall back to a single ``url`` field- # for forward/backward compatibility.- result_image_url: Optional[str] = None- urls = result.get("urls")- if isinstance(urls, list) and urls:- for candidate in urls:- if isinstance(candidate, str) and candidate.strip():- result_image_url = candidate.strip()- break- if result_image_url is None:- single = result.get("url")- if isinstance(single, str) and single.strip():- result_image_url = single.strip()+ return fail(f"Krea job {job_id} was cancelled", "cancelled")+ if not isinstance(job.get("result"), dict):+ return fail("Krea job completed but result was missing", "empty_response")+ result_image_url = _extract_result_url(job)if result_image_url is None:- return error_response(- error="Krea result contained no image URL",- error_type="empty_response",- provider="krea",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("Krea result contained no image URL", "empty_response")- # High-resolution pass (Krea Enhance). Precedence: explicit kwarg >- # ``image_gen.krea.upscale`` config > per-model catalog default- # (1.5K-native tiers default on; 2K-native Large stays off). Best-- # effort: failure falls back to the original image rather than- # failing the generation.+ # Krea Enhance pass. Precedence: explicit kwarg > ``image_gen.krea.upscale``+ # config > per-model catalog default. Best-effort: failure falls back to+ # the original image rather than failing the generation.upscaled = Falseupscale_requested = kwargs.get("upscale")if not isinstance(upscale_requested, bool):- cfg_krea = _load_krea_config().get("krea")- cfg_upscale = cfg_krea.get("upscale") if isinstance(cfg_krea, dict) else None- if isinstance(cfg_upscale, bool):- upscale_requested = cfg_upscale- else:- upscale_requested = bool(meta.get("upscale", False))+ cfg_upscale = _krea_section().get("upscale")+ upscale_requested = (+ cfg_upscale if isinstance(cfg_upscale, bool) else bool(meta.get("upscale", False))+ )if upscale_requested:enhanced_url = _enhance_image(- base_url,- auth_token,- result_image_url,- prompt,- managed=managed is not None,+ base_url, auth_token, result_image_url, prompt, managed=managed is not None,)if enhanced_url:result_image_url = enhanced_urlupscaled = Trueelse:- logger.warning(- "Krea Enhance pass failed — returning native-resolution image"- )+ logger.warning("Krea Enhance pass failed — returning native-resolution image")- # Materialise locally — Krea result URLs may expire, mirroring- # what we do for xAI / OpenAI URL responses (#26942).+ # Materialise locally — Krea result URLs may expire.try:- saved_path = save_url_image(result_image_url, prefix=f"krea_{model_id}")+ image_ref = str(save_url_image(result_image_url, prefix=f"krea_{model_id}"))except Exception as exc: # noqa: BLE001logger.warning("Krea image URL %s could not be cached (%s); falling back to bare URL.",- result_image_url,- exc,+ result_image_url, exc,)image_ref = result_image_url- else:- image_ref = str(saved_path)extra: Dict[str, Any] = {"krea_aspect_ratio": krea_ar,@@ -911,11 +642,6 @@ class KreaImageGenProvider(ImageGenProvider):)-# ----------------------------------------------------------------------------# Plugin entry point-# -----------------------------------------------------------------------------def register(ctx) -> None:"""Plugin entry point — wire ``KreaImageGenProvider`` into the registry."""ctx.register_image_gen_provider(KreaImageGenProvider())diff --git a/plugins/image_gen/meta-ai/__init__.py b/plugins/image_gen/meta-ai/__init__.pyindex e5c2d439934..ef610bb1805 100644--- a/plugins/image_gen/meta-ai/__init__.py+++ b/plugins/image_gen/meta-ai/__init__.py@@ -3,16 +3,12 @@Exposes Meta's ``muse-image`` model(s) as an :class:`ImageGenProvider`.The Meta Model API (https://api.meta.ai/v1) is OpenAI-compatible, so we reusethe OpenAI Python SDK pointed at Meta's base URL and authenticate with-``META_MODEL_API_KEY``.+``META_MODEL_API_KEY``. Output is base64 JSON (WebP) → ``$HERMES_HOME/cache/images/``.-Output is base64 JSON (WebP) -> saved under ``$HERMES_HOME/cache/images/``.--Selection precedence (first hit wins):- 1. ``model`` kwarg forwarded by the dispatcher (the ``hermes tools`` pick)- 2. ``META_IMAGE_MODEL`` env var (escape hatch for scripts / tests)- 3. ``image_gen.meta-ai.model`` in ``config.yaml``- 4. ``image_gen.model`` in ``config.yaml`` (when it's one of our IDs)- 5. :data:`DEFAULT_MODEL`+Selection precedence (first hit wins): ``model`` kwarg forwarded by the+dispatcher (the ``hermes tools`` pick) → ``META_IMAGE_MODEL`` env →+``image_gen.meta-ai.model`` → ``image_gen.model`` (when it's one of our IDs)+→ :data:`DEFAULT_MODEL`."""from __future__ import annotations@@ -25,13 +21,21 @@ from agent.secret_scope import get_secretfrom agent.image_gen_provider import (DEFAULT_ASPECT_RATIO,ImageGenProvider,- error_response,- normalize_reference_images,resolve_aspect_ratio,save_b64_image,save_url_image,success_response,)+from plugins.image_gen._common import (+ api_key_setup_schema,+ catalog_rows,+ error_factory,+ import_openai,+ openai_importable,+ prompt_required_error,+ resolve_static_model,+ size_for,+)logger = logging.getLogger(__name__)@@ -59,9 +63,6 @@ def _resolve_base_url() -> str:return (os.environ.get(BASE_URL_ENV) or "").strip() or DEFAULT_BASE_URL-# ----------------------------------------------------------------------------# Model catalog-# ---------------------------------------------------------------------------# Catalog shown in `hermes tools` and matched against `image_gen.model`.# The model id is sent verbatim to the Meta Model API (`/v1/images/generations`)._MODELS: Dict[str, Dict[str, Any]] = {@@ -74,44 +75,13 @@ _MODELS: Dict[str, Dict[str, Any]] = {}DEFAULT_MODEL = "muse-image-1.0"-# aspect_ratio -> OpenAI-style size string-_SIZES: Dict[str, str] = {- "square": "1024x1024",- "landscape": "1536x1024",- "portrait": "1024x1536",-}-def _resolve_model(caller_model: Optional[str] = None) -> Tuple[str, Dict[str, Any]]:- """Return (model_id, metadata) using the documented precedence chain.-- ``caller_model`` is the ``model`` kwarg the dispatcher forwards from the- top-level ``image_gen.model`` config key (what ``hermes tools`` writes).- It wins when it names one of our models, mirroring the xai/krea/openrouter- providers, so a user's picker choice is never silently dropped.- """- if caller_model and caller_model in _MODELS:- return caller_model, _MODELS[caller_model]-- env_model = os.environ.get("META_IMAGE_MODEL")- if env_model and env_model in _MODELS:- return env_model, _MODELS[env_model]-- try:- from hermes_cli.config import load_config-- cfg = load_config() or {}- ig = cfg.get("image_gen") or {}- scoped = (ig.get("meta-ai") or {}).get("model")- if scoped and scoped in _MODELS:- return scoped, _MODELS[scoped]- top = ig.get("model")- if top and top in _MODELS:- return top, _MODELS[top]- except Exception:- logger.debug("Could not read image_gen model from config", exc_info=True)-- return DEFAULT_MODEL, _MODELS[DEFAULT_MODEL]+ """Return (model_id, metadata); ``caller_model`` is the dispatcher's ``model`` kwarg."""+ return resolve_static_model(+ _MODELS, DEFAULT_MODEL, env_var="META_IMAGE_MODEL", config_key="meta-ai",+ explicit=caller_model,+ )class MetaImageGenProvider(ImageGenProvider):@@ -126,46 +96,22 @@ class MetaImageGenProvider(ImageGenProvider):return "Meta Model API"def is_available(self) -> bool:- if not _resolve_api_key():- return False- try:- import openai # noqa: F401- except ImportError:- return False- return True+ return bool(_resolve_api_key()) and openai_importable()def list_models(self) -> List[Dict[str, Any]]:- return [- {- "id": mid,- "display": m["display"],- "speed": m["speed"],- "strengths": m["strengths"],- "price": m["price"],- }- for mid, m in _MODELS.items()- ]+ return catalog_rows(_MODELS)def default_model(self) -> Optional[str]:return DEFAULT_MODELdef get_setup_schema(self) -> Dict[str, Any]:- return {- "name": "Meta Model API",- "badge": "paid",- "tag": "Muse Image via Meta Model API (api.meta.ai)",- "env_vars": [- {- "key": API_KEY_ENV,- "prompt": "Meta Model API key (LLM|... token)",- "url": "https://api.meta.ai",- },- ],- }+ return api_key_setup_schema(+ "Meta Model API", "paid", "Muse Image via Meta Model API (api.meta.ai)",+ key=API_KEY_ENV, prompt="Meta Model API key (LLM|... token)", url="https://api.meta.ai",+ )def capabilities(self) -> Dict[str, Any]:- # Text-to-image only for now. Bump this once image-to-image is verified- # against the Meta endpoint.+ # Text-to-image only until image-to-image is verified against the Meta endpoint.return {"modalities": ["text"], "max_reference_images": 0}def generate(@@ -181,103 +127,50 @@ class MetaImageGenProvider(ImageGenProvider):aspect = resolve_aspect_ratio(aspect_ratio)if not prompt:- return error_response(- error="Prompt is required and must be a non-empty string",- error_type="invalid_argument",- provider="meta-ai",- aspect_ratio=aspect,- )+ return prompt_required_error("meta-ai", aspect)api_key = _resolve_api_key()if not api_key:- return error_response(- error=(- f"{API_KEY_ENV} not set. Run `hermes tools` -> Image "- "Generation -> Meta Model API to configure."- ),- error_type="auth_required",- provider="meta-ai",- aspect_ratio=aspect,+ return error_factory("meta-ai", aspect)(+ f"{API_KEY_ENV} not set. Run `hermes tools` -> Image "+ "Generation -> Meta Model API to configure.",+ "auth_required",)- try:- import openai- except ImportError:- return error_response(- error="openai Python package not installed (pip install openai)",- error_type="missing_dependency",- provider="meta-ai",- aspect_ratio=aspect,- )+ openai, err = import_openai("meta-ai", aspect)+ if err:+ return errmodel_id, _meta = _resolve_model(kwargs.get("model"))- size = _SIZES.get(aspect, _SIZES["square"])-+ size = size_for(aspect)+ fail = error_factory("meta-ai", aspect, model=model_id, prompt=prompt)client = openai.OpenAI(api_key=api_key, base_url=_resolve_base_url())- payload: Dict[str, Any] = {- "model": model_id,- "prompt": prompt,- "size": size,- "n": 1,- }-try:- response = client.images.generate(**payload)+ response = client.images.generate(model=model_id, prompt=prompt, size=size, n=1)except Exception as exc:logger.debug("Meta image generation failed", exc_info=True)- return error_response(- error=f"Meta image generation failed: {exc}",- error_type="api_error",- provider="meta-ai",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Meta image generation failed: {exc}", "api_error")try:first = response.data[0]except (AttributeError, IndexError, TypeError):- return error_response(- error="Meta response contained no image data",- error_type="empty_response",- provider="meta-ai",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("Meta response contained no image data", "empty_response")b64 = getattr(first, "b64_json", None)url = getattr(first, "url", None)-try:if b64:- path = save_b64_image(b64, prefix="meta", extension="webp")- image_ref = str(path)+ image_ref = str(save_b64_image(b64, prefix="meta", extension="webp"))elif url:- path = save_url_image(url, prefix="meta")- image_ref = str(path)+ image_ref = str(save_url_image(url, prefix="meta"))else:- return error_response(- error="Meta response contained neither b64_json nor URL",- error_type="empty_response",- provider="meta-ai",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("Meta response contained neither b64_json nor URL", "empty_response")except Exception as exc:- return error_response(- error=f"Failed to save Meta image: {exc}",- error_type="io_error",- provider="meta-ai",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Failed to save Meta image: {exc}", "io_error")- revised_prompt = getattr(first, "revised_prompt", None)extra: Dict[str, Any] = {"size": size}+ revised_prompt = getattr(first, "revised_prompt", None)if revised_prompt:extra["revised_prompt"] = revised_promptdiff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.pyindex 9823425e946..e13fe72278e 100644--- a/plugins/image_gen/openai-codex/__init__.py+++ b/plugins/image_gen/openai-codex/__init__.py@@ -1,21 +1,21 @@"""OpenAI image generation backend — ChatGPT/Codex OAuth variant.-Identical model catalog and tier semantics to the ``openai`` image-gen plugin-(``gpt-image-2`` at low/medium/high quality), but routes the request through-the Codex Responses API ``image_generation`` tool instead of the-``images.generate`` REST endpoint. This lets users who are already-authenticated with Codex/ChatGPT generate images without configuring a-separate ``OPENAI_API_KEY``.--Selection precedence for the tier (first hit wins):--1. ``OPENAI_IMAGE_MODEL`` env var (escape hatch for scripts / tests)-2. ``image_gen.openai-codex.model`` in ``config.yaml``-3. ``image_gen.model`` in ``config.yaml`` (when it's one of our tier IDs)-4. :data:`DEFAULT_MODEL` — ``gpt-image-2-medium``--Output is saved as PNG under ``$HERMES_HOME/cache/images/``. Source images for-image-to-image/editing are sent as Responses ``input_image`` content parts.+Same model catalog and tier semantics as the ``openai`` plugin (``gpt-image-2``+at low/medium/high quality), but routed through the Codex Responses API+``image_generation`` tool instead of ``images.generate``, so users already+authenticated with Codex/ChatGPT need no separate ``OPENAI_API_KEY``.++Tier precedence: ``OPENAI_IMAGE_MODEL`` env → ``image_gen.openai-codex.model``+→ ``image_gen.model`` (when it's one of our tier IDs) → :data:`DEFAULT_MODEL`.+Output is saved as PNG under ``$HERMES_HOME/cache/images/``; source images for+editing are sent as Responses ``input_image`` content parts.++Do NOT reintroduce an "account capability" classifier keyed on ``Tool choice+'image_generation' not found in 'tools' parameter``: that HTTP 400 is a+request-shape rejection emitted for every account (the Codex backend resolves+tool_choice as a function-tool name), not an entitlement problem. It is fixed+by omitting tool_choice (see ``_build_responses_payload``); any remaining HTTP+error must surface verbatim so it stays diagnosable."""from __future__ import annotations@@ -30,93 +30,30 @@ from typing import Any, Dict, List, Optional, Tuplefrom agent.image_gen_provider import (DEFAULT_ASPECT_RATIO,ImageGenProvider,- error_response,- normalize_reference_images,resolve_aspect_ratio,save_b64_image,success_response,)+from plugins.image_gen._common import (+ GPT_IMAGE_2_API_MODEL as API_MODEL,+ GPT_IMAGE_2_DEFAULT as DEFAULT_MODEL,+ GPT_IMAGE_2_TIERS,+ catalog_rows,+ collect_source_images,+ error_factory,+ prompt_required_error,+ resolve_static_model,+ size_for,+)logger = logging.getLogger(__name__)--# NOTE: do NOT reintroduce an "account capability" classifier keyed on-# ``Tool choice 'image_generation' not found in 'tools' parameter``. That HTTP-# 400 is a *request-shape* rejection (the Codex backend resolves tool_choice as-# a function-tool name and never recognizes hosted-tool entries) — it is-# emitted for every account, including accounts where image generation works.-# A previous version of this file translated that 400 into "Image generation is-# not enabled for the current Codex account. Switch the image provider to-# OpenAI API key, FAL, or xAI.", which reported a universal bug in our own-# payload as the user's entitlement problem and sent people away from a-# provider that was never actually tried. The request-shape bug is fixed by-# omitting tool_choice (see ``_build_responses_payload``); any remaining HTTP-# error must surface verbatim so it stays diagnosable. See issues #19505,-# #49008 and #31335.-_MAX_ERROR_BODY_CHARS = 500+_MODELS: Dict[str, Dict[str, Any]] = dict(GPT_IMAGE_2_TIERS)-def _summarize_error_body(body: str) -> str:- """Return a bounded, information-preserving summary of an error body.-- Prefers the parsed ``error.message`` field, because a blind head-truncation- of the raw body can cut the actual message off entirely — Codex error- payloads sometimes carry hundreds of bytes of leading metadata, so- ``body[:500]`` yielded a wall of padding and no diagnosis. Falls back to a- truncated raw body for non-JSON responses.- """- text = body or ""- try:- payload = json.loads(text)- error = payload.get("error") if isinstance(payload, dict) else None- message = error.get("message") if isinstance(error, dict) else None- if isinstance(message, str) and message.strip():- return message.strip()[:_MAX_ERROR_BODY_CHARS]- except (TypeError, ValueError):- pass- return text[:_MAX_ERROR_BODY_CHARS]----# ----------------------------------------------------------------------------# Model catalog — mirrors the ``openai`` plugin so the picker UX is identical.-# -----------------------------------------------------------------------------API_MODEL = "gpt-image-2"--_MODELS: Dict[str, Dict[str, Any]] = {- "gpt-image-2-low": {- "display": "GPT Image 2 (Low)",- "speed": "~15s",- "strengths": "Fast iteration, lowest cost",- "quality": "low",- },- "gpt-image-2-medium": {- "display": "GPT Image 2 (Medium)",- "speed": "~40s",- "strengths": "Balanced — default",- "quality": "medium",- },- "gpt-image-2-high": {- "display": "GPT Image 2 (High)",- "speed": "~2min",- "strengths": "Highest fidelity, strongest prompt adherence",- "quality": "high",- },-}--DEFAULT_MODEL = "gpt-image-2-medium"--_SIZES = {- "landscape": "1536x1024",- "square": "1024x1024",- "portrait": "1024x1536",-}--# Codex Responses surface used for the request. The chat model itself is only-# the host that calls the ``image_generation`` tool; the actual image work is-# done by ``API_MODEL``.+# Codex Responses surface used for the request. The chat model only hosts the+# ``image_generation`` tool call; the image work is done by ``API_MODEL``._CODEX_CHAT_MODEL = "gpt-5.5"_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex"_CODEX_INSTRUCTIONS = (@@ -126,65 +63,54 @@ _CODEX_INSTRUCTIONS = (_MAX_REFERENCE_IMAGES = 16_MAX_INPUT_IMAGE_BYTES = 25 * 1024 * 1024-# gpt-image-2's Responses ``input_image`` accepts raster formats only. The-# shared magic-byte sniffer also recognizes SVG/TIFF/ICO, which the API-# rejects server-side — gate to this allowlist so unsupported inputs fail-# locally with a clear error instead of an opaque HTTP 400.-_ACCEPTED_INPUT_MIME = frozenset(- {"image/png", "image/jpeg", "image/gif", "image/webp"}-)+# gpt-image-2's ``input_image`` accepts raster formats only. The shared sniffer+# also recognizes SVG/TIFF/ICO, which the API rejects server-side — gate to this+# allowlist so unsupported inputs fail locally instead of as an opaque HTTP 400.+_ACCEPTED_INPUT_MIME = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"})++# Progressive preview frames (partial_image_b64) are intermediate renders;+# saving them as finals produced the "smear" failure mode. Defense in depth:+# request 0 partials, never let a partial overwrite a final in the extractor,+# and only deliver source=final from generate(). Live streams may still emit a+# partial event even with 0 — fine as long as only a final ``result`` is saved.+_PARTIAL_IMAGES_REQUESTED = 0+# Content-agnostic retries when the stream yields no final result.+_NONFINAL_RETRIES = 1+_NO_AUTH = (+ "No Codex/ChatGPT OAuth credentials available. Run "+ "`hermes auth codex` (or `hermes setup` → Codex) to sign in."+)-# ----------------------------------------------------------------------------# Config + auth helpers-# ---------------------------------------------------------------------------+def _summarize_error_body(body: str) -> str:+ """Bounded error summary preferring parsed ``error.message``.-def _load_image_gen_config() -> Dict[str, Any]:- """Read ``image_gen`` from config.yaml (returns {} on any failure)."""+ A blind head-truncation of the raw body can cut the actual message off —+ Codex error payloads sometimes carry hundreds of bytes of leading metadata.+ """+ text = body or ""try:- from hermes_cli.config import load_config-- cfg = load_config()- section = cfg.get("image_gen") if isinstance(cfg, dict) else None- return section if isinstance(section, dict) else {}- except Exception as exc:- logger.debug("Could not load image_gen config: %s", exc)- return {}+ payload = json.loads(text)+ error = payload.get("error") if isinstance(payload, dict) else None+ message = error.get("message") if isinstance(error, dict) else None+ if isinstance(message, str) and message.strip():+ return message.strip()[:_MAX_ERROR_BODY_CHARS]+ except (TypeError, ValueError):+ pass+ return text[:_MAX_ERROR_BODY_CHARS]def _resolve_model() -> Tuple[str, Dict[str, Any]]:"""Decide which tier to use and return ``(model_id, meta)``."""- import os-- env_override = os.environ.get("OPENAI_IMAGE_MODEL")- if env_override and env_override in _MODELS:- return env_override, _MODELS[env_override]-- cfg = _load_image_gen_config()- sub = cfg.get("openai-codex") if isinstance(cfg.get("openai-codex"), dict) else {}- candidate: Optional[str] = None- if isinstance(sub, dict):- value = sub.get("model")- if isinstance(value, str) and value in _MODELS:- candidate = value- if candidate is None:- top = cfg.get("model")- if isinstance(top, str) and top in _MODELS:- candidate = top-- if candidate is not None:- return candidate, _MODELS[candidate]-- return DEFAULT_MODEL, _MODELS[DEFAULT_MODEL]+ return resolve_static_model(+ _MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai-codex"+ )def _read_codex_access_token() -> Optional[str]:- """Return a usable Codex OAuth token, or None.-- Delegates to the canonical reader in ``agent.auxiliary_client`` so token- expiry, credential pool selection, and JWT decoding stay in one place.- """+ """Usable Codex OAuth token or None; the canonical reader in+ ``agent.auxiliary_client`` owns expiry, pool selection and JWT decoding."""try:from agent.auxiliary_client import _read_codex_access_token as _reader@@ -198,21 +124,21 @@ def _read_codex_access_token() -> Optional[str]:def _sniff_image_mime(raw: bytes) -> Optional[str]:- """Return a safe raster image MIME from magic bytes (not filename labels).-- Delegates magic-byte detection to the shared sniffer in- ``agent.image_routing`` (single source of truth), then gates the result- to :data:`_ACCEPTED_INPUT_MIME` — the raster formats gpt-image-2's- ``input_image`` actually accepts. SVG/TIFF/ICO (which the shared sniffer- also recognizes) are rejected here so they fail locally with a clear- error instead of an opaque server-side HTTP 400.- """+ """Raster MIME from magic bytes (shared sniffer), gated to :data:`_ACCEPTED_INPUT_MIME`."""from agent.image_routing import _sniff_mime_from_bytesmime = _sniff_mime_from_bytes(raw)- if mime in _ACCEPTED_INPUT_MIME:- return mime- return None+ return mime if mime in _ACCEPTED_INPUT_MIME else None+++def _encode_input_image(raw: bytes, too_big: str, unsupported: str) -> str:+ """Size- and MIME-check raw image bytes, then return a canonical ``data:`` URL."""+ if len(raw) > _MAX_INPUT_IMAGE_BYTES:+ raise ValueError(too_big)+ mime = _sniff_image_mime(raw)+ if mime is None:+ raise ValueError(unsupported)+ return f"data:{mime};base64,{base64.b64encode(raw).decode('ascii')}"def _data_url_to_input_image_url(value: str) -> str:@@ -223,14 +149,11 @@ def _data_url_to_input_image_url(value: str) -> str:header_lc = header.lower()if not header_lc.startswith("data:image/") or ";base64" not in header_lc:raise ValueError("Only base64 data:image URLs are supported as Codex image inputs")- raw = base64.b64decode(data, validate=True)- if len(raw) > _MAX_INPUT_IMAGE_BYTES:- raise ValueError("Image data URL exceeds 25MB cap")- mime = _sniff_image_mime(raw)- if mime is None:- raise ValueError("Image data URL does not contain supported image bytes")- encoded = base64.b64encode(raw).decode("ascii")- return f"data:{mime};base64,{encoded}"+ return _encode_input_image(+ base64.b64decode(data, validate=True),+ "Image data URL exceeds 25MB cap",+ "Image data URL does not contain supported image bytes",+ )def _local_image_to_data_url(value: str) -> str:@@ -249,17 +172,13 @@ def _local_image_to_data_url(value: str) -> str:path = Path(os.path.expanduser(value)).resolve()if not path.is_file():raise ValueError(f"Image input path does not exist or is not a file: {value}")- size = path.stat().st_size- if size <= 0:+ if path.stat().st_size <= 0:raise ValueError(f"Image input path is empty: {value}")- if size > _MAX_INPUT_IMAGE_BYTES:- raise ValueError(f"Image input path exceeds 25MB cap: {value}")- raw = path.read_bytes()- mime = _sniff_image_mime(raw)- if mime is None:- raise ValueError(f"Image input path is not a supported image: {value}")- encoded = base64.b64encode(raw).decode("ascii")- return f"data:{mime};base64,{encoded}"+ return _encode_input_image(+ path.read_bytes(),+ f"Image input path exceeds 25MB cap: {value}",+ f"Image input path is not a supported image: {value}",+ )def _to_input_image_part(value: str) -> Dict[str, str]:@@ -268,7 +187,7 @@ def _to_input_image_part(value: str) -> Dict[str, str]:if not candidate:raise ValueError("Blank image input")lowered = candidate.lower()- if lowered.startswith("http://") or lowered.startswith("https://"):+ if lowered.startswith(("http://", "https://")):image_url = candidateelif lowered.startswith("data:"):image_url = _data_url_to_input_image_url(candidate)@@ -282,29 +201,10 @@ def _normalize_input_images(reference_image_urls: Optional[List[str]],) -> List[Dict[str, str]]:"""Collect primary + reference images as ordered Responses content parts."""- values: List[str] = []- if isinstance(image_url, str) and image_url.strip():- values.append(image_url.strip())- for ref in (normalize_reference_images(reference_image_urls) or []):- values.append(ref)- values = values[:_MAX_REFERENCE_IMAGES]+ values = collect_source_images(image_url, reference_image_urls, limit=_MAX_REFERENCE_IMAGES)return [_to_input_image_part(value) for value in values]-# Progressive preview frames (partial_image_b64) are intermediate renders.-# Saving them as finals produced the long-running "smear" failure mode on the-# Codex Responses path. Defense in depth:-# 1) request layer prefers no progressive frames when the backend honors it-# 2) extractor never lets a partial overwrite a final result-# 3) generate() only delivers source=final; partial-only / empty are not success-# Live streams sometimes still emit a partial event even with 0; that is fine as-# long as only a final ``result`` can be saved.-_PARTIAL_IMAGES_REQUESTED = 0-# Content-agnostic retries when the stream does not yield a final result-# (empty stream or progressive-only). No prompt-class branching.-_NONFINAL_RETRIES = 1--def _build_responses_payload(*,prompt: str,@@ -312,7 +212,13 @@ def _build_responses_payload(quality: str,input_images: Optional[List[Dict[str, str]]] = None,) -> Dict[str, Any]:- """Build the Codex Responses request body for an image_generation call."""+ """Build the Codex Responses request body for an image_generation call.++ No ``tool_choice`` is sent: the Codex backend rejects every shape for+ forcing the hosted ``image_generation`` tool (it looks tool_choice up as a+ *function* name), so letting the host model decide — nudged by+ ``instructions`` — is the only accepted shape.+ """content: List[Dict[str, Any]] = [{"type": "input_text", "text": prompt}]if input_images:content.extend(input_images)@@ -320,11 +226,7 @@ def _build_responses_payload("model": _CODEX_CHAT_MODEL,"store": False,"instructions": _CODEX_INSTRUCTIONS,- "input": [{- "type": "message",- "role": "user",- "content": content,- }],+ "input": [{"type": "message", "role": "user", "content": content}],"tools": [{"type": "image_generation","model": API_MODEL,@@ -332,22 +234,8 @@ def _build_responses_payload("quality": quality,"output_format": "png","background": "opaque",- # Prefer 0 progressive preview frames. Preview frames can arrive- # without a later final ``result`` and look like smeared /- # unfinished images if saved as the deliverable. Even when the- # backend still emits a partial event, generate() refuses to- # deliver anything except source=final."partial_images": _PARTIAL_IMAGES_REQUESTED,}],- # No ``tool_choice`` is sent: the chatgpt.com/backend-api/codex backend- # rejects every shape we have for forcing the hosted ``image_generation``- # tool. ``{"type": "allowed_tools", "mode": "required", "tools": [{"type":- # "image_generation"}]}`` (and the simpler ``{"type": "image_generation"}``- # form) both 400 with ``Tool choice 'image_generation' not found in 'tools'- # parameter`` — the backend looks up tool_choice as a *function* name and- # never recognizes hosted-tool entries. Letting the host model decide is- # the only shape Codex currently accepts; the ``instructions`` above are- # what nudge it toward the tool. See issue #19505."stream": True,}@@ -355,9 +243,8 @@ def _build_responses_payload(def _extract_image_candidates(value: Any) -> Tuple[Optional[str], Optional[str]]:"""Return ``(final_result_b64, latest_partial_b64)`` from a payload tree.- Final ``image_generation_call.result`` and progressive ``partial_image_b64``- are tracked separately so a partial can never overwrite a genuine final,- including when both coexist in the same event payload.+ Tracked separately so a partial can never overwrite a genuine final, even+ when both coexist in the same event payload."""result_b64: Optional[str] = Nonepartial_b64: Optional[str] = None@@ -383,23 +270,16 @@ def _extract_image_candidates(value: Any) -> Tuple[Optional[str], Optional[str]]def _extract_image_b64(value: Any) -> Optional[str]:- """Return image b64 from a payload, preferring final result over partial.-- Progressive ``partial_image_b64`` is only used when no final- ``image_generation_call.result`` is present in the same payload tree.- """+ """Image b64 from a payload, preferring a final result over a partial."""result_b64, partial_b64 = _extract_image_candidates(value)return result_b64 or partial_b64def _png_pixel_size(raw: bytes) -> Optional[str]:- """Return ``\"{w}x{h}\"`` for a PNG payload, or None if not a PNG IHDR."""+ """Return ``"{w}x{h}"`` for a PNG payload, or None if not a PNG IHDR."""import struct- if len(raw) < 24 or raw[:8] != b"\x89PNG\r\n\x1a\n":- return None- # IHDR: length(4) + type(4) + width(4) + height(4)- if raw[12:16] != b"IHDR":+ if len(raw) < 24 or raw[:8] != b"\x89PNG\r\n\x1a\n" or raw[12:16] != b"IHDR":return Nonewidth, height = struct.unpack(">II", raw[16:24])return f"{width}x{height}"@@ -408,9 +288,8 @@ def _png_pixel_size(raw: bytes) -> Optional[str]:def _iter_sse_json(response: Any):"""Yield JSON payloads from an SSE response without OpenAI SDK parsing.- The ChatGPT/Codex backend can emit image-generation events newer than the- pinned Python SDK understands. Parsing raw SSE keeps this provider tolerant- of those event-shape changes.+ The Codex backend can emit image-generation events newer than the pinned+ SDK understands; raw SSE parsing stays tolerant of those shape changes."""event_name: Optional[str] = Nonedata_lines: List[str] = []@@ -462,11 +341,9 @@ def _collect_image_b64() -> Optional[Dict[str, str]]:"""Stream a Codex Responses image_generation call.- Returns ``{\"b64\": ..., \"source\": \"final\"|\"partial\"}`` or ``None``.-- Final ``result`` frames are preferred across the whole stream. A progressive- ``partial_image_b64`` is retained only when no final result ever arrives;- callers must not treat partial-only as an unconditional success.+ Returns ``{"b64": ..., "source": "final"|"partial"}`` or ``None``. A+ progressive partial is retained only when no final result ever arrives;+ callers must not treat partial-only as success."""import httpxfrom agent.codex_headers import codex_cloudflare_headers@@ -478,10 +355,7 @@ def _collect_image_b64("Content-Type": "application/json",})payload = _build_responses_payload(- prompt=prompt,- size=size,- quality=quality,- input_images=input_images,+ prompt=prompt, size=size, quality=quality, input_images=input_images,)timeout = httpx.Timeout(300.0, connect=30.0, read=300.0, write=30.0, pool=30.0)@@ -511,11 +385,6 @@ def _collect_image_b64(return None-# ----------------------------------------------------------------------------# Provider-# -----------------------------------------------------------------------------class OpenAICodexImageGenProvider(ImageGenProvider):"""gpt-image-2 routed through ChatGPT/Codex OAuth instead of an API key."""@@ -537,16 +406,7 @@ class OpenAICodexImageGenProvider(ImageGenProvider):return Truedef list_models(self) -> List[Dict[str, Any]]:- return [- {- "id": model_id,- "display": meta["display"],- "speed": meta["speed"],- "strengths": meta["strengths"],- "price": "varies",- }- for model_id, meta in _MODELS.items()- ]+ return catalog_rows(_MODELS, price="varies")def default_model(self) -> Optional[str]:return DEFAULT_MODEL@@ -564,10 +424,8 @@ class OpenAICodexImageGenProvider(ImageGenProvider):}def capabilities(self) -> Dict[str, Any]:- # The Codex Responses image_generation tool accepts source/reference- # images as `input_image` message content parts. Keep this capability- # honest so the dynamic `image_generate` schema encourages identity-- # preserving edits instead of unrelated text-to-image redraws.+ # Source/reference images travel as `input_image` content parts; keep+ # this honest so the dynamic schema encourages identity-preserving edits.return {"modalities": ["text", "image"], "max_reference_images": _MAX_REFERENCE_IMAGES}def generate(@@ -583,71 +441,34 @@ class OpenAICodexImageGenProvider(ImageGenProvider):aspect = resolve_aspect_ratio(aspect_ratio)if not prompt:- return error_response(- error="Prompt is required and must be a non-empty string",- error_type="invalid_argument",- provider="openai-codex",- aspect_ratio=aspect,- )+ return prompt_required_error("openai-codex", aspect)- if not _read_codex_access_token():- return error_response(- error=(- "No Codex/ChatGPT OAuth credentials available. Run "- "`hermes auth codex` (or `hermes setup` → Codex) to sign in."- ),- error_type="auth_required",- provider="openai-codex",- aspect_ratio=aspect,- )+ token = _read_codex_access_token()+ if not token:+ return error_factory("openai-codex", aspect)(_NO_AUTH, "auth_required")try:import httpx # noqa: F401except ImportError:- return error_response(- error="httpx Python package not installed (pip install httpx)",- error_type="missing_dependency",- provider="openai-codex",- aspect_ratio=aspect,+ return error_factory("openai-codex", aspect)(+ "httpx Python package not installed (pip install httpx)", "missing_dependency")tier_id, meta = _resolve_model()- size = _SIZES.get(aspect, _SIZES["square"])-- token = _read_codex_access_token()- if not token:- return error_response(- error=(- "No Codex/ChatGPT OAuth credentials available. Run "- "`hermes auth codex` (or `hermes setup` → Codex) to sign in."- ),- error_type="auth_required",- provider="openai-codex",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ size = size_for(aspect)+ fail = error_factory("openai-codex", aspect, model=tier_id, prompt=prompt)+ attempts = _NONFINAL_RETRIES + 1try:input_images = _normalize_input_images(image_url, reference_image_urls)except Exception as exc:- return error_response(- error=f"Invalid image input for Codex image editing: {exc}",- error_type="invalid_image_input",- provider="openai-codex",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Invalid image input for Codex image editing: {exc}", "invalid_image_input")try:collected: Optional[Dict[str, str]] = None- for attempt in range(_NONFINAL_RETRIES + 1):+ for attempt in range(attempts):collected = _collect_image_b64(- token,- prompt=prompt,- size=size,- quality=meta["quality"],+ token, prompt=prompt, size=size, quality=meta["quality"],input_images=input_images or None,)if collected and collected.get("source") == "final" and collected.get("b64"):@@ -661,65 +482,34 @@ class OpenAICodexImageGenProvider(ImageGenProvider):logger.warning("Codex image stream ended with %s (attempt %s/%s); ""retrying once before failing closed.",- kind,- attempt + 1,- _NONFINAL_RETRIES + 1,+ kind, attempt + 1, attempts,)- continue- breakexcept Exception as exc:logger.debug("Codex image generation failed", exc_info=True)- return error_response(- error=f"OpenAI image generation via Codex auth failed: {exc}",- error_type="api_error",- provider="openai-codex",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"OpenAI image generation via Codex auth failed: {exc}", "api_error")if not collected or not collected.get("b64"):- return error_response(- error=(- "Codex response contained no image_generation_call result "- f"after {_NONFINAL_RETRIES + 1} attempt(s)"- ),- error_type="empty_response",- provider="openai-codex",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,+ return fail(+ f"Codex response contained no image_generation_call result after {attempts} attempt(s)",+ "empty_response",)image_source = collected.get("source") or "unknown"b64 = collected["b64"]- # Defense in depth: never deliver a progressive-only frame as success.- # Partials are intermediate previews and have presented as smeared /- # unfinished images when saved as finals.+ # Never deliver a progressive-only frame as success (smeared previews).if image_source != "final":- pixel_hint = Nonetry:- import base64 as _b64mod-- pixel_hint = _png_pixel_size(_b64mod.b64decode(b64, validate=False))+ pixel_hint = _png_pixel_size(base64.b64decode(b64, validate=False))except Exception:pixel_hint = Nonedetail = ("Codex returned only a progressive partial image frame after "- f"{_NONFINAL_RETRIES + 1} attempt(s); refusing to save it "- "as a final deliverable."+ f"{attempts} attempt(s); refusing to save it as a final deliverable.")if pixel_hint:detail = f"{detail} partial_pixel_size={pixel_hint}."- err = error_response(- error=detail,- error_type="incomplete_image",- provider="openai-codex",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ err = fail(detail, "incomplete_image")err["image_source"] = image_sourceerr["requested_size"] = sizeerr["partial_pixel_size"] = pixel_hint@@ -727,20 +517,10 @@ class OpenAICodexImageGenProvider(ImageGenProvider):return errtry:- import base64 as _b64mod-- raw_bytes = _b64mod.b64decode(b64)- pixel_size = _png_pixel_size(raw_bytes)+ pixel_size = _png_pixel_size(base64.b64decode(b64))saved_path = save_b64_image(b64, prefix=f"openai_codex_{tier_id}")except Exception as exc:- return error_response(- error=f"Could not save image to cache: {exc}",- error_type="io_error",- provider="openai-codex",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Could not save image to cache: {exc}", "io_error")return success_response(image=str(saved_path),@@ -760,11 +540,6 @@ class OpenAICodexImageGenProvider(ImageGenProvider):)-# ----------------------------------------------------------------------------# Plugin entry point-# -----------------------------------------------------------------------------def register(ctx) -> None:"""Plugin entry point — register the Codex-backed image-gen provider."""ctx.register_image_gen_provider(OpenAICodexImageGenProvider())diff --git a/plugins/image_gen/openai/__init__.py b/plugins/image_gen/openai/__init__.pyindex 6fc4bc58e04..3fb909f20bc 100644--- a/plugins/image_gen/openai/__init__.py+++ b/plugins/image_gen/openai/__init__.py@@ -1,24 +1,13 @@"""OpenAI image generation backend.-Exposes OpenAI's ``gpt-image-2`` model at three quality tiers as an-:class:`ImageGenProvider` implementation. The tiers are implemented as-three virtual model IDs so the ``hermes tools`` model picker and the-``image_gen.model`` config key behave like any other multi-model backend:-- gpt-image-2-low ~15s fastest, good for iteration- gpt-image-2-medium ~40s default — balanced- gpt-image-2-high ~2min slowest, highest fidelity--All three hit the same underlying API model (``gpt-image-2``) with a-different ``quality`` parameter. Output is base64 JSON → saved under+Exposes OpenAI's ``gpt-image-2`` model at three quality tiers+(``gpt-image-2-low`` ~15s, ``-medium`` ~40s default, ``-high`` ~2min) as+virtual model ids so the picker and ``image_gen.model`` behave like any other+multi-model backend. Output is base64 JSON → saved under``$HERMES_HOME/cache/images/``.-Selection precedence (first hit wins):--1. ``OPENAI_IMAGE_MODEL`` env var (escape hatch for scripts / tests)-2. ``image_gen.openai.model`` in ``config.yaml``-3. ``image_gen.model`` in ``config.yaml`` (when it's one of our tier IDs)-4. :data:`DEFAULT_MODEL` — ``gpt-image-2-medium``+Selection precedence: ``OPENAI_IMAGE_MODEL`` env → ``image_gen.openai.model``+→ ``image_gen.model`` (when it is one of our tier ids) → :data:`DEFAULT_MODEL`."""from __future__ import annotations@@ -31,105 +20,39 @@ from agent.secret_scope import get_secretfrom agent.image_gen_provider import (DEFAULT_ASPECT_RATIO,ImageGenProvider,- error_response,- normalize_reference_images,resolve_aspect_ratio,- save_b64_image,- save_url_image,success_response,)+from plugins.image_gen._common import (+ GPT_IMAGE_2_API_MODEL as API_MODEL,+ GPT_IMAGE_2_DEFAULT as DEFAULT_MODEL,+ GPT_IMAGE_2_TIERS,+ api_key_setup_schema,+ catalog_rows,+ collect_source_images,+ error_factory,+ import_openai,+ materialize_image,+ openai_importable,+ prompt_required_error,+ resolve_static_model,+ size_for,+)logger = logging.getLogger(__name__)--# ----------------------------------------------------------------------------# Model catalog-# ----------------------------------------------------------------------------#-# All three IDs resolve to the same underlying API model with a different-# ``quality`` setting. ``api_model`` is what gets sent to OpenAI;-# ``quality`` is the knob that changes generation time and output fidelity.--API_MODEL = "gpt-image-2"--_MODELS: Dict[str, Dict[str, Any]] = {- "gpt-image-2-low": {- "display": "GPT Image 2 (Low)",- "speed": "~15s",- "strengths": "Fast iteration, lowest cost",- "quality": "low",- },- "gpt-image-2-medium": {- "display": "GPT Image 2 (Medium)",- "speed": "~40s",- "strengths": "Balanced — default",- "quality": "medium",- },- "gpt-image-2-high": {- "display": "GPT Image 2 (High)",- "speed": "~2min",- "strengths": "Highest fidelity, strongest prompt adherence",- "quality": "high",- },-}--DEFAULT_MODEL = "gpt-image-2-medium"--_SIZES = {- "landscape": "1536x1024",- "square": "1024x1024",- "portrait": "1024x1536",-}---def _load_openai_config() -> Dict[str, Any]:- """Read ``image_gen`` from config.yaml (returns {} on any failure)."""- try:- from hermes_cli.config import load_config-- cfg = load_config()- section = cfg.get("image_gen") if isinstance(cfg, dict) else None- return section if isinstance(section, dict) else {}- except Exception as exc:- logger.debug("Could not load image_gen config: %s", exc)- return {}+_MODELS: Dict[str, Dict[str, Any]] = dict(GPT_IMAGE_2_TIERS)def _resolve_model() -> Tuple[str, Dict[str, Any]]:"""Decide which tier to use and return ``(model_id, meta)``."""- env_override = os.environ.get("OPENAI_IMAGE_MODEL")- if env_override and env_override in _MODELS:- return env_override, _MODELS[env_override]-- cfg = _load_openai_config()- openai_cfg = cfg.get("openai") if isinstance(cfg.get("openai"), dict) else {}- candidate: Optional[str] = None- if isinstance(openai_cfg, dict):- value = openai_cfg.get("model")- if isinstance(value, str) and value in _MODELS:- candidate = value- if candidate is None:- top = cfg.get("model")- if isinstance(top, str) and top in _MODELS:- candidate = top-- if candidate is not None:- return candidate, _MODELS[candidate]-- return DEFAULT_MODEL, _MODELS[DEFAULT_MODEL]---# ----------------------------------------------------------------------------# Source-image loading (for image-to-image / edit)-# ---------------------------------------------------------------------------+ return resolve_static_model(+ _MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai"+ )def _load_image_bytes(ref: str) -> Tuple[bytes, str]:- """Load image bytes from a URL or local file path.-- Returns ``(data, filename)``. Raises on any network / IO error so the- caller can surface a clean error_response.- """+ """Load ``(data, filename)`` from a URL, data URI or local path; raises on IO/network error."""ref = ref.strip()lower = ref.lower()if lower.startswith(("http://", "https://")):@@ -153,13 +76,7 @@ def _load_image_bytes(ref: str) -> Tuple[bytes, str]:raise_if_read_blocked(ref)with open(ref, "rb") as fh:data = fh.read()- name = os.path.basename(ref) or "image.png"- return data, name---# ----------------------------------------------------------------------------# Provider-# ---------------------------------------------------------------------------+ return data, os.path.basename(ref) or "image.png"class OpenAIImageGenProvider(ImageGenProvider):@@ -174,46 +91,24 @@ class OpenAIImageGenProvider(ImageGenProvider):return "OpenAI"def is_available(self) -> bool:- if not get_secret("OPENAI_API_KEY"):- return False- try:- import openai # noqa: F401- except ImportError:- return False- return True+ return bool(get_secret("OPENAI_API_KEY")) and openai_importable()def list_models(self) -> List[Dict[str, Any]]:- return [- {- "id": model_id,- "display": meta["display"],- "speed": meta["speed"],- "strengths": meta["strengths"],- "price": "varies",- }- for model_id, meta in _MODELS.items()- ]+ return catalog_rows(_MODELS, price="varies")def default_model(self) -> Optional[str]:return DEFAULT_MODELdef get_setup_schema(self) -> Dict[str, Any]:- return {- "name": "OpenAI",- "badge": "paid",- "tag": "gpt-image-2 at low/medium/high quality tiers — text-to-image & image editing",- "env_vars": [- {- "key": "OPENAI_API_KEY",- "prompt": "OpenAI API key",- "url": "https://platform.openai.com/api-keys",- },- ],- }+ return api_key_setup_schema(+ "OpenAI", "paid",+ "gpt-image-2 at low/medium/high quality tiers — text-to-image & image editing",+ key="OPENAI_API_KEY", prompt="OpenAI API key",+ url="https://platform.openai.com/api-keys",+ )def capabilities(self) -> Dict[str, Any]:- # gpt-image-2 supports editing via images.edit() with up to 16 source- # images.+ # images.edit() accepts up to 16 source images.return {"modalities": ["text", "image"], "max_reference_images": 16}def generate(@@ -229,54 +124,30 @@ class OpenAIImageGenProvider(ImageGenProvider):aspect = resolve_aspect_ratio(aspect_ratio)if not prompt:- return error_response(- error="Prompt is required and must be a non-empty string",- error_type="invalid_argument",- provider="openai",- aspect_ratio=aspect,- )+ return prompt_required_error("openai", aspect)api_key = get_secret("OPENAI_API_KEY")if not api_key:- return error_response(- error=(- "OPENAI_API_KEY not set. Run `hermes tools` → Image "- "Generation → OpenAI to configure, or `hermes setup` "- "to add the key."- ),- error_type="auth_required",- provider="openai",- aspect_ratio=aspect,+ return error_factory("openai", aspect)(+ "OPENAI_API_KEY not set. Run `hermes tools` → Image "+ "Generation → OpenAI to configure, or `hermes setup` "+ "to add the key.",+ "auth_required",)- try:- import openai- except ImportError:- return error_response(- error="openai Python package not installed (pip install openai)",- error_type="missing_dependency",- provider="openai",- aspect_ratio=aspect,- )+ openai, err = import_openai("openai", aspect)+ if err:+ return errtier_id, meta = _resolve_model()- size = _SIZES.get(aspect, _SIZES["square"])-- # Collect source images (primary + references) for image-to-image.- sources: List[str] = []- if isinstance(image_url, str) and image_url.strip():- sources.append(image_url.strip())- for ref in (normalize_reference_images(reference_image_urls) or []):- sources.append(ref)- sources = sources[:16] # gpt-image-2 edit caps at 16 images+ size = size_for(aspect)+ sources = collect_source_images(image_url, reference_image_urls, limit=16)is_edit = bool(sources)- modality = "image" if is_edit else "text"-+ fail = error_factory("openai", aspect, model=tier_id, prompt=prompt)client = openai.OpenAI(api_key=api_key)if is_edit:- # images.edit() expects file-like objects. Download/read each- # source into a named BytesIO so the SDK sends correct multipart.+ # images.edit() expects named file-like objects for correct multipart.import iotry:@@ -287,114 +158,46 @@ class OpenAIImageGenProvider(ImageGenProvider):bio.name = fnamefiles.append(bio)except Exception as exc:- return error_response(- error=f"Could not load source image for editing: {exc}",- error_type="io_error",- provider="openai",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Could not load source image for editing: {exc}", "io_error")try:response = client.images.edit(model=API_MODEL,image=files if len(files) > 1 else files[0],prompt=prompt,- size=size, # type: ignore[arg-type] # _SIZES values are valid gpt-image sizes+ size=size, # type: ignore[arg-type] # OPENAI_SIZES values are valid gpt-image sizesquality=meta["quality"],n=1,)except Exception as exc:logger.debug("OpenAI image edit failed", exc_info=True)- return error_response(- error=f"OpenAI image editing failed: {exc}",- error_type="api_error",- provider="openai",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"OpenAI image editing failed: {exc}", "api_error")else:# gpt-image-2 returns b64_json unconditionally and REJECTS# ``response_format`` as an unknown parameter. Don't send it.- payload: Dict[str, Any] = {- "model": API_MODEL,- "prompt": prompt,- "size": size,- "n": 1,- "quality": meta["quality"],- }-try:- response = client.images.generate(**payload)+ response = client.images.generate(+ model=API_MODEL, prompt=prompt, size=size, n=1, quality=meta["quality"],+ )except Exception as exc:logger.debug("OpenAI image generation failed", exc_info=True)- return error_response(- error=f"OpenAI image generation failed: {exc}",- error_type="api_error",- provider="openai",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"OpenAI image generation failed: {exc}", "api_error")data = getattr(response, "data", None) or []if not data:- return error_response(- error="OpenAI returned no image data",- error_type="empty_response",- provider="openai",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("OpenAI returned no image data", "empty_response")first = data[0]- b64 = getattr(first, "b64_json", None)- url = getattr(first, "url", None)- revised_prompt = getattr(first, "revised_prompt", None)-- if b64:- try:- saved_path = save_b64_image(b64, prefix=f"openai_{tier_id}")- except Exception as exc:- return error_response(- error=f"Could not save image to cache: {exc}",- error_type="io_error",- provider="openai",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )- image_ref = str(saved_path)- elif url:- # Defensive — gpt-image-2 returns b64 today, but OpenAI's API- # has previously returned URLs. Cache the bytes locally so the- # gateway never tries to fetch an ephemeral / signed URL after- # it expires — same rationale as the xAI provider (#26942).- try:- saved_path = save_url_image(url, prefix=f"openai_{tier_id}")- except Exception as exc:- logger.warning(- "OpenAI image URL %s could not be cached (%s); falling back to bare URL.",- url,- exc,- )- image_ref = url- else:- image_ref = str(saved_path)- else:- return error_response(- error="OpenAI response contained neither b64_json nor URL",- error_type="empty_response",- provider="openai",- model=tier_id,- prompt=prompt,- aspect_ratio=aspect,- )+ image_ref, err = materialize_image(+ getattr(first, "b64_json", None), getattr(first, "url", None),+ prefix=f"openai_{tier_id}", label="OpenAI", provider="openai",+ model=tier_id, prompt=prompt, aspect=aspect, log=logger,+ )+ if err:+ return errextra: Dict[str, Any] = {"size": size, "quality": meta["quality"]}+ revised_prompt = getattr(first, "revised_prompt", None)if revised_prompt:extra["revised_prompt"] = revised_prompt@@ -404,16 +207,11 @@ class OpenAIImageGenProvider(ImageGenProvider):prompt=prompt,aspect_ratio=aspect,provider="openai",- modality=modality,+ modality="image" if is_edit else "text",extra=extra,)-# ----------------------------------------------------------------------------# Plugin entry point-# -----------------------------------------------------------------------------def register(ctx) -> None:"""Plugin entry point — wire ``OpenAIImageGenProvider`` into the registry."""ctx.register_image_gen_provider(OpenAIImageGenProvider())diff --git a/plugins/image_gen/openrouter/__init__.py b/plugins/image_gen/openrouter/__init__.pyindex bb3f23e7031..4bff8f218ed 100644--- a/plugins/image_gen/openrouter/__init__.py+++ b/plugins/image_gen/openrouter/__init__.py@@ -2,61 +2,41 @@Both OpenRouter and the Nous Portal inference endpoint speak the sameOpenAI-style ``/chat/completions`` image-generation protocol: send-``modalities: ["image", "text"]`` with an image-output model (e.g.-``google/gemini-3-pro-image``), pass reference images as ``image_url``-content parts for grounding, and read the generated images back from-``choices[0].message.images[].image_url.url`` (a ``data:image/...;base64`` URI).--Nous Portal proxies OpenRouter, so one implementation services both — we only-swap the resolved ``(base_url, api_key)``. Credentials are resolved through the-agent's existing :func:`~hermes_cli.runtime_provider.resolve_runtime_provider`,-which already understands OpenRouter's key pool and the Nous OAuth device-code-token, so this plugin never reinvents auth.--Reference grounding is the reason pet sprite generation cares about this-backend: each animation row must stay the same character as the chosen base-frame, which only works on models that accept image input. Gemini Flash Image-("nano-banana") does, so both providers advertise image-to-image support.+``modalities: ["image", "text"]`` with an image-output model, pass reference+images as ``image_url`` content parts for grounding, and read generated+images back from ``choices[0].message.images[].image_url.url`` (a base64 data+URI). Nous Portal proxies OpenRouter, so one implementation services both —+only the resolved ``(base_url, api_key)`` differs, obtained through+:func:`~hermes_cli.runtime_provider.resolve_runtime_provider` (which already+understands OpenRouter's key pool and the Nous OAuth token).++Reference grounding matters for pet sprite generation: every animation row+must stay the same character as the base frame, which only works on models+that accept image input.Two request surfaces---------------------OpenRouter ships a *second*, entirely separate image surface: the **Dedicated-Image API** at ``POST /api/v1/images/generations``, with its own catalog-(``GET /api/v1/images/models``) and the full OpenAI-style parameter set.-``openai/gpt-image-2``, ``openai/gpt-image-1-mini``, ``krea/krea-2-*``,-``qwen/qwen-image-3-pro``, ``microsoft/mai-image-2.5*`` and-``x-ai/grok-imagine-image-quality`` are reachable *only* there.--Why routing is not "is it in the image catalog?"- The two catalogs **overlap**. As of 2026-08 ``GET /images/models`` lists 40- models, and that list includes this backend's own chat-completions defaults- (``openai/gpt-5.4-image-2`` and ``google/gemini-3-pro-image``). Routing on- catalog membership alone would therefore move every existing default call- off ``/chat/completions`` — a silent behaviour change for setups that work- today, and one that changes how reference images are passed (content parts- vs ``input_references``).--So the surface is chosen conservatively, per model, by-:func:`_select_surface`:--* ``image_gen.openrouter.surface`` / ``OPENROUTER_IMAGE_API_SURFACE`` forces- ``images`` or ``chat`` when an operator wants to decide themselves;-* otherwise (``auto``, the default) only ids in :data:`_IMAGE_API_MODELS` —- curated, and none of them reachable over chat-completions — take the new- path. The chat defaults stay pinned to chat-completions no matter what the- catalog says;-* an id in neither group keeps today's behaviour, and the cached, best-effort- ``GET /images/models`` probe is used only to log a one-line hint that the- model is available on the Image API and how to switch. Nothing reroutes- itself behind the operator's back, and a failed probe costs nothing.--On the Image API path the request gains exact per-model aspect ratios plus-``resolution`` / ``quality`` / ``background`` / ``seed`` / ``n`` /-``output_compression``, and up to 16 reference images instead of 3.--The Image API is OpenRouter-only: Nous Portal proxies the chat-completions-protocol and has no ``/images/generations`` route, so the second surface is-enabled per provider (see ``supports_image_api``) and stays off for Nous.+OpenRouter also ships a separate **Dedicated Image API** at+``POST /api/v1/images/generations`` with its own catalog+(``GET /api/v1/images/models``) and the full OpenAI-style parameter set;+``openai/gpt-image-2``, ``krea/krea-2-*``, ``qwen/qwen-image-3-pro``,+``microsoft/mai-image-2.5*`` … are reachable *only* there.++Routing is not "is it in the image catalog?" — the two catalogs overlap and+``/images/models`` lists this backend's own chat-completions defaults. Routing+on membership alone would silently move every default call off+``/chat/completions`` and change how references are passed (content parts vs+``input_references``). So :func:`_select_surface` decides conservatively:+``image_gen.openrouter.surface`` / ``OPENROUTER_IMAGE_API_SURFACE`` force a+surface; otherwise curated :data:`_IMAGE_API_MODELS` take the Image API, the+chat defaults stay pinned to chat-completions, and an id in neither table is+checked against the cached live catalog. On the Image API path the request+gains exact per-model aspect ratios plus ``resolution`` / ``quality`` /+``background`` / ``seed`` / ``n`` / ``output_compression`` and up to 16+reference images instead of 3.++The Image API is OpenRouter-only: Nous Portal has no ``/images/generations``+route, so the surface is enabled per provider (``supports_image_api``)."""from __future__ import annotations@@ -79,59 +59,62 @@ from agent.image_gen_provider import (save_url_image,success_response,)+from plugins.image_gen._common import (+ HttpFailure as HttpFailure,+ error_factory,+ load_image_gen_config,+ post_json,+)logger = logging.getLogger(__name__)-# Quality-first model chain for OpenRouter-compatible endpoints.-#-# Default behavior (no env/config override): try the highest-fidelity OpenAI-# image model first, then fall back to Gemini 3 Pro Image if the OpenAI model-# is access-gated / unavailable / times out on this endpoint.-#-# Explicit override (OPENROUTER_IMAGE_MODEL, image_gen.<provider>.model, or-# image_gen.model from ``hermes tools``): use exactly that model (no auto-# fallback), so power users keep full control.+# Quality-first default chain: try the highest-fidelity OpenAI image model,+# then fall back to Gemini 3 Pro Image if it is access-gated / unavailable /+# times out. Any explicit override (env, scoped config, or ``image_gen.model``+# from ``hermes tools``) means "use exactly that model", no auto fallback.DEFAULT_MODEL = "openai/gpt-5.4-image-2"_FALLBACK_MODEL = "google/gemini-3-pro-image"_DEFAULT_MODEL_CHAIN = (DEFAULT_MODEL, _FALLBACK_MODEL)+_MODEL_PRIORITY = {DEFAULT_MODEL: 0, _FALLBACK_MODEL: 1}-# Semantic aspect ratio (the image_gen contract) → OpenRouter's image_config-# aspect_ratio strings.-_ASPECT_RATIOS = {- "square": "1:1",- "landscape": "16:9",- "portrait": "9:16",-}+# Semantic aspect ratio → OpenRouter ``image_config.aspect_ratio``.+_ASPECT_RATIOS = {"square": "1:1", "landscape": "16:9", "portrait": "9:16"}-# Gemini Flash Image accepts up to 3 input images per prompt; clamp references-# so we never overflow the model's limit.+# Gemini Flash Image accepts up to 3 input images per prompt._MAX_REFERENCE_IMAGES = 3-# Per single image call. The quality-first default (OpenAI image via OpenRouter)-# is genuinely slow — a single cold row can run well past 3 minutes — so give-# each call real headroom before we treat it as hung and fall back / retry.+# Per single image call. The quality-first default is genuinely slow — a cold+# row can run past 3 minutes — so give each call real headroom before we treat+# it as hung and fall back / retry._REQUEST_TIMEOUT = 300.0+# Curated metadata for well-known chat-completions image models; anything else+# discovered via the live catalog gets a generic strengths line.+_KNOWN_MODEL_META = {+ DEFAULT_MODEL: {+ "display": "OpenAI GPT-5.4 Image 2",+ "strengths": "Highest fidelity; best prompt adherence; slower on OpenRouter",+ },+ _FALLBACK_MODEL: {+ "display": "Gemini 3 Pro Image",+ "strengths": "Fast, reliable fallback with good layout adherence",+ },+}++# Router pseudo-models advertise image output but are not image models.+_EXCLUDED_MODEL_PREFIXES = ("openrouter/auto",)-def _load_image_gen_config() -> Dict[str, Any]:- """Read the ``image_gen`` section from config.yaml (``{}`` on failure)."""- try:- from hermes_cli.config import load_config+_LIVE_CACHE_TTL = 300.0+_LIVE_TIMEOUT = 10.0- cfg = load_config()- section = cfg.get("image_gen") if isinstance(cfg, dict) else None- return section if isinstance(section, dict) else {}- except Exception as exc: # noqa: BLE001 - config is best-effort- logger.debug("could not load image_gen config: %s", exc)- return {}+_load_image_gen_config = load_image_gen_configdef _to_image_url_part(ref: str) -> Optional[str]:"""Turn a reference (local path or http URL) into an ``image_url`` value.- Remote URLs pass through unchanged; local files are inlined as base64 data- URIs so the request is self-contained (the provider endpoint can't reach a- path on our disk). Returns ``None`` when the reference can't be read.+ Remote URLs pass through; local files are inlined as base64 data URIs so+ the request is self-contained. ``None`` when the reference can't be read."""ref = str(ref or "").strip()if not ref:@@ -149,29 +132,18 @@ def _to_image_url_part(ref: str) -> Optional[str]:logger.debug("could not read reference image %s: %s", ref, exc)return Nonemime = mimetypes.guess_type(path.name)[0] or "image/png"- encoded = base64.b64encode(raw).decode("ascii")- return f"data:{mime};base64,{encoded}"+ return f"data:{mime};base64,{base64.b64encode(raw).decode('ascii')}"def _extract_images(payload: Dict[str, Any]) -> List[str]:- """Pull generated image URLs from a chat-completions response.-- OpenRouter returns generated images under- ``choices[0].message.images[].image_url.url`` (typically a base64 data URI).- """+ """Generated image URLs from ``choices[].message.images[].image_url.url``."""out: List[str] = []choices = payload.get("choices") if isinstance(payload, dict) else None- if not isinstance(choices, list):- return out- for choice in choices:+ for choice in choices if isinstance(choices, list) else []:message = choice.get("message") if isinstance(choice, dict) else Noneimages = message.get("images") if isinstance(message, dict) else None- if not isinstance(images, list):- continue- for image in images:- if not isinstance(image, dict):- continue- image_url = image.get("image_url")+ for image in images if isinstance(images, list) else []:+ image_url = image.get("image_url") if isinstance(image, dict) else Noneurl = image_url.get("url") if isinstance(image_url, dict) else Noneif isinstance(url, str) and url.strip():out.append(url.strip())@@ -181,13 +153,11 @@ def _extract_images(payload: Dict[str, Any]) -> List[str]:def _access_error_hint(display: str, model_id: str, env_var: str, status: int, err_msg: str) -> Optional[str]:- """A targeted hint when an access-gated OpenAI image model can't be reached.+ """One actionable line when an access-gated OpenAI image model is unreachable.- Some OpenAI image models on OpenRouter need account enablement / BYOK, so the- failure isn't a missing key (the key is valid) — the *model* is unreachable.- The generic "check your key" message is misleading there, so we detect that- case and point the user at the real fix. Returns one actionable line, or- ``None`` when this isn't the access-gated case.+ Some OpenAI image models on OpenRouter need account enablement / BYOK, so+ the key is valid but the *model* is unreachable and "check your key" would+ mislead. ``None`` when this isn't that case."""if not model_id.startswith("openai/"):return None@@ -203,109 +173,68 @@ def _access_error_hint()-def _dedupe_models(models: list[str]) -> list[str]:- out: list[str] = []- seen: set[str] = set()- for model in models:- m = (model or "").strip()- if not m or m in seen:- continue- seen.add(m)- out.append(m)- return out---# Curated metadata for well-known image models; anything else discovered via-# the live catalog gets a generic strengths line.-_KNOWN_MODEL_META = {- DEFAULT_MODEL: {- "display": "OpenAI GPT-5.4 Image 2",- "strengths": "Highest fidelity; best prompt adherence; slower on OpenRouter",- },- _FALLBACK_MODEL: {- "display": "Gemini 3 Pro Image",- "strengths": "Fast, reliable fallback with good layout adherence",- },-}--# Router pseudo-models advertise image output but are not image models.-_EXCLUDED_MODEL_PREFIXES = ("openrouter/auto",)+def _fetch_catalog(+ base_url: str, api_key: str, *, path: str, meta: Dict[str, Dict[str, Any]],+ generic: str, image_output_only: bool,+) -> List[Dict[str, Any]]:+ """Picker rows from ``GET {base_url}{path}``; raises on failure.-_LIVE_CACHE_TTL = 300.0-_LIVE_TIMEOUT = 10.0---def _fetch_live_image_models(base_url: str, api_key: str) -> List[Dict[str, Any]]:- """List image-output models from the endpoint's ``/models`` catalog.-- Filters on ``architecture.output_modalities`` containing ``image`` and- drops router pseudo-models (``openrouter/auto*``). Raises on failure —- callers fall back to the static default chain.+ ``image_output_only`` keeps entries whose ``architecture.output_modalities``+ includes ``image`` and drops router pseudo-models. Curated ``meta`` wins+ for known ids; unknown ones get the API name and ``generic`` strengths."""import requestsresponse = requests.get(- f"{base_url}/models",+ f"{base_url}{path}",headers={"Authorization": f"Bearer {api_key}"} if api_key else {},timeout=_LIVE_TIMEOUT,)response.raise_for_status()- entries = response.json().get("data") or []out: List[Dict[str, Any]] = []- for entry in entries:+ for entry in response.json().get("data") or []:if not isinstance(entry, dict):continuemodel_id = entry.get("id")if not isinstance(model_id, str) or not model_id.strip():continuemodel_id = model_id.strip()- if model_id.startswith(_EXCLUDED_MODEL_PREFIXES):- continuearch_raw = entry.get("architecture")arch: Dict[str, Any] = arch_raw if isinstance(arch_raw, dict) else {}- if "image" not in (arch.get("output_modalities") or []):+ if image_output_only and (+ model_id.startswith(_EXCLUDED_MODEL_PREFIXES)+ or "image" not in (arch.get("output_modalities") or [])+ ):continue- meta = _KNOWN_MODEL_META.get(model_id, {})- out.append(- {- "id": model_id,- "display": meta.get("display", entry.get("name") or model_id),- "strengths": meta.get(- "strengths", "Image-output model (from live OpenRouter catalog)"- ),- "input_modalities": arch.get("input_modalities") or [],- }- )- # Stable order: defaults first, then alphabetical.- priority = {DEFAULT_MODEL: 0, _FALLBACK_MODEL: 1}- out.sort(key=lambda m: (priority.get(m["id"], 2), m["id"]))+ known = meta.get(model_id, {})+ out.append({+ "id": model_id,+ "display": known.get("display", entry.get("name") or model_id),+ "strengths": known.get("strengths", generic),+ "input_modalities": arch.get("input_modalities") or [],+ })return out# ===========================================================================# OpenRouter Dedicated Image API (POST /images/generations)# ===========================================================================-#-# Everything below serves the second surface described in the module docstring.-# The chat-completions path above is untouched.-#: Env prefix for the Image API knobs (``OPENROUTER_IMAGE_API_QUALITY`` …).-#: Deliberately distinct from ``OPENROUTER_IMAGE_MODEL``, which selects the-#: model on either surface.+#: Env prefix for the Image API knobs (``OPENROUTER_IMAGE_API_QUALITY`` …),+#: distinct from ``OPENROUTER_IMAGE_MODEL`` which selects the model on either surface._IMAGE_API_ENV_PREFIX = "OPENROUTER_IMAGE_API_"-#: Connect budget, separate from the read budget. If DNS + TCP + TLS hasn't-#: completed in 20s the endpoint is effectively down, and waiting out the full-#: generation timeout only delays the error.+#: Connect budget, separate from the read budget: if DNS + TCP + TLS hasn't+#: completed in 20s the endpoint is down, and waiting out the generation+#: timeout only delays the error._IMAGE_API_CONNECT_TIMEOUT = 20.0-#: How long a fetched ``/images/models`` catalog stays usable. The catalog only-#: grows, and a stale entry costs one wasted 404 at worst.+#: How long a fetched ``/images/models`` catalog stays usable. It only grows,+#: and a stale entry costs one wasted 404 at worst._CATALOG_TTL_SECONDS = 900.0-#: Cached catalog probes, keyed by base URL: ``(fetched_at, model_ids)``. An-#: empty set is cached too, so a failing endpoint is probed once per TTL rather-#: than on every call.+#: Cached catalog probes keyed by base URL: ``(fetched_at, model_ids)``. Empty+#: sets are cached too, so a failing endpoint is probed once per TTL._CATALOG_CACHE: Dict[str, Tuple[float, frozenset]] = {}_GEMINI_RATIOS = (@@ -314,122 +243,94 @@ _GEMINI_RATIOS = ()_MAI_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "auto")_KREA_RATIOS = ("1:1", "4:3", "3:2", "16:9", "4:5", "2:3", "9:16")+_NO_KNOBS = {"quality": (), "background": (), "output_format": (), "compression": False, "seed": False}+-#: Curated Image API models and the parameters each one declares in-#: ``GET /images/models`` (catalog snapshot 2026-08). The catalog is larger and-#: keeps growing; an id missing from here still works — it just gets no-#: per-model parameter filtering, and it costs one cached catalog probe to-#: recognise. Keys mirror the payload field they gate; an empty tuple means the-#: model has no such knob.+def _image_api_model(display: str, strengths: str, **spec: Any) -> Dict[str, Any]:+ """Curated Image API model entry; unspecified knobs default to "not supported"."""+ return {"display": display, "strengths": strengths, **_NO_KNOBS, "resolutions": (), **spec}+++#: Curated Image API models and the parameters each declares in+#: ``GET /images/models``. The catalog is larger and keeps growing; an id+#: missing here still works — it just gets no per-model parameter filtering+#: and costs one cached catalog probe to recognise. Keys mirror the payload+#: field they gate; an empty tuple means the model has no such knob._IMAGE_API_MODELS: Dict[str, Dict[str, Any]] = {- "google/gemini-3.1-flash-lite-image": {- "display": "Nano Banana 2 Lite (Gemini 3.1 Flash Lite Image)",- "strengths": "Cheap and fast; 14 exact aspect ratios; 14 reference images",- "aspect_ratios": _GEMINI_RATIOS,- "resolutions": ("1K",),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": False, "max_n": 1, "max_refs": 14,- },- "google/gemini-3.1-flash-image": {- "display": "Nano Banana 2 (Gemini 3.1 Flash Image)",- "strengths": "Same ratios as Lite plus resolution control (512/1K/2K/4K)",- "aspect_ratios": _GEMINI_RATIOS,- "resolutions": ("512", "1K", "2K", "4K"),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": False, "max_n": 1, "max_refs": 14,- },- "openai/gpt-image-2": {- "display": "OpenAI GPT Image 2",- "strengths": "Best editing fidelity; up to 16 references; strongest prompt adherence",- "aspect_ratios": ("1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16", "21:9", "auto"),- "resolutions": (),- "quality": ("auto", "low", "medium", "high"),- "background": ("auto", "opaque"), "output_format": (),- "compression": True, "seed": False, "max_n": 10, "max_refs": 16,- },- "openai/gpt-image-1-mini": {- "display": "OpenAI GPT Image 1 Mini",- "strengths": "The only model here with background=transparent (cut-out PNG)",- "aspect_ratios": ("1:1", "3:2", "2:3", "auto"),- "resolutions": (),- "quality": ("auto", "low", "medium", "high"),- "background": ("auto", "transparent", "opaque"), "output_format": (),- "compression": True, "seed": False, "max_n": 10, "max_refs": 16,- },- "microsoft/mai-image-2.5": {- "display": "Microsoft MAI-Image-2.5",- "strengths": "Standard ratios; a good second opinion next to Gemini",- "aspect_ratios": _MAI_RATIOS, "resolutions": (),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": False, "max_n": 1, "max_refs": 1,- },- "microsoft/mai-image-2.5-pro": {- "display": "Microsoft MAI-Image-2.5 Pro",- "strengths": "Reach for it when gpt-image-2 misses the brief",- "aspect_ratios": _MAI_RATIOS, "resolutions": (),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": False, "max_n": 1, "max_refs": 1,- },- "x-ai/grok-imagine-image-quality": {- "display": "Grok Imagine (Image Quality)",- "strengths": "Photoreal; widest exotic-ratio set (9:19.5, 20:9, 2:1 …); 1K/2K",- "aspect_ratios": (+ "google/gemini-3.1-flash-lite-image": _image_api_model(+ "Nano Banana 2 Lite (Gemini 3.1 Flash Lite Image)",+ "Cheap and fast; 14 exact aspect ratios; 14 reference images",+ aspect_ratios=_GEMINI_RATIOS, resolutions=("1K",), max_n=1, max_refs=14,+ ),+ "google/gemini-3.1-flash-image": _image_api_model(+ "Nano Banana 2 (Gemini 3.1 Flash Image)",+ "Same ratios as Lite plus resolution control (512/1K/2K/4K)",+ aspect_ratios=_GEMINI_RATIOS, resolutions=("512", "1K", "2K", "4K"), max_n=1, max_refs=14,+ ),+ "openai/gpt-image-2": _image_api_model(+ "OpenAI GPT Image 2",+ "Best editing fidelity; up to 16 references; strongest prompt adherence",+ aspect_ratios=("1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16", "21:9", "auto"),+ quality=("auto", "low", "medium", "high"), background=("auto", "opaque"),+ compression=True, max_n=10, max_refs=16,+ ),+ "openai/gpt-image-1-mini": _image_api_model(+ "OpenAI GPT Image 1 Mini",+ "The only model here with background=transparent (cut-out PNG)",+ aspect_ratios=("1:1", "3:2", "2:3", "auto"),+ quality=("auto", "low", "medium", "high"), background=("auto", "transparent", "opaque"),+ compression=True, max_n=10, max_refs=16,+ ),+ "microsoft/mai-image-2.5": _image_api_model(+ "Microsoft MAI-Image-2.5", "Standard ratios; a good second opinion next to Gemini",+ aspect_ratios=_MAI_RATIOS, max_n=1, max_refs=1,+ ),+ "microsoft/mai-image-2.5-pro": _image_api_model(+ "Microsoft MAI-Image-2.5 Pro", "Reach for it when gpt-image-2 misses the brief",+ aspect_ratios=_MAI_RATIOS, max_n=1, max_refs=1,+ ),+ "x-ai/grok-imagine-image-quality": _image_api_model(+ "Grok Imagine (Image Quality)",+ "Photoreal; widest exotic-ratio set (9:19.5, 20:9, 2:1 …); 1K/2K",+ aspect_ratios=("1:1", "3:4", "4:3", "9:16", "16:9", "2:3", "3:2","9:19.5", "19.5:9", "9:20", "20:9", "1:2", "2:1", "auto",),- "resolutions": ("1K", "2K"),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": False, "max_n": 1, "max_refs": 3,- },- "krea/krea-2-medium": {- "display": "Krea 2 Medium",- "strengths": "Realistic, expressive styles; deterministic via seed",- "aspect_ratios": _KREA_RATIOS, "resolutions": ("1K",),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": True, "max_n": 1, "max_refs": 1,- },- "krea/krea-2-medium-turbo": {- "display": "Krea 2 Medium Turbo",- "strengths": "Cheapest here — bulk content, cards, thumbnails; seed support",- "aspect_ratios": _KREA_RATIOS, "resolutions": ("1K",),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": True, "max_n": 1, "max_refs": 1,- },- "qwen/qwen-image-3-pro": {- "display": "Qwen Image 3 Pro",- "strengths": "Precise small text and detail rendering; n up to 6; 1K/2K; seed",- "aspect_ratios": (+ resolutions=("1K", "2K"), max_n=1, max_refs=3,+ ),+ "krea/krea-2-medium": _image_api_model(+ "Krea 2 Medium", "Realistic, expressive styles; deterministic via seed",+ aspect_ratios=_KREA_RATIOS, resolutions=("1K",), seed=True, max_n=1, max_refs=1,+ ),+ "krea/krea-2-medium-turbo": _image_api_model(+ "Krea 2 Medium Turbo", "Cheapest here — bulk content, cards, thumbnails; seed support",+ aspect_ratios=_KREA_RATIOS, resolutions=("1K",), seed=True, max_n=1, max_refs=1,+ ),+ "qwen/qwen-image-3-pro": _image_api_model(+ "Qwen Image 3 Pro", "Precise small text and detail rendering; n up to 6; 1K/2K; seed",+ aspect_ratios=("1:1", "1:2", "1:4", "2:1", "2:3", "3:2", "3:4","4:1", "4:3", "4:5", "5:4", "9:16", "16:9",),- "resolutions": ("1K", "2K"),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": True, "max_n": 6, "max_refs": 4,- },+ resolutions=("1K", "2K"), seed=True, max_n=6, max_refs=4,+ ),}-#: Applied to a catalog model this table doesn't describe, so a newly released-#: id still generates instead of erroring out. Empty ``aspect_ratios`` means-#: "enum unknown" and the field is omitted rather than guessed.-_UNKNOWN_IMAGE_API_MODEL: Dict[str, Any] = {- "display": "", "strengths": "",- "aspect_ratios": (), "resolutions": (),- "quality": (), "background": (), "output_format": (),- "compression": False, "seed": False, "max_n": 1, "max_refs": 16,-}+#: Applied to a catalog model the table doesn't describe, so a newly released+#: id still generates. Empty ``aspect_ratios`` means "enum unknown" and the+#: field is omitted rather than guessed.+_UNKNOWN_IMAGE_API_MODEL = _image_api_model("", "", aspect_ratios=(), max_n=1, max_refs=16)-#: The union of exact ratios the endpoint's validator accepts across all-#: models. Used to sanity-check an override aimed at a model whose own enum we-#: don't know.+#: Union of exact ratios the endpoint's validator accepts across all models;+#: sanity-checks an override aimed at a model whose own enum we don't know._ENDPOINT_ASPECT_RATIOS = frozenset({"1:1", "1:2", "1:4", "1:8", "2:1", "2:3", "3:2", "3:4", "4:1", "4:3","4:5", "5:4", "8:1", "9:16", "16:9", "9:19.5", "19.5:9", "9:20", "20:9","9:21", "21:9", "auto",})-#: Semantic ratio → exact ratios, best first. The first one the model supports-#: wins, so ``landscape`` lands on 16:9 where it exists and degrades to 3:2 on-#: ``gpt-image-1-mini``, which has no 16:9 at all.+#: Semantic ratio → exact ratios, best first. ``landscape`` lands on 16:9 where+#: it exists and degrades to 3:2 on ``gpt-image-1-mini``, which has no 16:9._ASPECT_PREFERENCES: Dict[str, Tuple[str, ...]] = {"landscape": ("16:9", "3:2", "4:3", "5:4", "21:9", "2:1", "19.5:9", "20:9", "4:1", "8:1"),"portrait": ("9:16", "2:3", "3:4", "4:5", "9:21", "1:2", "9:19.5", "9:20", "1:4", "1:8"),@@ -446,11 +347,15 @@ _MEDIA_TYPE_EXTENSIONS = {}#: HTTP statuses worth retrying on the next model of the chain. 400 is our own-#: payload being wrong and would repeat; 401/403 are account-level and are-#: answered before this set is consulted. 502 matters because the Image API-#: bills all-or-nothing and reports a failed (unbilled) generation that way.+#: payload and would repeat; 401/403 are account-level and answered before this+#: set is consulted. 502 matters because the Image API bills all-or-nothing and+#: reports a failed (unbilled) generation that way._IMAGE_API_FALLBACK_STATUSES = frozenset({402, 404, 408, 409, 425, 429, 500, 502, 503, 504})+#: Ids that stay on ``/chat/completions`` whatever the image catalog says —+#: they are this backend's tested defaults (see the module docstring).+_CHAT_ONLY_MODELS = frozenset({DEFAULT_MODEL, _FALLBACK_MODEL})+def _image_api_model_meta(model_id: str) -> Dict[str, Any]:"""Catalog metadata for *model_id*, or permissive defaults when unknown."""@@ -493,22 +398,14 @@ def _fetch_image_api_catalog(base_url: str, api_key: str) -> frozenset:return resolved-#: Ids that stay on ``/chat/completions`` whatever the image catalog says.-#: Both are *in* that catalog, but they are this backend's tested defaults and-#: rerouting them would be a silent behaviour change — see the module docstring.-_CHAT_ONLY_MODELS = frozenset({DEFAULT_MODEL, _FALLBACK_MODEL})---def _select_surface(model_id: str, base_url: str, api_key: str, config_key: str) -> str:"""Return ``"images"`` or ``"chat"`` for *model_id*.- Deterministic and offline for curated ids: the decision comes from- :data:`_IMAGE_API_MODELS` and :data:`_CHAT_ONLY_MODELS`. An id in neither- table is checked against the (cached) live ``/images/models`` catalog —- models the dedicated API serves route there, so a model picked from the- live picker works even when it postdates the curated snapshot. Offline- the probe returns empty and unknown ids stay on chat-completions.+ Deterministic and offline for curated ids (:data:`_IMAGE_API_MODELS`,+ :data:`_CHAT_ONLY_MODELS`). An id in neither table is checked against the+ cached live ``/images/models`` catalog — a positive probe must route there,+ since staying on chat would 404/400 a model the live picker offered.+ Offline the probe is empty and unknown ids stay on chat-completions."""if not model_id:return "chat"@@ -519,31 +416,20 @@ def _select_surface(model_id: str, base_url: str, api_key: str, config_key: str)if model_id in _CHAT_ONLY_MODELS:return "chat"- if model_id in _IMAGE_API_MODELS:- return "images"-- # Unknown id: the live catalog decides. Most of the endpoint's image- # models exist only on the dedicated API, so a positive probe must route- # there — staying on chat would 404/400 a model the live picker offered.- if model_id in _fetch_image_api_catalog(base_url, api_key):+ if model_id in _IMAGE_API_MODELS or model_id in _fetch_image_api_catalog(base_url, api_key):return "images"return "chat"def _image_api_setting(name: str, explicit: Any, config_key: str) -> Any:- """Resolve one Image API knob: call kwarg → env → scoped config.-- ``name`` is the payload field (``quality``); the env var checked is- ``OPENROUTER_IMAGE_API_QUALITY``. Blank strings count as unset, so an empty- env var doesn't shadow config.- """+ """Resolve one Image API knob: call kwarg → ``OPENROUTER_IMAGE_API_<NAME>``+ env → scoped config. Blank strings count as unset."""if explicit is not None and not (isinstance(explicit, str) and not explicit.strip()):return explicitenv_value = os.environ.get(f"{_IMAGE_API_ENV_PREFIX}{name.upper()}", "").strip()if env_value:return env_value- cfg = _load_image_gen_config()- scoped = cfg.get(config_key)+ scoped = _load_image_gen_config().get(config_key)value = scoped.get(name) if isinstance(scoped, dict) else Noneif isinstance(value, str):return value.strip() or None@@ -572,9 +458,9 @@ def _pick_exact_aspect_ratio(forced: Optional[str],notes: List[str],) -> Optional[str]:- """Choose the exact ``aspect_ratio`` to send, or ``None`` to omit it.+ """Exact ``aspect_ratio`` to send, or ``None`` to omit it.- *forced* is an exact ratio from config/env/kwarg. It wins when the model+ *forced* (an exact ratio from config/env/kwarg) wins when the modelsupports it; otherwise the downgrade is noted and the per-model mapping of*semantic* applies."""@@ -590,10 +476,9 @@ def _pick_exact_aspect_ratio()if not supported:- # A model outside the table: we don't know its enum, and an- # out-of-enum aspect_ratio is a hard 400 (unlike an unknown- # *parameter*, which the endpoint ignores). Omitting the field lets the- # model apply its own default instead of failing every call.+ # Unknown enum: an out-of-enum aspect_ratio is a hard 400 (unlike an+ # unknown *parameter*, which the endpoint ignores), so omit the field+ # and let the model apply its own default.notes.append("model is not in this backend's catalog, so its aspect_ratio enum is "f"unknown; the field was omitted and '{semantic}' was not applied"@@ -604,9 +489,7 @@ def _pick_exact_aspect_ratio(if candidate in supported:return candidate- if "auto" in supported:- return "auto"- return supported[0] if supported else None+ return "auto" if "auto" in supported else supported[0]def _image_api_enum(@@ -615,13 +498,15 @@ def _image_api_enum(meta: Dict[str, Any],config_key: str,notes: List[str],+ *,+ meta_key: Optional[str] = None,) -> Optional[str]:"""Resolve an enum knob and drop it when this model doesn't accept it."""value = _image_api_setting(name, explicit, config_key)if not isinstance(value, str) or not value.strip():return Nonevalue = value.strip()- allowed: Tuple[str, ...] = tuple(meta.get(name) or ())+ allowed: Tuple[str, ...] = tuple(meta.get(meta_key or name) or ())if not allowed:notes.append(f"'{name}' is not supported by this model; dropped")return None@@ -647,58 +532,37 @@ def _build_image_api_payload(Every optional knob is filtered against what the model declares, because aparameter the model doesn't know is silently *ignored* by the endpoint —- which would otherwise let a caller believe ``background=transparent`` took- effect on a model that has no transparency.+ which would let a caller believe ``background=transparent`` took effect on+ a model that has no transparency."""meta = _image_api_model_meta(model_id)notes: List[str] = []payload: Dict[str, Any] = {"model": model_id, "prompt": prompt}- forced_ratio = _image_api_setting(- "aspect_ratio", kwargs.get("aspect_ratio_exact"), config_key- )+ forced_ratio = _image_api_setting("aspect_ratio", kwargs.get("aspect_ratio_exact"), config_key)ratio = _pick_exact_aspect_ratio(semantic_aspect, meta, forced_ratio, notes)if ratio:payload["aspect_ratio"] = ratio- resolution = _image_api_setting("resolution", kwargs.get("resolution"), config_key)- if isinstance(resolution, str) and resolution.strip():- allowed = tuple(meta.get("resolutions") or ())- value = resolution.strip()- if allowed and value in allowed:- payload["resolution"] = value- elif allowed:- notes.append(- f"'resolution={value}' is not valid for this model "- f"(accepts {', '.join(allowed)}); dropped"- )- else:- notes.append("'resolution' is not supported by this model; dropped")-- for enum_name, explicit in (- ("quality", kwargs.get("quality")),- ("background", kwargs.get("background")),- ("output_format", kwargs.get("output_format")),+ for enum_name, meta_key in (+ ("resolution", "resolutions"), ("quality", None), ("background", None), ("output_format", None),):- value = _image_api_enum(enum_name, explicit, meta, config_key, notes)+ value = _image_api_enum(+ enum_name, kwargs.get(enum_name), meta, config_key, notes, meta_key=meta_key+ )if value:payload[enum_name] = value- compression = _coerce_int(- _image_api_setting("output_compression", kwargs.get("output_compression"), config_key)- )- if compression is not None:- if meta.get("compression"):- payload["output_compression"] = max(0, min(100, compression))- else:- notes.append("'output_compression' is not supported by this model; dropped")-- seed = _coerce_int(_image_api_setting("seed", kwargs.get("seed"), config_key))- if seed is not None:- if meta.get("seed"):- payload["seed"] = seed- else:- notes.append("'seed' is not supported by this model; dropped")+ for name, gate, clamp in (+ ("output_compression", "compression", lambda v: max(0, min(100, v))),+ ("seed", "seed", lambda v: v),+ ):+ value = _coerce_int(_image_api_setting(name, kwargs.get(name), config_key))+ if value is not None:+ if meta.get(gate):+ payload[name] = clamp(value)+ else:+ notes.append(f"'{name}' is not supported by this model; dropped")count = _coerce_int(_image_api_setting("n", kwargs.get("n"), config_key))if count is not None and count > 1:@@ -728,8 +592,7 @@ def _extract_image_api_error(response: Any, fallback: str) -> str:``{"error": {"message", "code"}}`` covers routing / auth / unknown model;``{"success": false, "error": {"name": "ZodError", "message": "<json>"}}``- covers request validation, where ``message`` is a JSON-encoded array of- issues that is unreadable as-is.+ covers request validation, where ``message`` is a JSON-encoded issue array."""if response is None:return fallback@@ -776,11 +639,8 @@ def _model_slug(model_id: str) -> str:def _save_image_api_entry(entry: Dict[str, Any], prefix: str) -> Optional[str]:- """Persist one ``data[]`` entry to the image cache; return its path.-- ``None`` when the entry carries neither base64 nor a URL. Raises on write- failure so the caller can report ``io_error``.- """+ """Persist one ``data[]`` entry to the image cache; ``None`` when it carries+ neither base64 nor a URL. Raises on write failure (caller reports ``io_error``)."""b64 = entry.get("b64_json")if isinstance(b64, str) and b64.strip():return str(save_b64_image(b64, prefix=prefix, extension=_extension_for(entry.get("media_type"))))@@ -795,9 +655,9 @@ def _save_image_api_entry(entry: Dict[str, Any], prefix: str) -> Optional[str]:class OpenRouterCompatImageProvider(ImageGenProvider):"""Image generation over an OpenRouter-compatible chat-completions endpoint.- Instantiated once per backend (OpenRouter, Nous Portal). The two differ only- in which runtime provider supplies ``(base_url, api_key)`` and in the config- namespace used for the model override.+ Instantiated once per backend (OpenRouter, Nous Portal); they differ only+ in which runtime provider supplies ``(base_url, api_key)``, the config+ namespace for the model override, and Image API support."""def __init__(@@ -819,9 +679,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):self._setup_schema = setup_schemaself._live_models_cache: Optional[tuple] = Noneself._image_api_models_cache: Optional[tuple] = None- # OpenRouter only: Nous Portal proxies the chat-completions protocol- # and has no /images/generations route, so routing a model there would- # turn a working setup into a 404.+ # OpenRouter only: Nous Portal has no /images/generations route.self._supports_image_api = supports_image_api@property@@ -838,42 +696,41 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return resolve_runtime_provider(requested=self._runtime_name)+ def _credentials(self) -> Tuple[str, str]:+ """``(api_key, base_url)`` — either may be ``""``; raises on resolution failure."""+ runtime = self._resolve_runtime()+ return (+ str(runtime.get("api_key") or "").strip(),+ str(runtime.get("base_url") or "").strip().rstrip("/"),+ )+def is_available(self) -> bool:try:- runtime = self._resolve_runtime()+ return bool(self._credentials()[0])except Exception as exc: # noqa: BLE001 - treat resolution failure as unavailablelogger.debug("%s runtime resolution failed: %s", self._name, exc)return False- return bool(str(runtime.get("api_key") or "").strip())def capabilities(self) -> Dict[str, Any]:- # Both text-to-image and image-to-image (reference grounding) — the- # latter is what makes this backend usable for pet sprite rows.+ # Text-to-image and image-to-image (reference grounding). Image API+ # models take far more references than chat-completions, so report the+ # cap of the model that would service the next call.max_refs = _MAX_REFERENCE_IMAGESif self._supports_image_api:- # Report the cap of the model that would actually service the next- # call, so the tool schema advertises the right number. Image API- # models take far more references than chat-completions does.chain = self._resolve_model_chain()resolved = chain[0] if chain else ""if resolved in _IMAGE_API_MODELS:max_refs = int(_image_api_model_meta(resolved).get("max_refs") or max_refs)- return {- "modalities": ["text", "image"],- "max_reference_images": max_refs,- }+ return {"modalities": ["text", "image"], "max_reference_images": max_refs}def list_models(self) -> List[Dict[str, Any]]:"""Picker catalog: the endpoint's full live image-model surface.- For Image-API-capable backends (OpenRouter) this is the union of the- dedicated ``GET /images/models`` catalog (40+ models: Seedream, Flux,- Recraft, Qwen, MAI, Krea, ...) and the chat-completions image models,- so every image model the endpoint serves — including ones released- after this code shipped — is selectable in ``hermes tools``. Nous+ OpenRouter: union of ``GET /images/models`` (40+ models) and the+ chat-completions image models, so every image model the endpoint serves+ — including ones released after this code shipped — is selectable. NousPortal (no ``/images`` route) lists the chat-completions catalog only.- Offline fallback: the static default chain plus the curated Image API- snapshot.+ Offline fallback: the static default chain plus the curated Image API snapshot."""merged: Dict[str, Dict[str, Any]] = {}if self._supports_image_api:@@ -882,111 +739,54 @@ class OpenRouterCompatImageProvider(ImageGenProvider):for entry in self._live_models():merged.setdefault(entry["id"], entry)if merged:- priority = {DEFAULT_MODEL: 0, _FALLBACK_MODEL: 1}return sorted(- merged.values(), key=lambda m: (priority.get(m["id"], 2), m["id"])+ merged.values(), key=lambda m: (_MODEL_PRIORITY.get(m["id"], 2), m["id"]))- models = [- {- "id": DEFAULT_MODEL,- "display": "OpenAI GPT-5.4 Image 2",- "strengths": "Highest fidelity; best prompt adherence; slower on OpenRouter",- },- {- "id": _FALLBACK_MODEL,- "display": "Gemini 3 Pro Image",- "strengths": "Fast, reliable fallback with good layout adherence",- },- ]+ models = [{"id": model_id, **meta} for model_id, meta in _KNOWN_MODEL_META.items()]if self._supports_image_api:# Curated snapshot keeps the Image API models pickable offline.models.extend(- {- "id": model_id,- "display": meta["display"],- "strengths": f"{meta['strengths']} (Image API)",- }+ {"id": model_id, "display": meta["display"], "strengths": f"{meta['strengths']} (Image API)"}for model_id, meta in _IMAGE_API_MODELS.items()- if model_id not in (DEFAULT_MODEL, _FALLBACK_MODEL))return models- def _image_api_live_models(self) -> List[Dict[str, Any]]:- """Cached live ``GET /images/models`` entries (``[]`` when unreachable).-- Curated metadata from :data:`_IMAGE_API_MODELS` wins for known ids;- unknown (newly released) models get the API-provided name and a- generic strengths line so they are pickable the day they launch.- """- import time-- cached = self._image_api_models_cache+ def _cached_catalog(self, attr: str, label: str, **fetch: Any) -> List[Dict[str, Any]]:+ """Cached (per TTL) live catalog rows for this backend; ``[]`` when unreachable."""+ cached = getattr(self, attr)if cached is not None and time.monotonic() - cached[1] < _LIVE_CACHE_TTL:return cached[0]models: List[Dict[str, Any]] = []try:- import requests-- runtime = self._resolve_runtime()- api_key = str(runtime.get("api_key") or "").strip()- base_url = str(runtime.get("base_url") or "").strip().rstrip("/")+ api_key, base_url = self._credentials()if base_url:- response = requests.get(- f"{base_url}/images/models",- headers={"Authorization": f"Bearer {api_key}"} if api_key else {},- timeout=_LIVE_TIMEOUT,- )- response.raise_for_status()- for entry in response.json().get("data") or []:- if not isinstance(entry, dict):- continue- model_id = entry.get("id")- if not isinstance(model_id, str) or not model_id.strip():- continue- model_id = model_id.strip()- meta = _IMAGE_API_MODELS.get(model_id, {})- arch_raw = entry.get("architecture")- arch: Dict[str, Any] = arch_raw if isinstance(arch_raw, dict) else {}- models.append(- {- "id": model_id,- "display": meta.get("display", entry.get("name") or model_id),- "strengths": meta.get(- "strengths", "Image API model (from live OpenRouter catalog)"- ),- "input_modalities": arch.get("input_modalities") or [],- }- )+ models = _fetch_catalog(base_url, api_key, **fetch)except Exception as exc: # noqa: BLE001 - offline/unauth → fallback path- logger.debug("%s live Image API catalog unavailable: %s", self._name, exc)+ logger.debug("%s live %s unavailable: %s", self._name, label, exc)models = []- self._image_api_models_cache = (models, time.monotonic())+ setattr(self, attr, (models, time.monotonic()))return models- def _live_models(self) -> List[Dict[str, Any]]:- """Cached live catalog for this backend (``[]`` when unreachable)."""- import time+ def _image_api_live_models(self) -> List[Dict[str, Any]]:+ """Cached live ``GET /images/models`` entries; curated metadata for known ids."""+ return self._cached_catalog(+ "_image_api_models_cache", path="/images/models", meta=_IMAGE_API_MODELS,+ generic="Image API model (from live OpenRouter catalog)", image_output_only=False,+ label="Image API catalog",+ )- cached = self._live_models_cache- if cached is not None and time.monotonic() - cached[1] < _LIVE_CACHE_TTL:- return cached[0]- models: List[Dict[str, Any]] = []- try:- runtime = self._resolve_runtime()- api_key = str(runtime.get("api_key") or "").strip()- base_url = str(runtime.get("base_url") or "").strip().rstrip("/")- if base_url:- models = _fetch_live_image_models(base_url, api_key)- except Exception as exc: # noqa: BLE001 - offline/unauth → static fallback- logger.debug("%s live image model catalog unavailable: %s", self._name, exc)- models = []- self._live_models_cache = (models, time.monotonic())- return models+ def _live_models(self) -> List[Dict[str, Any]]:+ """Cached image-output models from the endpoint's ``/models`` catalog."""+ return self._cached_catalog(+ "_live_models_cache", path="/models", meta=_KNOWN_MODEL_META,+ generic="Image-output model (from live OpenRouter catalog)", image_output_only=True,+ label="image model catalog",+ )def default_model(self) -> Optional[str]:- # This is the catalog default, not the effective runtime model.- # Runtime overrides are resolved separately by _resolve_model_chain().+ # The catalog default, not the effective runtime model+ # (that is _resolve_model_chain()).return DEFAULT_MODELdef get_setup_schema(self) -> Dict[str, Any]:@@ -997,31 +797,19 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return self._resolve_model_chain(explicit)[0]def _resolve_model_chain(self, explicit: Optional[str] = None) -> list[str]:- """Ordered model attempts for this request.-- Precedence: explicit caller override (the ``model`` kwarg) → the- provider's ``*_IMAGE_MODEL`` env override → scoped- ``image_gen.<provider>.model`` → top-level ``image_gen.model`` (written- by ``hermes tools``) → the quality-first default chain.-- Any explicit user/model selection means "use this exact model", so no- fallback. Only the bare default chain carries a Gemini fallback.- """- if isinstance(explicit, str) and explicit.strip():- return [explicit.strip()]- env_override = os.environ.get(self._model_env_var, "").strip()- if env_override:- return [env_override]+ """Ordered model attempts: explicit ``model`` kwarg → ``*_IMAGE_MODEL``+ env → ``image_gen.<provider>.model`` → top-level ``image_gen.model`` →+ the quality-first default chain. Any explicit selection means "use+ exactly this model", so only the bare default chain carries a fallback."""+ for candidate in (explicit, os.environ.get(self._model_env_var)):+ if isinstance(candidate, str) and candidate.strip():+ return [candidate.strip()]cfg = _load_image_gen_config()- scoped = cfg.get(self._config_key) if isinstance(cfg.get(self._config_key), dict) else {}- if isinstance(scoped, dict):- value = scoped.get("model")- if isinstance(value, str) and value.strip():- return [value.strip()]- top = cfg.get("model")- if isinstance(top, str) and top.strip():- return [top.strip()]- return _dedupe_models(list(_DEFAULT_MODEL_CHAIN))+ scoped = cfg.get(self._config_key)+ for candidate in ((scoped or {}).get("model") if isinstance(scoped, dict) else None, cfg.get("model")):+ if isinstance(candidate, str) and candidate.strip():+ return [candidate.strip()]+ return list(_DEFAULT_MODEL_CHAIN)def _generate_via_image_api(self,@@ -1036,28 +824,19 @@ class OpenRouterCompatImageProvider(ImageGenProvider):) -> Dict[str, Any]:"""Serve one model through ``POST {base_url}/images/generations``.- Returns the usual success/error dict. A failure that the caller may- retry on the next model of the chain carries a private ``_retryable``- flag, which :meth:`generate` strips before returning.+ A failure the caller may retry on the next model of the chain carries a+ private ``_retryable`` flag, which :meth:`generate` strips."""- import requests+ base_fail = error_factory(self._name, semantic_aspect, model=model_id, prompt=prompt)def _fail(error: str, error_type: str, retryable: bool = False) -> Dict[str, Any]:- response = error_response(- error=error,- error_type=error_type,- provider=self._name,- model=model_id,- prompt=prompt,- aspect_ratio=semantic_aspect,- )+ response = base_fail(error, error_type)if retryable:response["_retryable"] = Truereturn response# References become data URIs here rather than reusing the chat path's- # `content`, because that one is clamped to 3 and these models take up- # to 16.+ # `content`, because that one is clamped to 3 and these models take up to 16.usable_refs: List[str] = []unreadable: List[str] = []try:@@ -1071,8 +850,8 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return _fail(f"Could not load reference image: {exc}", "io_error")# An edit whose every source image failed to load must not quietly- # become a text-to-image generation: that bills a new picture unrelated- # to what the caller asked to edit, and success=True hides it.+ # become a text-to-image generation: that bills an unrelated picture+ # and success=True hides it.if unreadable and not usable_refs:return _fail("Could not read the reference image(s) requested for editing: "@@ -1082,12 +861,8 @@ class OpenRouterCompatImageProvider(ImageGenProvider):)payload, notes = _build_image_api_payload(- model_id=model_id,- prompt=prompt,- semantic_aspect=semantic_aspect,- references=usable_refs,- config_key=self._config_key,- kwargs=kwargs,+ model_id=model_id, prompt=prompt, semantic_aspect=semantic_aspect,+ references=usable_refs, config_key=self._config_key, kwargs=kwargs,)if unreadable:notes.insert(0, f"dropped unreadable reference image(s): {', '.join(unreadable)}")@@ -1100,29 +875,23 @@ class OpenRouterCompatImageProvider(ImageGenProvider):except (TypeError, ValueError):logger.debug("%s: ignoring non-numeric image API timeout %r", self._name, configured)- endpoint = f"{base_url}/images/generations"- try:- response = requests.post(- endpoint,- headers=headers,- json=payload,- # (connect, read): an unreachable endpoint fails in seconds- # instead of burning the whole read budget on a connection that- # will never be established.- timeout=(min(_IMAGE_API_CONNECT_TIMEOUT, timeout), timeout),- )- response.raise_for_status()- except requests.HTTPError as exc:- resp = exc.response- status = resp.status_code if resp is not None else 0- message = _extract_image_api_error(resp, str(exc))+ # (connect, read): an unreachable endpoint fails in seconds instead of+ # burning the whole read budget.+ body, failure = post_json(+ f"{base_url}/images/generations", headers=headers, payload=payload,+ timeout=(min(_IMAGE_API_CONNECT_TIMEOUT, timeout), timeout), label=self._display,+ error_message=lambda resp, exc: _extract_image_api_error(resp, str(exc)),+ catch_request_exception=True,+ )+ if failure is not None:+ if failure.kind != "http":+ return _fail(failure.error, failure.error_type, retryable=failure.kind == "timeout")+ status, message = failure.status, failure.messagelogger.error(- "%s image API generation failed (%s) on %s: %s",- self._name, status, model_id, message,+ "%s image API generation failed (%s) on %s: %s", self._name, status, model_id, message,)- # 401/403 are answered first so one account-level rejection does- # not get two different error_types depending on where in the chain- # it landed.+ # 401/403 first so one account-level rejection does not get two+ # different error_types depending on where in the chain it landed.if status in (401, 403):return _fail(f"{self._display} rejected the API key ({status}): {message}", "auth_error")if status == 404:@@ -1133,26 +902,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):"model_access",retryable=True,)- return _fail(- f"{self._display} image generation failed ({status}): {message}",- "api_error",- retryable=status in _IMAGE_API_FALLBACK_STATUSES,- )- except requests.Timeout:- return _fail(- f"{self._display} image generation timed out ({int(timeout)}s)",- "timeout",- retryable=True,- )- except requests.ConnectionError as exc:- return _fail(f"{self._display} connection error: {exc}", "connection_error")- except requests.RequestException as exc:- return _fail(f"{self._display} request failed: {exc}", "api_error")-- try:- body = response.json()- except Exception as exc: # noqa: BLE001- return _fail(f"{self._display} returned invalid JSON: {exc}", "invalid_response")+ return _fail(failure.error, "api_error", retryable=status in _IMAGE_API_FALLBACK_STATUSES)entries = body.get("data") if isinstance(body, dict) else Noneentries = [e for e in entries if isinstance(e, dict)] if isinstance(entries, list) else []@@ -1170,10 +920,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return _fail(f"Could not save generated image: {exc}", "io_error")if not saved:- return _fail(- f"{self._display} response carried neither b64_json nor url.",- "empty_response",- )+ return _fail(f"{self._display} response carried neither b64_json nor url.", "empty_response")extra: Dict[str, Any] = {"endpoint": "images/generations",@@ -1215,10 +962,8 @@ class OpenRouterCompatImageProvider(ImageGenProvider):reference_image_urls: Optional[List[str]] = None,**kwargs: Any,) -> Dict[str, Any]:- import requests-try:- runtime = self._resolve_runtime()+ api_key, base_url = self._credentials()except Exception as exc: # noqa: BLE001return error_response(error=f"Could not resolve {self._display} credentials: {exc}",@@ -1226,8 +971,6 @@ class OpenRouterCompatImageProvider(ImageGenProvider):provider=self._name,aspect_ratio=aspect_ratio,)- api_key = str(runtime.get("api_key") or "").strip()- base_url = str(runtime.get("base_url") or "").strip().rstrip("/")if not api_key or not base_url:return error_response(error=(@@ -1241,18 +984,13 @@ class OpenRouterCompatImageProvider(ImageGenProvider):model_chain = self._resolve_model_chain(kwargs.get("model"))aspect = resolve_aspect_ratio(aspect_ratio)- or_aspect = _ASPECT_RATIOS.get(aspect, "1:1")-- # Collect every reference: the pet generator passes local paths via the- # ``reference_images`` kwarg; the generic tool surface uses ``image_url``- # / ``reference_image_urls``. Accept all three.- references: List[str] = []- for ref in kwargs.get("reference_images") or []:- references.append(str(ref))++ # The pet generator passes local paths via ``reference_images``; the+ # generic tool surface uses ``image_url`` / ``reference_image_urls``.+ references: List[str] = [str(ref) for ref in kwargs.get("reference_images") or []]if image_url:references.append(str(image_url))- for ref in reference_image_urls or []:- references.append(str(ref))+ references.extend(str(ref) for ref in reference_image_urls or [])content: List[Dict[str, Any]] = [{"type": "text", "text": prompt}]for ref in references[:_MAX_REFERENCE_IMAGES]:@@ -1270,34 +1008,27 @@ class OpenRouterCompatImageProvider(ImageGenProvider):last_error: Optional[Dict[str, Any]] = Nonefor i, model_id in enumerate(model_chain):is_last = i == len(model_chain) - 1+ fail = error_factory(self._name, aspect, model=model_id, prompt=prompt)++ def retry_with_fallback(reason: str) -> None:+ logger.info(+ "%s model %s %s; retrying with fallback %s",+ self._name, model_id, reason, model_chain[i + 1],+ )- # Surface selection. An Image API model cannot be served by- # /chat/completions (and vice versa), so this is a routing- # decision, not a preference.+ # An Image API model cannot be served by /chat/completions (and vice+ # versa), so this is a routing decision, not a preference.if self._supports_image_api and _select_surface(model_id, base_url, api_key, self._config_key) == "images":outcome = self._generate_via_image_api(- model_id=model_id,- prompt=prompt,- semantic_aspect=aspect,- references=references,- base_url=base_url,- headers=headers,- kwargs=kwargs,+ model_id=model_id, prompt=prompt, semantic_aspect=aspect,+ references=references, base_url=base_url, headers=headers, kwargs=kwargs,)- if outcome.get("success"):- return outcome- if is_last or not outcome.get("_retryable"):- outcome.pop("_retryable", None)+ retryable = outcome.pop("_retryable", False)+ if outcome.get("success") or is_last or not retryable:return outcome- outcome.pop("_retryable", None)- logger.info(- "%s model %s failed on the image API; retrying with fallback %s",- self._name,- model_id,- model_chain[i + 1],- )+ retry_with_fallback("failed on the image API")last_error = outcomecontinue@@ -1305,104 +1036,42 @@ class OpenRouterCompatImageProvider(ImageGenProvider):"model": model_id,"modalities": ["image", "text"],"messages": [{"role": "user", "content": content}],- "image_config": {"aspect_ratio": or_aspect},+ "image_config": {"aspect_ratio": _ASPECT_RATIOS.get(aspect, "1:1")},}- try:- response = requests.post(- f"{base_url}/chat/completions",- headers=headers,- json=payload,- timeout=_REQUEST_TIMEOUT,- )- response.raise_for_status()- except requests.HTTPError as exc:- resp = exc.response- status = resp.status_code if resp is not None else 0- try:- err_msg = resp.json().get("error", {}).get("message", resp.text[:300])- except Exception: # noqa: BLE001- err_msg = resp.text[:300] if resp is not None else str(exc)- logger.error("%s image gen failed (%d) on %s: %s", self._name, status, model_id, err_msg)- hint = _access_error_hint(self._display, model_id, self._model_env_var, status, err_msg)- if hint and not is_last:- logger.info(- "%s model %s unavailable; retrying with fallback %s",- self._name,- model_id,- model_chain[i + 1],+ result, failure = post_json(+ f"{base_url}/chat/completions", headers=headers, payload=payload,+ timeout=_REQUEST_TIMEOUT, label=self._display,+ )+ if failure is not None:+ if failure.kind == "http":+ logger.error(+ "%s image gen failed (%d) on %s: %s",+ self._name, failure.status, model_id, failure.message,)- continue- last_error = error_response(- error=hint or f"{self._display} image generation failed ({status}): {err_msg}",- error_type="model_access" if hint else "api_error",- provider=self._name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- return last_error- except requests.Timeout:- if not is_last:- logger.info(- "%s model %s timed out; retrying with fallback %s",- self._name,- model_id,- model_chain[i + 1],+ hint = _access_error_hint(+ self._display, model_id, self._model_env_var, failure.status, failure.message)+ if hint and not is_last:+ retry_with_fallback("unavailable")+ continue+ last_error = fail(hint or failure.error, "model_access" if hint else "api_error")+ return last_error+ if failure.kind == "timeout" and not is_last:+ retry_with_fallback("timed out")continue- return error_response(- error=f"{self._display} image generation timed out "- f"({int(_REQUEST_TIMEOUT)}s)",- error_type="timeout",- provider=self._name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- except requests.ConnectionError as exc:- return error_response(- error=f"{self._display} connection error: {exc}",- error_type="connection_error",- provider=self._name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )-- try:- result = response.json()- except Exception as exc: # noqa: BLE001- return error_response(- error=f"{self._display} returned invalid JSON: {exc}",- error_type="invalid_response",- provider=self._name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(failure.error, failure.error_type)images = _extract_images(result)if not images:if not is_last:- logger.info(- "%s model %s returned no image; retrying with fallback %s",- self._name,- model_id,- model_chain[i + 1],- )+ retry_with_fallback("returned no image")continue- # A response with text but no image usually means the model didn't- # honor image output (wrong model or modalities); surface that.- return error_response(- error=(- f"{self._display} returned no image. Ensure the model "- f"'{model_id}' supports image output."- ),- error_type="empty_response",- provider=self._name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,+ # Text but no image usually means the model didn't honor image+ # output (wrong model or modalities); surface that.+ return fail(+ f"{self._display} returned no image. Ensure the model "+ f"'{model_id}' supports image output.",+ "empty_response",)first = images[0]@@ -1413,14 +1082,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):else:saved_path = save_url_image(first, prefix=f"{self._name}_gen")except Exception as exc: # noqa: BLE001- return error_response(- error=f"Could not save generated image: {exc}",- error_type="io_error",- provider=self._name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail(f"Could not save generated image: {exc}", "io_error")return success_response(image=str(saved_path),diff --git a/plugins/image_gen/xai/__init__.py b/plugins/image_gen/xai/__init__.pyindex f35ffacfd04..ecd40cea9ab 100644--- a/plugins/image_gen/xai/__init__.py+++ b/plugins/image_gen/xai/__init__.py@@ -1,18 +1,11 @@"""xAI image generation backend.-Exposes xAI's ``grok-imagine-image`` model as an-:class:`ImageGenProvider` implementation.--Features:-- Text-to-image generation-- Multiple aspect ratios (1:1, 16:9, 9:16, etc.)-- Multiple resolutions (1K, 2K)-- Base64 output saved to cache--Selection precedence (first hit wins):-1. ``XAI_IMAGE_MODEL`` env var-2. ``image_gen.xai.model`` in ``config.yaml``-3. :data:`DEFAULT_MODEL`+Exposes xAI's ``grok-imagine-image`` models as an :class:`ImageGenProvider`:+text-to-image (``/v1/images/generations``, several aspect ratios, 1K/2K) and+image editing (``/v1/images/edits``), base64 output saved to cache.++Selection precedence (first hit wins): ``model`` kwarg → ``XAI_IMAGE_MODEL``+env → ``image_gen.xai.model`` → :data:`DEFAULT_MODEL`."""from __future__ import annotations@@ -27,13 +20,17 @@ import requestsfrom agent.image_gen_provider import (DEFAULT_ASPECT_RATIO,ImageGenProvider,- error_response,- normalize_reference_images,resolve_aspect_ratio,- save_b64_image,- save_url_image,success_response,)+from plugins.image_gen._common import (+ catalog_rows,+ collect_source_images,+ error_factory,+ load_image_gen_config,+ materialize_image,+ post_json,+)from tools.xai_http import (build_xai_storage_options,hermes_xai_user_agent,@@ -45,10 +42,6 @@ from tools.xai_http import (logger = logging.getLogger(__name__)-# ----------------------------------------------------------------------------# Model catalog-# ----------------------------------------------------------------------------_MODELS: Dict[str, Dict[str, Any]] = {"grok-imagine-image": {"display": "Grok Imagine Image",@@ -68,16 +61,37 @@ _MODELS: Dict[str, Dict[str, Any]] = {}DEFAULT_MODEL = "grok-imagine-image"+# xAI documents the quality model as the edit-capable baseline.+_EDIT_FALLBACK_MODEL = "grok-imagine-image-quality"# Live catalog cache: (models_dict, fetched_monotonic). xAI's# ``/image-generation-models`` endpoint is the source of truth so newly-# released Imagine models appear in the picker without a code change;-# the static ``_MODELS`` table is the offline fallback and supplies curated+# released Imagine models appear in the picker without a code change; the+# static ``_MODELS`` table is the offline fallback and supplies curated# speed/strengths text for the models we know about._LIVE_CACHE: Optional[Tuple[Dict[str, Dict[str, Any]], float]] = None_LIVE_CACHE_TTL = 300.0_LIVE_TIMEOUT = 10.0+# xAI aspect ratios (more options than FAL/OpenAI)+_XAI_ASPECT_RATIOS = {+ "landscape": "16:9",+ "square": "1:1",+ "portrait": "9:16",+ "4:3": "4:3",+ "3:4": "3:4",+ "3:2": "3:2",+ "2:3": "2:3",+}+_XAI_RESOLUTIONS = {"1k", "2k"}+DEFAULT_RESOLUTION = "1k"+_MAX_SOURCE_IMAGES = 3+_REQUEST_TIMEOUT = 120+++def _base_url(creds: Dict[str, Any]) -> str:+ return str(creds.get("base_url") or "https://api.x.ai/v1").strip().rstrip("/")+def _fetch_live_models() -> Dict[str, Dict[str, Any]]:"""Fetch image models from xAI's ``/image-generation-models`` endpoint.@@ -89,13 +103,9 @@ def _fetch_live_models() -> Dict[str, Dict[str, Any]]:api_key = str(creds.get("api_key") or "").strip()if not api_key:raise RuntimeError("no xAI credentials")- base_url = str(creds.get("base_url") or "https://api.x.ai/v1").strip().rstrip("/")response = requests.get(- f"{base_url}/image-generation-models",- headers={- "Authorization": f"Bearer {api_key}",- "User-Agent": hermes_xai_user_agent(),- },+ f"{_base_url(creds)}/image-generation-models",+ headers={"Authorization": f"Bearer {api_key}", "User-Agent": hermes_xai_user_agent()},timeout=_LIVE_TIMEOUT,)response.raise_for_status()@@ -134,157 +144,91 @@ def _live_models() -> Dict[str, Dict[str, Any]]:def _catalog() -> Dict[str, Dict[str, Any]]:"""Merged model catalog: live endpoint IDs + curated static metadata.- Known models keep their curated display/speed/strengths; models xAI- ships after this file was written still show up (with generic metadata)- so users can pick them the day they launch. Static table alone when the- API is unreachable.+ Known models keep their curated display/speed/strengths; models xAI ships+ later still show up (with generic metadata) so users can pick them the day+ they launch. Curated entries the live list momentarily omits are kept;+ static table alone when the API is unreachable."""live = _live_models()if not live:return dict(_MODELS)merged: Dict[str, Dict[str, Any]] = {}for model_id in live:- meta = _MODELS.get(model_id)- if meta is None:- meta = {- "display": model_id,- "speed": "",- "strengths": "New xAI Imagine model (from live xAI catalog)",- }+ meta = _MODELS.get(model_id) or {+ "display": model_id,+ "speed": "",+ "strengths": "New xAI Imagine model (from live xAI catalog)",+ }merged[model_id] = dict(meta)merged[model_id]["input_modalities"] = live[model_id].get("input_modalities") or []- # Keep curated entries that the live list may momentarily omit.for model_id, meta in _MODELS.items():merged.setdefault(model_id, dict(meta))return merged-# xAI aspect ratios (more options than FAL/OpenAI)-_XAI_ASPECT_RATIOS = {- "landscape": "16:9",- "square": "1:1",- "portrait": "9:16",- "4:3": "4:3",- "3:4": "3:4",- "3:2": "3:2",- "2:3": "2:3",-}--# xAI resolutions-_XAI_RESOLUTIONS = {"1k", "2k"}--DEFAULT_RESOLUTION = "1k"---# ----------------------------------------------------------------------------# Config-# ----------------------------------------------------------------------------def _load_xai_config() -> Dict[str, Any]:- """Read ``image_gen.xai`` from config.yaml."""- try:- from hermes_cli.config import load_config+ return load_image_gen_config("xai")- cfg = load_config()- section = cfg.get("image_gen") if isinstance(cfg, dict) else None- xai_section = section.get("xai") if isinstance(section, dict) else None- return xai_section if isinstance(xai_section, dict) else {}- except Exception as exc:- logger.debug("Could not load image_gen.xai config: %s", exc)- return {}++def _configured_model() -> Optional[str]:+ value = _load_xai_config().get("model")+ return value if isinstance(value, str) else Nonedef _resolve_model(caller_model: Optional[str] = None) -> Tuple[str, Dict[str, Any]]:- """Decide which model to use and return ``(model_id, meta)``.-- Priority:- 1. Caller-supplied ``caller_model`` — the dispatcher forwards top-level- ``image_gen.model`` (what ``hermes tools`` writes) as the ``model``- kwarg, mirroring the openrouter provider.- 2. ``XAI_IMAGE_MODEL`` env override.- 3. Scoped ``image_gen.xai.model`` in config.yaml.- 4. :data:`DEFAULT_MODEL`.-- Every candidate is validated against the merged live+static catalog,- so a newly released xAI model is selectable the day it appears in the- live catalog — no code change required.+ """Return ``(model_id, meta)``: caller kwarg → ``XAI_IMAGE_MODEL`` → config → default.++ Every candidate is validated against the merged live+static catalog, so a+ newly released xAI model is selectable the day it appears in the live catalog."""catalog = _catalog()- if caller_model and caller_model in catalog:- return caller_model, catalog[caller_model]-- env_override = os.environ.get("XAI_IMAGE_MODEL")- if env_override and env_override in catalog:- return env_override, catalog[env_override]-- cfg = _load_xai_config()- candidate = cfg.get("model") if isinstance(cfg.get("model"), str) else None- if candidate and candidate in catalog:- return candidate, catalog[candidate]-+ for candidate in (caller_model, os.environ.get("XAI_IMAGE_MODEL"), _configured_model()):+ if candidate and candidate in catalog:+ return candidate, catalog[candidate]return DEFAULT_MODEL, catalog.get(DEFAULT_MODEL, _MODELS[DEFAULT_MODEL])def _resolve_edit_model(caller_model: Optional[str] = None) -> str:- """Model for ``/v1/images/edits`` requests.-- An explicitly selected model (caller kwarg, env, or config) that accepts- image input is honored for edits; otherwise fall back to the quality- model, which xAI documents as the edit-capable baseline.- """+ """Model for ``/v1/images/edits``: an explicitly selected model that accepts+ image input is honored; otherwise the documented quality baseline."""catalog = _catalog()- explicit = caller_model or os.environ.get("XAI_IMAGE_MODEL") or (- _load_xai_config().get("model") if isinstance(_load_xai_config().get("model"), str) else None- )+ explicit = caller_model or os.environ.get("XAI_IMAGE_MODEL") or _configured_model()if explicit and explicit in catalog:- modalities = catalog[explicit].get("input_modalities") or []- if "image" in modalities:+ if "image" in (catalog[explicit].get("input_modalities") or []):return explicit- return "grok-imagine-image-quality"+ return _EDIT_FALLBACK_MODELdef _resolve_resolution() -> str:- """Get configured resolution."""- cfg = _load_xai_config()- res = cfg.get("resolution") if isinstance(cfg.get("resolution"), str) else None- if res and res in _XAI_RESOLUTIONS:- return res- return DEFAULT_RESOLUTION+ res = _load_xai_config().get("resolution")+ return res if isinstance(res, str) and res in _XAI_RESOLUTIONS else DEFAULT_RESOLUTIONdef _xai_image_field(source: str) -> Dict[str, str]:"""Build the xAI ``image`` field for an edit request.- xAI's ``/v1/images/edits`` accepts a public HTTPS URL or a base64 data URI.- Local file paths are read and encoded into a ``data:`` URI.+ ``/v1/images/edits`` accepts a public HTTPS URL or a base64 data URI; local+ file paths are read and encoded into a ``data:`` URI."""source = source.strip()- lower = source.lower()- if lower.startswith(("http://", "https://", "data:")):+ if source.lower().startswith(("http://", "https://", "data:")):return {"url": source, "type": "image_url"}- # Local file path → base64 data URI.import base64- import os as _os- # Enforce the shared credential-read guard before reading local bytes- # (same boundary the OpenAI / OpenRouter / Codex image providers apply).+ # Shared credential-read guard before reading local bytes (same boundary+ # the OpenAI / OpenRouter / Codex image providers apply).from agent.file_safety import raise_if_read_blockedraise_if_read_blocked(source)- with open(_os.path.expanduser(source), "rb") as fh: # windows-footgun: ok+ with open(os.path.expanduser(source), "rb") as fh: # windows-footgun: okraw = fh.read()- ext = (_os.path.splitext(source)[1].lstrip(".") or "png").lower()+ ext = (os.path.splitext(source)[1].lstrip(".") or "png").lower()if ext == "jpg":ext = "jpeg"b64 = base64.b64encode(raw).decode("utf-8")return {"url": f"data:image/{ext};base64,{b64}", "type": "image_url"}-# ----------------------------------------------------------------------------# Provider-# -----------------------------------------------------------------------------class XAIImageGenProvider(ImageGenProvider):"""xAI ``grok-imagine-image`` backend."""@@ -297,25 +241,15 @@ class XAIImageGenProvider(ImageGenProvider):return "xAI (Grok)"def is_available(self) -> bool:- creds = resolve_xai_http_credentials()- return bool(creds.get("api_key"))+ return bool(resolve_xai_http_credentials().get("api_key"))def list_models(self) -> List[Dict[str, Any]]:- return [- {- "id": model_id,- "display": meta.get("display", model_id),- "speed": meta.get("speed", ""),- "strengths": meta.get("strengths", ""),- }- for model_id, meta in _catalog().items()- ]+ return catalog_rows(_catalog(), ("display", "speed", "strengths"))def get_setup_schema(self) -> Dict[str, Any]:- # Auth resolution is delegated to the shared ``xai_grok`` post_setup- # hook (``hermes_cli/tools_config.py``); identical to the TTS / video- # gen entries so users see the same OAuth-or-API-key choice for every- # xAI service.+ # Auth resolution is delegated to the shared ``xai_grok`` post_setup hook+ # (``hermes_cli/tools_config.py``), identical to the TTS / video-gen+ # entries, so every xAI service shows the same OAuth-or-API-key choice.storage_notice = xai_storage_notice_text("image_gen")tag = ("grok-imagine-image - text-to-image & image editing; uses xAI "@@ -332,12 +266,11 @@ class XAIImageGenProvider(ImageGenProvider):}def capabilities(self) -> Dict[str, Any]:- # xAI's /v1/images/edits supports image editing via grok-imagine-image- # -quality, including up to 3 total source images.+ # /v1/images/edits accepts up to 3 total source images.return {"modalities": ["text", "image"],"max_reference_images": 2,- "max_source_images": 3,+ "max_source_images": _MAX_SOURCE_IMAGES,}def generate(@@ -349,258 +282,128 @@ class XAIImageGenProvider(ImageGenProvider):reference_image_urls: Optional[List[str]] = None,**kwargs: Any,) -> Dict[str, Any]:- """Generate an image (text-to-image) or edit a source image (image-to-image).+ """Text-to-image via ``/v1/images/generations``, or image editing via+ ``/v1/images/edits`` when source images are supplied.- Routing: when ``image_url`` is provided, POST to ``/v1/images/edits``- with the source image; otherwise POST to ``/v1/images/generations``.- Per xAI docs, editing uses the ``grok-imagine-image-quality`` model and- a JSON body (the OpenAI SDK's multipart ``images.edit()`` is NOT- supported by xAI).+ Editing uses a JSON body (xAI does not support the OpenAI SDK's+ multipart ``images.edit()``) and an image-input-capable model."""creds = resolve_xai_http_credentials()api_key = str(creds.get("api_key") or "").strip()provider_name = str(creds.get("provider") or "xai").strip() or "xai"if not api_key:- return error_response(- error="No xAI credentials found. Configure xAI OAuth in `hermes model` or set XAI_API_KEY.",- error_type="missing_api_key",- provider=provider_name,- aspect_ratio=aspect_ratio,+ return error_factory(provider_name, aspect_ratio)(+ "No xAI credentials found. Configure xAI OAuth in `hermes model` or set XAI_API_KEY.",+ "missing_api_key",)model_id, meta = _resolve_model(kwargs.get("model"))aspect = resolve_aspect_ratio(aspect_ratio)- xai_ar = _XAI_ASPECT_RATIOS.get(aspect, "1:1")- resolution = _resolve_resolution()- xai_res = resolution if resolution in _XAI_RESOLUTIONS else DEFAULT_RESOLUTION-- source_images: List[str] = []- if isinstance(image_url, str) and image_url.strip():- source_images.append(image_url.strip())- refs = normalize_reference_images(reference_image_urls)- if refs:- source_images.extend(refs)- if len(source_images) > 3:- return error_response(- error="xAI image editing supports at most 3 source images",- error_type="too_many_references",- provider=provider_name,- model="grok-imagine-image-quality",- prompt=prompt,- aspect_ratio=aspect,+ xai_res = _resolve_resolution()++ source_images = collect_source_images(image_url, reference_image_urls)+ edit_fail = error_factory(provider_name, aspect, model=_EDIT_FALLBACK_MODEL, prompt=prompt)+ if len(source_images) > _MAX_SOURCE_IMAGES:+ return edit_fail(+ f"xAI image editing supports at most {_MAX_SOURCE_IMAGES} source images",+ "too_many_references",)for index, source in enumerate(source_images):field = "image_url" if index == 0 and image_url and image_url.strip() == source else "reference_image_urls"- lower = source.lower()- if not lower.startswith(("http://", "https://", "data:")):- path = Path(source).expanduser()- if not path.is_file():- return error_response(- error=(- f"{field} must be a public HTTPS URL or data URI "- "(e.g. the `image`/`public_url` from a prior Imagine result)"- ),- error_type="invalid_image_url",- provider=provider_name,- model="grok-imagine-image-quality",- prompt=prompt,- aspect_ratio=aspect,+ if not source.lower().startswith(("http://", "https://", "data:")):+ if not Path(source).expanduser().is_file():+ return edit_fail(+ f"{field} must be a public HTTPS URL or data URI "+ "(e.g. the `image`/`public_url` from a prior Imagine result)",+ "invalid_image_url",)is_edit = bool(source_images)- modality = "image" if is_edit else "text"headers = {"Authorization": f"Bearer {api_key}","Content-Type": "application/json","User-Agent": hermes_xai_user_agent(),}-- base_url = str(creds.get("base_url") or "https://api.x.ai/v1").strip().rstrip("/")+ base_url = _base_url(creds)storage_options = build_xai_storage_options(- "image_gen",- filename_prefix="hermes-xai-image",- extension="png",+ "image_gen", filename_prefix="hermes-xai-image", extension="png",)storage_notice = maybe_mark_xai_storage_notice_seen("image_gen")storage_cfg = read_xai_imagine_storage_config("image_gen")if is_edit:- # Editing needs an image-input-capable model. An explicit user- # selection that accepts image input (e.g. grok-imagine-image-2.0)- # is honored; otherwise the documented quality baseline is used.- # The source image may be a public URL or a base64 data URI;- # local file paths are converted to a data URI here.- edit_model = _resolve_edit_model(kwargs.get("model"))+ # An explicit user selection that accepts image input (e.g.+ # grok-imagine-image-2.0) is honored; otherwise the quality baseline.+ model_id = _resolve_edit_model(kwargs.get("model"))try:image_fields = [_xai_image_field(source) for source in source_images]except Exception as exc:- return error_response(- error=f"Could not load source image for editing: {exc}",- error_type="io_error",- provider=provider_name,- model=edit_model,- prompt=prompt,- aspect_ratio=aspect,+ return edit_fail(+ f"Could not load source image for editing: {exc}", "io_error", model=model_id,)- payload: Dict[str, Any] = {- "model": edit_model,- "prompt": prompt,- }+ payload: Dict[str, Any] = {"model": model_id, "prompt": prompt}if len(image_fields) == 1:payload["image"] = image_fields[0]else:payload["images"] = image_fieldsendpoint_url = f"{base_url}/images/edits"- model_id = edit_modelelse:payload = {"model": model_id,"prompt": prompt,- "aspect_ratio": xai_ar,+ "aspect_ratio": _XAI_ASPECT_RATIOS.get(aspect, "1:1"),"resolution": xai_res,}endpoint_url = f"{base_url}/images/generations"if storage_options is not None:payload["storage_options"] = storage_options- try:- response = requests.post(- endpoint_url,- headers=headers,- json=payload,- timeout=120,- )- response.raise_for_status()- except requests.HTTPError as exc:- response = exc.response- status = response.status_code if response is not None else 0- try:- err_msg = response.json().get("error", {}).get("message", response.text[:300])- except Exception:- err_msg = response.text[:300] if response is not None else str(exc)- logger.error("xAI image gen failed (%d): %s", status, err_msg)- return error_response(- error=f"xAI image generation failed ({status}): {err_msg}",- error_type="api_error",- provider=provider_name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- except requests.Timeout:- return error_response(- error="xAI image generation timed out (120s)",- error_type="timeout",- provider=provider_name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- except requests.ConnectionError as exc:- return error_response(- error=f"xAI connection error: {exc}",- error_type="connection_error",- provider=provider_name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )-- try:- result = response.json()- except Exception as exc:- return error_response(- error=f"xAI returned invalid JSON: {exc}",- error_type="invalid_response",- provider=provider_name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ fail = error_factory(provider_name, aspect, model=model_id, prompt=prompt)+ result, failure = post_json(+ endpoint_url, headers=headers, payload=payload, timeout=_REQUEST_TIMEOUT, label="xAI",+ )+ if failure:+ if failure.kind == "http":+ logger.error("xAI image gen failed (%d): %s", failure.status, failure.message)+ return fail(failure.error, failure.error_type)- # Parse response - xAI returns data[0].b64_json, data[0].url, and- # optionally data[0].file_output when storage_options were requested.+ # xAI returns data[0].b64_json, data[0].url, and optionally+ # data[0].file_output when storage_options were requested.data = result.get("data", [])if not data:- return error_response(- error="xAI returned no image data",- error_type="empty_response",- provider=provider_name,- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )+ return fail("xAI returned no image data", "empty_response")first = data[0]- b64 = first.get("b64_json")- url = first.get("url")file_output = first.get("file_output") if isinstance(first, dict) else Nonefile_output = file_output if isinstance(file_output, dict) else {}public_url = file_output.get("public_url") if isinstance(file_output.get("public_url"), str) else Noneif public_url:image_ref = public_url- elif b64:- try:- saved_path = save_b64_image(b64, prefix=f"xai_{model_id}")- except Exception as exc:- return error_response(- error=f"Could not save image to cache: {exc}",- error_type="io_error",- provider="xai",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,- )- image_ref = str(saved_path)- elif url:- # xAI's grok-imagine-image returns ephemeral ``imgen.x.ai/xai-tmp-*``- # URLs that 404 within minutes — by the time Telegram's- # ``send_photo`` or any downstream consumer fetches them, the- # asset is gone (#26942). Materialise the bytes locally at- # tool-completion time so the gateway has a stable file path to- # upload, mirroring the b64 branch above and the audio_cache- # pattern used by text_to_speech.- try:- saved_path = save_url_image(url, prefix=f"xai_{model_id}")- except Exception as exc:- logger.warning(- "xAI image URL %s could not be cached (%s); falling back to bare URL.",- url,- exc,- )- image_ref = url- else:- image_ref = str(saved_path)else:- return error_response(- error="xAI response contained neither b64_json nor URL",- error_type="empty_response",- provider="xai",- model=model_id,- prompt=prompt,- aspect_ratio=aspect,+ # grok-imagine-image URLs (``imgen.x.ai/xai-tmp-*``) 404 within+ # minutes; materialise locally so downstream consumers (Telegram+ # send_photo …) get a stable path.+ image_ref, err = materialize_image(+ first.get("b64_json"), first.get("url"),+ prefix=f"xai_{model_id}", label="xAI", provider="xai",+ model=model_id, prompt=prompt, aspect=aspect, log=logger,)+ if err:+ return err- extra: Dict[str, Any] = {- "storage_enabled": bool(storage_cfg["enabled"]),- }+ extra: Dict[str, Any] = {"storage_enabled": bool(storage_cfg["enabled"])}if not is_edit:extra["resolution"] = xai_resif storage_notice:extra["storage_notice"] = storage_noticeif public_url:extra["public_url"] = public_url- if file_output:- for key in (- "filename",- "expires_at",- "public_url_expires_at",- "public_url_error",- "storage_error",- ):- if key in file_output:- extra[key] = file_output[key]+ for key in (+ "filename", "expires_at", "public_url_expires_at", "public_url_error", "storage_error",+ ):+ if key in file_output:+ extra[key] = file_output[key]if result.get("usage"):extra["usage"] = result["usage"]@@ -610,16 +413,11 @@ class XAIImageGenProvider(ImageGenProvider):prompt=prompt,aspect_ratio=aspect,provider="xai",- modality=modality,+ modality="image" if is_edit else "text",extra=extra,)-# ----------------------------------------------------------------------------# Plugin registration-# -----------------------------------------------------------------------------def register(ctx: Any) -> None:"""Register this provider with the image gen registry."""ctx.register_image_gen_provider(XAIImageGenProvider())diff --git a/tests/plugins/image_gen/test_openai_provider.py b/tests/plugins/image_gen/test_openai_provider.pyindex f662b13f8dd..a3306f4372e 100644--- a/tests/plugins/image_gen/test_openai_provider.py+++ b/tests/plugins/image_gen/test_openai_provider.py@@ -230,7 +230,7 @@ class TestGenerate:)with _patched_openai(fake_client), patch(- "plugins.image_gen.openai.save_url_image",+ "plugins.image_gen._common.save_url_image",return_value=Path("/tmp/openai_gpt-image-2_20260524_000000_deadbeef.png"),) as mock_save_url:result = provider.generate("a cat")diff --git a/tests/plugins/image_gen/test_xai_provider.py b/tests/plugins/image_gen/test_xai_provider.pyindex 723f54937eb..d7a5e9bd32f 100644--- a/tests/plugins/image_gen/test_xai_provider.py+++ b/tests/plugins/image_gen/test_xai_provider.py@@ -152,7 +152,7 @@ class TestConfig:mock_resp.json.return_value = {"data": [{"b64_json": "dGVzdA=="}]}with patch("plugins.image_gen.xai.requests.post", return_value=mock_resp) as mock_post:- with patch("plugins.image_gen.xai.save_b64_image", return_value="/tmp/out.png"):+ with patch("plugins.image_gen._common.save_b64_image", return_value="/tmp/out.png"):provider = XAIImageGenProvider()result = provider.generate(prompt="test", model="grok-imagine-image-quality")@@ -265,7 +265,7 @@ class TestGenerate:}with patch("plugins.image_gen.xai.requests.post", return_value=mock_resp):- with patch("plugins.image_gen.xai.save_b64_image", return_value="/tmp/test.png"):+ with patch("plugins.image_gen._common.save_b64_image", return_value="/tmp/test.png"):provider = XAIImageGenProvider()result = provider.generate(prompt="A cat playing piano")@@ -295,7 +295,7 @@ class TestGenerate:with patch("plugins.image_gen.xai.requests.post", return_value=mock_resp), \patch(- "plugins.image_gen.xai.save_url_image",+ "plugins.image_gen._common.save_url_image",side_effect=req_lib.HTTPError("404 from CDN"),):provider = XAIImageGenProvider()@@ -401,7 +401,7 @@ class TestGenerate:mock_resp.json.return_value = {"data": [{"url": "https://xai.image/edited.png"}]}with patch("plugins.image_gen.xai.requests.post", return_value=mock_resp) as mock_post, \- patch("plugins.image_gen.xai.save_url_image", return_value="/tmp/edited.png"):+ patch("plugins.image_gen._common.save_url_image", return_value="/tmp/edited.png"):provider = XAIImageGenProvider()result = provider.generate(prompt="make the robot red",@@ -422,7 +422,7 @@ class TestGenerate:mock_resp.json.return_value = {"data": [{"url": "https://xai.image/edited.png"}]}with patch("plugins.image_gen.xai.requests.post", return_value=mock_resp) as mock_post, \- patch("plugins.image_gen.xai.save_url_image", return_value="/tmp/edited.png"):+ patch("plugins.image_gen._common.save_url_image", return_value="/tmp/edited.png"):provider = XAIImageGenProvider()result = provider.generate(prompt="combine these robots into one product shot",@@ -447,7 +447,7 @@ class TestGenerate:mock_resp.json.return_value = {"data": [{"b64_json": "dGVzdA=="}]}with patch("plugins.image_gen.xai.requests.post", return_value=mock_resp) as mock_post, \- patch("plugins.image_gen.xai.save_b64_image", return_value="/tmp/test.png"):+ patch("plugins.image_gen._common.save_b64_image", return_value="/tmp/test.png"):provider = XAIImageGenProvider()provider.generate(prompt="test")@@ -475,7 +475,7 @@ class TestGenerate:}with patch("plugins.image_gen.xai.requests.post", return_value=mock_resp), \- patch("plugins.image_gen.xai.save_url_image") as mock_save_url:+ patch("plugins.image_gen._common.save_url_image") as mock_save_url:provider = XAIImageGenProvider()result = provider.generate(prompt="A cat playing piano")