The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(codex): share response socket walk and simplify post-terminal drain
kshitijk4poor06be0643c932
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 28437478bc1..72e714a0f62 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -3411,6 +3411,21 @@ def _socket_from_candidate(candidate: Any):return sock if sock is not None else _socket_from_stream(candidate)+def _socket_from_response(response: Any):+ """Raw socket behind an httpx response's network stream (``extensions["network_stream"]``+ first, then ``response.stream``), or None. Callers own their error handling."""+ exts = getattr(response, "extensions", None) or {}+ direct = exts.get("network_stream") if isinstance(exts, dict) else None+ for start in (direct, getattr(response, "stream", None)):+ if start is None:+ continue+ for candidate in _connection_candidates(start):+ sock = _socket_from_candidate(candidate)+ if sock is not None:+ return sock+ return None++def _socket_from_stream(stream: Any):"""Raw socket behind an httpcore network stream (several backends), or None."""sock = getattr(stream, "_sock", None)diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 30b30f8dd22..db9ea4fa367 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -3909,22 +3909,13 @@ class _StreamingCall(StreamingWaitMonitor):if response is None or response is not self._attempt_stream_response:returntry:- from agent.agent_runtime_helpers import (- _connection_candidates, _shutdown_socket, _socket_from_candidate,- )- exts = getattr(response, "extensions", None) or {}- direct = exts.get("network_stream") if isinstance(exts, dict) else None- for start in (direct, getattr(response, "stream", None)):- if start is None:- continue- for candidate in _connection_candidates(start):- sock = _socket_from_candidate(candidate)- if sock is None:- continue- _shutdown_socket(sock)- logger.info("Shut down the stale stream's socket to unblock the reader "- "(attempt superseded; model=%s).", self.api_kwargs.get("model", "unknown"))- return+ from agent.agent_runtime_helpers import _shutdown_socket, _socket_from_response+ sock = _socket_from_response(response)+ if sock is not None:+ _shutdown_socket(sock)+ logger.info("Shut down the stale stream's socket to unblock the reader "+ "(attempt superseded; model=%s).", self.api_kwargs.get("model", "unknown"))+ returnlogger.debug("Stale stream socket shutdown found no socket; pool sweep is the only abort")except Exception:logger.debug("Stale stream socket shutdown failed", exc_info=True)diff --git a/agent/codex_runtime.py b/agent/codex_runtime.pyindex 9514a1e5258..6b2ecb60998 100644--- a/agent/codex_runtime.py+++ b/agent/codex_runtime.py@@ -1215,27 +1215,19 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltalogger.debug("Codex stream opened (attempt=%s/%s, model=%s)",attempt + 1, max_stream_retries + 1, model)- def _post_terminal_socket(*streams: Any):- """Return the raw socket for the current Responses stream, if it can be interrupted safely."""- from agent.agent_runtime_helpers import _connection_candidates, _socket_from_candidate+ def _post_terminal_socket(raw_stream: Any):+ """Return the raw socket for the provider Responses stream, if it can be interrupted safely.+ Only the raw SDK stream carries ``.response``; the ManagedLlmStream wrapper does not."""+ from agent.agent_runtime_helpers import _socket_from_response++ response = getattr(raw_stream, "response", None)+ if response is None:+ return Nonetry:- for stream in streams:- response = getattr(stream, "response", None)- if response is None:- continue- extensions = getattr(response, "extensions", None) or {}- network_stream = extensions.get("network_stream") if isinstance(extensions, dict) else None- for root in (network_stream, getattr(response, "stream", None)):- if root is None:- continue- for candidate in _connection_candidates(root):- sock = _socket_from_candidate(candidate)- if sock is not None:- return sock+ return _socket_from_response(response)except Exception:return None- return Nonedef _drain_for_finalizer(event_stream: Any) -> None:# The final response is already assembled. Keep the finalizer drain on THIS owner thread:@@ -1246,7 +1238,7 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltaif budget <= 0:returnraw_stream = writer_token.get("raw_stream")- sock = _post_terminal_socket(raw_stream, event_stream)+ sock = _post_terminal_socket(raw_stream)if sock is None:# Without a shutdown-capable socket a synchronous drain could become unbounded. The drain# is only for Relay's finalizer, so skip it and let the owner-thread finally close below.@@ -1268,19 +1260,6 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltawatchdog.daemon = Truetry:watchdog.start()- except BaseException as exc:- # If an interrupt lands inside start(), cancel first; if the timer thread already exists,- # join it before the owner can close the stream.- watchdog.cancel()- if watchdog.ident is not None:- with suppress(Exception):- watchdog.join()- if not isinstance(exc, Exception):- raise- logger.debug("Codex post-terminal watchdog failed to start; skipping finalizer drain", exc_info=True)- return-- try:for _ignored in event_stream:passexcept (*transport_errors, _APIConnectionError) as exc:@@ -1298,9 +1277,11 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltalogger.debug("Codex Responses stream finalization failed after a terminal response", exc_info=True)finally:# cancel() wins if the budget has not fired; join() also waits for an already-running shutdown- # callback, preserving shutdown-before-close ordering at the exact timeout boundary.+ # callback, preserving shutdown-before-close ordering at the exact timeout boundary. A failed+ # or interrupted start() leaves no thread (ident None) to join.watchdog.cancel()- watchdog.join()+ if watchdog.ident is not None:+ watchdog.join()if timed_out.is_set():logger.warning(@@ -1402,11 +1383,12 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltasum(len(p) for p in agent._codex_streamed_text_parts), agent._client_log_context())return finalfinally:- managed_owns_close = callable(getattr(event_stream, "close", None))- _close_event_stream(event_stream)- raw_stream = writer_token.get("raw_stream")- if not managed_owns_close and raw_stream is not None and raw_stream is not event_stream:- _close_event_stream(raw_stream)+ # relay_llm.stream is ManagedLlmStream, whose close() always owns the provider stream; only+ # when construction itself failed (event_stream None) may a raw stream be left to close here.+ if event_stream is None:+ _close_event_stream(writer_token.get("raw_stream"))+ else:+ _close_event_stream(event_stream)__all__ = [