Skip to content

stdio

Class info

Classes

Name Children Inherits
StdinStream
aclientp.stdio
Wrapper for stdin that implements ByteReceiveStream interface.
    StdoutStream
    aclientp.stdio
    Wrapper for stdout that implements ByteSendStream interface.

      🛈 DocStrings

      StdinStream

      Bases: ByteReceiveStream

      Wrapper for stdin that implements ByteReceiveStream interface.

      Source code in src/aclientp/stdio.py
      class StdinStream(ByteReceiveStream):
          """Wrapper for stdin that implements ByteReceiveStream interface."""
      
          async def receive(self, max_bytes: int = 65536) -> bytes:
              """Read bytes from stdin.
      
              Uses read1() which returns as soon as any data is available,
              rather than blocking until max_bytes are read.
              """
              loop = asyncio.get_running_loop()
              # read1() returns immediately when any data is available (up to max_bytes)
              # unlike read() which blocks until exactly max_bytes are read or EOF
              stdin_buffer = sys.stdin.buffer
              if not isinstance(stdin_buffer, io.BufferedIOBase):
                  raise TypeError(f"Unsupported stdin buffer type: {type(stdin_buffer)}")
              data = await loop.run_in_executor(None, lambda: stdin_buffer.read1(max_bytes))
              if not data:
                  raise anyio.EndOfStream
              return data
      
          async def aclose(self) -> None:
              """Close is a no-op for stdin."""
      

      aclose async

      aclose() -> None
      

      Close is a no-op for stdin.

      Source code in src/aclientp/stdio.py
      async def aclose(self) -> None:
          """Close is a no-op for stdin."""
      

      receive async

      receive(max_bytes: int = 65536) -> bytes
      

      Read bytes from stdin.

      Uses read1() which returns as soon as any data is available, rather than blocking until max_bytes are read.

      Source code in src/aclientp/stdio.py
      async def receive(self, max_bytes: int = 65536) -> bytes:
          """Read bytes from stdin.
      
          Uses read1() which returns as soon as any data is available,
          rather than blocking until max_bytes are read.
          """
          loop = asyncio.get_running_loop()
          # read1() returns immediately when any data is available (up to max_bytes)
          # unlike read() which blocks until exactly max_bytes are read or EOF
          stdin_buffer = sys.stdin.buffer
          if not isinstance(stdin_buffer, io.BufferedIOBase):
              raise TypeError(f"Unsupported stdin buffer type: {type(stdin_buffer)}")
          data = await loop.run_in_executor(None, lambda: stdin_buffer.read1(max_bytes))
          if not data:
              raise anyio.EndOfStream
          return data
      

      StdoutStream

      Bases: ByteSendStream

      Wrapper for stdout that implements ByteSendStream interface.

      Source code in src/aclientp/stdio.py
      class StdoutStream(ByteSendStream):
          """Wrapper for stdout that implements ByteSendStream interface."""
      
          async def send(self, item: bytes) -> None:
              """Write bytes to stdout."""
              loop = asyncio.get_running_loop()
              await loop.run_in_executor(None, self._write, item)
      
          def _write(self, data: bytes) -> None:
              sys.stdout.buffer.write(data)
              sys.stdout.buffer.flush()
      
          async def aclose(self) -> None:
              """Close is a no-op for stdout."""
      

      aclose async

      aclose() -> None
      

      Close is a no-op for stdout.

      Source code in src/aclientp/stdio.py
      async def aclose(self) -> None:
          """Close is a no-op for stdout."""
      

      send async

      send(item: bytes) -> None
      

      Write bytes to stdout.

      Source code in src/aclientp/stdio.py
      async def send(self, item: bytes) -> None:
          """Write bytes to stdout."""
          loop = asyncio.get_running_loop()
          await loop.run_in_executor(None, self._write, item)
      

      connect_to_agent

      connect_to_agent(
          client: Client,
          input_stream: ByteSendStream,
          output_stream: ByteReceiveStream,
          **connection_kwargs: Any,
      ) -> ClientSideConnection
      

      Create a ClientSideConnection to an ACP agent.

      This is the recommended entry point for client-side connections.

      Parameters:

      Name Type Description Default
      client Client

      The client implementation.

      required
      input_stream ByteSendStream

      ByteSendStream for sending to the agent.

      required
      output_stream ByteReceiveStream

      ByteReceiveStream for receiving from the agent.

      required
      **connection_kwargs Any

      Additional keyword arguments for ClientSideConnection.

      {}

      Returns:

      Type Description
      ClientSideConnection

      A ClientSideConnection connected to the agent.

      Source code in src/aclientp/stdio.py
      def connect_to_agent(
          client: Client,
          input_stream: ByteSendStream,
          output_stream: ByteReceiveStream,
          **connection_kwargs: Any,
      ) -> ClientSideConnection:
          """Create a ClientSideConnection to an ACP agent.
      
          This is the recommended entry point for client-side connections.
      
          Args:
              client: The client implementation.
              input_stream: ByteSendStream for sending to the agent.
              output_stream: ByteReceiveStream for receiving from the agent.
              **connection_kwargs: Additional keyword arguments for ClientSideConnection.
      
          Returns:
              A ClientSideConnection connected to the agent.
          """
      
          # Create a factory that ignores the connection parameter
          def client_factory(connection: Agent) -> Client:
              return client
      
          return ClientSideConnection(client_factory, input_stream, output_stream, **connection_kwargs)
      

      run_agent async

      run_agent(
          agent: Agent | Callable[[AgentSideConnection], Agent],
          input_stream: ByteSendStream | None = None,
          output_stream: ByteReceiveStream | None = None,
          **connection_kwargs: Any,
      ) -> None
      

      Run an ACP agent over stdio or provided streams.

      This is the recommended entry point for running agents. It handles stream setup and connection lifecycle automatically, and returns once the client disconnects (or raises when cancelled).

      Parameters:

      Name Type Description Default
      agent Agent | Callable[[AgentSideConnection], Agent]

      An Agent implementation or a factory callable that takes an AgentSideConnection and returns an Agent. Using a factory allows the agent to access the connection for client communication.

      required
      input_stream ByteSendStream | None

      ByteSendStream the agent writes to (defaults to stdout).

      None
      output_stream ByteReceiveStream | None

      ByteReceiveStream the agent reads from (defaults to stdin).

      None
      **connection_kwargs Any

      Additional keyword arguments for AgentSideConnection.

      {}
      Example with direct agent
      class MyAgent(Agent):
          async def initialize(self, params: InitializeRequest) -> InitializeResponse:
              return InitializeResponse(protocol_version=params.protocol_version)
          # ... implement protocol methods ...
      
      await run_agent(MyAgent())
      
      Example with factory
      class MyAgent(Agent):
          def __init__(self, connection: AgentSideConnection):
              self.connection = connection
          # ... implement protocol methods ...
      
      def create_agent(conn: AgentSideConnection) -> MyAgent:
          return MyAgent(conn)
      
      await run_agent(create_agent)
      
      Source code in src/aclientp/stdio.py
      async def run_agent(
          agent: Agent | Callable[[AgentSideConnection], Agent],
          input_stream: ByteSendStream | None = None,
          output_stream: ByteReceiveStream | None = None,
          **connection_kwargs: Any,
      ) -> None:
          """Run an ACP agent over stdio or provided streams.
      
          This is the recommended entry point for running agents. It handles stream
          setup and connection lifecycle automatically, and returns once the client
          disconnects (or raises when cancelled).
      
          Args:
              agent: An Agent implementation or a factory callable that takes
                  an AgentSideConnection and returns an Agent. Using a factory allows
                  the agent to access the connection for client communication.
              input_stream: ByteSendStream the agent writes to (defaults to stdout).
              output_stream: ByteReceiveStream the agent reads from (defaults to stdin).
              **connection_kwargs: Additional keyword arguments for AgentSideConnection.
      
          Example with direct agent:
              ```python
              class MyAgent(Agent):
                  async def initialize(self, params: InitializeRequest) -> InitializeResponse:
                      return InitializeResponse(protocol_version=params.protocol_version)
                  # ... implement protocol methods ...
      
              await run_agent(MyAgent())
              ```
      
          Example with factory:
              ```python
              class MyAgent(Agent):
                  def __init__(self, connection: AgentSideConnection):
                      self.connection = connection
                  # ... implement protocol methods ...
      
              def create_agent(conn: AgentSideConnection) -> MyAgent:
                  return MyAgent(conn)
      
              await run_agent(create_agent)
              ```
          """
          if (input_stream is None) != (output_stream is None):
              msg = "Pass both input_stream and output_stream, or neither to use stdio"
              raise ValueError(msg)
          if input_stream is None or output_stream is None:
              output_stream, input_stream = await stdio_streams()
      
          conn = AgentSideConnection(agent, input_stream, output_stream, **connection_kwargs)
          try:
              await conn.wait_closed()
          finally:
              await conn.close()
      

      spawn_agent_process async

      spawn_agent_process(
          to_client: Callable[[Agent], Client],
          command: str,
          *args: str,
          env: Mapping[str, str] | None = None,
          cwd: str | Path | None = None,
          log_stderr: bool = False,
          **connection_kwargs: Any,
      ) -> AsyncGenerator[tuple[ClientSideConnection, Process]]
      

      Spawn an ACP agent subprocess and return a ClientSideConnection to it.

      Parameters:

      Name Type Description Default
      to_client Callable[[Agent], Client]

      Factory function that creates a Client from an Agent.

      required
      command str

      The command to execute.

      required
      *args str

      Arguments for the command.

      ()
      env Mapping[str, str] | None

      Environment variables for the subprocess.

      None
      cwd str | Path | None

      Working directory for the subprocess.

      None
      log_stderr bool

      If True, log stderr output from the subprocess.

      False
      **connection_kwargs Any

      Additional arguments for ClientSideConnection.

      {}
      Source code in src/aclientp/stdio.py
      @asynccontextmanager
      async def spawn_agent_process(
          to_client: Callable[[Agent], Client],
          command: str,
          *args: str,
          env: Mapping[str, str] | None = None,
          cwd: str | Path | None = None,
          log_stderr: bool = False,
          **connection_kwargs: Any,
      ) -> AsyncGenerator[tuple[ClientSideConnection, Process]]:
          """Spawn an ACP agent subprocess and return a ClientSideConnection to it.
      
          Args:
              to_client: Factory function that creates a Client from an Agent.
              command: The command to execute.
              *args: Arguments for the command.
              env: Environment variables for the subprocess.
              cwd: Working directory for the subprocess.
              log_stderr: If True, log stderr output from the subprocess.
              **connection_kwargs: Additional arguments for ClientSideConnection.
          """
          async with spawn_stdio_transport(
              command,
              *args,
              env=env,
              cwd=cwd,
              log_stderr=log_stderr,
          ) as (reader, writer, process):
              conn = ClientSideConnection(to_client, writer, reader, **connection_kwargs)
              try:
                  yield conn, process
              finally:
                  await conn.close()
      

      spawn_client_process async

      spawn_client_process(
          to_agent: Callable[[AgentSideConnection], Agent],
          command: str,
          *args: str,
          env: Mapping[str, str] | None = None,
          cwd: str | Path | None = None,
          log_stderr: bool = False,
          **connection_kwargs: Any,
      ) -> AsyncGenerator[tuple[AgentSideConnection, Process]]
      

      Spawn an ACP client subprocess and return an AgentSideConnection to it.

      Parameters:

      Name Type Description Default
      to_agent Callable[[AgentSideConnection], Agent]

      Factory function that creates an Agent from an AgentSideConnection.

      required
      command str

      The command to execute.

      required
      *args str

      Arguments for the command.

      ()
      env Mapping[str, str] | None

      Environment variables for the subprocess.

      None
      cwd str | Path | None

      Working directory for the subprocess.

      None
      log_stderr bool

      If True, log stderr output from the subprocess.

      False
      **connection_kwargs Any

      Additional arguments for AgentSideConnection.

      {}
      Source code in src/aclientp/stdio.py
      @asynccontextmanager
      async def spawn_client_process(
          to_agent: Callable[[AgentSideConnection], Agent],
          command: str,
          *args: str,
          env: Mapping[str, str] | None = None,
          cwd: str | Path | None = None,
          log_stderr: bool = False,
          **connection_kwargs: Any,
      ) -> AsyncGenerator[tuple[AgentSideConnection, Process]]:
          """Spawn an ACP client subprocess and return an AgentSideConnection to it.
      
          Args:
              to_agent: Factory function that creates an Agent from an AgentSideConnection.
              command: The command to execute.
              *args: Arguments for the command.
              env: Environment variables for the subprocess.
              cwd: Working directory for the subprocess.
              log_stderr: If True, log stderr output from the subprocess.
              **connection_kwargs: Additional arguments for AgentSideConnection.
          """
          async with spawn_stdio_transport(
              command,
              *args,
              env=env,
              cwd=cwd,
              log_stderr=log_stderr,
          ) as (reader, writer, process):
              conn = AgentSideConnection(to_agent, writer, reader, **connection_kwargs)
              try:
                  yield conn, process
              finally:
                  await conn.close()
      

      spawn_stdio_connection async

      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,
          log_stderr: bool = False,
      ) -> AsyncGenerator[tuple[Connection, Process]]
      

      Spawn a subprocess and bind its stdio to a low-level Connection.

      Parameters:

      Name Type Description Default
      handler MethodHandler

      Method handler for the connection.

      required
      command str

      The command to execute.

      required
      *args str

      Arguments for the command.

      ()
      env Mapping[str, str] | None

      Environment variables for the subprocess.

      None
      cwd str | Path | None

      Working directory for the subprocess.

      None
      observers list[StreamObserver] | None

      Optional stream observers.

      None
      log_stderr bool

      If True, log stderr output from the subprocess.

      False
      Source code in src/aclientp/stdio.py
      @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,
          log_stderr: bool = False,
      ) -> AsyncGenerator[tuple[Connection, Process]]:
          """Spawn a subprocess and bind its stdio to a low-level Connection.
      
          Args:
              handler: Method handler for the connection.
              command: The command to execute.
              *args: Arguments for the command.
              env: Environment variables for the subprocess.
              cwd: Working directory for the subprocess.
              observers: Optional stream observers.
              log_stderr: If True, log stderr output from the subprocess.
          """
          async with spawn_stdio_transport(command, *args, env=env, cwd=cwd, log_stderr=log_stderr) as (
              reader,
              writer,
              process,
          ):
              conn = Connection(handler, writer, reader, observers=observers)
              try:
                  yield conn, process
              finally:
                  await conn.close()
      

      stdio_streams async

      stdio_streams() -> tuple[StdinStream, StdoutStream]
      

      Create stdio anyio-compatible streams (cross-platform).

      Returns (stdin, stdout) as byte stream wrappers compatible with ByteReceiveStream and ByteSendStream interfaces.

      Source code in src/aclientp/stdio.py
      async def stdio_streams() -> tuple[StdinStream, StdoutStream]:
          """Create stdio anyio-compatible streams (cross-platform).
      
          Returns (stdin, stdout) as byte stream wrappers compatible with
          ByteReceiveStream and ByteSendStream interfaces.
          """
          return StdinStream(), StdoutStream()