The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): gateway transport agent accepts image/resource prompt blocks again
Teknium0390a345ab72
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 26e3e01a3b3..6b79d485fd7 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -17,6 +17,36 @@ from hermes_constants import get_hermes_homefrom acp_adapter.session import _translate_acp_cwd, _normalize_cwd_for_compare+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."""+ if isinstance(content, str):+ return content, []+ import base64+ from gateway.platforms.base import cache_image_from_bytes+ texts, attachments = [], []+ for part in content:+ if part.get('type') == 'text':+ texts.append(part['text'])+ continue+ url = part['image_url']['url']+ if not url.startswith('data:'):+ texts.append(f"[Image attached: {url}]")+ continue+ header, _, data = url.partition(',')+ mime = header[len('data:'):].split(';', 1)[0] or 'image/png'+ try:+ path = cache_image_from_bytes(base64.b64decode(data), '.' + mime.split('/', 1)[1])+ except ValueError as exc:+ raise GatewayClientError('acp_content_invalid') from exc+ attachments.append({'path': path, 'mime': mime})+ return "\n".join(texts), attachments++class GatewayACPAgent(acp.Agent):def __init__(self):self._conn = None@@ -43,7 +73,7 @@ class GatewayACPAgent(acp.Agent):return InitializeResponse(protocol_version=acp.PROTOCOL_VERSION,agent_info=Implementation(name="hermes-agent", version=__version__),agent_capabilities=AgentCapabilities(load_session=True,- prompt_capabilities=PromptCapabilities(image=False),+ prompt_capabilities=PromptCapabilities(image=True),session_capabilities=SessionCapabilities(resume=SessionResumeCapabilities())),auth_methods=build_auth_methods())@@ -164,10 +194,9 @@ class GatewayACPAgent(acp.Agent):async def prompt(self, prompt, session_id, **kwargs):if session_id not in self._snapshots:raise GatewayClientError("not_found")- if any(getattr(block, "type", None) != "text" for block in prompt):- raise GatewayClientError("acp_content_unavailable")- text = "\n".join(block.text for block in prompt)- if text.lstrip().startswith('/'):+ from acp_adapter.content import _content_blocks_to_openai_user_content+ text, attachments = _stage_user_content(_content_blocks_to_openai_user_content(prompt))+ if text.lstrip().startswith('/') and not attachments:from hermes_cli.gateway_mutations import slash_mutationparts = text.strip().split(None, 1)operation, payload = slash_mutation(parts[0], parts[1] if len(parts) > 1 else '')@@ -179,8 +208,11 @@ class GatewayACPAgent(acp.Agent):self._mutations.acknowledge(session_id, operation, payload)return PromptResponse(stop_reason='end_turn')client = await self._client()+ submit = {'text': text}+ if attachments:+ submit['attachments'] = attachmentsreceipt = await client.rpc("prompt.submit", session_id=session_id,- input_id=uuid.uuid4().hex, text=text)+ input_id=uuid.uuid4().hex, **submit)admission_id = receipt["admission_id"]async with self._changed:await self._changed.wait_for(lambda: admission_id in self._terminals or self._failure is not None)diff --git a/tests/acp/test_gateway_prompt_content.py b/tests/acp/test_gateway_prompt_content.pynew file mode 100644index 00000000000..fe90976dd04--- /dev/null+++ b/tests/acp/test_gateway_prompt_content.py@@ -0,0 +1,56 @@+"""ACP prompt blocks reach canonical admission with the same conversion main's server uses."""+import base64++import pytest+from acp.schema import ImageContentBlock, TextContentBlock++from acp_adapter.gateway_server import GatewayACPAgent++_ONE_PX_PNG = bytes.fromhex(+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"+ "890000000a49444154789c6300010000000500010d0a2db40000000049454e44ae426082"+)+++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'}+++async def test_image_prompt_is_staged_in_profile_cache_and_submitted_as_attachment(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ from gateway.platforms.base import get_image_cache_dir+ agent = GatewayACPAgent()+ agent._gateway = _Client(agent)+ agent._snapshots['s'] = {}+ response = await agent.prompt([+ TextContentBlock(type='text', text='What is in this image?'),+ ImageContentBlock(type='image', data=base64.b64encode(_ONE_PX_PNG).decode(), mimeType='image/png'),+ ], 's')+ assert response.stop_reason == 'end_turn'+ ((method, params),) = agent._gateway.calls+ assert method == 'prompt.submit'+ assert params['text'] == 'What is in this image?'+ (attachment,) = params['attachments']+ assert attachment['mime'] == 'image/png'+ staged = tmp_path.joinpath(attachment['path'])+ assert staged.parent == get_image_cache_dir().resolve()+ assert staged.read_bytes() == _ONE_PX_PNG+++async def test_text_only_prompt_keeps_plain_submit(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ agent = GatewayACPAgent()+ agent._gateway = _Client(agent)+ agent._snapshots['s'] = {}+ await agent.prompt([TextContentBlock(type='text', text='hello')], 's')+ ((_, params),) = agent._gateway.calls+ assert params['text'] == 'hello' and 'attachments' not in params