The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/relay): hoist relay_tools guard closure; suppress/tuple-swap micro-collapses
Tekniumc6b813e9d6a1
diff --git a/agent/relay_llm.py b/agent/relay_llm.pyindex 9b0574b9c01..65d28e17b83 100644--- a/agent/relay_llm.py+++ b/agent/relay_llm.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import contextlibimport contextvarsimport inspectimport json@@ -407,12 +408,9 @@ class ManagedLlmStream(Iterator[Any]):def _prime_completed_response(self) -> None:"""Advance once while preserving a genuine first chunk."""- if self._closed or self._prefetched_chunks:- return- try:- self._prefetched_chunks.append(next(self))- except StopIteration:- pass+ if not self._closed and not self._prefetched_chunks:+ with contextlib.suppress(StopIteration):+ self._prefetched_chunks.append(next(self))def _recoverable_relay_failure(self, exc: BaseException) -> bool:"""Relay post-processing failed after the provider already succeeded."""@@ -484,8 +482,7 @@ class ManagedLlmStream(Iterator[Any]):def close(self) -> None:"""Close an explicitly abandoned stream and cancel its logical call."""self._close(logical_outcome="cancelled")- close_error = self._close_error- self._close_error = None+ close_error, self._close_error = self._close_error, Noneif close_error is not None:raise close_error@@ -547,8 +544,7 @@ class ManagedLlmStream(Iterator[Any]):self._release_runtime_lease()def _release_runtime_lease(self) -> None:- lease = self._runtime_lease- self._runtime_lease = None+ lease, self._runtime_lease = self._runtime_lease, Noneif lease is not None:lease.release()diff --git a/agent/relay_tools.py b/agent/relay_tools.pyindex 1c07f2ef56a..42f4e45bc78 100644--- a/agent/relay_tools.py+++ b/agent/relay_tools.py@@ -26,17 +26,16 @@ def execute(callback_error: BaseException | None = Nonecallback_context = contextvars.copy_context()+ def guarded(final_args: dict[str, Any]) -> Any:+ # Everything the tool transitively calls (incl. auxiliary LLM calls on worker+ # threads) must bypass managed Relay: the pipeline's Futures bind to THIS loop,+ # which is blocked until the tool returns.+ with relay_runtime.managed_callback_guard():+ return callback(final_args)+def invoke(next_args: Any) -> Any:nonlocal callback_error, observed_argsobserved_args = next_args if isinstance(next_args, dict) else args-- def guarded(final_args: dict[str, Any]) -> Any:- # Everything the tool transitively calls (incl. auxiliary LLM calls on worker- # threads) must bypass managed Relay: the pipeline's Futures bind to THIS loop,- # which is blocked until the tool returns.- with relay_runtime.managed_callback_guard():- return callback(final_args)-try:result = callback_context.copy().run(guarded, observed_args)except BaseException as exc:@@ -65,9 +64,7 @@ def execute(raiseif "value" in raw_result and _json_equal(managed, raw_result["json"]):return raw_result["value"], observed_args- if isinstance(managed, str):- return managed, observed_args- return json.dumps(_jsonable(managed), ensure_ascii=False), observed_args+ return (managed if isinstance(managed, str) else json.dumps(_jsonable(managed), ensure_ascii=False)), observed_argsdef _jsonable(value: Any) -> Any: