Skip to content

The agent that grows with you

fix(codex): preserve calls across rotating stream item IDs

DragonLi-Mi5e24de476dcb
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py
index 00225296506..cce81119d24 100644
--- a/agent/codex_runtime.py
+++ b/agent/codex_runtime.py
@@ -927,9 +927,21 @@ class _CodexResponseAssembler:
if isinstance(refusal_text, str) and refusal_text:
self.text_deltas.append(refusal_text)
+ def _pending_function_key(self, item_id: str, output_index: Any) -> str | None:
+ if item_id in self.pending_function_calls:
+ return item_id
+ # Copilot rotates opaque item IDs between SSE events. The response-local
+ # output_index still identifies the call, including index zero.
+ if output_index is not None:
+ return next((key for key, pending in self.pending_function_calls.items()
+ if pending["output_index"] == output_index), None)
+ return None
+
def _on_function_call(self, event: Any, event_type: str) -> None:
self.has_tool_calls = True
- pending = self.pending_function_calls.get(str(_event_field(event, "item_id", "")))
+ key = self._pending_function_key(str(_event_field(event, "item_id", "")),
+ _event_field(event, "output_index"))
+ pending = self.pending_function_calls.get(key)
if pending is None:
return # the item itself lands on output_item.done
if "delta" in event_type:
@@ -959,13 +971,16 @@ class _CodexResponseAssembler:
# Reuse the announced position when known (fresh tail sequence for unannounced items); the .done
# event's own output_index wins over the announced one.
done_id = str(_event_field(done_item, "id", ""))
- announced_sequence, announced_index = self.announced_output_order.get(done_id, (None, None))
+ pending_key = None
+ if "function_call" in str(_event_field(done_item, "type", "")):
+ pending_key = self._pending_function_key(done_id, _event_field(event, "output_index"))
+ announced_sequence, announced_index = self.announced_output_order.get(pending_key or done_id, (None, None))
if announced_sequence is None:
announced_sequence, self.next_output_sequence = self.next_output_sequence, self.next_output_sequence + 1
self.output_indexes.append(_event_field(event, "output_index", announced_index))
self.output_sequences.append(announced_sequence)
# Confirmed by the authoritative done event; never settle it twice.
- self.pending_function_calls.pop(done_id, None)
+ self.pending_function_calls.pop(pending_key or done_id, None)
if _message_phase(done_item) == "commentary" and self.on_commentary_message is not None:
commentary_text = "".join(self.commentary_text_deltas).strip() or _output_text_of(done_item)
if commentary_text:
@@ -1030,15 +1045,13 @@ class _CodexResponseAssembler:
return [entry[2] for entry in indexed]
def result(self) -> SimpleNamespace:
+ # Successful completion orders all output, even when no calls remain pending.
+ # Done items stay authoritative; only successful streams settle missing done events.
+ output: list[Any] = self._settled_output() if self.saw_response_completed else list(self.output_items)
# With only plain text deltas (no tool calls), synthesize one message item.
- output: list[Any] = list(self.output_items)
if not output and self.text_deltas and not self.has_tool_calls:
content = [SimpleNamespace(type="output_text", text="".join(self.text_deltas))]
output = [SimpleNamespace(type="message", role="assistant", status="completed", content=content)]
- # Done items stay authoritative; settlement only fills the gap left by backends that omit
- # per-item done events on a successful completion.
- if self.pending_function_calls and self.saw_response_completed:
- output = self._settled_output()
# No terminal frame AND no usable content = truncated / rejected stream.
if not self.saw_terminal and not output:
raise RuntimeError("Codex Responses stream did not emit a terminal response")
diff --git a/tests/agent/test_codex_stream_rotating_item_ids.py b/tests/agent/test_codex_stream_rotating_item_ids.py
new file mode 100644
index 00000000000..fb9cdc2d304
--- /dev/null
+++ b/tests/agent/test_codex_stream_rotating_item_ids.py
@@ -0,0 +1,60 @@
+"""Copilot rotates opaque item IDs within a call; output_index remains stable.
+
+Reproduced with a live Responses request: one announced call plus its done
+item became two executable calls, with the stale announcement carrying {}.
+"""
+import json
+
+import pytest
+
+from agent.codex_runtime import _consume_codex_event_stream
+
+
[email protected](('completion', 'done_order'), [
+ ('item_done', (0, 1)),
+ pytest.param('item_done', (1, 0), id='item_done_reversed'),
+ ('arguments_done', (0, 1)),
+ ('deltas', (0, 1)),
+])
+def test_rotating_item_ids_preserve_distinct_calls_and_arguments(completion, done_order):
+ events = []
+ for index in range(2):
+ events.append({
+ 'type': 'response.output_item.added', 'output_index': index,
+ 'item': {'type': 'function_call', 'id': f'announced_{index}',
+ 'call_id': f'call_{index}', 'name': 'diagnostic_echo', 'arguments': ''},
+ })
+ # Interleave argument chunks so associating by "latest call" cannot pass.
+ for chunk in range(2):
+ for index in range(2):
+ events.append({
+ 'type': 'response.function_call_arguments.delta', 'output_index': index,
+ 'item_id': f'delta_{index}_{chunk}',
+ 'delta': ['{"text":', f'"probe-{index}"}}'][chunk],
+ })
+ if completion != 'deltas':
+ for index in range(2):
+ events.append({
+ 'type': 'response.function_call_arguments.done', 'output_index': index,
+ 'item_id': f'arguments_done_{index}',
+ 'arguments': json.dumps({'text': f'confirmed-{index}'}),
+ })
+ if completion == 'item_done':
+ # Completion order must not reorder the announced calls, even when
+ # rotated-ID done events confirm every call and leave none pending.
+ for index in done_order:
+ events.append({
+ 'type': 'response.output_item.done', 'output_index': index,
+ 'item': {'type': 'function_call', 'id': f'completed_{index}',
+ 'call_id': f'call_{index}', 'name': 'diagnostic_echo',
+ 'arguments': json.dumps({'text': f'authoritative-{index}'})},
+ })
+ events.append({'type': 'response.completed', 'response': {'status': 'completed'}})
+ response = _consume_codex_event_stream(events, model='diagnostic')
+ def field(item, name):
+ return item[name] if isinstance(item, dict) else getattr(item, name)
+ expected = {'item_done': 'authoritative', 'arguments_done': 'confirmed', 'deltas': 'probe'}[completion]
+ assert [(field(item, 'call_id'), json.loads(field(item, 'arguments')))
+ for item in response.output] == [
+ (f'call_{i}', {'text': f'{expected}-{i}'}) for i in range(2)
+ ]