The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preserve admitted images and async usage in managed workers
Teknium4abbb3f9788c
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 121fe0f352e..7b1e0a5380c 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -3431,10 +3431,12 @@ def _retry_same_provider_sync(*, resolved_provider: str, resolved_api_mode: Optiasync def _retry_same_provider_async(*, resolved_provider: str, resolved_api_mode: Optional[str], task: Optional[str], **prep) -> Any:+ import asyncioretry_client, retry_kwargs = _prepare_same_provider_retry(task=task, resolved_provider=resolved_provider, resolved_api_mode=resolved_api_mode, async_mode=True, **prep,)- return _validate_llm_response(+ return await asyncio.to_thread(+ _validate_llm_response,await _relay_async_completion(retry_client, retry_kwargs, provider=resolved_provider, api_mode=resolved_api_mode),task,)@@ -3793,7 +3795,9 @@ async def _call_fallback_candidate_async()async def _send(client: Any, request_kwargs: Dict[str, Any], dest: _FallbackDestination) -> Any:- return _validate_llm_response(+ import asyncio+ return await asyncio.to_thread(+ _validate_llm_response,await _relay_async_completion(client, request_kwargs, provider=dest.provider, api_mode=dest.api_mode),task,)@@ -6069,7 +6073,8 @@ def _validate_llm_response("""Validate the .choices[0].message shape (fail fast, not a downstream AttributeError).Also the single aux-usage accounting chokepoint: every successful non-streaming response- passes here exactly once; *provider*/*base_url* are optional hints.+ passes here exactly once; *provider*/*base_url* are optional hints. Async callers+ await this off-loop because accounting may commit through synchronous worker RPC.See #7264.Recording is best-effort and never affects validation. *provider*/*base_url* are optional accounting@@ -7426,7 +7431,9 @@ async def _async_call_llm_impl(return await _acreate_with_progress(client, _kwargs, task, force_stream=_force_stream_async)async def _primary(**validate_kw: Any) -> Any:- return _validate_llm_response(+ import asyncio+ return await asyncio.to_thread(+ _validate_llm_response,await _relay_async_completion(client, kwargs, provider=request_provider, api_mode=req.resolved_api_mode,create=_acreate),@@ -7444,7 +7451,8 @@ async def _async_call_llm_impl(async def _perform(step: _LadderStep) -> Any:kind, args, kw = _ladder_step_call(step, req, retry_kwargs, candidate_kwargs)if kind == "call":- return _validate_llm_response(await _relay_async_completion(*args, **kw), task)+ import asyncio+ return await asyncio.to_thread(_validate_llm_response, await _relay_async_completion(*args, **kw), task)if kind == "retry":return await _retry_same_provider_async(**kw)fb_client, fb_model, fb_label = argsdiff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex ab60ce60557..a87e79aa382 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -35,7 +35,7 @@ def encode_frame(frame):def validate_bootstrap(frame):- if set(frame) != BOOTSTRAP_FIELDS or frame['version'] != 1:+ if set(frame) - {'attachments_v1'} != BOOTSTRAP_FIELDS or frame['version'] != 1:raise ValueError('invalid_managed_worker_bootstrap')scope = frame['scope']fields = {'profile_id', 'session_id', 'execution_id', 'generation', 'pid', 'birth', 'secret', 'epoch'}@@ -198,6 +198,14 @@ def execute(frame, channel):channel.send('ready', pid=os.getpid())history = store.get_messages_as_conversation(scope['session_id'])from gateway.session_kanban import run_worker_turns+ if 'attachments_v1' in frame:+ from gateway.session_ingress_media import restore_attachments+ from agent.image_routing import build_native_content_parts+ media = restore_attachments(frame)+ content, skipped = build_native_content_parts(frame['text'], media['media_urls'])+ if skipped:+ raise ValueError('managed_attachment_unavailable')+ frame = {**frame, 'text': content}result = run_worker_turns(agent, frame, history)agent._end_session_on_close = Falseagent.close()diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 7714c030f2e..fd1b4a30b35 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -48,6 +48,7 @@ def _bootstrap(authority, ref, row, policy, scope):return {'version': 1, 'home': authority.profile_id, 'scope': scope,'policy': asdict(hydrated), 'api_key': launch_key(authority, policy),'text': row['payload']['text'], 'route': live.route,+ **({'attachments_v1': row['payload']['attachments_v1']} if 'attachments_v1' in row['payload'] else {}),'user_id': live.source.user_id, 'chat_id': live.source.chat_id,'safe_mode': policy.safe_mode, 'ignore_user_config': policy.ignore_user_config}diff --git a/tests/gateway/test_managed_worker_images.py b/tests/gateway/test_managed_worker_images.pynew file mode 100644index 00000000000..577e5b2addf--- /dev/null+++ b/tests/gateway/test_managed_worker_images.py@@ -0,0 +1,80 @@+"""A managed assignment preserves the image bytes committed at admission."""+import asyncio+import json+from http.server import ThreadingHTTPServer+from pathlib import Path+import threading++from PIL import Image+import pytest++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket++[email protected]('mode', ['normal', 'managed', 'safe'])[email protected]('model', ['gpt-4o', 'image-fixture'])+def test_admitted_images_reach_managed_worker(tmp_path, mode, model):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False, 'managed_workers': mode == 'managed'},+ 'model': {'provider': 'custom', 'default': model, 'base_url': url},+ 'agent': {'image_input_mode': 'native'}, 'platform_toolsets': {'cli': []},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ async def exercise(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='create', source='cli', cwd=str(home),+ model=model, provider='custom', base_url=url, toolsets=[],+ safe_mode=mode == 'safe', ignore_user_config=mode == 'safe')+ assert 'result' in created, created+ sid = created['result']['session_id']+ image = home / 'cache/images/owned.png'+ image.parent.mkdir(parents=True, exist_ok=True)+ Image.new('RGB', (16, 16), 'blue').save(image)+ original = image.read_bytes()+ accepted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='image', text='IMAGE_SENTINEL',+ attachments=[{'path': str(image), 'mime': 'image/png'}])+ assert 'result' in accepted, accepted+ image.unlink() # Execution must use retained bytes, never the staging path.+ async with asyncio.timeout(40):+ while True:+ receipt = await rpc(ws, 'prompt.receipt', session_id=sid,+ admission_id=accepted['result']['admission_id'])+ if receipt.get('result', {}).get('status') in ('terminal', 'unknown'):+ break+ await asyncio.sleep(.05)+ assert receipt['result']['outcome'] == 'completed', receipt+ import base64+ parts = [part for request in peer.requests for message in request['messages']+ if message['role'] == 'user' and isinstance(message.get('content'), list)+ for part in message['content'] if part.get('type') == 'image_url']+ assert parts, peer.requests+ assert base64.b64decode(parts[-1]['image_url']['url'].split(',', 1)[1]) == original+ if model == 'image-fixture':+ import sqlite3+ from contextlib import closing+ with closing(sqlite3.connect((home / 'state.db').as_uri() + '?mode=ro', uri=True)) as db:+ assert db.execute('SELECT SUM(input_tokens) FROM session_model_usage WHERE session_id=? AND task=?',+ (sid, 'vision')).fetchone()[0] > 0++ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ asyncio.run(exercise(desc))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)