The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(image_gen): keep legacy non-dict Krea refs passing through and cap the bytes actually read
kshitijk4poorde479f646988
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.pyindex 2155022c9b8..ee0d60cd77a 100644--- a/plugins/image_gen/krea/__init__.py+++ b/plugins/image_gen/krea/__init__.py@@ -12,7 +12,6 @@ from __future__ import annotationsimport base64import loggingimport mimetypes-import osimport timeimport uuidfrom pathlib import Path@@ -317,19 +316,19 @@ def _collect_style_refs(def _inline_local_style_refs(- style_refs: List[Dict[str, Any]], fail: ErrorFn-) -> Tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]:+ style_refs: List[Any], fail: ErrorFn+) -> Tuple[List[Any], Optional[Dict[str, Any]]]:"""Embed local image files as data URIs; URLs and data URIs pass through unchanged."""from agent.file_safety import raise_if_read_blocked- inlined: List[Dict[str, Any]] = []+ inlined: List[Any] = []total_bytes = 0for ref in style_refs:- source = ref.get("url")+ source = ref.get("url") if isinstance(ref, dict) else None # legacy non-dict refs pass throughif not isinstance(source, str) or source.lower().startswith(_REMOTE_REFERENCE_PREFIXES):inlined.append(ref)continue- path = Path(os.path.expanduser(source))+ path = Path(source).expanduser()# Guard first: a denied path must not reveal whether it exists or how large it is.try:raise_if_read_blocked(str(path))@@ -337,13 +336,16 @@ def _inline_local_style_refs(return [], fail(str(exc), "invalid_image_url")if not path.is_file():return [], fail(f"Style reference image not found: {source}", "invalid_image_url")- total_bytes += path.stat().st_size+ # Read at most one byte past the remaining budget: the cap bounds what is sent, not a stat.+ with path.open("rb") as fh:+ data = fh.read(_MAX_LOCAL_REFERENCE_BYTES - total_bytes + 1)+ total_bytes += len(data)if total_bytes > _MAX_LOCAL_REFERENCE_BYTES:return [], fail(f"Local style reference images total over {_MAX_LOCAL_REFERENCE_BYTES / 2**20:g} MB; ""resize them or pass public URLs", "source_too_large")mime = mimetypes.guess_type(path.name)[0] or "image/png"- inlined.append({**ref, "url": f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"})+ inlined.append({**ref, "url": f"data:{mime};base64,{base64.b64encode(data).decode('ascii')}"})return inlined, Nonediff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.pyindex eac2e0f0391..0ddd583b57a 100644--- a/tests/plugins/image_gen/test_krea_provider.py+++ b/tests/plugins/image_gen/test_krea_provider.py@@ -299,28 +299,28 @@ class TestGenerate:expected = "data:image/png;base64," + base64.b64encode(image.read_bytes()).decode("ascii")assert ref == {"url": expected, "strength": 0.6}- @pytest.mark.parametrize("case", ["missing", "total_over_limit", "credential_file"])- def test_unusable_local_style_references_are_refused_before_submit(self, case, tmp_path, monkeypatch):+ @pytest.mark.parametrize("names, error_type, message", [+ (["nowhere.png"], "invalid_image_url", "not found"),+ (["a.png", "b.png"], "source_too_large", "total over"), # 6 bytes each: fit alone, not together+ ([".env"], "invalid_image_url", "Access denied"), # absent on disk: the guard must answer first+ ])+ def test_unusable_local_style_references_are_refused_before_submit(+ self, names, error_type, message, tmp_path, monkeypatch):"""Refused with no request sent: a missing file, local files whose TOTAL (not each) exceeds the- cap, and a path the credential-read guard denies (refused before its existence is probed)."""+ cap, and a path the credential-read guard denies (before its existence is probed)."""from plugins.image_gen import kreamonkeypatch.setenv("HERMES_HOME", str(tmp_path))monkeypatch.setattr(krea, "_MAX_LOCAL_REFERENCE_BYTES", 10)for name in ("a.png", "b.png"):- (tmp_path / name).write_bytes(b"\x89PNG\r\n") # 6 bytes each: fits alone, not together- refs = {- "missing": [str(tmp_path / "nowhere.png")],- "total_over_limit": [str(tmp_path / "a.png"), str(tmp_path / "b.png")],- "credential_file": [str(tmp_path / ".env")], # absent on disk: the guard must answer first- }[case]+ (tmp_path / name).write_bytes(b"\x89PNG\r\n")with patch("plugins.image_gen.krea.requests.post") as mock_post:- result = krea.KreaImageGenProvider().generate(prompt="test", reference_image_urls=refs)+ result = krea.KreaImageGenProvider().generate(+ prompt="test", reference_image_urls=[str(tmp_path / n) for n in names])- assert result["success"] is False- assert (result["error_type"] == "source_too_large") is (case == "total_over_limit")- assert ("not found" in result["error"]) is (case == "missing")+ assert (result["success"], result["error_type"]) == (False, error_type)+ assert message in result["error"]mock_post.assert_not_called()def test_unknown_kwargs_ignored(self):