The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(image_gen,browser): AST-neutral layout compaction — hug call/import closers
Teknium9adcfb4abdb9
diff --git a/plugins/browser/_common.py b/plugins/browser/_common.pyindex ab0c708fded..c0aef2e6878 100644--- a/plugins/browser/_common.py+++ b/plugins/browser/_common.py@@ -103,8 +103,7 @@ class CloudBrowserProvider(BrowserProvider):if not response.ok:raise RuntimeError(f"Failed to create {self.label}{self.create_label_suffix} session: "- f"{response.status_code} {response.text}"- )+ f"{response.status_code} {response.text}")def close_session(self, session_id: str) -> bool:try:@@ -119,8 +118,7 @@ class CloudBrowserProvider(BrowserProvider):return Trueself._log.warning(self.close_fail_fmt or f"Failed to close {self.label} session %s: HTTP %s - %s",- session_id, response.status_code, response.text[:200],- )+ session_id, response.status_code, response.text[:200])return Falseexcept Exception as e:self._log.error("Exception closing %s session %s: %s", self.label, session_id, e)diff --git a/plugins/browser/browser_use/provider.py b/plugins/browser/browser_use/provider.pyindex 13bf0507203..b842c1d6c10 100644--- a/plugins/browser/browser_use/provider.py+++ b/plugins/browser/browser_use/provider.py@@ -86,8 +86,7 @@ class BrowserUseBrowserProvider(CloudBrowserProvider):def _managed_config() -> Optional[Dict[str, Any]]:# Keep availability scans off the synchronous OAuth refresh path.managed = resolve_managed_tool_gateway(- "browser-use", token_reader=None if refresh_token else peek_nous_access_token- )+ "browser-use", token_reader=None if refresh_token else peek_nous_access_token)if managed is None:return Nonereturn {@@ -111,8 +110,7 @@ class BrowserUseBrowserProvider(CloudBrowserProvider):def _get_config(self) -> Dict[str, Any]:from tools.tool_backend_helpers import (- NOUS_MANAGED_PROVIDER, managed_nous_tools_enabled, read_selection, selection_error,- )+ NOUS_MANAGED_PROVIDER, managed_nous_tools_enabled, read_selection, selection_error)config = self._get_config_or_none()if config is not None:@@ -121,15 +119,13 @@ class BrowserUseBrowserProvider(CloudBrowserProvider):if selected == NOUS_MANAGED_PROVIDER:raise ValueError(selection_error("browser", NOUS_MANAGED_PROVIDER,- "the Nous Tool Gateway is not available (not entitled or unreachable)",- ))+ "the Nous Tool Gateway is not available (not entitled or unreachable)"))if selected is not None:raise ValueError(selection_error("browser", selected, "BROWSER_USE_API_KEY is not set"))if managed_nous_tools_enabled():raise ValueError("Browser Use requires either a direct BROWSER_USE_API_KEY "- "credential or a managed Browser Use gateway configuration."- )+ "credential or a managed Browser Use gateway configuration.")raise ValueError("Browser Use requires a direct BROWSER_USE_API_KEY credential.")def _headers(self, config: Dict[str, Any]) -> Dict[str, str]:@@ -149,13 +145,11 @@ class BrowserUseBrowserProvider(CloudBrowserProvider):# default to a long Browser-Use timeout for a task-scoped browser.payload = ({"timeout": _DEFAULT_MANAGED_TIMEOUT_MINUTES, "proxyCountryCode": _DEFAULT_MANAGED_PROXY_COUNTRY_CODE}- if managed_mode else {}- )+ if managed_mode else {})# Managed mode propagates network errors raw so callers can retry with# the preserved idempotency key; direct mode wraps them.response = self._post_create(- f"{config['base_url']}/browsers", headers, payload, wrap_errors=not managed_mode- )+ f"{config['base_url']}/browsers", headers, payload, wrap_errors=not managed_mode)if not response.ok and managed_mode and not _should_preserve_pending_create_key(response):_clear_pending_create_key(task_id)self._check_created(response)diff --git a/plugins/browser/browserbase/provider.py b/plugins/browser/browserbase/provider.pyindex c3627ff4547..baee17f0651 100644--- a/plugins/browser/browserbase/provider.py+++ b/plugins/browser/browserbase/provider.py@@ -28,8 +28,7 @@ class BrowserbaseBrowserProvider(CloudBrowserProvider):release_path = "/v1/sessions/{session_id}"missing_credentials_error = ("Browserbase requires BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID "- "environment variables."- )+ "environment variables.")close_fail_fmt = "Failed to close session %s: HTTP %s - %s"setup_tag = "Cloud browser with stealth and proxies"setup_env_vars = [@@ -89,8 +88,7 @@ class BrowserbaseBrowserProvider(CloudBrowserProvider):keepalive_fallback = Truelogger.warning("keepAlive may require paid plan (402), retrying without it. "- "Sessions may timeout during long operations."- )+ "Sessions may timeout during long operations.")session_config.pop("keepAlive", None)response = self._post_create(url, headers, session_config)if response.status_code == 402 and enable_proxies:diff --git a/plugins/browser/firecrawl/provider.py b/plugins/browser/firecrawl/provider.pyindex c1682a598ab..2be9b52820a 100644--- a/plugins/browser/firecrawl/provider.py+++ b/plugins/browser/firecrawl/provider.py@@ -50,8 +50,7 @@ class FirecrawlBrowserProvider(CloudBrowserProvider):if not api_key:raise ValueError("FIRECRAWL_API_KEY environment variable is required. "- "Get your key at https://firecrawl.dev"- )+ "Get your key at https://firecrawl.dev")return {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}def create_session(self, task_id: str) -> Dict[str, object]:diff --git a/plugins/image_gen/_common.py b/plugins/image_gen/_common.pyindex 13ad39fb137..8c927426a0b 100644--- a/plugins/image_gen/_common.py+++ b/plugins/image_gen/_common.py@@ -13,8 +13,7 @@ from dataclasses import dataclassfrom typing import Any, Callable, Dict, Iterable, List, Optional, Tuplefrom agent.image_gen_provider import (- ImageGenProvider, error_response, normalize_reference_images, save_b64_image, save_url_image-)+ ImageGenProvider, error_response, normalize_reference_images, save_b64_image, save_url_image)logger = logging.getLogger(__name__)@@ -278,12 +277,10 @@ def post_json(message = error_message(resp, exc)return None, HttpFailure("http", f"{label} image generation failed ({status}): {message}", "api_error",- status=status, message=message, response=resp,- )+ status=status, message=message, response=resp)except requests.Timeout:return None, HttpFailure(- "timeout", f"{label} image generation timed out ({int(read_timeout)}s)", "timeout"- )+ "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:diff --git a/plugins/image_gen/deepinfra/__init__.py b/plugins/image_gen/deepinfra/__init__.pyindex cb3b552808f..fa0ef284d87 100644--- a/plugins/image_gen/deepinfra/__init__.py+++ b/plugins/image_gen/deepinfra/__init__.py@@ -19,12 +19,10 @@ from typing import Any, Dict, List, Optionalfrom agent.secret_scope import get_secretfrom agent.image_gen_provider import (- DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, save_b64_image, save_url_image, success_response-)+ DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, save_b64_image, save_url_image, success_response)from plugins.image_gen._common import (StaticImageGenProvider, error_factory, import_openai, load_image_gen_config,- prompt_required_error, size_for,-)+ prompt_required_error, size_for)logger = logging.getLogger(__name__)@@ -107,8 +105,7 @@ class DeepInfraImageGenProvider(StaticImageGenProvider):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,- )+ "modality_unsupported", prompt=prompt)if not prompt:return prompt_required_error("deepinfra", aspect)api_key = (get_secret("DEEPINFRA_API_KEY", "") or "").strip()@@ -117,8 +114,7 @@ class DeepInfraImageGenProvider(StaticImageGenProvider):"DEEPINFRA_API_KEY not set. Run `hermes tools` → Image ""Generation → DeepInfra to configure, or `hermes setup` ""to add the key.",- "auth_required",- )+ "auth_required")di_cfg = load_image_gen_config("deepinfra")model_id = _resolve_model(_live_models() or [], di_cfg)if not model_id:@@ -127,8 +123,7 @@ class DeepInfraImageGenProvider(StaticImageGenProvider):"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,- )+ "no_model_available", prompt=prompt)size = size_for(aspect)from hermes_cli.models import deepinfra_base_url@@ -173,8 +168,7 @@ class DeepInfraImageGenProvider(StaticImageGenProvider):return fail("DeepInfra response contained neither b64_json nor URL", "empty_response")return success_response(image=image_ref, model=model_id, prompt=prompt, aspect_ratio=aspect, provider="deepinfra",- extra={"size": size},- )+ extra={"size": size})def register(ctx) -> None:diff --git a/plugins/image_gen/fal/__init__.py b/plugins/image_gen/fal/__init__.pyindex d85b238e5fe..0ce42a39d8f 100644--- a/plugins/image_gen/fal/__init__.py+++ b/plugins/image_gen/fal/__init__.py@@ -18,8 +18,7 @@ from plugins.image_gen._common import StaticImageGenProvider, catalog_rowslogger = logging.getLogger(__name__)_PASSTHROUGH_KWARGS = (- "num_inference_steps", "guidance_scale", "num_images", "output_format", "seed", "upscale",-)+ "num_inference_steps", "guidance_scale", "num_images", "output_format", "seed", "upscale")class FalImageGenProvider(StaticImageGenProvider):@@ -30,8 +29,7 @@ class FalImageGenProvider(StaticImageGenProvider):setup = dict(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",- key="FAL_KEY", prompt="FAL API key", url="https://fal.ai/dashboard/keys",- )+ key="FAL_KEY", prompt="FAL API key", url="https://fal.ai/dashboard/keys")def is_available(self) -> bool:# Direct FAL_KEY or a managed Nous fal-queue origin, per the legacy module.diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.pyindex b5c15a34a81..6550c3ab6eb 100644--- a/plugins/image_gen/krea/__init__.py+++ b/plugins/image_gen/krea/__init__.py@@ -20,8 +20,7 @@ from agent.secret_scope import get_secretfrom agent.image_gen_provider import DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, save_url_image, success_responsefrom plugins.image_gen._common import (ErrorFn, StaticImageGenProvider, collect_source_images, error_factory, load_image_gen_config, post_json,- prompt_required_error, resolve_static_model,-)+ prompt_required_error, resolve_static_model)logger = logging.getLogger(__name__)@@ -83,8 +82,7 @@ _POLL_FAILURES: Dict[str, Tuple[str, Callable[[str, Any], str]]] = {"invalid_json": ("invalid_response", lambda job_id, detail: f"Krea poll returned invalid JSON: {detail}"),"deadline": ("timeout", lambda job_id, detail: (f"Krea job {job_id} did not complete within "- f"{int(_POLL_TIMEOUT_SECONDS)}s (last status: {detail or 'unknown'})"- )),+ f"{int(_POLL_TIMEOUT_SECONDS)}s (last status: {detail or 'unknown'})")),}# Managed gateway prices base text-to-image and URL style references only._MANAGED_UNSUPPORTED = (("trained styles (LoRAs)", "styles"), ("moodboards", "moodboards"))@@ -103,8 +101,7 @@ def _krea_section() -> Dict[str, Any]:def _resolve_model(explicit: Optional[str] = None) -> Tuple[str, Dict[str, Any]]:return resolve_static_model(_MODELS, DEFAULT_MODEL, env_var="KREA_IMAGE_MODEL", config_key="krea", explicit=explicit,- config=_load_krea_config(),- )+ config=_load_krea_config())def _resolve_managed_krea_gateway():@@ -253,8 +250,7 @@ def _poll_krea_job(if time.monotonic() >= deadline:return give_up("deadline", last_status,- "Krea enhance job %s did not finish in %ds", job_id, int(timeout_seconds),- )+ "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]:@@ -284,8 +280,7 @@ def _enhance_image(try:resp = requests.post(f"{base_url}{_ENHANCE_PATH}", headers=_headers(auth_token, managed=managed, json_body=True),- json=payload, timeout=30,- )+ json=payload, timeout=30)resp.raise_for_status()job_id = (resp.json() or {}).get("job_id")except Exception as exc: # noqa: BLE001@@ -356,8 +351,7 @@ def _submit_job(submit_body, failure = post_json(f"{base_url}/generate/image/krea/krea-2/{model_path}",headers=_headers(auth_token, managed=managed, json_body=True),- payload=payload, timeout=30, label="Krea", error_message=_submit_error_message,- )+ payload=payload, timeout=30, label="Krea", error_message=_submit_error_message)if failure is not None:if failure.kind == "http":status, err_msg = failure.status, failure.message@@ -369,13 +363,11 @@ def _submit_job("Krea's shared-key concurrency cap was hit — retry shortly." if status == 429 elsef"Model '{model_id}' may not be enabled/priced on the Nous Portal's Krea gateway. ""Set KREA_API_KEY to use Krea directly, or pick a different model via "- "`hermes tools` → Image Generation."- )+ "`hermes tools` → Image Generation.")return None, fail(f"Nous Subscription Krea gateway rejected '{model_id}' "f"(HTTP {status}): {err_msg}. {hint}",- "api_error",- )+ "api_error")return None, fail(failure.error, "api_error")if failure.kind == "timeout":return None, fail("Krea submit timed out (30s)", "timeout")@@ -424,8 +416,7 @@ class KreaImageGenProvider(StaticImageGenProvider):setup = dict(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.",- key="KREA_API_KEY", prompt="Krea API key", url="https://www.krea.ai/settings/api-tokens",- )+ key="KREA_API_KEY", prompt="Krea API key", url="https://www.krea.ai/settings/api-tokens")def is_available(self) -> bool:# Direct key OR the managed Nous gateway, so portal users without a@@ -466,8 +457,7 @@ class KreaImageGenProvider(StaticImageGenProvider):"https://www.krea.ai/settings/api-tokens, or sign in to ""a Nous account with the managed Krea gateway enabled ""(`hermes setup`).",- "auth_required",- )+ "auth_required")model_id, meta = _resolve_model(kwargs.get("model"))creativity = _resolve_creativity(kwargs.get("creativity"))@@ -482,13 +472,11 @@ class KreaImageGenProvider(StaticImageGenProvider):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",- )+ "unsupported_argument")# 1. Submit job.job_id, err = _submit_job(- base_url, auth_token, meta["path"], payload, managed is not None, model_id, fail,- )+ base_url, auth_token, meta["path"], payload, managed is not None, model_id, fail)if err is not None:return err@@ -516,8 +504,7 @@ class KreaImageGenProvider(StaticImageGenProvider):upscaled = Falseif _upscale_requested(kwargs.get("upscale"), meta):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 = True@@ -542,8 +529,7 @@ class KreaImageGenProvider(StaticImageGenProvider):extra["completed_at"] = job["completed_at"]return success_response(image=image_ref, model=model_id, prompt=prompt, aspect_ratio=aspect, provider="krea",- modality="image" if style_refs else "text", extra=extra,- )+ modality="image" if style_refs else "text", extra=extra)def register(ctx) -> None:diff --git a/plugins/image_gen/meta-ai/__init__.py b/plugins/image_gen/meta-ai/__init__.pyindex 2cc0be8b5ad..b5a01e79368 100644--- a/plugins/image_gen/meta-ai/__init__.py+++ b/plugins/image_gen/meta-ai/__init__.py@@ -15,12 +15,10 @@ from typing import Any, Dict, List, Optional, Tuplefrom agent.secret_scope import get_secretfrom agent.image_gen_provider import (- DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, save_b64_image, save_url_image, success_response-)+ DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, save_b64_image, save_url_image, success_response)from plugins.image_gen._common import (StaticImageGenProvider, error_factory, import_openai, openai_importable, prompt_required_error,- resolve_static_model, size_for,-)+ resolve_static_model, size_for)logger = logging.getLogger(__name__)@@ -70,8 +68,7 @@ class MetaImageGenProvider(StaticImageGenProvider):default_model_id = DEFAULT_MODELsetup = dict(name="Meta Model API", badge="paid", tag="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",- )+ key=API_KEY_ENV, prompt="Meta Model API key (LLM|... token)", url="https://api.meta.ai")def is_available(self) -> bool:return bool(_resolve_api_key()) and openai_importable()@@ -94,8 +91,7 @@ class MetaImageGenProvider(StaticImageGenProvider):return error_factory("meta-ai", aspect)(f"{API_KEY_ENV} not set. Run `hermes tools` -> Image ""Generation -> Meta Model API to configure.",- "auth_required",- )+ "auth_required")openai, err = import_openai("meta-ai", aspect)if err:@@ -131,8 +127,7 @@ class MetaImageGenProvider(StaticImageGenProvider):extra["revised_prompt"] = first.revised_promptreturn success_response(image=image_ref, model=model_id, prompt=prompt, aspect_ratio=aspect, provider="meta-ai",- modality="text", extra=extra,- )+ modality="text", extra=extra)def register(ctx) -> None:diff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.pyindex 059318cb15f..98d1c8f17f7 100644--- a/plugins/image_gen/openai-codex/__init__.py+++ b/plugins/image_gen/openai-codex/__init__.py@@ -24,8 +24,7 @@ from agent.image_gen_provider import DEFAULT_ASPECT_RATIO, resolve_aspect_ratio,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,StaticImageGenProvider, collect_source_images, error_factory, prompt_required_error,- resolve_static_model, size_for,-)+ resolve_static_model, size_for)logger = logging.getLogger(__name__)@@ -38,8 +37,7 @@ _CODEX_CHAT_MODEL = "gpt-5.5"_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex"_CODEX_INSTRUCTIONS = ("You are an assistant that must fulfill image generation and image editing "- "requests by using the image_generation tool when provided."-)+ "requests by using the image_generation tool when provided.")_MAX_REFERENCE_IMAGES = 16_MAX_INPUT_IMAGE_BYTES = 25 * 1024 * 1024@@ -56,8 +54,7 @@ _NONFINAL_RETRIES = 1_NO_AUTH = ("No Codex/ChatGPT OAuth credentials available. Run "- "`hermes auth codex` (or `hermes setup` → Codex) to sign in."-)+ "`hermes auth codex` (or `hermes setup` → Codex) to sign in.")def _summarize_error_body(body: str) -> str:@@ -77,8 +74,7 @@ def _summarize_error_body(body: str) -> str:def _resolve_model() -> Tuple[str, Dict[str, Any]]:return resolve_static_model(- _MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai-codex"- )+ _MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai-codex")def _read_codex_access_token() -> Optional[str]:@@ -121,8 +117,7 @@ def _data_url_to_input_image_url(value: str) -> str:return _encode_input_image(base64.b64decode(data, validate=True),"Image data URL exceeds 25MB cap",- "Image data URL does not contain supported image bytes",- )+ "Image data URL does not contain supported image bytes")def _local_image_to_data_url(value: str) -> str:@@ -144,8 +139,7 @@ def _local_image_to_data_url(value: str) -> str: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}",- )+ f"Image input path is not a supported image: {value}")def _to_input_image_part(value: str) -> Dict[str, str]:@@ -297,8 +291,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)final_b64: Optional[str] = None@@ -350,8 +343,7 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):"env_vars": [],"post_setup_hint": ("Sign in with `hermes auth codex` (or `hermes setup` → Codex) "- "if you haven't already. No API key needed."- ),+ "if you haven't already. No API key needed."),}def capabilities(self) -> Dict[str, Any]:@@ -373,8 +365,7 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):import httpx # noqa: F401except ImportError:return error_factory("openai-codex", aspect)(- "httpx Python package not installed (pip install httpx)", "missing_dependency"- )+ "httpx Python package not installed (pip install httpx)", "missing_dependency")tier_id, meta = _resolve_model()size = size_for(aspect)@@ -390,21 +381,18 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):for attempt in range(attempts):collected = _collect_image_b64(token, prompt=prompt, size=size, quality=meta["quality"],- input_images=input_images or None,- )+ input_images=input_images or None)if collected and collected.get("source") == "final" and collected.get("b64"):breakif attempt < _NONFINAL_RETRIES:kind = ("progressive-only partial frame"if collected and collected.get("source") == "partial"- else "no image_generation_call result"- )+ else "no image_generation_call result")logger.warning("Codex image stream ended with %s (attempt %s/%s); ""retrying once before failing closed.",- kind, attempt + 1, attempts,- )+ kind, attempt + 1, attempts)except Exception as exc:logger.debug("Codex image generation failed", exc_info=True)return fail(f"OpenAI image generation via Codex auth failed: {exc}", "api_error")@@ -412,8 +400,7 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):if not collected or not collected.get("b64"):return fail(f"Codex response contained no image_generation_call result after {attempts} attempt(s)",- "empty_response",- )+ "empty_response")image_source = collected.get("source") or "unknown"b64 = collected["b64"]# Never deliver a progressive-only frame as success (smeared previews).@@ -424,15 +411,13 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):pixel_hint = Nonedetail = ("Codex returned only a progressive partial image frame after "- f"{attempts} 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 = fail(detail, "incomplete_image")err.update(image_source=image_source, requested_size=size,- partial_pixel_size=pixel_hint, nonfinal_retries=_NONFINAL_RETRIES,- )+ partial_pixel_size=pixel_hint, nonfinal_retries=_NONFINAL_RETRIES)return errtry:@@ -450,8 +435,7 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):"image_source": image_source,"requested_size": size,"pixel_size": pixel_size,- },- )+ })def register(ctx) -> None:diff --git a/plugins/image_gen/openai/__init__.py b/plugins/image_gen/openai/__init__.pyindex b6a59f973f4..1315066160c 100644--- a/plugins/image_gen/openai/__init__.py+++ b/plugins/image_gen/openai/__init__.py@@ -15,8 +15,7 @@ from agent.image_gen_provider import DEFAULT_ASPECT_RATIO, resolve_aspect_ratio,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,StaticImageGenProvider, collect_source_images, error_factory, import_openai, materialize_image,- openai_importable, prompt_required_error, resolve_static_model, size_for,-)+ openai_importable, prompt_required_error, resolve_static_model, size_for)logger = logging.getLogger(__name__)@@ -64,8 +63,7 @@ class OpenAIImageGenProvider(StaticImageGenProvider):setup = dict(name="OpenAI", badge="paid",tag="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",- )+ key="OPENAI_API_KEY", prompt="OpenAI API key", url="https://platform.openai.com/api-keys")def is_available(self) -> bool:return bool(get_secret("OPENAI_API_KEY")) and openai_importable()@@ -89,8 +87,7 @@ class OpenAIImageGenProvider(StaticImageGenProvider):"OPENAI_API_KEY not set. Run `hermes tools` → Image ""Generation → OpenAI to configure, or `hermes setup` ""to add the key.",- "auth_required",- )+ "auth_required")openai, err = import_openai("openai", aspect)if err:@@ -119,8 +116,7 @@ class OpenAIImageGenProvider(StaticImageGenProvider):response = client.images.edit(model=API_MODEL, image=files if len(files) > 1 else files[0], prompt=prompt,size=size, # type: ignore[arg-type] # OPENAI_SIZES values are valid gpt-image sizes- quality=meta["quality"], n=1,- )+ quality=meta["quality"], n=1)except Exception as exc:logger.debug("OpenAI image edit failed", exc_info=True)return fail(f"OpenAI image editing failed: {exc}", "api_error")@@ -129,8 +125,7 @@ class OpenAIImageGenProvider(StaticImageGenProvider):# ``response_format`` as an unknown parameter. Don't send it.try:response = client.images.generate(- model=API_MODEL, prompt=prompt, size=size, n=1, quality=meta["quality"],- )+ 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 fail(f"OpenAI image generation failed: {exc}", "api_error")@@ -142,8 +137,7 @@ class OpenAIImageGenProvider(StaticImageGenProvider):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,- )+ model=tier_id, prompt=prompt, aspect=aspect, log=logger)if err:return errextra: Dict[str, Any] = {"size": size, "quality": meta["quality"]}@@ -151,8 +145,7 @@ class OpenAIImageGenProvider(StaticImageGenProvider):extra["revised_prompt"] = first.revised_promptreturn success_response(image=image_ref, model=tier_id, prompt=prompt, aspect_ratio=aspect, provider="openai",- modality="image" if is_edit else "text", extra=extra,- )+ modality="image" if is_edit else "text", extra=extra)def register(ctx) -> None:diff --git a/plugins/image_gen/openrouter/__init__.py b/plugins/image_gen/openrouter/__init__.pyindex 4c826715fcd..31ff849e100 100644--- a/plugins/image_gen/openrouter/__init__.py+++ b/plugins/image_gen/openrouter/__init__.py@@ -21,8 +21,7 @@ from typing import Any, Dict, List, Optional, Tuplefrom agent.image_gen_provider import (DEFAULT_ASPECT_RATIO, ImageGenProvider, error_response, resolve_aspect_ratio, save_b64_image,- save_url_image, success_response,-)+ save_url_image, success_response)from plugins.image_gen._common import error_factory, load_image_gen_config, post_jsonlogger = logging.getLogger(__name__)@@ -96,13 +95,11 @@ _IMAGE_API_MODELS: Dict[str, Dict[str, Any]] = {"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,- ),+ 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,- ),+ 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",@@ -114,38 +111,30 @@ _IMAGE_API_MODELS: Dict[str, Dict[str, Any]] = {"The only model here with background=transparent (cut-out PNG)",aspect_ratios=("1:1", "3:2", "2:3", "auto"),quality=_OPENAI_QUALITY, background=("auto", "transparent", "opaque"), compression=True,- max_n=10, max_refs=16,- ),+ 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,- ),+ 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,- ),+ 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"), max_n=1, max_refs=3,- ),+ "auto"),+ 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,- ),+ 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,- ),+ 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"), seed=True, max_n=6, max_refs=4,- ),+ resolutions=("1K", "2K"), seed=True, max_n=6, max_refs=4),}# Applied to a catalog model the table doesn't describe. Empty ``aspect_ratios``@@ -187,8 +176,7 @@ _IMAGE_API_EXTRA_KEYS = ("resolution", "quality", "background", "output_format",# Enum knobs: payload field → catalog key holding the allowed values._IMAGE_API_ENUMS = (- ("resolution", "resolutions"), ("quality", None), ("background", None), ("output_format", None),-)+ ("resolution", "resolutions"), ("quality", None), ("background", None), ("output_format", None))# Integer knobs: payload field → (catalog gate flag, clamp)._IMAGE_API_INTS = (("output_compression", "compression", lambda v: max(0, min(100, v))), ("seed", "seed", lambda v: v),@@ -253,14 +241,12 @@ def _access_error_hint(display: str, model_id: str, env_var: str, status: int, ereturn Nonelow = (err_msg or "").lower()gated = status in (402, 403, 404) or any(- s in low for s in ("no endpoints", "no allowed", "not a valid model", "data policy")- )+ s in low for s in ("no endpoints", "no allowed", "not a valid model", "data policy"))if not gated:return Nonereturn (f"{display} can't reach image model '{model_id}' ({status}) — enable OpenAI "- f"image access in your {display} account, or set {env_var}={_FALLBACK_MODEL}."- )+ f"image access in your {display} account, or set {env_var}={_FALLBACK_MODEL}.")def _get_catalog(base_url: str, path: str, api_key: str, timeout: Any) -> List[Tuple[str, Dict[str, Any]]]:@@ -390,15 +376,13 @@ def _pick_exact_aspect_ratio(return valuenotes.append(f"requested aspect_ratio '{value}' is unsupported by this model; "- f"used the '{semantic}' mapping instead"- )+ f"used the '{semantic}' mapping instead")if not supported:# Unknown enum: an out-of-enum aspect_ratio is a hard 400 (unlike an# unknown *parameter*, which the endpoint ignores), so omit the field.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"- )+ f"unknown; the field was omitted and '{semantic}' was not applied")return Nonefor candidate in _ASPECT_PREFERENCES.get(semantic, ()):if candidate in supported:@@ -467,8 +451,7 @@ def _build_image_api_payload(if len(references) > len(usable):notes.append(f"{len(references)} reference image(s) supplied but this model "- f"accepts {max_refs}; extras dropped"- )+ f"accepts {max_refs}; extras dropped")if usable:payload["input_references"] = [{"type": "image_url", "image_url": {"url": url}} for url in usable]return payload, notes@@ -625,8 +608,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):if self._supports_image_api:models.extend({"id": model_id, "display": meta["display"], "strengths": f"{meta['strengths']} (Image API)"}- for model_id, meta in _IMAGE_API_MODELS.items()- )+ for model_id, meta in _IMAGE_API_MODELS.items())return modelsdef _cached_catalog(self, attr: str, label: str, **fetch: Any) -> List[Dict[str, Any]]:@@ -648,14 +630,12 @@ class OpenRouterCompatImageProvider(ImageGenProvider):def _image_api_live_models(self) -> List[Dict[str, Any]]:return self._cached_catalog("_image_api_models_cache", "Image API catalog", path="/images/models", meta=_IMAGE_API_MODELS,- generic="Image API model (from live OpenRouter catalog)", image_output_only=False,- )+ generic="Image API model (from live OpenRouter catalog)", image_output_only=False)def _live_models(self) -> List[Dict[str, Any]]:return self._cached_catalog("_live_models_cache", "image model catalog", path="/models", meta=_KNOWN_MODEL_META,- generic="Image-output model (from live OpenRouter catalog)", image_output_only=True,- )+ generic="Image-output model (from live OpenRouter catalog)", image_output_only=True)def default_model(self) -> Optional[str]:# The catalog default, not the effective runtime model (_resolve_model_chain).@@ -714,12 +694,10 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return _fail("Could not read the reference image(s) requested for editing: "+ ", ".join(unreadable) + ". Refusing to silently fall back to text-to-image.",- "io_error",- )+ "io_error")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,- )+ references=usable_refs, config_key=self._config_key, kwargs=kwargs)if unreadable:notes.insert(0, f"dropped unreadable reference image(s): {', '.join(unreadable)}")@@ -736,8 +714,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):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,- )+ catch_request_exception=True)if failure is not None:if failure.kind != "http":return _fail(failure.error, failure.error_type, retryable=failure.kind == "timeout")@@ -752,8 +729,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):f"Model '{model_id}' does not exist on the OpenRouter Image API "f"(its catalog is separate from chat-completions — check "f"GET {base_url}/images/models).",- "model_access", retryable=True,- )+ "model_access", retryable=True)return _fail(failure.error, "api_error", retryable=status in _IMAGE_API_FALLBACK_STATUSES)entries = [e for e in _list_at(body, "data") if isinstance(e, dict)]@@ -771,8 +747,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return success_response(image=saved[0], model=model_id, prompt=prompt, aspect_ratio=semantic_aspect, provider=self._name,modality="image" if usable_refs else "text",- extra=_image_api_extra(payload, saved, usable_refs, notes, body),- )+ extra=_image_api_extra(payload, saved, usable_refs, notes, body))def _generate_via_chat(self, *, model_id: str, prompt: str, aspect: str, content: List[Dict[str, Any]],@@ -789,8 +764,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):}result, failure = post_json(f"{base_url}/chat/completions", headers=headers, payload=payload, timeout=_REQUEST_TIMEOUT,- label=self._display,- )+ label=self._display)if failure is not None:if failure.kind != "http":reason = "timed out" if failure.kind == "timeout" else None@@ -836,8 +810,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return fail(f"No {self._display} credentials found. "f"Configure {self._display} in `hermes tools` → Image Generation.",- "missing_api_key",- )+ "missing_api_key")model_chain = self._resolve_model_chain(kwargs.get("model"))aspect = resolve_aspect_ratio(aspect_ratio)@@ -864,14 +837,12 @@ class OpenRouterCompatImageProvider(ImageGenProvider):if surface == "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,- )+ references=references, base_url=base_url, headers=headers, kwargs=kwargs)reason = "failed on the image API" if outcome.pop("_retryable", False) else Noneelse:outcome, reason = self._generate_via_chat(model_id=model_id, prompt=prompt, aspect=aspect, content=content,- base_url=base_url, headers=headers,- )+ base_url=base_url, headers=headers)if outcome.get("success") or reason is None or i == len(model_chain) - 1:return outcomelogger.info(@@ -882,8 +853,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):return last_error or error_response(error=f"{self._display} image generation failed after trying all candidate models.",error_type="api_error", provider=self._name,- model=model_chain[-1] if model_chain else "", prompt=prompt, aspect_ratio=aspect,- )+ model=model_chain[-1] if model_chain else "", prompt=prompt, aspect_ratio=aspect)def _build_providers() -> List[OpenRouterCompatImageProvider]:@@ -898,8 +868,7 @@ def _build_providers() -> List[OpenRouterCompatImageProvider]:"env_vars": [{"key": "OPENROUTER_API_KEY", "prompt": "OpenRouter API key", "url": "https://openrouter.ai/keys",}],- },- ),+ }),OpenRouterCompatImageProvider(provider_name="nous", display_name="Nous Portal", runtime_name="nous", config_key="nous",model_env_var="NOUS_IMAGE_MODEL",@@ -909,8 +878,7 @@ def _build_providers() -> List[OpenRouterCompatImageProvider]:"tag": "Reference-grounded image generation via Nous Portal (OpenRouter-backed)","env_vars": [],"requires_nous_auth": True,- },- ),+ }),]diff --git a/plugins/image_gen/xai/__init__.py b/plugins/image_gen/xai/__init__.pyindex d3c695fafac..107af84fb8d 100644--- a/plugins/image_gen/xai/__init__.py+++ b/plugins/image_gen/xai/__init__.py@@ -20,20 +20,16 @@ import requestsfrom agent.image_gen_provider import DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, success_responsefrom plugins.image_gen._common import (StaticImageGenProvider, catalog_rows, collect_source_images, error_factory,- load_image_gen_config, materialize_image, post_json,-)+ load_image_gen_config, materialize_image, post_json)from tools.xai_http import (build_xai_storage_options, hermes_xai_user_agent, maybe_mark_xai_storage_notice_seen,- read_xai_imagine_storage_config, resolve_xai_http_credentials, xai_storage_notice_text,-)+ read_xai_imagine_storage_config, resolve_xai_http_credentials, xai_storage_notice_text)logger = logging.getLogger(__name__)_MODELS: Dict[str, Dict[str, Any]] = {"grok-imagine-image": {- "display": "Grok Imagine Image",- "speed": "~5-10s",- "strengths": "Fast, high-quality",+ "display": "Grok Imagine Image", "speed": "~5-10s", "strengths": "Fast, high-quality"},"grok-imagine-image-2.0": {"display": "Grok Imagine Image 2.0",@@ -89,8 +85,7 @@ def _fetch_live_models() -> Dict[str, Dict[str, Any]]:response = requests.get(f"{_base_url(creds)}/image-generation-models",headers={"Authorization": f"Bearer {api_key}", "User-Agent": hermes_xai_user_agent()},- timeout=_LIVE_TIMEOUT,- )+ timeout=_LIVE_TIMEOUT)response.raise_for_status()payload = response.json()out: Dict[str, Dict[str, Any]] = {}@@ -246,8 +241,7 @@ class XAIImageGenProvider(StaticImageGenProvider):if not api_key: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",- )+ "missing_api_key")model_id, meta = _resolve_model(kwargs.get("model"))aspect = resolve_aspect_ratio(aspect_ratio)@@ -266,8 +260,7 @@ class XAIImageGenProvider(StaticImageGenProvider):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",- )+ "invalid_image_url")is_edit = bool(source_images)headers = {@@ -277,8 +270,7 @@ class XAIImageGenProvider(StaticImageGenProvider):}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")@@ -290,8 +282,7 @@ class XAIImageGenProvider(StaticImageGenProvider):return edit_fail(f"Could not load source image for editing: {exc}", "io_error", model=model_id)payload: Dict[str, Any] = {"model": model_id, "prompt": prompt}payload["image" if len(image_fields) == 1 else "images"] = (- image_fields[0] if len(image_fields) == 1 else image_fields- )+ image_fields[0] if len(image_fields) == 1 else image_fields)endpoint_url = f"{base_url}/images/edits"else:payload = {@@ -306,8 +297,7 @@ class XAIImageGenProvider(StaticImageGenProvider):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",- )+ 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)@@ -328,8 +318,7 @@ class XAIImageGenProvider(StaticImageGenProvider):# materialise locally so downstream consumers 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,- )+ model=model_id, prompt=prompt, aspect=aspect, log=logger)if err:return err@@ -345,8 +334,7 @@ class XAIImageGenProvider(StaticImageGenProvider):extra["usage"] = result["usage"]return success_response(image=image_ref, model=model_id, prompt=prompt, aspect_ratio=aspect, provider="xai",- modality="image" if is_edit else "text", extra=extra,- )+ modality="image" if is_edit else "text", extra=extra)def register(ctx: Any) -> None: