libvt.aio — Async Stream¶
asyncio stream transport adapter exported from libvt.aio.
Bidirectional
asynciostream adapter overTerminal.Coalesces frame wakeups across DEC mode
?2026synchronized-output batches (bounded by sync_timeout using generation-safe expiry), expires any active?2026hold onEOFandaclose(), and queues outboundsend(),send_event(),send_key(),paste(), and automatic query replies onto a non-blocking single-FIFO writer queue so inbound reads never block on outbound backpressure.Signal half-close EOF on
writerafter queued outbound bytes flush.- Raises:
RuntimeError– If nowriterwas attached to this stream.OSError– If the stream has already been closed viaaclose().
- Return type:
Examples
>>> import asyncio >>> from libvt.aio import AsyncTerminalStream >>> class _EofWriter: ... def __init__(self) -> None: ... self.eof_sent = False ... def write(self, data: bytes, /) -> None: ... pass ... def write_eof(self) -> None: ... self.eof_sent = True ... async def drain(self) -> None: ... pass ... def close(self) -> None: ... pass ... async def wait_closed(self) -> None: ... pass >>> async def _demo() -> bool: ... w = _EofWriter() ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: ... stream.write_eof() ... return w.eof_sent >>> asyncio.run(_demo()) True
Flush queued outbound frames and await
writer.drain().Always yields at least one event-loop turn (
await asyncio.sleep(0)) and propagates non-EOF peer write errors recorded by the background writer task.Examples
>>> import asyncio >>> from libvt.aio import AsyncTerminalStream >>> async def _check() -> int: ... s = AsyncTerminalStream(asyncio.StreamReader()) ... await s.drain() ... return s.write_buffer_size >>> asyncio.run(_check()) 0
Feed one stream read and return whether it delivered data.
Concurrent callers join the current read and share its result. EOF or close returns
False. Cancelling the last caller releases the reader.- Return type:
Start background stream pumping on the running event loop.
Join owned tasks, close the writer and expire any held frame.
Concurrent callers share cleanup. A cancelled caller receives
asyncio.CancelledErroronce cleanup finishes.- Return type:
Return
Trueonce inbound terminal output reaches end-of-stream.
Encode text as an atomic
PasteEventframe.Wraps text in
ESC [ 200 ~ ... ESC [ 201 ~when DEC mode?2004is enabled onself.terminaland enqueues the entire bracketed frame as a single FIFO item so concurrent replies never interleave inside it.- Parameters:
text (
str) – Clipboard text to paste.sanitize (
bool) – WhenFalse(default), raiseUnsafePasteErroron control/escape injection bytes; whenTrue, strip them.
- Raises:
UnsafePasteError– If sanitize isFalseand text contains disallowed controls.- Return type:
References
Examples
>>> import asyncio >>> from libvt.aio import AsyncTerminalStream >>> class _MemWriter: ... def __init__(self) -> None: ... self.buf = bytearray() ... def write(self, data: bytes, /) -> None: ... self.buf.extend(data) ... async def drain(self) -> None: ... pass ... def close(self) -> None: ... pass ... async def wait_closed(self) -> None: ... pass >>> async def _demo() -> bytes: ... w = _MemWriter() ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: ... stream.terminal.feed(b"\x1b[?2004h") ... stream.paste("line1\nline2") ... return bytes(w.buf) >>> asyncio.run(_demo()) b'\x1b[200~line1\nline2\x1b[201~'
Enqueue raw data bytes (or UTF-8 string) onto the outbound write queue.
- Parameters:
data (
collections.abc.Buffer|str) – Raw outbound bytes or text encoded as UTF-8.- Raises:
RuntimeError– If no outbound writer is attached.OSError– If the outbound transport is closed or half-closed.BufferError– If buffered outbound bytes exceedmax_write_buffer.
- Return type:
Examples
>>> import asyncio >>> from libvt.aio import AsyncTerminalStream >>> class _MemWriter: ... def __init__(self) -> None: ... self.buf = bytearray() ... def write(self, data: bytes, /) -> None: ... self.buf.extend(data) ... async def drain(self) -> None: ... pass ... def close(self) -> None: ... pass ... async def wait_closed(self) -> None: ... pass >>> async def _demo() -> bytes: ... w = _MemWriter() ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: ... stream.send("ls\n") ... return bytes(w.buf) >>> asyncio.run(_demo()) b'ls\n'
Encode event (filtering
?1002drags) and enqueue outbound bytes.- Parameters:
event (
InputEvent) – Keyboard, mouse, focus, or paste event to encode againstself.terminal.modes.- Return type:
References
Examples
>>> import asyncio >>> from libvt.aio import AsyncTerminalStream >>> from libvt.input import KeyEvent >>> class _MemWriter: ... def __init__(self) -> None: ... self.buf = bytearray() ... def write(self, data: bytes, /) -> None: ... self.buf.extend(data) ... async def drain(self) -> None: ... pass ... def close(self) -> None: ... pass ... async def wait_closed(self) -> None: ... pass >>> async def _demo() -> bytes: ... w = _MemWriter() ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: ... stream.send_event(KeyEvent("up")) ... return bytes(w.buf) >>> asyncio.run(_demo()) b'\x1b[A'
Parse chord (e.g.
"ctrl+c","enter") and enqueue outbound.Examples
>>> import asyncio >>> from libvt.aio import AsyncTerminalStream >>> class _MemWriter: ... def __init__(self) -> None: ... self.buf = bytearray() ... def write(self, data: bytes, /) -> None: ... self.buf.extend(data) ... async def drain(self) -> None: ... pass ... def close(self) -> None: ... pass ... async def wait_closed(self) -> None: ... pass >>> async def _demo() -> bytes: ... w = _MemWriter() ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: ... stream.send_key("ctrl+c") ... return bytes(w.buf) >>> asyncio.run(_demo()) b'\x03'
Wait until predicate matches
Snapshot.- Parameters:
predicate (
collections.abc.Callable[[Snapshot],bool] |str) – Callable evaluated in the waiting task at read and synchronized frame boundaries, or a substring matched againstunwrapped_textacross soft-wrapped rows. Hard linebreaks remain"\n". Use a callable withtextto match physical rows.timeout (
float) – Maximum wait duration in seconds before raisingTerminalTimeoutError.attach_note (
bool) – WhenTrue(default), attach multi-line screen and flight recorder diagnostics via PEP 678__notes__.
- Returns:
First matching
Snapshot.- Return type:
- Raises:
TerminalTimeoutError– If the session reaches EOF/close before matching or timeout expires.
Return number of outbound bytes currently buffered for writing.
Examples
>>> import asyncio >>> from libvt.aio import AsyncTerminalStream >>> async def _check() -> int: ... return AsyncTerminalStream(asyncio.StreamReader()).write_buffer_size >>> asyncio.run(_check()) 0