Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions src/acp/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from __future__ import annotations

import asyncio
from contextlib import nullcontext
from typing import Any

from .agent.connection import AgentSideConnection
Expand Down Expand Up @@ -58,22 +59,26 @@ async def run_agent(
**connection_kwargs: Additional keyword arguments to pass to the
:class:`AgentSideConnection` constructor.
"""
from .stdio import stdio_streams

if input_stream is None and output_stream is None:
output_stream, input_stream = await stdio_streams(limit=stdio_buffer_limit_bytes)
conn = AgentSideConnection(
agent,
input_stream,
output_stream,
listening=False,
use_unstable_protocol=use_unstable_protocol,
**connection_kwargs,
from .stdio import _owned_stdio_streams

streams = (
_owned_stdio_streams(stdio_buffer_limit_bytes)
if input_stream is None and output_stream is None
else nullcontext((output_stream, input_stream))
)
try:
await conn.listen()
finally:
await asyncio.shield(conn.close())
async with streams as (reader, writer):
conn = AgentSideConnection(
agent,
writer,
reader,
listening=False,
use_unstable_protocol=use_unstable_protocol,
**connection_kwargs,
)
try:
await conn.listen()
finally:
await asyncio.shield(conn.close())


def connect_to_agent(
Expand Down
29 changes: 17 additions & 12 deletions src/acp/experimental/negotiation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
from collections.abc import Callable
from contextlib import nullcontext
from typing import Any, cast

from pydantic import BaseModel
Expand Down Expand Up @@ -220,17 +221,21 @@ async def run(
stdio_buffer_limit_bytes: int = 50 * 1024 * 1024,
**connection_kwargs: Any,
) -> None:
if input_stream is None and output_stream is None:
from acp.stdio import stdio_streams
from acp.stdio import _owned_stdio_streams

output_stream, input_stream = await stdio_streams(limit=stdio_buffer_limit_bytes)
connection = self._connect(
input_stream,
output_stream,
listening=False,
**connection_kwargs,
streams = (
_owned_stdio_streams(stdio_buffer_limit_bytes)
if input_stream is None and output_stream is None
else nullcontext((output_stream, input_stream))
)
try:
await connection.listen()
finally:
await asyncio.shield(connection.close())
async with streams as (reader, writer):
connection = self._connect(
writer,
reader,
listening=False,
**connection_kwargs,
)
try:
await connection.listen()
finally:
await asyncio.shield(connection.close())
33 changes: 19 additions & 14 deletions src/acp/experimental/v2/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
from collections.abc import Callable
from contextlib import nullcontext
from functools import partial
from typing import Any, Literal, cast

Expand Down Expand Up @@ -244,18 +245,22 @@ async def run_agent(
stdio_buffer_limit_bytes: int = 50 * 1024 * 1024,
**connection_kwargs: Any,
) -> None:
if input_stream is None and output_stream is None:
from acp.stdio import stdio_streams

output_stream, input_stream = await stdio_streams(limit=stdio_buffer_limit_bytes)
connection = AgentSideConnection(
agent,
input_stream,
output_stream,
listening=False,
**connection_kwargs,
from acp.stdio import _owned_stdio_streams

streams = (
_owned_stdio_streams(stdio_buffer_limit_bytes)
if input_stream is None and output_stream is None
else nullcontext((output_stream, input_stream))
)
try:
await connection.listen()
finally:
await asyncio.shield(connection.close())
async with streams as (reader, writer):
connection = AgentSideConnection(
agent,
writer,
reader,
listening=False,
**connection_kwargs,
)
try:
await connection.listen()
finally:
await asyncio.shield(connection.close())
98 changes: 85 additions & 13 deletions src/acp/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
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, cast
from typing import Any, BinaryIO, Literal, cast

from .agent.connection import AgentSideConnection
from .client.connection import ClientSideConnection
Expand Down Expand Up @@ -118,20 +119,53 @@ async def _windows_stdio_streams(
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]:
# Reader from stdin
) -> 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)
await loop.connect_read_pipe(lambda: reader_protocol, sys.stdin)

# Writer to stdout with protocol providing _drain_helper
write_protocol = _WritePipeProtocol()
transport, _ = await loop.connect_write_pipe(lambda: write_protocol, sys.stdout)
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
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]:
Expand All @@ -141,13 +175,51 @@ async def stdio_streams(limit: int | None = None) -> tuple[asyncio.StreamReader,
``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.
"""
loop = asyncio.get_running_loop()
if platform.system() == "Windows":
return await _windows_stdio_streams(loop, limit=limit)
return await _posix_stdio_streams(loop, limit=limit)
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
Expand Down
Loading
Loading