The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): image gen/source — drop redundant never-raises guards, extract credential guard
Teknium4b691d2ca8be
diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.pyindex 2e3ddf984f2..23a33f0feb8 100644--- a/tools/image_generation_tool.py+++ b/tools/image_generation_tool.py@@ -489,8 +489,7 @@ def _build_no_backend_setup_message() -> str:lines.append(" - FAL_KEY is not set and the managed FAL gateway is unreachable")else:lines.append(" - FAL_KEY environment variable is not set")- gateway_message = nous_tool_gateway_unavailable_message("managed FAL image generation")- if gateway_message:+ if gateway_message := nous_tool_gateway_unavailable_message("managed FAL image generation"):lines.append(f" - {gateway_message}")lines += ["", "To enable image generation, do one of:"," 1. Get a free API key at https://fal.ai and set FAL_KEY=<your-key> (then restart the session)"]@@ -777,18 +776,15 @@ def _active_image_capabilities() -> Dict[str, Any]:return infoexcept Exception: # noqa: BLE001pass- # In-tree FAL path (provider unset or == "fal").- try:- model_id, meta = _resolve_fal_model()- can_edit = bool(meta.get("edit_endpoint"))- info["provider"] = "FAL.ai"- info["model"] = meta.get("display", model_id)- info["modalities"] = ["text", "image"] if can_edit else ["text"]- info["max_reference_images"] = int(meta.get("max_reference_images") or 1) if can_edit else 0- # Clarity is available on request for ANY catalog model (``upscale`` is only the default).- info["supports_upscale"] = True- except Exception: # noqa: BLE001- pass+ # In-tree FAL path (provider unset or == "fal"); _resolve_fal_model() never raises.+ model_id, meta = _resolve_fal_model()+ can_edit = bool(meta.get("edit_endpoint"))+ info["provider"] = "FAL.ai"+ info["model"] = meta.get("display", model_id)+ info["modalities"] = ["text", "image"] if can_edit else ["text"]+ info["max_reference_images"] = int(meta.get("max_reference_images") or 1) if can_edit else 0+ # Clarity is available on request for ANY catalog model (``upscale`` is only the default).+ info["supports_upscale"] = Truereturn info@@ -822,16 +818,11 @@ def _build_dynamic_image_schema() -> Dict[str, Any]:"file path; reference it in your response using the current ""platform's file-delivery convention.")- try:- info = _active_image_capabilities()- except Exception: # noqa: BLE001- info = dict(_NO_CAPABILITIES)+ info = _active_image_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"]- properties: Dict[str, Any] = {- "prompt": static_props["prompt"], "aspect_ratio": static_props["aspect_ratio"],- }+ properties: Dict[str, Any] = {"prompt": static_props["prompt"], "aspect_ratio": static_props["aspect_ratio"]}if can_edit:edit_clause = ", or edit / transform an existing image by passing image_url"properties["image_url"] = _IMAGE_URL_PARAM@@ -850,10 +841,8 @@ 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"]},- }+ return {"description": base_desc.format(edit_clause=edit_clause),+ "parameters": {"type": "object", "properties": properties, "required": ["prompt"]}}registry.register(diff --git a/tools/image_source.py b/tools/image_source.pyindex cdd28d6f63e..9f14bfd947e 100644--- a/tools/image_source.py+++ b/tools/image_source.py@@ -76,17 +76,7 @@ async def resolve_image_source(src: str, ctx: ResolveContext, *, permitted: tuplp = Path(os.path.expanduser(candidate))host_target = _permitted_host_read_target(p, ctx)if host_target is not None and host_target.is_file():- # Shared credential-read guard: refuse secret-bearing files (.env, auth.json) with a- # specific error. Guard import is best-effort; a real block always propagates.- try:- from agent.file_safety import raise_if_read_blocked- except Exception: # noqa: BLE001 — guard unavailable: proceed- raise_if_read_blocked = None- if raise_if_read_blocked is not None:- try:- raise_if_read_blocked(str(host_target))- except ValueError as exc:- raise SourceUnsafe(str(exc), src=s, origin="file")+ _guard_credential_read(host_target, s)data = await asyncio.to_thread(host_target.read_bytes)return _finalize(data, "", "file", s, permitted)if _is_local_terminal_backend():@@ -95,6 +85,19 @@ async def resolve_image_source(src: str, ctx: ResolveContext, *, permitted: tuplreturn await _resolve_container_fallback(p, ctx, s, permitted)+def _guard_credential_read(host_target: Path, src: str) -> None:+ """Shared credential-read guard: refuse secret-bearing files (.env, auth.json) with a specific+ error. Guard import is best-effort; a real block always propagates."""+ try:+ from agent.file_safety import raise_if_read_blocked+ except Exception: # noqa: BLE001 — guard unavailable: proceed+ return+ try:+ raise_if_read_blocked(str(host_target))+ except ValueError as exc:+ raise SourceUnsafe(str(exc), src=src, origin="file")++def _resolve_data_url(s: str) -> tuple[bytes, str]:header, _, payload = s.partition(",")if ";base64" not in header:@@ -117,8 +120,7 @@ def _http_block_reason(url: str) -> Optional[str]:from tools.website_policy import check_website_accessif not is_safe_url(url):return "blocked: unsafe or private URL"- blocked = check_website_access(url)- if blocked:+ if blocked := check_website_access(url):return blocked.get("message") or "blocked by website policy"return None@@ -173,12 +175,8 @@ def _permitted_host_read_target(p: Path, ctx: ResolveContext) -> Optional[Path]:real = Path(from_agent_visible_cache_path(str(p))).resolve()except Exception: # noqa: BLE001 — cannot resolve -> not a safe host readreturn None- for root in _media_cache_roots():- try:- real.relative_to(root.resolve())- return real- except ValueError:- continue+ if any(real.is_relative_to(root.resolve()) for root in _media_cache_roots()):+ return realreturn None