Skip to content

The agent that grows with you

feat: consume event-bound hosted files through canonical admissions

Tekniume87bd098eab1
diff --git a/gateway/session_hosted_attachments.py b/gateway/session_hosted_attachments.py
new file mode 100644
index 00000000000..1c902dbff01
--- /dev/null
+++ b/gateway/session_hosted_attachments.py
@@ -0,0 +1,94 @@
+"""Owner-authorized room byte RPCs and committed task input materialization."""
+import base64
+import binascii
+import os
+from pathlib import Path
+import tempfile
+
+from gateway.hosted_room_attachments import HostedRoomAttachmentStore, MAX_ATTACHMENT_BYTES
+from hermes_state_runtime import RuntimeStoreError
+
+
+def _authorize(service, actor, params, capability):
+ if actor.profile_id != service.authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if capability not in actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ room_id = params.get('room_id')
+ service.authorize_room(actor.subject, room_id)
+ service._owned_authority(room_id)
+ service._room(room_id)
+ return room_id
+
+
+def upload(service, actor, params):
+ room_id = _authorize(service, actor, params, 'session:submit')
+ encoded = params.get('data_base64')
+ if not isinstance(encoded, str) or len(encoded) > ((MAX_ATTACHMENT_BYTES + 2) // 3) * 4:
+ raise RuntimeStoreError('invalid_params')
+ try:
+ data = base64.b64decode(encoded, validate=True)
+ except (ValueError, binascii.Error) as exc:
+ raise RuntimeStoreError('invalid_params') from exc
+ return HostedRoomAttachmentStore(service.db_path).put(
+ room_id=room_id, upload_id=params.get('upload_id'), kind=params.get('kind'),
+ name=params.get('name'), mime=params.get('mime'), data=data)
+
+
+def download(service, actor, params):
+ room_id = _authorize(service, actor, params, 'session:read')
+ if not params.get('event_id'):
+ raise RuntimeStoreError('invalid_params')
+ gateway_id, epoch = service._owned_authority(room_id)
+ saved = HostedRoomAttachmentStore(service.db_path).read_viewer(
+ room_id=room_id, attachment_id=params.get('attachment_id'), event_id=params['event_id'],
+ authority_gateway_id=gateway_id, authority_epoch=epoch)
+ return {**saved.attachment, 'data_base64': base64.b64encode(saved.data).decode('ascii')}
+
+
+def append_user_event(service, *, room_id, event_id, payload, gateway_id, epoch):
+ from gateway import hosted_rooms
+ store = HostedRoomAttachmentStore(service.db_path)
+ manifest = payload.get('attachments', [])
+ transitioned = []
+ if manifest:
+ _, transitioned = store.commit_message_with_receipt(
+ room_id=room_id, event_id=event_id, manifest=manifest,
+ recipient_member_ids=[m['member_id'] for m in service._room(room_id)['members']],
+ viewer_access=True, hold_until_event=True)
+ try:
+ return hosted_rooms.append_event(
+ service.db_path, room_id=room_id, event_id=event_id, kind='message.user',
+ actor={'kind': 'user', 'id': 'desktop'}, payload=payload,
+ authority_gateway_id=gateway_id, authority_epoch=epoch)
+ except Exception:
+ if transitioned:
+ store.abort_message_commit(room_id=room_id, event_id=event_id, attachment_ids=transitioned)
+ raise
+
+
+def submission_payload(rpc, prompt, attachments=None):
+ """Resolve only event-bound, member-authorized bytes, never a caller path."""
+ if not attachments:
+ return {'text': prompt}
+ from gateway.hosted_room_driver import validate_bound_task_manifest
+ from gateway.session_ingress_media import capture_native_media, restore_native_media
+ manifest = validate_bound_task_manifest(attachments)
+ store = HostedRoomAttachmentStore(rpc.authority.db.db_path)
+ references = []
+ for item in manifest:
+ saved = store.read(room_id=rpc.room_id, attachment_id=item['attachment_id'],
+ event_id=item['event_id'], recipient_member_id=rpc.member_id)
+ if any(saved.attachment[key] != item[key] for key in ('kind', 'name', 'mime', 'size')):
+ raise RuntimeStoreError('permission_denied')
+ # Retained native-inputs are excluded from age-only document cleanup. The
+ # content-addressed destination is stable on retry and refuses corruption.
+ with tempfile.TemporaryDirectory(prefix='hermes-room-input-') as directory:
+ path = Path(directory) / item['name']
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(fd, 'wb') as output:
+ output.write(saved.data)
+ reference = capture_native_media([path])[0]
+ references.append(reference)
+ paths = restore_native_media(references)
+ return {'text': prompt + ''.join('\n[Shared attachment] file: ' + path + '\n' for path in paths)}
diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.py
index 430baf8b06e..96b2340c35c 100644
--- a/gateway/session_hosted_rpc.py
+++ b/gateway/session_hosted_rpc.py
@@ -127,8 +127,10 @@ class HostedRoomAuthorityRPC:
rows = self._rows()
if any(row['status'] == 'unknown' for row, _, _ in rows):
raise RuntimeStoreError('unknown_execution')
+ from gateway.session_hosted_attachments import submission_payload
+ payload = submission_payload(self, params['prompt'], params.get('attachments'))
receipt = await self.authority.submit(self.principal, Submission(
- request_id, self.ref, {'text': params['prompt']}, 'queue'))
+ request_id, self.ref, payload, 'queue'))
self.callbacks[receipt.admission_id] = params['on_terminal']
if receipt.status in {'queued', 'started'}:
waiter = self.authority.waiters.get(receipt.admission_id)
@@ -233,9 +235,10 @@ class HostedRoomAuthorityRPC:
def resume(self, *, profile, session_id, source):
return self._call('resume', profile=profile, session_id=session_id, source=source)
- def submit(self, *, profile, session_id, prompt, source, task, execution_generation, on_terminal):
+ def submit(self, *, profile, session_id, prompt, source, task, execution_generation, on_terminal, attachments=None):
return self._call('submit', profile=profile, session_id=session_id, source=source,
- prompt=prompt, task=task, execution_generation=execution_generation, on_terminal=on_terminal)
+ prompt=prompt, task=task, execution_generation=execution_generation, on_terminal=on_terminal,
+ attachments=attachments)
def history(self, *, profile, session_id, source):
return self._call('history', profile=profile, session_id=session_id, source=source)
diff --git a/tests/gateway/test_hosted_attachment_bridge.py b/tests/gateway/test_hosted_attachment_bridge.py
new file mode 100644
index 00000000000..d91a573398f
--- /dev/null
+++ b/tests/gateway/test_hosted_attachment_bridge.py
@@ -0,0 +1,65 @@
+import base64
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+def test_authorized_upload_send_download_and_task_consumption(tmp_path):
+ from gateway.session_hosted_attachments import upload, download, submission_payload
+ from gateway.hosted_room_attachments import HostedRoomAttachmentStore
+ from gateway import hosted_rooms
+ hosted_rooms.create_room(tmp_path / "state.db", room_id="room", name="Room", members=[], authority_gateway_id="gateway")
+ from hermes_state_runtime import RuntimeStoreError
+ allowed = [True]
+ def authorize(subject, room_id):
+ if not allowed[0] or subject != 'owner' or room_id != 'room':
+ raise RuntimeStoreError('permission_denied')
+ service = SimpleNamespace(authority=SimpleNamespace(profile_id='owned'), db_path=tmp_path / 'state.db', authorize_room=authorize,
+ _room=lambda room: {'members': [{'member_id': 'member', 'profile': 'default'}]},
+ _owned_authority=lambda room: ('gateway', 1))
+ actor = SimpleNamespace(subject='owner', profile_id='owned', capabilities={'session:read','session:submit'})
+ params = dict(room_id='room', upload_id='upload', kind='file', name='note.txt', mime='text/plain', data_base64=base64.b64encode(b'committed bytes').decode())
+ metadata = upload(service, actor, params)
+ manifest = [{k: metadata[k] for k in ('attachment_id', 'kind', 'name', 'size', 'mime')}]
+ store = HostedRoomAttachmentStore(service.db_path)
+ from gateway.session_hosted_attachments import append_user_event
+ append_user_event(service, room_id='room', event_id='event', payload={'text':'read', 'attachments':manifest}, gateway_id='gateway', epoch=1)
+ bound = [{**manifest[0], 'event_id': 'event'}]
+ rpc = SimpleNamespace(authority=SimpleNamespace(db=SimpleNamespace(db_path=service.db_path)), room_id='room', member_id='member')
+ payload = submission_payload(rpc, 'read it', bound)
+ path = Path(payload['text'].split('file: ')[1].split('\n')[0])
+ assert path.read_bytes() == b'committed bytes'
+ assert submission_payload(rpc, 'read it', bound) == payload
+ assert base64.b64decode(download(service, actor, dict(room_id='room', event_id='event', attachment_id=metadata['attachment_id']))['data_base64']) == path.read_bytes()
+ with pytest.raises(Exception):
+ submission_payload(rpc, 'read it', [{**bound[0], 'event_id': 'wrong'}])
+ allowed[0] = False
+ for call in (lambda: upload(service, actor, params), lambda: download(service, actor, dict(room_id='room', attachment_id=metadata['attachment_id'], event_id='event'))):
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ call()
+
+
+def test_rpc_accepts_only_bound_manifest_after_producer_authorization(owner):
+ from gateway.session_hosted_rpc import HostedRoomAuthorityRPC
+ from gateway.hosted_room_driver import TaskIdentity
+ from gateway.hosted_room_attachments import HostedRoomAttachmentStore
+ from hermes_state_runtime import list_session_admissions
+ authority, loop, principal, _ = owner
+ rpc = HostedRoomAuthorityRPC(authority, loop, room_id='room', member_id='member', profile='default', principal=principal, authorize=lambda *args: True)
+ coords = dict(profile='default', source='bot_room')
+ sid = rpc.create(**coords, title='Group: room')['session_id']
+ store = HostedRoomAttachmentStore(authority.db.db_path)
+ saved = store.put(room_id='room', upload_id='upload', kind='file', name='note.txt', mime='text/plain', data=b'exact bytes')
+ manifest = [{k: saved[k] for k in ('attachment_id', 'kind', 'name', 'size', 'mime')}]
+ store.commit_message(room_id='room', event_id='event', manifest=manifest, recipient_member_ids=['member'])
+ args = dict(**coords, session_id=sid, prompt='read', task=TaskIdentity('room','task','thread','turn'), execution_generation=1, on_terminal=lambda receipt: None, attachments=[{**manifest[0], 'event_id':'event'}])
+ first = rpc.submit(**args)
+ assert rpc.submit(**args)['admission_id'] == first['admission_id']
+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)
+ assert len(rows) == 1
+ path = Path(rows[0]['payload']['text'].split('file: ')[1].split('\n')[0])
+ assert path.read_bytes() == b'exact bytes'
+
+
+from tests.gateway.test_session_hosted_rpc import owner # noqa: F401,E402
diff --git a/tui_gateway/hosted_room_driver.py b/tui_gateway/hosted_room_driver.py
index 5e4f5eab464..1603eb96bcb 100644
--- a/tui_gateway/hosted_room_driver.py
+++ b/tui_gateway/hosted_room_driver.py
@@ -593,6 +593,7 @@ class HostedRoomRuntime:
transport.submit(
**_session_kw(profile, session_id), prompt=task["payload"]["prompt"],
task=attempt.identity, execution_generation=attempt.execution_generation,
+ **({"attachments": task["payload"]["attachments"]} if task["payload"].get("attachments") else {}),
on_terminal=lambda receipt: self._on_terminal(binding, attempt, receipt))
self._unavailable_route_retries.pop(
(task["identity"].room_id, _member_id(task)), None)