The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): prompt.submit accepts staged image attachments committed at admission
Teknium94260c1cb2d1
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex bb080c71450..0dc0fef2d8a 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -223,11 +223,14 @@ class SessionAuthority:async def submit(self, actor: Principal, request: Submission):self.authorize(actor, request.ref, 'session:submit')self._require_admission_open()- if request.intent != 'queue' or set(request.payload) != {'text'} or not isinstance(request.payload['text'], str):+ if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {'text', 'attachments'}+ or not isinstance(request.payload['text'], str)):raise RuntimeStoreError('invalid_params')+ from gateway.session_ingress_media import admit_attachments+ payload = {'text': request.payload['text'], **admit_attachments(request.payload.get('attachments'))}row = admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,session_id=request.ref.session_id, request_id=request.request_id,- payload=dict(request.payload), intent=request.intent)+ payload=payload, intent=request.intent)self._publish_pending(request.ref)self._schedule(request.ref)return self._receipt(row)@@ -330,7 +333,8 @@ class SessionAuthority:if 'local_automation_v1' in first['payload']:from gateway.session_automation import check_local_automationcheck_local_automation(self, ref, first)- elif first['principal_id'] != live.source.user_id or set(first['payload']) != {'text'}:+ elif (first['principal_id'] != live.source.user_id+ or not {'text'} <= set(first['payload']) <= {'text', 'attachments_v1'}):raise RuntimeStoreError('permission_denied')if first is not None and 'native_text_v1' in first['payload']:from gateway.session_envelope import check_native_routediff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 7addf102e64..c1df446b230 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -191,14 +191,16 @@ class AuthorityConnection:async def submit(self, ref, params):if ref.session_id not in self.subscriptions:raise RuntimeStoreError('permission_denied')- forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued'}+ forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued', 'attachments'}if forbidden:raise RuntimeStoreError('invalid_params')request_id = params.get('submission_id') or params.get('input_id')if not isinstance(request_id, str) or not request_id:raise RuntimeStoreError('invalid_params')- receipt = await self.authority.submit(self.actor, Submission(- request_id, ref, {'text': params.get('text')}, 'queue'))+ payload = {'text': params.get('text')}+ if 'attachments' in params:+ payload['attachments'] = params['attachments']+ receipt = await self.authority.submit(self.actor, Submission(request_id, ref, payload, 'queue'))return asdict(receipt)async def mutate(self, ref, params):diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 72564b5b77c..6b23b446ad7 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -31,8 +31,9 @@ async def execute_admission(authority, ref, row):if 'native_text_v1' in row['payload']:event = restore_native(row['payload'], authority.runner)else:+ from gateway.session_ingress_media import restore_attachmentsevent = MessageEvent(text=row['payload']['text'], source=live.source,- message_id=row['admission_id'])+ message_id=row['admission_id'], **restore_attachments(row['payload']))if 'local_automation_v1' in row['payload']:from gateway.session_automation import restore_local_automationevent = restore_local_automation(authority, ref, row)diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 302fb158ea0..5b8133546d3 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -18,6 +18,40 @@ def _media_root():return get_document_cache_dir().resolve() / 'native-inputs'+# Public ``prompt.submit`` attachments: a local client stages image bytes in the+# profile image cache (where messaging adapters stage downloads), the authority+# commits them as immutable bytes at admission so no later mutation or cache+# cleanup of the staging file can change what executes.+_ATTACHMENT_MIMES = frozenset({'image/png', 'image/jpeg', 'image/gif', 'image/webp'})+_ATTACHMENT_LIMIT = 10+++def admit_attachments(attachments):+ """Wire ``attachments: [{path, mime}]`` -> committed payload fields (``{}`` when absent)."""+ if attachments is None:+ return {}+ if (not isinstance(attachments, list) or not attachments or len(attachments) > _ATTACHMENT_LIMIT+ or any(not isinstance(item, dict) or set(item) != {'path', 'mime'}+ or not isinstance(item['path'], str) or item['mime'] not in _ATTACHMENT_MIMES+ for item in attachments)):+ raise RuntimeStoreError('invalid_params')+ from gateway.platforms.base import get_image_cache_dir+ staging = get_image_cache_dir().resolve()+ paths = [Path(item['path']) for item in attachments]+ if any(not path.is_absolute() or path.resolve().parent != staging for path in paths):+ raise RuntimeStoreError('invalid_params')+ return {'attachments_v1': {'media': capture_native_media(paths),+ 'media_types': [item['mime'] for item in attachments]}}+++def restore_attachments(payload):+ """Committed attachment fields -> ``MessageEvent`` media kwargs (``{}`` for text-only rows)."""+ data = payload.get('attachments_v1')+ if not data:+ return {}+ return {'media_urls': restore_native_media(data['media']), 'media_types': list(data['media_types'])}++def _sync_directory(path):# Windows cannot open directories through os.open; file fsync still precedes ACK.if os.name != 'nt':diff --git a/tests/gateway/test_prompt_attachments.py b/tests/gateway/test_prompt_attachments.pynew file mode 100644index 00000000000..62d6daa15c2--- /dev/null+++ b/tests/gateway/test_prompt_attachments.py@@ -0,0 +1,69 @@+"""Public ``prompt.submit`` attachments: scoped to the profile staging dir, committed as bytes."""+from types import SimpleNamespace++import pytest++_ONE_PX_PNG = bytes.fromhex(+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"+ "890000000a49444154789c6300010000000500010d0a2db40000000049454e44ae426082"+)+++async def _authority(tmp_path, monkeypatch, answer):+ from gateway.config import GatewayConfig, Platform+ from gateway.session import SessionSource, SessionStore+ from gateway.session_authority import LiveSession, initialize_session_authority++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False,+ _handle_message=answer, _adapter_for_source=lambda source: None)+ authority = await initialize_session_authority(runner, profile_id='p', instance_id='owner')+ store._db.create_session('s', source='telegram')+ authority.sessions['s'] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id='c'), 's')+ return authority+++async def test_submit_rejects_attachment_outside_profile_staging_dir(tmp_path, monkeypatch):+ from gateway.session_contract import Principal, SessionRef, Submission+ from hermes_state_runtime import RuntimeStoreError, list_session_admissions++ seen = []+ async def answer(event):+ seen.append(event)+ return 'ok'+ authority = await _authority(tmp_path, monkeypatch, answer)+ outside = tmp_path / 'elsewhere.png'+ outside.write_bytes(_ONE_PX_PNG)+ actor = Principal('human', 'p', frozenset({'session:submit'}), 't')+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ await authority.submit(actor, Submission('r1', SessionRef('p', 's'),+ {'text': 'look', 'attachments': [{'path': str(outside), 'mime': 'image/png'}]}, 'queue'))+ assert list_session_admissions(authority.db, session_id='s', pending_only=False) == []+ assert seen == []+++async def test_staged_attachment_reaches_message_event_media(tmp_path, monkeypatch):+ from gateway.platforms.base import cache_image_from_bytes+ from gateway.session_contract import Principal, SessionRef, Submission++ seen = []+ async def answer(event):+ seen.append(event)+ return 'ok'+ authority = await _authority(tmp_path, monkeypatch, answer)+ staged = cache_image_from_bytes(_ONE_PX_PNG, '.png')+ actor = Principal('human', 'p', frozenset({'session:submit'}), 't')+ receipt = await authority.submit(actor, Submission('r2', SessionRef('p', 's'),+ {'text': 'look', 'attachments': [{'path': staged, 'mime': 'image/png'}]}, 'queue'))+ await authority.sessions['s'].task+ assert receipt.status == 'queued'+ (event,) = seen+ assert event.text == 'look'+ assert event.media_types == ['image/png']+ (path,) = event.media_urls+ assert path != staged, 'execution must read committed bytes, not the mutable staging file'+ with open(path, 'rb') as fh:+ assert fh.read() == _ONE_PX_PNG