Skip to content

The agent that grows with you

refactor(image_generate): capability-gated dynamic schema (554 → 317 tok/call, −43%) (#97057)

Tekniuma619db663374
diff --git a/plugins/image_gen/fal/__init__.py b/plugins/image_gen/fal/__init__.py
index face534286d..6acd54c1905 100644
--- a/plugins/image_gen/fal/__init__.py
+++ b/plugins/image_gen/fal/__init__.py
@@ -108,12 +108,18 @@ class FalImageGenProvider(ImageGenProvider):
_model_id, meta = _it._resolve_fal_model()
except Exception: # noqa: BLE001
return {"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}
+ return {
+ "modalities": ["text"],
+ "max_reference_images": 0,
+ "supports_upscale": True,
+ }
def generate(
self,
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.py
index 0027a8f9b1f..bbaded47b05 100644
--- a/plugins/image_gen/krea/__init__.py
+++ b/plugins/image_gen/krea/__init__.py
@@ -406,8 +406,13 @@ class KreaImageGenProvider(ImageGenProvider):
def capabilities(self) -> Dict[str, Any]:
# Krea supports reference-guided generation (image-to-image style
- # transfer) via image_style_references — up to 10 refs.
- return {"modalities": ["text", "image"], "max_reference_images": 10}
+ # transfer) via image_style_references — up to 10 refs — and an
+ # opt-in Enhance upscale pass (see generate()'s upscale_requested).
+ return {
+ "modalities": ["text", "image"],
+ "max_reference_images": 10,
+ "supports_upscale": True,
+ }
# ------------------------------------------------------------------
# generate()
diff --git a/tests/tools/test_image_generate_schema.py b/tests/tools/test_image_generate_schema.py
new file mode 100644
index 00000000000..1a82af41045
--- /dev/null
+++ b/tests/tools/test_image_generate_schema.py
@@ -0,0 +1,181 @@
+"""image_generate dynamic schema — capability-gated params (#95681 diet).
+
+Contract: args the active model cannot honor are NOT advertised. Coverage
+is guaranteed two ways — every in-tree FAL catalog entry must declare the
+capability keys the schema builder reads (test below fails when a new
+model is added without them), and the plugin provider ABC's capabilities()
+default fails closed to text-only/no-upscale.
+"""
+import json
+import os
+import sys
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
+
+import tools.image_generation_tool as ig
+from tools.image_generation_tool import (
+ FAL_MODELS,
+ IMAGE_GENERATE_SCHEMA,
+ _build_dynamic_image_schema,
+)
+
+
+class TestCatalogCapabilityCoverage(unittest.TestCase):
+ """Every FAL catalog entry must carry what the schema builder reads."""
+
+ def test_every_model_declares_capability_keys(self):
+ for model_id, meta in FAL_MODELS.items():
+ with self.subTest(model=model_id):
+ # upscale default flag must be present and boolean.
+ self.assertIn("upscale", meta, model_id)
+ self.assertIsInstance(meta["upscale"], bool, model_id)
+ # Edit-capable models must cap their reference images.
+ if meta.get("edit_endpoint"):
+ self.assertIn("max_reference_images", meta, model_id)
+ self.assertGreaterEqual(
+ int(meta["max_reference_images"]), 1, model_id,
+ )
+
+ def test_provider_abc_default_fails_closed(self):
+ from agent.image_gen_provider import ImageGenProvider
+
+ caps_src = ImageGenProvider.capabilities
+ # Instantiate via a minimal concrete subclass.
+ class _P(ImageGenProvider):
+ name = "t"
+ display_name = "T"
+ def generate(self, prompt, aspect_ratio="landscape", **kw):
+ return {}
+ def list_models(self):
+ return []
+ caps = _P().capabilities()
+ self.assertEqual(caps.get("modalities"), ["text"])
+ self.assertFalse(caps.get("supports_upscale", False))
+
+ def test_every_intree_plugin_declares_what_it_implements(self):
+ """Fleet-wide declaration ⇄ implementation contract (maintainer
+ requirement: EVERY provider combo must carry capability info).
+
+ For each in-tree image_gen plugin: if its generate() source
+ implements an upscale pass, capabilities() must declare
+ supports_upscale — and vice versa, so a stale declaration can't
+ advertise an upscale that silently no-ops. modalities and
+ max_reference_images must always be declared."""
+ import ast
+ import pathlib
+
+ plugins_dir = (pathlib.Path(__file__).resolve().parents[2]
+ / "plugins" / "image_gen")
+ assert plugins_dir.is_dir(), plugins_dir
+ checked = 0
+ for plugin in sorted(plugins_dir.iterdir()):
+ src_file = plugin / "__init__.py"
+ if not src_file.is_file():
+ continue
+ src = src_file.read_text(encoding="utf-8")
+ if "def capabilities" not in src:
+ continue
+ checked += 1
+ with self.subTest(provider=plugin.name):
+ # capabilities() must declare the two mandatory axes.
+ self.assertIn("modalities", src, plugin.name)
+ self.assertIn("max_reference_images", src, plugin.name)
+ # upscale: declaration ⇄ implementation, both directions.
+ declares = "supports_upscale" in src
+ # Implementation = generate() (or its helpers in the same
+ # file) reads the upscale kwarg directly, or passes it
+ # through in a delegation whitelist (fal plugin → in-tree
+ # Clarity chain).
+ implements = ('kwargs.get("upscale")' in src
+ or "upscale_requested" in src
+ or 'kwargs["upscale"]' in src
+ or "def _upscale" in src
+ or '"upscale",' in src)
+ self.assertEqual(
+ declares, implements,
+ f"{plugin.name}: supports_upscale declaration "
+ f"({declares}) != implementation ({implements}) — "
+ "declare it in capabilities() iff generate() honors it",
+ )
+ # The audit must actually have covered the fleet.
+ self.assertGreaterEqual(checked, 6, "plugin sweep found too few providers")
+
+
+class TestDynamicParamGating(unittest.TestCase):
+ def _schema_for(self, model_id):
+ with patch.object(ig, "_resolve_fal_model",
+ return_value=(model_id, FAL_MODELS[model_id])), \
+ patch.object(ig, "_read_configured_image_provider",
+ return_value=None):
+ return _build_dynamic_image_schema()
+
+ def _t2i_only(self):
+ return next(m for m, meta in FAL_MODELS.items()
+ if not meta.get("edit_endpoint"))
+
+ def _edit_multi_ref(self):
+ return next(m for m, meta in FAL_MODELS.items()
+ if meta.get("edit_endpoint")
+ and int(meta.get("max_reference_images") or 0) > 1)
+
+ def test_t2i_only_model_hides_edit_args(self):
+ schema = self._schema_for(self._t2i_only())
+ props = schema["parameters"]["properties"]
+ self.assertNotIn("image_url", props)
+ self.assertNotIn("reference_image_urls", props)
+ self.assertIn("cannot edit", schema["description"])
+
+ def test_edit_model_advertises_edit_args_with_cap(self):
+ model = self._edit_multi_ref()
+ schema = self._schema_for(model)
+ props = schema["parameters"]["properties"]
+ self.assertIn("image_url", props)
+ self.assertIn("reference_image_urls", props)
+ self.assertEqual(
+ props["reference_image_urls"]["maxItems"],
+ int(FAL_MODELS[model]["max_reference_images"]),
+ )
+
+ def test_fal_always_advertises_upscale(self):
+ # Clarity Upscaler chains for any FAL model on explicit request.
+ for model in (self._t2i_only(), self._edit_multi_ref()):
+ schema = self._schema_for(model)
+ self.assertIn("upscale", schema["parameters"]["properties"], model)
+
+ def test_text_only_plugin_provider_hides_edit_and_upscale(self):
+ class _Prov:
+ display_name = "Codex Images"
+ def capabilities(self):
+ return {"modalities": ["text"], "max_reference_images": 0}
+ def default_model(self):
+ return "img-1"
+ with patch.object(ig, "_read_configured_image_provider",
+ return_value="codex"), \
+ patch("agent.image_gen_registry.get_provider",
+ return_value=_Prov()), \
+ patch("hermes_cli.plugins._ensure_plugins_discovered"):
+ schema = _build_dynamic_image_schema()
+ props = schema["parameters"]["properties"]
+ self.assertEqual(sorted(props), ["aspect_ratio", "prompt"])
+ self.assertNotIn("upscale", props)
+
+ def test_static_schema_carries_no_capability_args(self):
+ """The registration-time placeholder must stay minimal — dynamic
+ overrides own the capability args (do-not-re-add guard)."""
+ props = IMAGE_GENERATE_SCHEMA["parameters"]["properties"]
+ self.assertEqual(sorted(props), ["aspect_ratio", "prompt"])
+
+ def test_handler_still_rejects_unadvertised_edit_with_teaching_error(self):
+ """Wire compat: image_url on a t2i-only model is accepted by the
+ handler and answered with the capability error (not a schema-level
+ unknown-arg failure). Pin the error text's presence in the source."""
+ import inspect
+ handler_src = inspect.getsource(ig)
+ self.assertIn("capable of image-to-image / editing", handler_src)
+ self.assertIn("omit image_url", handler_src)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/tools/test_image_generation.py b/tests/tools/test_image_generation.py
index d5a7a65bfbc..d39d1214806 100644
--- a/tests/tools/test_image_generation.py
+++ b/tests/tools/test_image_generation.py
@@ -347,16 +347,18 @@ class TestAspectRatioNormalization:
class TestRegistryIntegration:
def test_schema_exposes_expected_agent_params(self, image_tool):
- """The agent-facing schema exposes the unified text+image surface:
- prompt (required), aspect_ratio, the image-to-image inputs
- image_url + reference_image_urls, and the opt-in upscale pass. Model
- selection stays a user-level config choice, never an agent-level arg."""
+ """The static registration schema stays minimal — prompt (required)
+ + aspect_ratio. Capability args (image_url, reference_image_urls,
+ upscale) are added per-model by the dynamic override so sessions
+ whose active model can't honor them never see them (#95681 diet).
+ Model selection stays a user-level config choice, never an
+ agent-level arg."""
props = image_tool.IMAGE_GENERATE_SCHEMA["parameters"]["properties"]
- assert set(props.keys()) == {
- "prompt", "aspect_ratio", "image_url", "reference_image_urls",
- "upscale",
- }
+ assert set(props.keys()) == {"prompt", "aspect_ratio"}
assert image_tool.IMAGE_GENERATE_SCHEMA["parameters"]["required"] == ["prompt"]
+ # The dynamic builder owns the capability args.
+ dyn = image_tool._build_dynamic_image_schema()
+ assert "parameters" in dyn and "prompt" in dyn["parameters"]["properties"]
def test_aspect_ratio_enum_is_three_values(self, image_tool):
enum = image_tool.IMAGE_GENERATE_SCHEMA["parameters"]["properties"]["aspect_ratio"]["enum"]
diff --git a/tests/tools/test_image_generation_image_to_image.py b/tests/tools/test_image_generation_image_to_image.py
index 250a452660e..6bfa308929a 100644
--- a/tests/tools/test_image_generation_image_to_image.py
+++ b/tests/tools/test_image_generation_image_to_image.py
@@ -276,9 +276,14 @@ class TestDynamicSchema:
from tools.image_generation_tool import _build_dynamic_image_schema
_write_cfg(cfg_home, {"image_gen": {"model": "fal-ai/nano-banana-pro"}})
- desc = _build_dynamic_image_schema()["description"]
- assert "text-to-image" in desc and "image-to-image" in desc
- assert "routes automatically" in desc
+ schema = _build_dynamic_image_schema()
+ # Edit capability now surfaces as ADVERTISED PARAMS, not prose
+ # (#95681 diet): image_url + reference_image_urls present with the
+ # catalog's per-model cap; description states the edit path.
+ props = schema["parameters"]["properties"]
+ assert "image_url" in props
+ assert "reference_image_urls" in props
+ assert "edit / transform" in schema["description"]
def test_builder_wired_into_registry(self):
diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.py
index 5f1d0e17f5a..c9144189704 100644
--- a/tools/image_generation_tool.py
+++ b/tools/image_generation_tool.py
@@ -1539,25 +1539,16 @@ from tools.registry import registry, tool_error
IMAGE_GENERATE_SCHEMA = {
"name": "image_generate",
- # Placeholder — the real description is rebuilt dynamically at
- # get_tool_definitions() time so it reflects the active backend's actual
- # capabilities (whether the selected model supports image-to-image /
- # editing). See _build_dynamic_image_schema() below and the
- # dynamic-tool-schemas skill.
+ # Placeholder — description AND params are rebuilt dynamically at
+ # get_tool_definitions() time from the active backend's declared
+ # capabilities (FAL catalog metadata, or plugin provider.capabilities()).
+ # Edit-only args (image_url, reference_image_urls) and upscale are
+ # advertised ONLY when the active model actually supports them; the
+ # handler accepts them regardless (replay compat + teaching errors).
+ # See _build_dynamic_image_schema().
"description": (
- "Generate high-quality images from text prompts (text-to-image), or "
- "edit / transform an existing image (image-to-image) when the active "
- "model supports it. Pass `image_url` to edit that image; add "
- "`reference_image_urls` for style/composition references; omit both "
- "for text-to-image. The underlying backend (FAL, OpenAI, xAI, etc.) "
- "and model are user-configured and not selectable by the agent. "
- "Returns the result in the `image` field — either a URL or an absolute "
- "file path. To show it to the user, reference that path/URL in your "
- "response using the file-delivery convention for the current platform "
- "(your platform guidance describes how files are delivered here). When "
- "the active terminal backend has a different filesystem, successful "
- "local-file results may also include `agent_visible_image` for "
- "follow-up terminal/file operations."
+ "Generate images from text prompts. The active model's edit/reference "
+ "capabilities are rendered at serving time."
),
"parameters": {
"type": "object",
@@ -1576,39 +1567,9 @@ IMAGE_GENERATE_SCHEMA = {
"description": "The aspect ratio of the generated image. 'landscape' is 16:9 wide, 'portrait' is 16:9 tall, 'square' is 1:1.",
"default": DEFAULT_ASPECT_RATIO,
},
- "image_url": {
- "type": "string",
- "description": (
- "Optional source image to edit/transform (image-to-image). "
- "When provided, the active backend routes to its image "
- "editing endpoint; when omitted, it generates from text "
- "alone. Pass a public URL or an absolute local file path "
- "from the conversation. Only honored by models that "
- "support editing — the description above indicates whether "
- "the active model does."
- ),
- },
- "reference_image_urls": {
- "type": "array",
- "items": {"type": "string"},
- "description": (
- "Optional list of additional reference image URLs / paths "
- "(style, character, or composition references) to guide an "
- "image-to-image edit. Supported only by some models and "
- "capped per-model; the description above indicates the max."
- ),
- },
- "upscale": {
- "type": "boolean",
- "description": (
- "Optional post-generation high-resolution pass (~2x, "
- "extra cost/latency). Off by default for every model — "
- "pass true to opt in. The upscaler is a creative "
- "enhancer and can alter fine detail (rendered text, "
- "faces), so only use it when resolution matters more "
- "than fidelity."
- ),
- },
+ # NOTE (schema diet, #95681): image_url / reference_image_urls /
+ # upscale are added per-capability by _build_dynamic_image_schema.
+ # Do not re-add them statically.
},
"required": ["prompt"],
},
@@ -2030,10 +1991,18 @@ def _active_image_capabilities() -> Dict[str, Any]:
1. If ``image_gen.provider`` is set, ask that plugin provider.
2. Otherwise inspect the in-tree FAL model catalog for the active model.
- Returns a dict like ``{"modalities": [...], "max_reference_images": N,
- "model": "...", "provider": "..."}``. Never raises.
+ Returns ``{"modalities": [...], "max_reference_images": N,
+ "supports_upscale": bool, "model": "...", "provider": "..."}``.
+ Fail-closed on every axis: an unknown/undeclared capability is
+ advertised as absent (a provider that can edit but didn't declare it
+ under-advertises — that is the provider's bug to fix in
+ ``capabilities()``, not a safety problem). Never raises.
"""
- info: Dict[str, Any] = {"modalities": ["text"], "max_reference_images": 0}
+ info: Dict[str, Any] = {
+ "modalities": ["text"],
+ "max_reference_images": 0,
+ "supports_upscale": False,
+ }
configured_provider = _read_configured_image_provider()
if configured_provider and configured_provider != "fal":
@@ -2055,6 +2024,8 @@ def _active_image_capabilities() -> Dict[str, Any]:
info["modalities"] = list(caps["modalities"])
if caps.get("max_reference_images"):
info["max_reference_images"] = int(caps["max_reference_images"])
+ # Plugins opt in explicitly; absent = no upscale param.
+ info["supports_upscale"] = bool(caps.get("supports_upscale"))
return info
except Exception: # noqa: BLE001
pass
@@ -2070,57 +2041,104 @@ def _active_image_capabilities() -> Dict[str, Any]:
else:
info["modalities"] = ["text"]
info["max_reference_images"] = 0
+ # FAL: the Clarity Upscaler is a separate endpoint chained on
+ # explicit request for ANY catalog model (the per-model ``upscale``
+ # key is only the default-on flag, retired Aug 2026 — not a
+ # capability). Plugin providers must declare supports_upscale.
+ info["supports_upscale"] = True
except Exception: # noqa: BLE001
pass
return info
+# Param snippets assembled per-capability by _build_dynamic_image_schema.
+_IMAGE_URL_PARAM = {
+ "type": "string",
+ "description": (
+ "Source image to edit/transform (image-to-image). A public URL or "
+ "an absolute local file path from the conversation. Omit for "
+ "text-to-image."
+ ),
+}
+
+_UPSCALE_PARAM = {
+ "type": "boolean",
+ "description": (
+ "Post-generation high-resolution pass (~2x, extra cost/latency), "
+ "off by default. A creative enhancer that can alter fine detail "
+ "(rendered text, faces) — use only when resolution matters more "
+ "than fidelity."
+ ),
+}
+
+
def _build_dynamic_image_schema() -> Dict[str, Any]:
- """Build a description reflecting whether the active model supports editing."""
- parts = [_GENERIC_IMAGE_DESCRIPTION]
+ """Render description AND params from the active model's capabilities.
+
+ Capability coverage is guaranteed: all in-tree FAL catalog entries
+ carry edit/refs/upscale metadata (contract-tested), and the plugin
+ provider ABC's capabilities() fail-closed default is text-only. Args a
+ model cannot honor are NOT advertised — the handler still accepts them
+ (replay compat) and answers with a capability error.
+ """
+ base_desc = (
+ "Generate high-quality images from text prompts{edit_clause}. "
+ "Returns the result in the `image` field — a URL or an absolute "
+ "file path; reference it in your response using the current "
+ "platform's file-delivery convention."
+ )
try:
info = _active_image_capabilities()
except Exception: # noqa: BLE001
- return {"description": _GENERIC_IMAGE_DESCRIPTION}
+ info = {"modalities": ["text"], "max_reference_images": 0,
+ "supports_upscale": False}
- provider = info.get("provider")
- model = info.get("model")
modalities = set(info.get("modalities") or ["text"])
+ max_refs = int(info.get("max_reference_images") or 0)
+ can_edit = "image" in modalities
- line = "\nActive backend"
- if provider:
- line += f": {provider}"
- if model:
- line += f" · model: {model}"
- parts.append(line)
-
- if "image" in modalities and "text" in modalities:
- max_refs = info.get("max_reference_images") or 0
- ref_note = (
- f"; up to {max_refs} reference image(s) via reference_image_urls"
- if max_refs and max_refs > 1
- else ""
- )
- parts.append(
- "- supports both text-to-image (omit image_url) and "
- f"image-to-image / editing (pass image_url){ref_note} — "
- "routes automatically"
- )
- elif "image" in modalities and "text" not in modalities:
- parts.append(
- "- this model is image-to-image / edit only — image_url is REQUIRED"
+ properties: Dict[str, Any] = {
+ "prompt": IMAGE_GENERATE_SCHEMA["parameters"]["properties"]["prompt"],
+ "aspect_ratio": IMAGE_GENERATE_SCHEMA["parameters"]["properties"]["aspect_ratio"],
+ }
+
+ if can_edit:
+ edit_clause = (
+ ", or edit / transform an existing image by passing image_url"
)
+ properties["image_url"] = _IMAGE_URL_PARAM
+ if max_refs > 1:
+ properties["reference_image_urls"] = {
+ "type": "array",
+ "items": {"type": "string"},
+ "maxItems": max_refs,
+ "description": (
+ f"Up to {max_refs} additional reference images (style, "
+ "character, or composition) guiding an edit. URLs or "
+ "absolute local paths."
+ ),
+ }
else:
- parts.append(
- "- this model is text-to-image only — it is NOT capable of "
- "image-to-image / editing; do not pass image_url or "
- "reference_image_urls (they will be rejected). Provide a "
- "text-only prompt."
+ edit_clause = (
+ " (text-to-image only — the active model cannot edit existing "
+ "images)"
)
- return {"description": "\n".join(parts)}
+ if info.get("supports_upscale"):
+ properties["upscale"] = _UPSCALE_PARAM
+
+ description = base_desc.format(edit_clause=edit_clause)
+
+ return {
+ "description": description,
+ "parameters": {
+ "type": "object",
+ "properties": properties,
+ "required": ["prompt"],
+ },
+ }
registry.register(