Skip to content

Commit c864d7d

Browse files
authored
feat: add receive_timeout parameter to Connection class (#84)
- Add optional receive_timeout parameter to Connection.__init__ - Implement timeout handling in _receive_loop using asyncio.wait_for - Raise RequestError.internal_error on timeout for graceful error handling This allows users to configure a timeout for receiving messages from agents, preventing indefinite hangs when an agent becomes unresponsive.
1 parent 589aff7 commit c864d7d

1 file changed

Lines changed: 5 additions & 1 deletion

File tree

src/acp/connection.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ def __init__(
7373
sender_factory: SenderFactory | None = None,
7474
observers: list[StreamObserver] | None = None,
7575
listening: bool = True,
76+
receive_timeout: float | None = None,
7677
) -> None:
7778
self._handler = handler
7879
self._writer = writer
@@ -103,6 +104,7 @@ def __init__(
103104
)
104105
self._dispatcher.start()
105106
self._observers: list[StreamObserver] = list(observers or [])
107+
self._receive_timeout = receive_timeout
106108

107109
async def close(self) -> None:
108110
"""Stop the receive loop and cancel any in-flight handler tasks."""
@@ -151,7 +153,7 @@ async def send_notification(self, method: str, params: JsonValue | None = None)
151153
async def _receive_loop(self) -> None:
152154
try:
153155
while True:
154-
line = await self._reader.readline()
156+
line = await asyncio.wait_for(self._reader.readline(), timeout=self._receive_timeout)
155157
if not line:
156158
break
157159
line = line.strip()
@@ -166,6 +168,8 @@ async def _receive_loop(self) -> None:
166168
await self._process_message(message)
167169
except asyncio.CancelledError:
168170
return
171+
except asyncio.TimeoutError:
172+
raise RequestError.internal_error({"details": "Agent timeout"}) from None
169173
self._disconnect()
170174

171175
async def _process_message(self, message: dict[str, Any]) -> None:

0 commit comments

Comments
 (0)