Skip to content

The agent that grows with you

fix: integrate hosted attachment admission hooks

Tekniumc094d91ec29a
diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.py
index bd4b5f67b9a..a5f57f1195b 100644
--- a/gateway/session_group_controls.py
+++ b/gateway/session_group_controls.py
@@ -14,6 +14,8 @@ GROUP_METHODS = {
'groups.rename': 'session:control',
'groups.disband': 'session:control',
'groups.send': 'session:submit',
+ 'groups.attachment.upload': 'session:submit',
+ 'groups.attachment.download': 'session:read',
'groups.stop': 'session:control',
'groups.retry': 'session:control',
'groups.discard': 'session:control',
@@ -28,6 +30,8 @@ _FIELDS = {
'groups.rename': {'room_id', 'event_id', 'name'},
'groups.disband': {'room_id', 'cancel_id'},
'groups.send': {'room_id', 'event_id', 'payload'},
+ 'groups.attachment.upload': {'room_id', 'upload_id', 'kind', 'name', 'mime', 'data_base64'},
+ 'groups.attachment.download': {'room_id', 'event_id', 'attachment_id'},
'groups.stop': {'room_id', 'cancel_id'},
'groups.retry': {'room_id', 'member_id', 'task_id', 'execution_generation'},
'groups.discard': {'room_id', 'member_id', 'task_id', 'execution_generation'},
@@ -92,6 +96,12 @@ def _group(authority, actor, home, method, params):
if room_authorizer is None:
raise RuntimeStoreError('permission_denied')
room_authorizer(actor.subject, params['room_id'], create=method == 'groups.create')
+ if method in {'groups.attachment.upload', 'groups.attachment.download'}:
+ if service is None:
+ raise RuntimeStoreError('runtime_coordination_required')
+ from gateway.session_hosted_attachments import upload, download
+ handler = upload if method == 'groups.attachment.upload' else download
+ return handler(service, actor, params)
if method in execution_methods:
if service is None:
raise RuntimeStoreError('runtime_coordination_required')
diff --git a/gateway/session_hosted_attachments.py b/gateway/session_hosted_attachments.py
index 1c902dbff01..020f443f971 100644
--- a/gateway/session_hosted_attachments.py
+++ b/gateway/session_hosted_attachments.py
@@ -76,10 +76,19 @@ def submission_payload(rpc, prompt, attachments=None):
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')):
+ transferred = getattr(rpc, 'hosted_attachment_data', None)
+ if transferred is not None and [item for item, data in transferred] != manifest:
+ raise RuntimeStoreError('permission_denied')
+ for index, item in enumerate(manifest):
+ if transferred is None:
+ 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')
+ data = saved.data
+ else:
+ data = transferred[index][1]
+ if len(data) != item['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.
@@ -87,8 +96,12 @@ def submission_payload(rpc, prompt, attachments=None):
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)
+ output.write(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)}
+ from gateway.session_ingress_media import _ATTACHMENT_MIMES
+ images = [(ref, item['mime']) for ref, item in zip(references, manifest)
+ if item['mime'] in _ATTACHMENT_MIMES]
+ 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 96b2340c35c..40a4416c4fb 100644
--- a/gateway/session_hosted_rpc.py
+++ b/gateway/session_hosted_rpc.py
@@ -128,7 +128,10 @@ class HostedRoomAuthorityRPC:
if any(row['status'] == 'unknown' for row, _, _ in rows):
raise RuntimeStoreError('unknown_execution')
from gateway.session_hosted_attachments import submission_payload
+ import faulthandler
+ faulthandler.dump_traceback_later(8)
payload = submission_payload(self, params['prompt'], params.get('attachments'))
+ faulthandler.cancel_dump_traceback_later()
receipt = await self.authority.submit(self.principal, Submission(
request_id, self.ref, payload, 'queue'))
self.callbacks[receipt.admission_id] = params['on_terminal']
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.py
index 0a026446bde..bf114edf7c1 100644
--- a/gateway/session_hosted_service.py
+++ b/gateway/session_hosted_service.py
@@ -167,6 +167,7 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):
"""Reconstruct the private producer from durable task state before claim."""
import json
from gateway.hosted_room_driver import TaskIdentity, list_tasks
+ from gateway.session_hosted_attachments import submission_payload
from tui_gateway.hosted_room_driver import HostedRoomBinding
try:
if not row['request_id'].startswith('hosted:'):
@@ -184,7 +185,7 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):
rpc = self._resolve_member_transport(HostedRoomBinding(identity.room_id,
room['authority_gateway_id'], room['authority_epoch']), task)
if (getattr(rpc, 'ref', None) != ref or task['status'] != 'running'
- or row['payload'] != {'text': task['payload']['prompt']}
+ or row['payload'] != submission_payload(rpc, task['payload']['prompt'], task['payload'].get('attachments'))
or rpc.authorizer('execute', identity, generation) is not True):
raise ValueError('changed hosted binding')
return task
diff --git a/tests/gateway/test_session_hosted_daemon.py b/tests/gateway/test_session_hosted_daemon.py
index e1c0e355e09..e99dfa441da 100644
--- a/tests/gateway/test_session_hosted_daemon.py
+++ b/tests/gateway/test_session_hosted_daemon.py
@@ -49,7 +49,7 @@ def test_native_room_service_local_member_and_restart(tmp_path):
base = f'http://127.0.0.1:{model.server_port}/v1'
(home / 'config.yaml').write_text(json.dumps({
'gateway': {'multiplex_profiles': False}, 'hosted_rooms': {'profiles': {'two': str(target)}},
- 'model': {'provider': 'custom', 'default': 'loopback-room', 'base_url': base},
+ 'model': {'provider': 'custom', 'default': 'gpt-4o', 'base_url': base},
'platform_toolsets': {'gui': [], 'bot_room': []},
'auxiliary': {'title_generation': {'enabled': False}},
'terminal': {'cwd': str(home)},
@@ -59,6 +59,9 @@ def test_native_room_service_local_member_and_restart(tmp_path):
PYTHONPATH=str(root), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1')
members = [{'member_id': 'one', 'profile': 'default', 'handle': 'one'},
{'member_id': 'two', 'profile': 'two', 'handle': 'two'}]
+ import base64
+ image = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aP1sAAAAASUVORK5CYII=')
+ saved = {}
async def probe(desc, restart):
async with websocket(home, desc) as ws:
capabilities = await rpc(ws, 'groups.capabilities')
@@ -70,10 +73,15 @@ def test_native_room_service_local_member_and_restart(tmp_path):
assert 'error' in rejected, rejected
created = await rpc(ws, 'groups.create', room_id='owned', name='Owned', members=members)
assert 'result' in created, created
+ if not restart:
+ uploaded = await rpc(ws, 'groups.attachment.upload', room_id='owned', upload_id='image',
+ kind='image', name='pixel.png', mime='image/png', data_base64=base64.b64encode(image).decode())
+ assert 'result' in uploaded, uploaded
+ saved['manifest'] = [{k: uploaded['result'][k] for k in ('attachment_id', 'kind', 'name', 'size', 'mime')}]
sent = await rpc(ws, 'groups.send', room_id='owned', event_id='input-one',
- payload={'text': 'LOCAL_HOSTED_PROOF', 'thread_id': 'thread'})
+ payload={'text': 'LOCAL_HOSTED_PROOF', 'thread_id': 'thread', 'attachments': saved['manifest']})
assert sent['result']['accepted'], sent
- async with asyncio.timeout(25):
+ async with asyncio.timeout(45):
while True:
log = await rpc(ws, 'groups.log', room_id='owned')
if sum(e['kind'] == 'turn.settled' for e in log['result']['events']) >= 2:
@@ -82,6 +90,14 @@ def test_native_room_service_local_member_and_restart(tmp_path):
state = await rpc(ws, 'groups.state', room_id='owned')
assert state['result']['driver_status']['counts'].get('settled') == 2, state
assert len(model.requests) == 2, model.requests
+ downloaded = await rpc(ws, 'groups.attachment.download', room_id='owned',
+ event_id=sent['result']['event']['event_id'], attachment_id=saved['manifest'][0]['attachment_id'])
+ assert base64.b64decode(downloaded['result']['data_base64']) == image
+ for request in model.requests:
+ images = [b for m in request['messages'] if isinstance(m.get('content'), list)
+ for b in m['content'] if b.get('type') == 'image_url']
+ assert images, request
+ assert base64.b64decode(images[0]['image_url']['url'].split(',')[1]) == image
try:
for restart in (False, True):
with daemon(root, target, env | {'HERMES_HOME': str(target)}, barrier=False), daemon(root, home, env, barrier=False) as (_, desc):
@@ -104,7 +120,7 @@ def test_room_unknown_discard_releases_only_its_followers(tmp_path):
base = f'http://127.0.0.1:{model.server_port}/v1'
(home / 'config.yaml').write_text(json.dumps({
'gateway': {'multiplex_profiles': False}, 'hosted_rooms': {'profiles': {'two': str(target)}},
- 'model': {'provider': 'custom', 'default': 'loopback-room', 'base_url': base},
+ 'model': {'provider': 'custom', 'default': 'gpt-4o', 'base_url': base},
'platform_toolsets': {'gui': [], 'bot_room': []},
'auxiliary': {'title_generation': {'enabled': False}},
'terminal': {'cwd': str(home)},