Repository navigation
Expand file tree
/
Copy pathstdio.py
More file actions
291 lines (247 loc) · 9.91 KB
/
Copy pathstdio.py
File metadata and controls
291 lines (247 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
from __future__ import annotations
import asyncio
import asyncio.subprocess as aio_subprocess
import contextlib
import logging
import os
import platform
import sys
from asyncio import transports as aio_transports
from asyncio.streams import FlowControlMixin
from collections.abc import AsyncIterator, Callable, Mapping
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, BinaryIO, Literal, cast
from .agent.connection import AgentSideConnection
from .client.connection import ClientSideConnection
from .connection import Connection, MethodHandler, StreamObserver
from .interfaces import Agent, Client
from .transports import spawn_stdio_transport
_logger = logging.getLogger(__name__)
__all__ = [
"spawn_agent_process",
"spawn_client_process",
"spawn_stdio_connection",
"stdio_streams",
]
class _WritePipeProtocol(FlowControlMixin):
def __init__(self) -> None:
loop = asyncio.get_running_loop()
super().__init__(loop=loop)
self._closed: asyncio.Future[None] = loop.create_future()
# Callers may handle a failed drain without also awaiting wait_closed.
self._closed.add_done_callback(lambda future: None if future.cancelled() else future.exception())
def connection_lost(self, exc: Exception | None) -> None:
super().connection_lost(exc)
if not self._closed.done():
if exc is None:
self._closed.set_result(None)
else:
self._closed.set_exception(exc)
def _get_close_waiter(self, stream: asyncio.StreamWriter) -> asyncio.Future[None]:
return self._closed
def _start_stdin_feeder(loop: asyncio.AbstractEventLoop, reader: asyncio.StreamReader) -> None:
# Feed stdin from a background thread line-by-line
def blocking_read() -> None:
try:
while True:
data = sys.stdin.buffer.readline()
if not data:
break
loop.call_soon_threadsafe(reader.feed_data, data)
finally:
loop.call_soon_threadsafe(reader.feed_eof)
import threading
threading.Thread(target=blocking_read, daemon=True).start()
class _StdoutTransport(asyncio.BaseTransport):
def __init__(self, protocol: _WritePipeProtocol) -> None:
self._is_closing = False
self._protocol = protocol
def write(self, data: bytes) -> None: # type: ignore[override]
if self._is_closing:
return
try:
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
except Exception as exc:
_logger.exception("Error writing to stdout")
self._is_closing = True
self._protocol.connection_lost(exc)
def can_write_eof(self) -> bool: # type: ignore[override]
return False
def is_closing(self) -> bool: # type: ignore[override]
return self._is_closing
def close(self) -> None: # type: ignore[override]
if self._is_closing:
return
self._is_closing = True
with contextlib.suppress(Exception):
sys.stdout.flush()
self._protocol.connection_lost(None)
def abort(self) -> None: # type: ignore[override]
self.close()
def get_extra_info(self, name: str, default=None): # type: ignore[override]
return default
async def _windows_stdio_streams(
loop: asyncio.AbstractEventLoop,
limit: int | None = None,
) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
reader = asyncio.StreamReader(limit=limit) if limit is not None else asyncio.StreamReader()
_ = asyncio.StreamReaderProtocol(reader)
_start_stdin_feeder(loop, reader)
write_protocol = _WritePipeProtocol()
transport = _StdoutTransport(write_protocol)
writer = asyncio.StreamWriter(cast(aio_transports.WriteTransport, transport), write_protocol, None, loop)
return reader, writer
def _duplicate_stdio_file(fd: int, mode: Literal["rb", "wb"]) -> BinaryIO:
duplicate = os.dup(fd)
try:
return os.fdopen(duplicate, mode, buffering=0)
except BaseException:
os.close(duplicate)
raise
async def _posix_stdio_streams(
loop: asyncio.AbstractEventLoop,
limit: int | None = None,
) -> tuple[asyncio.StreamReader, asyncio.StreamWriter, aio_transports.ReadTransport]:
reader = asyncio.StreamReader(limit=limit) if limit is not None else asyncio.StreamReader()
reader_protocol = asyncio.StreamReaderProtocol(reader)
stdin_file = _duplicate_stdio_file(sys.stdin.fileno(), "rb")
try:
read_transport, _ = await loop.connect_read_pipe(lambda: reader_protocol, stdin_file)
except BaseException:
stdin_file.close()
raise
try:
write_protocol = _WritePipeProtocol()
with contextlib.suppress(OSError):
sys.stdout.flush()
stdout_file = _duplicate_stdio_file(sys.stdout.fileno(), "wb")
try:
transport, _ = await loop.connect_write_pipe(lambda: write_protocol, stdout_file)
except BaseException:
stdout_file.close()
raise
except BaseException:
read_transport.close()
raise
writer = asyncio.StreamWriter(transport, write_protocol, None, loop)
return reader, writer, read_transport
async def _open_stdio_streams(
limit: int | None,
) -> tuple[asyncio.StreamReader, asyncio.StreamWriter, aio_transports.ReadTransport | None]:
loop = asyncio.get_running_loop()
if platform.system() == "Windows":
reader, writer = await _windows_stdio_streams(loop, limit=limit)
return reader, writer, None
return await _posix_stdio_streams(loop, limit=limit)
async def stdio_streams(limit: int | None = None) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""Create stdio asyncio streams; on Windows use a thread feeder + custom stdout transport.
The writer supports ``close()`` followed by ``await wait_closed()``.
``drain()`` reports a disconnected output pipe, including while waiting for
buffered output to be consumed.
On POSIX, closing the writer closes its duplicate of stdout. The original
standard streams remain open and share the duplicates' blocking modes.
Args:
limit: Optional buffer limit for the stdin reader.
"""
reader, writer, _ = await _open_stdio_streams(limit)
return reader, writer
@asynccontextmanager
async def _owned_stdio_streams(
limit: int,
*,
close_timeout: float = 2.0,
) -> AsyncIterator[tuple[asyncio.StreamReader, asyncio.StreamWriter]]:
# Duplicated POSIX descriptors share the original handles' blocking modes.
blocking_modes = (
{fd: os.get_blocking(fd) for fd in (sys.stdin.fileno(), sys.stdout.fileno())}
if platform.system() != "Windows"
else {}
)
try:
reader, writer, read_transport = await _open_stdio_streams(limit)
try:
yield reader, writer
finally:
if read_transport is not None:
read_transport.close()
writer.close()
try:
await asyncio.wait_for(asyncio.shield(writer.wait_closed()), timeout=close_timeout)
except asyncio.TimeoutError:
writer.transport.abort()
with contextlib.suppress(ConnectionError):
await asyncio.shield(writer.wait_closed())
except asyncio.CancelledError:
writer.transport.abort()
raise
except ConnectionError:
pass
finally:
for fd, blocking in blocking_modes.items():
with contextlib.suppress(OSError):
os.set_blocking(fd, blocking)
@asynccontextmanager
async def spawn_stdio_connection(
handler: MethodHandler,
command: str,
*args: str,
env: Mapping[str, str] | None = None,
cwd: str | Path | None = None,
observers: list[StreamObserver] | None = None,
**transport_kwargs: Any,
) -> AsyncIterator[tuple[Connection, aio_subprocess.Process]]:
"""Spawn a subprocess and bind its stdio to a low-level Connection."""
async with spawn_stdio_transport(command, *args, env=env, cwd=cwd, **transport_kwargs) as (reader, writer, process):
conn = Connection(handler, writer, reader, observers=observers)
try:
yield conn, process
finally:
await conn.close()
@asynccontextmanager
async def spawn_agent_process(
to_client: Callable[[Agent], Client] | Client,
command: str,
*args: str,
env: Mapping[str, str] | None = None,
cwd: str | Path | None = None,
transport_kwargs: Mapping[str, Any] | None = None,
**connection_kwargs: Any,
) -> AsyncIterator[tuple[ClientSideConnection, aio_subprocess.Process]]:
"""Spawn an ACP agent subprocess and return a ClientSideConnection to it."""
async with spawn_stdio_transport(
command,
*args,
env=env,
cwd=cwd,
**(dict(transport_kwargs) if transport_kwargs else {}),
) as (reader, writer, process):
conn = ClientSideConnection(to_client, writer, reader, **connection_kwargs)
try:
yield conn, process
finally:
await conn.close()
@asynccontextmanager
async def spawn_client_process(
to_agent: Callable[[AgentSideConnection], Agent] | Agent,
command: str,
*args: str,
env: Mapping[str, str] | None = None,
cwd: str | Path | None = None,
transport_kwargs: Mapping[str, Any] | None = None,
**connection_kwargs: Any,
) -> AsyncIterator[tuple[AgentSideConnection, aio_subprocess.Process]]:
"""Spawn an ACP client subprocess and return an AgentSideConnection to it."""
async with spawn_stdio_transport(
command,
*args,
env=env,
cwd=cwd,
**(dict(transport_kwargs) if transport_kwargs else {}),
) as (reader, writer, process):
conn = AgentSideConnection(to_agent, writer, reader, **connection_kwargs)
try:
yield conn, process
finally:
await conn.close()