Skip to content

The agent that grows with you

fix: preserve hosted image admission and execution across owners

Teknium2672b8201216
diff --git a/gateway/session_hosted_attachments.py b/gateway/session_hosted_attachments.py
index 0d588045a39..7cacf43c00d 100644
--- a/gateway/session_hosted_attachments.py
+++ b/gateway/session_hosted_attachments.py
@@ -101,16 +101,38 @@ def submission_payload(rpc, prompt, attachments=None):
references.append(reference)
paths = restore_native_media(references)
from gateway.session_ingress_media import _ATTACHMENT_MIMES
- image_paths = [path for path, item in zip(paths, manifest)
- if item['mime'] in _ATTACHMENT_MIMES]
- if image_paths:
- # Keep the canonical admission shape; the authority captures these
- # already-authorized cache paths and the normal runner restores them into
- # native image_url parts.
- return {'text': prompt, 'attachments': [
- {'path': path, 'mime': item['mime']}
- for path, item in zip(paths, manifest)
- if item['mime'] in _ATTACHMENT_MIMES
- ]}
- return {'text': prompt + ''.join('\n[Shared attachment] file: ' + path + '\n'
- for path in paths)}
+ from gateway.platforms.base import get_image_cache_dir
+ import hashlib
+ images, documents = [], []
+ for path, item in zip(paths, manifest):
+ if item['mime'] not in _ATTACHMENT_MIMES:
+ documents.append(path)
+ continue
+ # Public admission accepts only owner-local staging paths. Retained
+ # room bytes are copied under a deterministic name for exact retries.
+ data = Path(path).read_bytes()
+ staging = get_image_cache_dir().resolve()
+ staging.mkdir(parents=True, exist_ok=True)
+ target = staging / (hashlib.sha256(data).hexdigest() + Path(item['name']).suffix)
+ if target.exists():
+ if target.is_symlink() or target.read_bytes() != data:
+ raise RuntimeStoreError('storage_unavailable')
+ else:
+ fd, temporary = tempfile.mkstemp(dir=staging)
+ try:
+ with os.fdopen(fd, 'wb') as output:
+ output.write(data)
+ output.flush()
+ os.fsync(output.fileno())
+ os.replace(temporary, target)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+ images.append({'path': str(target), 'mime': item['mime']})
+ text = prompt + ''.join('\n[Shared attachment] file: ' + path + '\n' for path in documents)
+ return {'text': text, **({'attachments': images} if images else {})}
+
+
+def committed_submission_payload(rpc, prompt, attachments=None):
+ from gateway.session_ingress_media import admit_attachments
+ payload = submission_payload(rpc, prompt, attachments)
+ return {'text': payload['text'], **admit_attachments(payload.get('attachments'))}
diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.py
index 40a4416c4fb..b12818ea138 100644
--- a/gateway/session_hosted_rpc.py
+++ b/gateway/session_hosted_rpc.py
@@ -128,10 +128,8 @@ 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()
+ payload = await asyncio.to_thread(
+ submission_payload, self, params['prompt'], params.get('attachments'))
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 bf114edf7c1..25b9982faa0 100644
--- a/gateway/session_hosted_service.py
+++ b/gateway/session_hosted_service.py
@@ -167,7 +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 gateway.session_hosted_attachments import committed_submission_payload
from tui_gateway.hosted_room_driver import HostedRoomBinding
try:
if not row['request_id'].startswith('hosted:'):
@@ -185,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'] != submission_payload(rpc, task['payload']['prompt'], task['payload'].get('attachments'))
+ or row['payload'] != committed_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/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.py
index a7b70cbe0ee..67dfa7fbba8 100644
--- a/gateway/session_hosted_transport.py
+++ b/gateway/session_hosted_transport.py
@@ -212,10 +212,10 @@ def check_remote_hosted_admission(authority, ref, row):
attested = _attest(binding, 'execute', params)
if attested['owner'] != binding['owner']:
raise ValueError('owner changed')
- from gateway.session_hosted_attachments import submission_payload
+ from gateway.session_hosted_attachments import committed_submission_payload
rpc = SimpleNamespace(authority=authority, **binding['selector'],
hosted_attachment_data=_attachment_data(binding, attested, params))
- if row['payload'] != submission_payload(rpc, attested['prompt'], attested['attachments']):
+ if row['payload'] != committed_submission_payload(rpc, attested['prompt'], attested['attachments']):
raise ValueError('input changed')
except (ValueError, KeyError, TypeError) as exc:
raise RuntimeStoreError('permission_denied') from exc
diff --git a/tests/gateway/test_session_hosted_daemon.py b/tests/gateway/test_session_hosted_daemon.py
index e99dfa441da..fda0f302f84 100644
--- a/tests/gateway/test_session_hosted_daemon.py
+++ b/tests/gateway/test_session_hosted_daemon.py
@@ -49,7 +49,8 @@ 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': 'gpt-4o', 'base_url': base},
+ 'model': {'provider': 'custom', 'default': 'gpt-4o', 'base_url': base, 'supports_vision': True},
+ 'agent': {'image_input_mode': 'native'},
'platform_toolsets': {'gui': [], 'bot_room': []},
'auxiliary': {'title_generation': {'enabled': False}},
'terminal': {'cwd': str(home)},
@@ -93,6 +94,7 @@ def test_native_room_service_local_member_and_restart(tmp_path):
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
+ (tmp_path / 'wire.json').write_text(json.dumps(model.requests), encoding='utf-8')
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']
@@ -120,7 +122,8 @@ 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': 'gpt-4o', 'base_url': base},
+ 'model': {'provider': 'custom', 'default': 'gpt-4o', 'base_url': base, 'supports_vision': True},
+ 'agent': {'image_input_mode': 'native'},
'platform_toolsets': {'gui': [], 'bot_room': []},
'auxiliary': {'title_generation': {'enabled': False}},
'terminal': {'cwd': str(home)},