The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): stage a remote image URL as an attachment instead of text
Teknium059d01257c6a
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex ca7c5dab478..2424184c338 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -21,13 +21,43 @@ from acp_adapter.session import _translate_acp_cwd, _normalize_cwd_for_comparelogger = logging.getLogger(__name__)+def _fetch_remote_image(url):+ """Bytes of an editor's remote image URL, or None when it cannot be fetched.++ The in-process server passed such a URL to the model as an image part; admission carries only+ staged bytes, so the adapter downloads it through the gateway's SSRF-guarded image fetcher+ (pre-flight and per-redirect address checks, the inbound media size cap) and stages the bytes+ like any other image (#134889 ACP-16). Runs off the event loop (``prompt`` stages in a thread)."""+ from gateway.platforms.base import cache_image_from_url+ try:+ path = asyncio.run(cache_image_from_url(url, ".img", retries=0))+ except Exception:+ # Boundary: an unsafe address, an HTTP error, a non-image body or a transport failure+ # degrades to the URL as text, never a failed prompt.+ logger.info("ACP remote image not fetched; sent as text", exc_info=True)+ return None+ try:+ with open(path, "rb") as fetched:+ return fetched.read()+ finally:+ with suppress(OSError):+ os.unlink(path)+++def _has_remote_image(content):+ return not isinstance(content, str) and any(+ part.get('type') == 'image_url' and part['image_url']['url'].startswith(('http://', 'https://'))+ for part in content)++def _stage_user_content(content):"""Shared-converter output -> ``(text, attachments)`` for ``prompt.submit``.Text-only prompts stay a plain string. Media parts (image ``data:`` URLs from- image blocks, image resource links and embedded blobs) are staged as bytes in- the profile image cache; the authority commits them at admission. Remote- image URLs cannot be staged and are kept as text so the model still sees them."""+ image blocks, image resource links and embedded blobs, and remote image URLs once+ fetched) are staged as bytes in the profile image cache; the authority commits them+ at admission. A remote image URL that cannot be fetched is kept as text so the model+ still sees it. Blocking network I/O when ``_has_remote_image``: then call it off the loop."""if isinstance(content, str):return content, []import base64@@ -40,15 +70,18 @@ def _stage_user_content(content):texts.append(part['text'])continueurl = part['image_url']['url']- if not url.startswith('data:'):- texts.append(f"[Image attached: {url}]")- continueif len(attachments) >= _ATTACHMENT_LIMIT:raise GatewayClientError('acp_content_invalid')- try:- raw = base64.b64decode(url.partition(',')[2], validate=True)- except (binascii.Error, ValueError) as exc:- raise GatewayClientError('acp_content_invalid') from exc+ if url.startswith('data:'):+ try:+ raw = base64.b64decode(url.partition(',')[2], validate=True)+ except (binascii.Error, ValueError) as exc:+ raise GatewayClientError('acp_content_invalid') from exc+ else:+ raw = _fetch_remote_image(url) if url.startswith(('http://', 'https://')) else None+ if raw is None:+ texts.append(f"[Image attached: {url}]")+ continue# 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@@ -579,7 +612,10 @@ class GatewayACPAgent(acp.Agent):if self._has_unknown(session_id):raise GatewayClientError(self._unknown_recovery(session_id, submitted=False))from acp_adapter.content import _content_blocks_to_openai_user_content- text, attachments = _stage_user_content(_content_blocks_to_openai_user_content(prompt))+ content = _content_blocks_to_openai_user_content(prompt)+ # Only a remote image fetch leaves the loop; every other prompt stages inline, as before.+ text, attachments = (await asyncio.to_thread(_stage_user_content, content)) if _has_remote_image(content) \+ else _stage_user_content(content)# Only this session's very next prompt may be the editor's retry of an un-acked submit; any# prompt (slash work included) retires the retained identity, so a later repeat is new work.retained = self._unacked.pop(session_id, None)diff --git a/tests/acp_adapter/test_gateway_prompt_content.py b/tests/acp_adapter/test_gateway_prompt_content.pyindex fe90976dd04..1ccb03fcb31 100644--- a/tests/acp_adapter/test_gateway_prompt_content.py+++ b/tests/acp_adapter/test_gateway_prompt_content.py@@ -54,3 +54,73 @@ async def test_text_only_prompt_keeps_plain_submit(tmp_path, monkeypatch):await agent.prompt([TextContentBlock(type='text', text='hello')], 's')((_, params),) = agent._gateway.callsassert params['text'] == 'hello' and 'attachments' not in params+++def image_host():+ """A real HTTP server on loopback serving one PNG (the editor's remote image URL)."""+ import threading+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++ class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ body = _ONE_PX_PNG if self.path == '/pic' else b'<html>not found</html>'+ self.send_response(200 if self.path == '/pic' else 404)+ self.send_header('Content-Type', 'image/png' if self.path == '/pic' else 'text/html')+ self.send_header('Content-Length', str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f'http://127.0.0.1:{server.server_port}'+ finally:+ server.shutdown()+ server.server_close()+++def _allow_loopback(monkeypatch, allowed):+ from tools import url_safety+ monkeypatch.setenv('HERMES_ALLOW_PRIVATE_URLS', 'true' if allowed else 'false')+ url_safety._reset_allow_private_cache()+++async def test_remote_image_url_reaches_admission_as_an_image_attachment(tmp_path, monkeypatch, image_host):+ """#134889 ACP-16: main's in-process server handed the model a remote image as an image part; the+ gateway path admits only staged bytes, so the adapter fetches it (SSRF-guarded) and stages it."""+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ _allow_loopback(monkeypatch, True)+ agent = GatewayACPAgent()+ agent._gateway = _Client(agent)+ agent._snapshots['s'] = {}+ await agent.prompt([TextContentBlock(type='text', text='describe'),+ ImageContentBlock(type='image', data='', uri=f'{image_host}/pic', mimeType='image/png')], 's')+ ((_, params),) = agent._gateway.calls+ assert params['text'] == 'describe'+ (attachment,) = params['attachments']+ assert attachment['mime'] == 'image/png'+ from pathlib import Path+ assert Path(attachment['path']).read_bytes() == _ONE_PX_PNG++[email protected]('path, allowed', [('/pic', False), ('/missing', True)], ids=['ssrf-blocked', 'http-404'])+async def test_a_remote_image_that_cannot_be_fetched_stays_a_text_note(tmp_path, monkeypatch, image_host, path, allowed):+ """A private address (SSRF guard) or a failed download never fails the prompt: the model still gets+ the URL as text, as before."""+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ _allow_loopback(monkeypatch, allowed)+ agent = GatewayACPAgent()+ agent._gateway = _Client(agent)+ agent._snapshots['s'] = {}+ await agent.prompt([TextContentBlock(type='text', text='describe'),+ ImageContentBlock(type='image', data='', uri=f'{image_host}{path}', mimeType='image/png')], 's')+ ((_, params),) = agent._gateway.calls+ assert 'attachments' not in params+ assert params['text'].startswith('describe\n[Image attached: ') and f'{image_host}{path}' in params['text']