The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): an image part admission cannot carry degrades to a note, not a rejected prompt
Teknium2027870eebfa
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 736f97f0cc3..b288f93cdb3 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -42,23 +42,25 @@ def _stage_user_content(content):if not url.startswith('data:'):texts.append(f"[Image attached: {url}]")continue- header, _, data = url.partition(',')- declared = header[len('data:'):].split(';', 1)[0].strip().lower()if len(attachments) >= _ATTACHMENT_LIMIT:raise GatewayClientError('acp_content_invalid')try:- raw = base64.b64decode(data, validate=True)+ raw = base64.b64decode(url.partition(',')[2], validate=True)except (binascii.Error, ValueError) as exc:raise GatewayClientError('acp_content_invalid') from exc- # The staged extension and admitted type come from the sniffed bytes, never the client's- # text (``text/html`` -> .html, ``image/svg+xml``, or a path-shaped subtype on Windows).+ # The sniffed bytes are authoritative for the staged extension and admitted type; the+ # client's declared type (a file suffix, or image/png by default) is never trusted. A+ # part admission cannot carry (bmp/svg, over the media cap) degrades to a text note so+ # the user's text still runs, as main's in-process server did for oversize images.mime = sniff_image_mime(raw)- if mime is None or (declared and {'image/jpg': 'image/jpeg'}.get(declared, declared) != mime):- raise GatewayClientError('acp_content_invalid')+ if mime is None:+ texts.append("[Image omitted: unsupported image format]")+ continuetry:path = cache_image_from_bytes(raw, _IMAGE_EXT[mime])except ValueError as exc:- raise GatewayClientError('acp_content_invalid') from exc+ texts.append(f"[Image omitted: {exc}]")+ continueattachments.append({'path': path, 'mime': mime})return "\n".join(texts), attachmentsdiff --git a/tests/acp_adapter/test_acp_image_staging_boundary.py b/tests/acp_adapter/test_acp_image_staging_boundary.pyindex bc7ef7d6bf2..f400a2e5687 100644--- a/tests/acp_adapter/test_acp_image_staging_boundary.py+++ b/tests/acp_adapter/test_acp_image_staging_boundary.py@@ -28,17 +28,17 @@ def test_hardlink_in_staging_to_outside_file_is_refused(tmp_path, monkeypatch):@pytest.mark.parametrize("mime", ["image/png/../../../../escape", "image/svg+xml", "text/html", "image/gif"])def test_acp_image_mime_never_chooses_the_staged_extension(tmp_path, monkeypatch, mime):- """The extension comes from the sniffed bytes (png/jpeg/gif/webp), never the client's text;- a declared type that disagrees with the bytes (PNG bytes as image/gif) is refused too."""+ """The extension and admitted type come from the sniffed bytes (png/jpeg/gif/webp), never the+ client's declared text: PNG bytes declared as anything stage as ``.png`` / ``image/png``."""from acp.schema import ImageContentBlockfrom acp_adapter.content import _content_blocks_to_openai_user_contentfrom acp_adapter.gateway_server import _stage_user_contentfrom gateway.platforms import base- from hermes_cli.gateway_client import GatewayClientErrorstaging = tmp_path / "home" / "cache" / "images"staging.mkdir(parents=True)monkeypatch.setattr(base, "get_image_cache_dir", lambda: staging)block = ImageContentBlock(type="image", data=base64.b64encode(PNG).decode(), mime_type=mime)- with pytest.raises(GatewayClientError):- _stage_user_content(_content_blocks_to_openai_user_content([block]))- assert list(staging.iterdir()) == []+ _, (attachment,) = _stage_user_content(_content_blocks_to_openai_user_content([block]))+ assert attachment["mime"] == "image/png"+ assert [p.suffix for p in staging.iterdir()] == [".png"]+ assert Path(attachment["path"]).parent == stagingdiff --git a/tests/acp_adapter/test_acp_image_strict_reject.py b/tests/acp_adapter/test_acp_image_strict_reject.pynew file mode 100644index 00000000000..aa4ed5c3c1b--- /dev/null+++ b/tests/acp_adapter/test_acp_image_strict_reject.py@@ -0,0 +1,52 @@+"""An ACP image part admission cannot carry degrades to a text note; the user's text still runs (B2-12)."""+import base64++import pytest+from acp.schema import ImageContentBlock, ResourceContentBlock, TextContentBlock++from acp_adapter.gateway_server import GatewayACPAgent++PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 32+BMP = b"BM" + b"0" * 64+++class _Client:+ def __init__(self, agent):+ self.calls, self.agent = [], agent++ async def rpc(self, method, **params):+ self.calls.append((method, params))+ self.agent._terminals['adm-1'] = {}+ return {'admission_id': 'adm-1'}+++def _blocks(tmp_path, case):+ if case == 'jpg-named-png':+ (tmp_path / 'shot.jpg').write_bytes(PNG)+ return [ResourceContentBlock(type='resource_link', uri=(tmp_path / 'shot.jpg').as_uri(), name='shot.jpg')]+ if case == 'bmp':+ (tmp_path / 'pic.bmp').write_bytes(BMP)+ return [ResourceContentBlock(type='resource_link', uri=(tmp_path / 'pic.bmp').as_uri(), name='pic.bmp')]+ if case == 'oversize':+ return [ImageContentBlock(type='image', data=base64.b64encode(PNG).decode(), mimeType='image/png')]+ return [ImageContentBlock(type='image', data=base64.b64encode(b'\xff\xd8\xff' + b'0' * 32).decode(), mimeType='')]++[email protected]('case, mime', [('jpg-named-png', 'image/png'), ('jpeg-no-mime', 'image/jpeg'),+ ('bmp', None), ('oversize', None)])+async def test_mislabeled_or_unadmittable_image_never_rejects_the_prompt(tmp_path, monkeypatch, case, mime):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path / 'home'))+ if case == 'oversize':+ monkeypatch.setattr('gateway.platforms.base.get_inbound_media_max_bytes', lambda: 8)+ agent = GatewayACPAgent()+ agent._gateway = _Client(agent)+ agent._snapshots['s'] = {}+ response = await agent.prompt([TextContentBlock(type='text', text='what is this?'), *_blocks(tmp_path, case)], 's')+ assert response.stop_reason == 'end_turn'+ ((method, params),) = agent._gateway.calls+ assert method == 'prompt.submit' and params['text'].startswith('what is this?')+ if mime:+ assert [a['mime'] for a in params['attachments']] == [mime]+ else:+ assert 'attachments' not in params and '[Image omitted:' in params['text']