Skip to content

The agent that grows with you

refactor(tools): image gen/source — squeeze body blank lines

Teknium60544819ab93
diff --git a/tools/fal_common.py b/tools/fal_common.py
index daa1d37c019..fa72e9cb101 100644
--- a/tools/fal_common.py
+++ b/tools/fal_common.py
@@ -59,7 +59,6 @@ class _ManagedFalSyncClient:
def __init__(self, fal_client: Any, *, key: str, queue_run_origin: str):
sync_client_class = _require(getattr(fal_client, "SyncClient", None), "fal_client.SyncClient")
client_module = _require(getattr(fal_client, "client", None), "fal_client.client")
-
self._queue_url_format = _normalize_fal_queue_url_format(queue_run_origin)
self._sync_client = sync_client_class(key=key)
self._http_client = getattr(self._sync_client, "_client", None)
@@ -69,7 +68,6 @@ class _ManagedFalSyncClient:
self._add_hint_header = getattr(client_module, "add_hint_header", None)
self._add_priority_header = getattr(client_module, "add_priority_header", None)
self._add_timeout_header = getattr(client_module, "add_timeout_header", None)
-
_require(self._http_client, "fal_client.SyncClient._client")
if self._maybe_retry_request is None or self._raise_for_status is None:
raise RuntimeError("fal_client.client request helpers are required for managed FAL gateway mode")
@@ -85,7 +83,6 @@ class _ManagedFalSyncClient:
url += "/" + path.lstrip("/")
if webhook_url is not None:
url += "?" + urlencode({"fal_webhook": webhook_url})
-
request_headers = dict(headers or {})
if hint is not None and self._add_hint_header is not None:
self._add_hint_header(hint, request_headers)
@@ -97,13 +94,11 @@ class _ManagedFalSyncClient:
if self._add_timeout_header is None:
raise RuntimeError("fal_client.client.add_timeout_header is required for timeout requests")
self._add_timeout_header(start_timeout, request_headers)
-
response = self._maybe_retry_request(
self._http_client, "POST", url, json=arguments,
timeout=getattr(self._sync_client, "default_timeout", 120.0), headers=request_headers,
)
self._raise_for_status(response)
-
data = response.json()
return self._request_handle_class(
request_id=data["request_id"], response_url=data["response_url"],
diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.py
index 913ab61601f..35dee60876b 100644
--- a/tools/image_generation_tool.py
+++ b/tools/image_generation_tool.py
@@ -81,7 +81,6 @@ def _resolve_managed_fal_gateway():
def _get_managed_fal_client(managed_gateway):
"""Reuse the managed FAL client so its internal httpx.Client is not leaked per call."""
global _managed_fal_client, _managed_fal_client_config
-
client_config = (managed_gateway.gateway_origin.rstrip("/"), managed_gateway.nous_user_token)
with _managed_fal_client_lock:
if _managed_fal_client is None or _managed_fal_client_config != client_config:
@@ -105,7 +104,6 @@ def _wait_fal_result(handler, *, poll_seconds: float = 0.5):
interrupt the worker is abandoned (remote job keeps running).
"""
from tools.interrupt import is_interrupted
-
result_box: list = []
error_box: list = []
def _get():
@@ -113,7 +111,6 @@ def _wait_fal_result(handler, *, poll_seconds: float = 0.5):
result_box.append(handler.get())
except BaseException as exc: # noqa: BLE001 — re-raised on the caller thread
error_box.append(exc)
-
worker = threading.Thread(target=_get, daemon=True, name="fal-result-wait")
worker.start()
while worker.is_alive():
@@ -134,7 +131,6 @@ def _submit_fal_request(model: str, arguments: Dict[str, Any]):
managed_gateway = _resolve_managed_fal_gateway()
if managed_gateway is None:
return fal_client.submit(model, arguments=arguments, headers=request_headers)
-
try:
return _get_managed_fal_client(managed_gateway).submit(
model, arguments=arguments, headers=request_headers)
@@ -220,14 +216,12 @@ def _build_payload(model_id, prompt, aspect_ratio, seed, overrides, image_urls=N
aspect = (aspect_ratio or DEFAULT_ASPECT_RATIO).lower().strip()
if aspect not in sizes:
aspect = DEFAULT_ASPECT_RATIO
-
payload: Dict[str, Any] = dict(meta.get("defaults", {}))
payload["prompt"] = (prompt or "").strip()
required = {"prompt"}
if edit:
payload["image_urls"] = list(image_urls)
required.add("image_urls")
-
size_key = _SIZE_KEY_BY_STYLE.get(meta["size_style"])
if size_key is None and not edit:
raise ValueError(f"Unknown size_style: {meta['size_style']!r}")
@@ -336,7 +330,6 @@ def _postprocess_image_generate_result(raw: str, task_id: str | None = None) ->
image = payload.get("image")
if not isinstance(image, str) or not _looks_like_absolute_file_path(image):
return raw
-
env = _active_terminal_env(task_id)
cache_base = _agent_cache_base_for_env(env)
if not cache_base:
@@ -384,12 +377,10 @@ def _prepare_fal_request(model_id, meta, prompt, aspect_ratio, seed, overrides,
"""Validate inputs and return ``(endpoint, arguments)``; raises ValueError with the user-facing message."""
if not isinstance(prompt, str) or not prompt.strip():
raise ValueError("Prompt is required and must be a non-empty string")
-
# A stored-but-broken selection raises the selection-naming error from
# _resolve_managed_fal_gateway(); only never-configured reports "no backend at all".
if not (fal_key_is_configured() or _resolve_managed_fal_gateway()):
raise ValueError(_build_no_backend_setup_message())
-
edit_endpoint, display = meta.get("edit_endpoint"), meta.get("display", model_id)
# Fail clearly rather than silently dropping sources and producing an unrelated picture.
if source_images and not edit_endpoint:
@@ -397,12 +388,10 @@ def _prepare_fal_request(model_id, meta, prompt, aspect_ratio, seed, overrides,
f"Model '{display}' ({model_id}) is not capable of image-to-image / editing. "
f"Provide a text-only prompt (omit image_url), or switch to an edit-capable model "
f"via `hermes tools` → Image Generation.")
-
aspect_lc = (aspect_ratio or DEFAULT_ASPECT_RATIO).lower().strip()
if aspect_lc not in VALID_ASPECT_RATIOS:
logger.warning("Invalid aspect_ratio '%s', defaulting to '%s'", aspect_ratio, DEFAULT_ASPECT_RATIO)
aspect_lc = DEFAULT_ASPECT_RATIO
-
if source_images:
# Clamp reference count to the model's declared cap.
max_refs = int(meta.get("max_reference_images") or 1)
@@ -435,7 +424,6 @@ def image_generate_tool(
source_images = [c.strip() for c in candidates if isinstance(c, str) and c.strip()]
use_edit = bool(source_images) and bool(meta.get("edit_endpoint"))
modality = "image" if use_edit else "text"
-
overrides: Dict[str, Any] = {
"num_inference_steps": num_inference_steps, "guidance_scale": guidance_scale,
"num_images": num_images, "output_format": output_format,
@@ -453,31 +441,26 @@ def image_generate_tool(
_debug.log_call("image_generate_tool", debug_call_data)
_debug.save()
return json.dumps(response, indent=2, ensure_ascii=False)
-
try:
endpoint, arguments = _prepare_fal_request(
model_id, meta, prompt, aspect_ratio, seed,
{k: v for k, v in overrides.items() if v is not None}, source_images)
result = _wait_fal_result(_submit_fal_request(endpoint, arguments=arguments))
generation_time = (datetime.datetime.now() - start_time).total_seconds()
-
if not result or "images" not in result:
raise ValueError("Invalid response from FAL.ai API — no images returned")
images = result.get("images", [])
if not images:
raise ValueError("No images were generated")
-
# Explicit ``upscale`` wins, including for edits; the catalog default never upscales
# edits (Clarity is a text-to-image pass and must not silently alter compositions).
if upscale is not None:
should_upscale = bool(upscale)
else:
should_upscale = bool(meta.get("upscale", False)) and not use_edit
-
formatted_images = _format_images(images, should_upscale, prompt)
if not formatted_images:
raise ValueError("No valid image URLs returned from API")
-
upscaled_count = sum(1 for img in formatted_images if img.get("upscaled"))
logger.info("Generated %s image(s) in %.1fs (%s upscaled) via %s [%s]",
len(formatted_images), generation_time, upscaled_count, endpoint, modality)
@@ -534,7 +517,6 @@ def _get_plugin_provider(name: str, *, force: bool = False):
"""Discover plugins (local import: importing this module must not trigger discovery) and return the named provider."""
from agent.image_gen_registry import get_provider
from hermes_cli.plugins import _ensure_plugins_discovered
-
if force:
_ensure_plugins_discovered(force=True)
else:
@@ -551,7 +533,6 @@ def check_image_generation_requirements() -> bool:
return True
except ImportError:
pass
-
configured = _plugin_provider_name()
if configured is None:
return False
@@ -654,7 +635,6 @@ def _dispatch_to_plugin_provider(
return _provider_error(
f"image_gen.provider='{configured}' is set but no plugin registered that name. "
f"Run `hermes plugins list` to see available image gen backends.", "provider_not_registered")
-
pname = getattr(provider, "name", "?")
kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio}
try:
@@ -719,7 +699,6 @@ def _maybe_route_managed_krea(
return None
if provider is None:
return None
-
kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio, "model": normalized}
try:
_add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale)
@@ -739,13 +718,11 @@ def _confine_source_images(image_url, reference_image_urls, task_id, *, permitte
"""
if (os.getenv("TERMINAL_ENV") or "local").strip().lower() in ("", "local"):
return image_url, reference_image_urls, None
-
from model_tools import _run_async
from tools.image_source import ImageResolutionError, resolve_local_source_to_data_url
def resolve(ref):
return _run_async(resolve_local_source_to_data_url(ref, task_id, permitted=permitted))
-
try:
if isinstance(image_url, str) and image_url.strip():
image_url = resolve(image_url)
@@ -764,13 +741,11 @@ def _handle_image_generate(args, **kw):
aspect_ratio = args.get("aspect_ratio", DEFAULT_ASPECT_RATIO)
upscale = args.get("upscale")
task_id = kw.get("task_id")
-
# Confinement chokepoint BEFORE any dispatch: every route receives sandbox-confined bytes.
image_url, reference_image_urls, confine_error = _confine_source_images(
args.get("image_url"), args.get("reference_image_urls"), task_id)
if confine_error is not None:
return confine_error
-
# Order matters: explicit plugin provider (incl. "krea"), then model-driven managed Krea
# interception (only when no provider is set, so BYO/direct FAL stays untouched), then FAL.
sources = dict(image_url=image_url, reference_image_urls=reference_image_urls,
@@ -865,7 +840,6 @@ def _build_dynamic_image_schema() -> Dict[str, Any]:
info = _active_image_capabilities()
except Exception: # noqa: BLE001
info = dict(_NO_CAPABILITIES)
-
max_refs = int(info.get("max_reference_images") or 0)
can_edit = "image" in set(info.get("modalities") or ["text"])
static_props = IMAGE_GENERATE_SCHEMA["parameters"]["properties"]
@@ -890,7 +864,6 @@ def _build_dynamic_image_schema() -> Dict[str, Any]:
edit_clause = " (text-to-image only — the active model cannot edit existing images)"
if info.get("supports_upscale"):
properties["upscale"] = _UPSCALE_PARAM
-
return {
"description": base_desc.format(edit_clause=edit_clause),
"parameters": {"type": "object", "properties": properties, "required": ["prompt"]},
diff --git a/tools/image_source.py b/tools/image_source.py
index b0a59712f47..bb36f8b2f21 100644
--- a/tools/image_source.py
+++ b/tools/image_source.py
@@ -71,7 +71,6 @@ async def resolve_image_source(src: str, ctx: ResolveContext, *, permitted: tupl
"file path, a file:// URI, or a data: URL.",
src=s,
)
-
# Everything else is a filesystem path — including bare relative names like "pic.png"
# (a path-shape gate here regressed them once).
candidate = s[len("file://"):] if s.lower().startswith("file://") else s
@@ -117,7 +116,6 @@ def _http_block_reason(url: str) -> Optional[str]:
``_download_image`` re-checks per attempt and against the final redirect target (intentional)."""
from tools.url_safety import is_safe_url
from tools.website_policy import check_website_access
-
if not is_safe_url(url):
return "blocked: unsafe or private URL"
blocked = check_website_access(url)
@@ -129,7 +127,6 @@ def _http_block_reason(url: str) -> Optional[str]:
async def _download_to_bytes(url: str) -> bytes:
import tempfile
from tools.vision_tools import _download_image
-
with tempfile.NamedTemporaryFile(suffix=".img", delete=False) as tf:
tmp = Path(tf.name)
try:
@@ -173,9 +170,7 @@ def _permitted_host_read_target(p: Path, ctx: ResolveContext) -> Optional[Path]:
return p.resolve()
except Exception: # noqa: BLE001 — unresolved path: let is_file() fail downstream
return p
-
from tools.credential_files import from_agent_visible_cache_path
-
try:
real = Path(from_agent_visible_cache_path(str(p))).resolve()
except Exception: # noqa: BLE001 — cannot resolve -> not a safe host read
@@ -222,7 +217,6 @@ async def _resolve_container_fallback(
error so "no such file" / "permission denied" / "never came up" are distinguishable.
"""
import shlex
-
_ensure_container_env(ctx.task_id)
env = _get_active_env(ctx.task_id)
if env is None:
@@ -230,12 +224,10 @@ async def _resolve_container_fallback(
f"'{p}' is not reachable inside the sandbox and no active sandbox "
f"session is available to read it",
src=src, origin="container")
-
# Bound the read INSIDE the sandbox: head -c caps at ingest-limit+1 (+1 distinguishes "at the
# cap" from "over") so /dev/zero can't stream unbounded base64 into host memory. The input
# redirect avoids argv (leading-dash paths); tr -d instead of GNU-only base64 -w0 (BusyBox).
cmd = f"head -c {_MAX_INGEST_BYTES + 1} < {shlex.quote(str(p))} | base64 | tr -d '\\n'"
-
last_res: dict = {"returncode": 1, "output": ""}
for attempt in range(2):
last_res = await asyncio.to_thread(env.execute, cmd)
@@ -263,10 +255,8 @@ def _finalize(
"""Chokepoint: 50MB ingest cap + type check. Images by magic bytes; video (opt-in) by
extension + mp4 sniff — enough because every downstream consumer re-validates."""
from tools.vision_tools import _detect_image_mime_type_from_bytes
-
if len(data) > _MAX_INGEST_BYTES:
raise SourceTooLarge("media exceeds size limit", src=src, origin=origin)
-
sniffed = _detect_image_mime_type_from_bytes(data)
if sniffed is not None:
if "image" not in permitted:
@@ -288,7 +278,6 @@ def _detect_video_mime(data: bytes, src: str) -> Optional[str]:
offset 4 (covers extensionless data: URLs / query-string URLs)."""
from urllib.parse import urlsplit
from tools.vision_tools import _detect_video_mime_type
-
path_part = urlsplit(src).path if _SCHEME_RE.match(src) else src
by_extension = _detect_video_mime_type(Path(path_part))
if by_extension is not None: