Skip to content

The agent that grows with you

fix(api): canonical API turns keep images, tool payloads, controls and true outcomes

teknium1e918de809707
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.py
index f640b1c7067..db441b04224 100644
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@ -76,6 +76,10 @@ def _finish_reason(completed, is_partial, is_failed, err_msg, agent_error=None)
return 'cancelled' if not completed else 'stop'
+_RESPONSES_FINGERPRINT_KEYS = ("input", "instructions", "previous_response_id", "conversation", "model",
+ "provider", "model_options", "tools")
+
+
def _response_status(result):
if result.get('interrupted'):
return 'cancelled'
@@ -813,6 +817,20 @@ class OpenAICompatRoutesMixin:
store = _coerce_request_bool(body.get("store"), default=True)
if conversation and previous_response_id:
return _error_response("Cannot use both 'conversation' and 'previous_response_id'", 400)
+ durable_key = None
+ if getattr(self.gateway_runner, 'session_authority', None) is not None and request.headers.get('Idempotency-Key'):
+ # An exact retry replays the committed response BEFORE the conversation name is
+ # expanded: the first success already advanced the conversation, so re-expanding
+ # would build a different admission payload and refuse the retry as a conflict.
+ from gateway.platforms.api_server import _make_request_fingerprint
+ durable_key = ('idem:' + self._run_idempotency_scope(request) + ':' + request.headers['Idempotency-Key'],
+ _make_request_fingerprint(body, keys=_RESPONSES_FINGERPRINT_KEYS))
+ replay = self._response_store.get(durable_key[0])
+ if replay is not None:
+ if replay.get('fingerprint') != durable_key[1]:
+ from gateway.platforms.api_server import _openai_error
+ return web.json_response(_openai_error('admission_conflict', code='admission_conflict'), status=409)
+ return web.json_response(replay['response'], headers=replay.get('headers') or {})
if conversation:
# A conversation name resolves to its latest response_id (unknown = new conversation).
previous_response_id = self._response_store.get_conversation(conversation)
@@ -925,8 +943,7 @@ class OpenAICompatRoutesMixin:
return await self._run_agent(**run_kwargs)
outcome, err = await self._run_idempotent(
request, body, _compute_response, log_label="responses",
- fingerprint_keys=["input", "instructions", "previous_response_id", "conversation", "model", "provider", "model_options", "tools"],
- route="responses",
+ fingerprint_keys=list(_RESPONSES_FINGERPRINT_KEYS), route="responses",
)
if err is not None:
return err
@@ -964,6 +981,9 @@ class OpenAICompatRoutesMixin:
response_headers = {"X-Hermes-Session-Id": _effective_session_id}
if gateway_session_key:
response_headers["X-Hermes-Session-Key"] = gateway_session_key
+ if durable_key is not None:
+ self._response_store.put(durable_key[0], {
+ 'fingerprint': durable_key[1], 'response': response_data, 'headers': response_headers})
return web.json_response(response_data, headers=response_headers)
async def _handle_get_response(self, request: "web.Request") -> "web.Response":
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 9d96a96d66c..67728c8a721 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -38,10 +38,15 @@ _USAGE_FIELDS = (
("input_tokens", "session_prompt_tokens"), ("output_tokens", "session_completion_tokens"),
("total_tokens", "session_total_tokens"))
# Tool-progress event -> SSE payload fields (tool_name, preview, kwargs); key order is wire format.
+def _call_id(kw: Dict[str, Any]) -> Dict[str, Any]:
+ return {"tool_call_id": kw["tool_call_id"]} if kw.get("tool_call_id") else {}
+
+
_FIXED_EVENT_FIELDS = {
- "tool.started": lambda tool, preview, kw: {"tool": tool, "preview": preview},
+ "tool.started": lambda tool, preview, kw: {"tool": tool, "preview": preview, **_call_id(kw)},
"tool.completed": lambda tool, preview, kw: {
- "tool": tool, "duration": round(kw.get("duration", 0), 3), "error": kw.get("is_error", False)},
+ "tool": tool, "duration": round(kw.get("duration", 0), 3), "error": kw.get("is_error", False),
+ **_call_id(kw)},
"reasoning.available": lambda tool, preview, kw: {"text": preview or ""}}
@@ -647,8 +652,28 @@ async def _execute_run(self, run: _RunLaunch, *, _api_server) -> None:
_finish("cancelled")
return
if run.admission is not None:
- from gateway.session_api_turn import observe_api_turn
- result, usage = await observe_api_turn(run.admission, stream_delta_callback=_text_cb)
+ from gateway.session_api_turn import observe_api_controls, observe_api_turn
+ tool_cb = self._make_run_event_callback(run_id, loop)
+
+ def _control_cb(event_type, prompt):
+ # Same authority prompt the WS viewer and GET pending_controls expose, on the
+ # run's own stream so a streaming-only client learns it must respond.
+ with suppress(Exception):
+ loop.call_soon_threadsafe(run.put_event, _run_event(run_id, event_type, **prompt))
+
+ def _tool_start(call_id, name, args):
+ from agent.display import build_tool_preview
+ tool_cb("tool.started", name, build_tool_preview(name, args or {}) or "", args, tool_call_id=call_id)
+
+ def _tool_complete(call_id, name, args, result):
+ from agent.display import _detect_tool_failure
+ is_error, _ = _detect_tool_failure(name, result)
+ tool_cb("tool.completed", name, None, args, tool_call_id=call_id, is_error=bool(is_error))
+
+ with observe_api_controls(run.admission, _control_cb):
+ result, usage = await observe_api_turn(
+ run.admission, stream_delta_callback=_text_cb,
+ tool_start_callback=_tool_start, tool_complete_callback=_tool_complete)
else:
with self._profile_scope(run.request_profile):
agent = self._create_agent(
@@ -660,7 +685,9 @@ async def _execute_run(self, run: _RunLaunch, *, _api_server) -> None:
None, lambda: _run_agent_sync(self, run, agent, approval_notify, _api_server=_api_server))
if not isinstance(result, dict):
result = {}
- if run_id in self._stopping_run_ids and result.get("interrupted") is True:
+ # The committed outcome decides: a stop issued over WS by another viewer interrupts
+ # this run just as much as one issued through this adapter's own /stop.
+ if result.get("interrupted") is True:
_finish("cancelled")
elif result.get("failed"):
# Non-retryable client errors (401/400) return failed=True rather than raising.
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index ac51aa6cb7f..cc959007c51 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -725,6 +725,7 @@ class GatewayTurnProgressMixin:
"""Compose the voice ack + native task-card start consumers."""
self._publish_execution("tool.start", {
"tool_call_id": str(call_id or ""), "tool_name": str(tool_name or "tool")})
+ self._publish_api_tool("tool.start", call_id, tool_name, args)
if self._ctx._voice_ack_guild[0] is not None:
self.voice_ack_callback(call_id, tool_name, args)
if self._ctx._native_slack_task_cards:
@@ -736,6 +737,7 @@ class GatewayTurnProgressMixin:
self._publish_execution("tool.complete", {
"tool_call_id": str(call_id or ""), "tool_name": str(tool_name or "tool"),
"is_error": bool(is_error)})
+ self._publish_api_tool("tool.complete", call_id, tool_name, args, result)
if self._ctx._native_slack_task_cards:
self.native_tool_complete_callback(call_id, tool_name, args, result)
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 44633c74626..80ba8b51831 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -72,6 +72,15 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
return authority.publish_execution(session_id, generation, event_type, payload)
return False
+ def _publish_api_tool(self, event_type, call_id, tool_name, args, result=None):
+ """The retained tool payload reaches the API observers of this exact admission only;
+ the shared viewer stream keeps its ID-correlated frames."""
+ if self._approval_owner is not None:
+ from gateway.session_api_turn import publish_api_tool_event
+ authority, session_id, generation = self._approval_owner
+ publish_api_tool_event(authority, session_id, generation, event_type,
+ str(call_id or ""), str(tool_name or "tool"), args, result)
+
# ── stream consumer / interim commentary wiring ─────────────────────────────────────────
def _setup_stream_consumer(self, platform_key):
diff --git a/gateway/session_api_media.py b/gateway/session_api_media.py
new file mode 100644
index 00000000000..890729c00c3
--- /dev/null
+++ b/gateway/session_api_media.py
@@ -0,0 +1,68 @@
+"""API image parts become committed media references that outlive the transient turn."""
+import base64
+import hashlib
+import os
+from pathlib import Path
+
+_MIME_EXT = {'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp'}
+
+
+def _data_url_bytes(url):
+ """``(mime, bytes)`` for a committable ``data:image/...;base64,`` URL, else ``None``."""
+ header, _, encoded = url.partition(',')
+ mime = header[len('data:'):].split(';', 1)[0].strip().lower()
+ if not url.lower().startswith('data:') or mime not in _MIME_EXT or ';base64' not in header.lower():
+ return None
+ try:
+ return mime, base64.b64decode(encoded, validate=True)
+ except ValueError:
+ return None
+
+
+def _image_urls(content):
+ for part in content:
+ if isinstance(part, dict) and part.get('type') == 'image_url':
+ yield (part.get('image_url') or {}).get('url', '')
+
+
+def commit_api_images(content):
+ """Stage every inline ``data:`` image deterministically (same bytes -> same path, so an
+ exact retry keeps its admission digest) and commit the bytes as immutable media."""
+ from gateway.platforms.base import get_image_cache_dir
+ from gateway.session_ingress_media import capture_native_media
+ staged = []
+ for url in _image_urls(content):
+ decoded = _data_url_bytes(url)
+ if decoded is None:
+ continue
+ mime, data = decoded
+ path = Path(get_image_cache_dir()).resolve() / ('api_' + hashlib.sha256(data).hexdigest()[:32] + _MIME_EXT[mime])
+ if not path.exists():
+ temporary = path.with_name(path.name + '.%d.tmp' % os.getpid())
+ temporary.write_bytes(data)
+ os.replace(temporary, path)
+ staged.append(path)
+ return capture_native_media(staged)
+
+
+def restore_api_images(content, media):
+ """The transient content keeps its pixels; its text gains the validated committed reference
+ per inline image (remote URLs keep their address) so the persisted user row records what
+ was seen, exactly like native image turns."""
+ from gateway.session_ingress_media import restore_native_media
+ paths = iter(restore_native_media(media))
+ hints = []
+ for url in _image_urls(content):
+ if _data_url_bytes(url) is not None:
+ hints.append('[Image attached at: %s]' % next(paths))
+ else:
+ hints.append('[Image attached: %s]' % url)
+ if not hints:
+ return content
+ parts = [dict(part) for part in content]
+ text = next((part for part in parts if part.get('type') == 'text'), None)
+ if text is None:
+ text = {'type': 'text', 'text': 'What do you see in this image?'}
+ parts.insert(0, text)
+ text['text'] = text['text'] + '\n\n' + '\n'.join(hints)
+ return parts
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index 5b3f5fc7f3b..3a472e94282 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -34,7 +34,7 @@ def check_api_turn(authority, ref, payload):
raise RuntimeStoreError('runtime_draining')
if 'api_turn_v1' in payload:
data = payload['api_turn_v1']
- if (set(data) - {'history', 'settings', 'turn_author'}
+ if (set(data) - {'history', 'settings', 'turn_author', 'media'}
or not {'history', 'settings'} <= set(data)
or (data['history'] is not None and not isinstance(data['history'], list))):
raise RuntimeStoreError('invalid_params')
@@ -101,6 +101,9 @@ def admit_api_turn(adapter, **kwargs):
settings['route'] = {k: v for k, v in route.items() if k != 'api_key'}
payload = json.loads(_json({'text': kwargs['user_message'], 'api_turn_v1': {
'history': None if kwargs.get('history_from_session') else kwargs['conversation_history'], 'settings': settings}}))
+ if isinstance(kwargs['user_message'], list):
+ from gateway.session_api_media import commit_api_images
+ payload['api_turn_v1']['media'] = commit_api_images(kwargs['user_message'])
if kwargs.get('turn_author') is not None:
from agent.turn_author import parse_turn_author
author = parse_turn_author(kwargs['turn_author'])
@@ -187,6 +190,29 @@ async def observe_api_turn(admitted, **kwargs):
return saved['result'], saved['usage']
+_CONTROL_EVENTS = frozenset({'approval.request', 'approval.settled', 'clarify.request', 'clarify.settled'})
+
+
+@contextmanager
+def observe_api_controls(admitted, sink):
+ """Project the same approval/clarify prompts WS viewers receive to ``sink(type, payload)``
+ for the admission's lifetime; ``sink`` runs on the publishing thread under the stream lock."""
+ authority, ref, row = admitted
+ events = authority.sessions[ref.session_id].event_stream
+
+ def observer(frame):
+ params = frame['params']
+ if params.get('admission_id') == row['admission_id'] and params.get('type') in _CONTROL_EVENTS:
+ sink(params['type'], params.get('payload') or {})
+ with events.lock:
+ events.observers.add(observer)
+ try:
+ yield
+ finally:
+ with events.lock:
+ events.observers.discard(observer)
+
+
def prepare_api_execution(authority, ref, payload):
adapter = check_api_turn(authority, ref, payload)
data = payload.get('api_turn_v1')
@@ -198,27 +224,47 @@ def prepare_api_execution(authority, ref, payload):
'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
(_SETTINGS_PREFIX + ref.session_id, _json(settings)))
authority.db._execute_write(write)
+ content = payload['text']
+ if data and isinstance(content, list):
+ from gateway.session_api_media import restore_api_images
+ content = restore_api_images(content, data.get('media') or [])
return {'adapter': adapter, 'settings': settings, 'history': data['history'] if data else None,
- 'content': payload['text'], 'turn_author': data.get('turn_author') if data else None}
+ 'content': content, 'turn_author': data.get('turn_author') if data else None}
-def publish_api_event(authority, session_id, event_type, payload):
+def _api_observers(authority, session_id):
execution = authority.sessions[session_id].event_stream.execution
admission_id = execution.get('admission_id') if execution else None
- observers = getattr(authority, 'api_observers', {}).get(admission_id, ())
- for observer in tuple(observers):
- if event_type == 'message.delta':
- callback = observer.get('stream_delta_callback')
- if callback:
- callback(payload['text'])
- elif event_type == 'tool.start':
- callback = observer.get('tool_start_callback')
- if callback:
- callback(payload['tool_call_id'], payload['tool_name'], {})
- elif event_type == 'tool.complete':
- callback = observer.get('tool_complete_callback')
- if callback:
- callback(payload['tool_call_id'], payload['tool_name'], {}, {})
+ return tuple(getattr(authority, 'api_observers', {}).get(admission_id, ()))
+
+
+def publish_api_event(authority, session_id, event_type, payload):
+ if event_type != 'message.delta':
+ return
+ for observer in _api_observers(authority, session_id):
+ callback = observer.get('stream_delta_callback')
+ if callback:
+ callback(payload['text'])
+
+
+def publish_api_tool_event(authority, session_id, generation, event_type, call_id, tool_name, args, result=None):
+ """Real tool arguments/results for the admission's API observers (Responses streaming,
+ runs SSE); never part of the shared viewer event stream."""
+ live = authority.sessions[session_id]
+ with live.event_stream.lock:
+ try:
+ authority.check_approval_generation(session_id, generation)
+ except RuntimeStoreError:
+ return
+ for observer in _api_observers(authority, session_id):
+ if event_type == 'tool.start':
+ callback = observer.get('tool_start_callback')
+ if callback:
+ callback(call_id, tool_name, args or {})
+ elif event_type == 'tool.complete':
+ callback = observer.get('tool_complete_callback')
+ if callback:
+ callback(call_id, tool_name, args or {}, result)
def prepare_api_runtime(model, runtime_kwargs):
diff --git a/gateway/session_events.py b/gateway/session_events.py
index 8d28503fa1d..216ddd950a2 100644
--- a/gateway/session_events.py
+++ b/gateway/session_events.py
@@ -17,6 +17,9 @@ class SessionEvents:
self.epoch = uuid.uuid4().hex
self.sequence = 0
self.execution = {}
+ # Synchronous same-thread recipients (API run projections): unlike fanout peers they
+ # cannot lose a frame to a detach that races the writer thread.
+ self.observers = set()
def watermark(self):
with self.lock:
@@ -43,6 +46,8 @@ class SessionEvents:
frame['params']['session_id'] = session_id
self.sequence = frame['params']['seq']
self.fanout.write(frame)
+ for observer in tuple(self.observers):
+ observer(frame)
def since(self, epoch, sequence):
with self.lock:
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.py
index 82b39e9fae6..b8a58bd92b4 100644
--- a/gateway/session_ingress.py
+++ b/gateway/session_ingress.py
@@ -60,21 +60,33 @@ async def execute_admission(authority, ref, row):
from gateway.session_api_turn import api_execution, prepare_api_execution
from gateway.session_results import execution_result
is_api = live.source.platform == Platform.API_SERVER
- prepared = prepare_api_execution(authority, ref, row['payload']) if is_api else None
- if is_api:
- if isinstance(event.text, list):
- event.text = '\n'.join(part['text'] for part in event.text if part.get('type') == 'text')
- event.allow_gateway_control = False
- event.internal = True # trust comes from the private binding and preclaim, never client JSON
author_token = admission_author.set(event.metadata.get('turn_author'))
- api_token = api_execution.set(prepared)
+ api_token = api_execution.set(None)
captured = {}
result_token = execution_result.set(captured)
token = executing_admission.set(True)
try:
with scope:
+ if is_api:
+ # Committed media resolves under the owning profile's home, like admission did.
+ prepared = prepare_api_execution(authority, ref, row['payload'])
+ api_execution.set(prepared)
+ if isinstance(event.text, list):
+ # The durable transcript keeps the committed media references (the same
+ # ``[Image attached ...]`` hints native transports persist), not only the caption.
+ event.text = '\n'.join(part['text'] for part in prepared['content'] if part.get('type') == 'text')
+ event.allow_gateway_control = False
+ event.internal = True # trust comes from the private binding and preclaim, never client JSON
response = await authority.runner._handle_message(event)
- result = captured.get('result') or {'final_response': response or '', 'messages': []}
+ result = captured.get('result')
+ if result is None:
+ # No TurnRunner result means the handler answered without executing the turn
+ # (agent initialization failure, refusal notice). An API caller asked for work,
+ # so its receipt is a failure, never a completed turn with an apology as output.
+ result = {'final_response': response or '', 'messages': []}
+ if is_api:
+ result = {'final_response': '', 'messages': [], 'failed': True, 'completed': False,
+ 'error': response or 'The admitted turn failed.'}
# The drain commits this under the stream lock so no viewer reads `terminal`
# before the completion event exists in the replay ring.
authority.pending_results[row['admission_id']] = {'result': result, 'usage': captured.get('usage', {})}
diff --git a/tests/gateway/test_api_canonical_projection.py b/tests/gateway/test_api_canonical_projection.py
new file mode 100644
index 00000000000..9953584c234
--- /dev/null
+++ b/tests/gateway/test_api_canonical_projection.py
@@ -0,0 +1,168 @@
+"""Canonical API admissions project the real turn: media, tool payloads, controls, outcomes."""
+import asyncio
+import base64
+from types import SimpleNamespace
+
+import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+from gateway.platforms import api_server as _api_server
+from gateway.platforms.api_server_runs import _RunLaunch, _execute_run
+from gateway.session_api_turn import admit_api_turn
+from gateway.session_ingress import execute_admission
+from tests.gateway.test_api_cutover_contract import api # noqa: F401
+from tests.gateway.test_api_source_binding import owner # noqa: F401
+
+PNG = base64.b64encode(b'\x89PNG\r\n\x1a\n' + b'\x00' * 64).decode()
+
+
+def _turn_runner(owner, ref):
+ from gateway.run_turn_runner import TurnRunner
+ turn = object.__new__(TurnRunner)
+ turn._ctx = SimpleNamespace(_native_slack_task_cards=False, _voice_ack_guild=[None])
+ turn._approval_owner = (owner, ref.session_id, owner.db.get_session(ref.session_id)['runtime_generation'])
+ return turn
+
+
+def _launch(api, admitted, run_id='run_test'):
+ queue = asyncio.Queue()
+ api._run_streams[run_id] = queue
+ api._run_statuses[run_id] = {}
+ launch = _RunLaunch(api, run_id, queue, admitted[1].session_id, None, False, 'hello', [], False,
+ agent_kwargs={}, request_profile=None, browser_control_principal=None,
+ browser_control_transport_family=None, admission=admitted)
+ return launch, queue
+
+
+def _events(queue):
+ events = []
+ while not queue.empty():
+ item = queue.get_nowait()
+ if item is not None:
+ events.append(item)
+ return events
+
+
+async def test_api_images_are_committed_media_in_canonical_history(api, owner):
+ content = [{'type': 'text', 'text': 'what is this'},
+ {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,' + PNG}}]
+ args = dict(session_id='vision', request_id='img-1', user_message=content, conversation_history=[])
+ _, ref, row = admit_api_turn(api, **args)
+ media = row['payload']['api_turn_v1']['media']
+ assert len(media) == 1 and media[0]['size'] == 72
+ # An exact retry commits the same bytes to the same reference: no admission conflict.
+ assert admit_api_turn(api, **args)[2]['admission_id'] == row['admission_id']
+ seen = {}
+
+ async def handle(event):
+ from gateway.session_api_turn import api_execution
+ from gateway.session_results import execution_result
+ seen['text'] = event.text
+ seen['content'] = api_execution.get()['content']
+ execution_result.get()['result'] = {'final_response': 'ok'}
+ return 'ok'
+ owner.runner._handle_message = handle
+ await execute_admission(owner, ref, row)
+ committed = media[0]['path']
+ assert f'[Image attached at: {committed}]' in seen['text']
+ assert seen['content'][0]['text'].endswith(f'[Image attached at: {committed}]')
+ assert seen['content'][1]['image_url']['url'].startswith('data:image/png;base64,')
+
+
+async def test_initialization_failure_is_a_failed_receipt_not_completed(api, owner):
+ _, ref, row = admit_api_turn(api, session_id='init', user_message='hello', conversation_history=[])
+
+ async def handle(event):
+ return 'Sorry, I encountered an unexpected error.' # handler apology, no TurnRunner result
+ owner.runner._handle_message = handle
+ await execute_admission(owner, ref, row)
+ result = owner.pending_results[row['admission_id']]['result']
+ assert result['failed'] is True and result['completed'] is False
+ assert result['final_response'] == '' and 'unexpected error' in result['error']
+
+
+async def test_run_sse_carries_controls_tool_payloads_and_authoritative_cancellation(api, owner):
+ from tools import clarify_gateway
+ admitted = admit_api_turn(api, session_id='sse', user_message='hello', conversation_history=[])
+ _, ref, row = admitted
+ launch, queue = _launch(api, admitted)
+ tool_payloads = []
+
+ async def handle(event):
+ from gateway.session_results import execution_result
+ turn = _turn_runner(owner, ref)
+ entry = clarify_gateway.register('clarify-1', 'api', 'Which one?', ['a', 'b'])
+ owner.register_clarify(ref.session_id, turn._approval_owner[2], entry)
+ turn.combined_tool_start_callback('call-1', 'read_file', {'path': '/tmp/x'})
+ turn.combined_tool_complete_callback('call-1', 'read_file', {'path': '/tmp/x'}, {'content': 'body'})
+ entry.event.set()
+ # Interrupted over another transport (WS /stop): this adapter never marked the run stopping.
+ execution_result.get()['result'] = {'final_response': 'partial', 'interrupted': True}
+ return 'partial'
+ owner.runner._handle_message = handle
+ api._make_run_event_callback = lambda run_id, loop: _wrap(api, run_id, loop, tool_payloads)
+ await _execute_run(api, launch, _api_server=_api_server)
+ await asyncio.sleep(0) # call_soon_threadsafe projections land on the loop
+ events = _events(queue)
+ names = [e['event'] for e in events]
+ clarify = next((e for e in events if e['event'] == 'clarify.request'), None)
+ assert clarify is not None, events
+ assert clarify['prompt_id'] == 'clarify-1' and clarify['choices'] == ['a', 'b']
+ assert [e['tool_call_id'] for e in events if e['event'].startswith('tool.')] == ['call-1', 'call-1']
+ assert tool_payloads == [('read_file', {'path': '/tmp/x'}), ('read_file', {'path': '/tmp/x'})]
+ assert 'run_test' not in api._stopping_run_ids
+ assert 'run.cancelled' in names and 'run.completed' not in names
+
+
+def _wrap(api, run_id, loop, sink):
+ from gateway.platforms.api_server_runs import _make_run_event_callback
+ inner = _make_run_event_callback(api, run_id, loop, _api_server=_api_server)
+
+ def callback(event_type, tool_name=None, preview=None, args=None, **kwargs):
+ sink.append((tool_name, args))
+ return inner(event_type, tool_name, preview, args, **kwargs)
+ return callback
+
+
+async def test_responses_streaming_projects_real_tool_arguments_and_results(api, owner):
+ from gateway.session_api_turn import observe_api_turn
+ admitted = admit_api_turn(api, session_id='stream', user_message='hello', conversation_history=[])
+ _, ref, _ = admitted
+ seen = []
+
+ async def handle(event):
+ from gateway.session_results import execution_result
+ turn = _turn_runner(owner, ref)
+ turn.combined_tool_complete_callback('call-9', 'read_file', {'path': 'a.txt'}, 'file body')
+ execution_result.get()['result'] = {'final_response': 'ok'}
+ return 'ok'
+ owner.runner._handle_message = handle
+ await observe_api_turn(admitted, tool_complete_callback=lambda *a: seen.append(a))
+ assert seen == [('call-9', 'read_file', {'path': 'a.txt'}, 'file body')]
+
+
+async def test_exact_responses_retry_replays_before_conversation_expansion(api, owner):
+ calls = []
+
+ async def handle(event):
+ from gateway.session_results import execution_result
+ calls.append(event.text)
+ execution_result.get()['result'] = {'final_response': 'reply', 'messages': []}
+ return 'reply'
+ owner.runner._handle_message = handle
+ app = web.Application()
+ app.router.add_post('/v1/responses', api._handle_responses)
+ async with TestClient(TestServer(app)) as client:
+ statuses = []
+ for _ in range(2):
+ resp = await client.post('/v1/responses', json={'input': 'hello', 'conversation': 'named'},
+ headers={'Idempotency-Key': 'retry-1'})
+ statuses.append((resp.status, (await resp.json()).get('status')))
+ assert statuses == [(200, 'completed'), (200, 'completed')]
+ assert calls == ['hello']
diff --git a/tests/gateway/test_api_cutover_contract.py b/tests/gateway/test_api_cutover_contract.py
index 74337fcfcaa..a57c7c2d9d1 100644
--- a/tests/gateway/test_api_cutover_contract.py
+++ b/tests/gateway/test_api_cutover_contract.py
@@ -54,7 +54,10 @@ async def test_structured_content_bypasses_text_parser_without_losing_parts(api,
turn = object.__new__(TurnRunner)
turn._ctx = SimpleNamespace(message=event.text, session_key=owner.sessions[ref.session_id].route)
turn._runner = SimpleNamespace(_consume_pending_native_image_paths=lambda key: [])
- assert turn._native_image_run_message() == content
+ # The transient image survives; the text part now carries the durable reference hint.
+ message = turn._native_image_run_message()
+ assert message[1] == content[1]
+ assert message[0]['text'] == '/literal prompt\n\n[Image attached: https://example.com/image.png]'
assert api_execution.get()['history'] == []
execution_result.get()['result'] = {'final_response': 'ok'}
return 'ok'