Asyncio sessions
Asyncio PTY sessions, offset-tracked output rings, and named session registries.
PtySession wraps a Rust PTY reader thread (ptymini._core.PtyCore) and bounded byte Ring behind an asyncio API, scheduling change notifications on the running loop via call_soon_threadsafe. One session supports both streaming consumers (attach, which replays scrollback and yields live bytes) and offset-paged cursor consumers (read_from and wait_change). Import ptymini.core explicitly (ptymini does not re-export it at top level).
async with PtySession(["python3", "-i"]) as sess:
sess.write(b"2 + 2\n")
async for chunk in sess.attach():
if b"4" in chunk: break
PtySession and PtyRegistry are async context managers that force-terminate their child processes on exit. Non-positive buffer sizes raise ValueError, PTY spawn or I/O failures raise OSError, signaling an exited child with kill raises ProcessLookupError, and deleting an unknown registry name raises KeyError.
PtySession
def PtySession(
argv:list[str], # Command and arguments to spawn on the PTY
cwd:str=None, # Working directory for the child process
env:dict=None, # Child environment; None inherits this process's environment
rows:int=24, # Initial terminal height in rows
cols:int=80, # Initial terminal width in columns
buffer_bytes:int=1000000, # Maximum recent output bytes retained in the ring
name:str=None, # Optional handle assigned by `PtyRegistry`
):
Asyncio PTY session over a bounded Ring buffer.
Use as an async context manager to force-terminate the child on exit. Multiple readers can call attach or read_from on the same session independently without advancing each other.
PtySession.attach
def attach(
gaps:bool=False, # Yield `Gap(n)` markers when output was trimmed before the stream read it?
from_start:bool=True, # Start at the oldest retained byte (replay); False starts at the live edge
)->AsyncIterator[bytes | Gap]:
Stream session output as an async iterator, ending at EOF.
Each call tracks its own offset in the ring. Stopping iteration leaves the session and other readers untouched.
PtySession.read_from
def read_from(
offset:int, # Absolute byte offset to read from
max_bytes_out:int=None, # Max bytes to return; None returns all retained bytes from `offset`
)->tuple[bytes, int, int]: # `(data, next_offset, dropped_bytes)`
Read output starting at absolute offset without affecting other readers.
PtySession.wait_change
async def wait_change(
seen_end:int=None, # Wake when `ring.end` passes this (None uses the value at call time)
timeout:float=None, # Max seconds to wait; None waits indefinitely
)->bool: # True when new output or EOF arrived, False on timeout
Wait until the ring grows past seen_end, or EOF.
PtySession.write
def write(
data:bytes
)->None:
Write raw bytes to the PTY input.
PtySession.resize
def resize(
rows:int, cols:int
)->None:
Resize the PTY window and notify the child process.
PtySession.terminate
async def terminate(
force:bool=False
)->bool:
Send SIGHUP, SIGCONT, SIGINT, and SIGTERM in turn, escalating to SIGKILL when force=True; return True once the child has exited.
PtySession.kill
def kill(
sig:int=<Signals.SIGTERM: 15>
)->None:
Send a signal directly to the child process.
PtySession.wait
async def wait()->int: # Exit code, or negative signal number if terminated by signal
Wait until the child exits and return its exit status.
PtySession.model
def model()->dict:
Return a dict with name, alive, and last_activity.
PtySession.ring
def ring()->PtyCore:
Ring view of the session (read_from, start, and end).
PtySession.alive
def alive()->bool:
PtySession.exit_code
def exit_code()->int | None:
Child exit code once exited (negative for terminating signal), or None while running.
PtySession.last_activity
def last_activity()->float:
Unix timestamp of the last read or write on the PTY.
Gap
def Gap():
Count of bytes lost to ring trimming between two yields of an attach(gaps=True) stream.
Ring
def Ring(
max_bytes:int=1000000
):
Bounded byte buffer with absolute offsets (start..end of the retained window; end is total bytes ever appended).
Ring.append
def append(
data
):
Append data, trimming the oldest bytes to keep at most max_bytes.
Ring.read_from
def read_from(
offset, max_bytes_out=None
):
Read from absolute offset, returning (data, new_offset, dropped).
Ring.max_bytes
@property
def max_bytes(self):
The ring bound: how many recent bytes are retained.
Ring.end
@property
def end(self):
Total bytes ever appended.
Ring.start
@property
def start(self):
The absolute offset of the oldest retained byte.
PtyRegistry
def PtyRegistry(
argv:list[str]=None, # Default spawn command; `create` calls may override it
cull_timeout:float=0, # Seconds of inactivity before a session is eligible for culling (0 disables)
):
Named-session registry with get-or-create semantics, shell setup injection, and idle culling.
async with PtyRegistry(argv=["/bin/bash"], cull_timeout=600) as reg:
sess = await reg.create("shell-1")
task = asyncio.create_task(cull_loop(reg, interval=60))
PtyRegistry.create
async def create(
name:str=None, # Existing name returns that session; None auto-numbers starting at `"1"`
argv:list[str]=None, # Spawn command; uses the registry default if None
cwd:str=None, # Working directory for the child process
env:dict=None, # Replaces the inherited environment when provided
appendenv:dict=None, # Overlays keys onto the base environment
rc:str=None, # Shell setup script written to a private temp dir; substitutes `{rcfile}` and `{rcdir}` in `argv` and env values
rows:int=24, # Initial terminal height in rows
cols:int=80, # Initial terminal width in columns
)->PtySession: # Existing or newly spawned session
Return session name if it exists, or spawn and register a new one.
When rc is given, it is written as .zshrc inside a private directory removed automatically when the session exits. Pass --rcfile {rcfile} for Bash or ZDOTDIR={rcdir} for Zsh.
PtyRegistry.get
def get(
name:str
)->PtySession | None:
Return the session registered under name, or None if absent.
PtyRegistry.values
def values()->Iterable[PtySession]:
Return active PtySession instances in the registry.
PtyRegistry.delete
async def delete(
name:str
)->None:
Remove session name from the registry and force-terminate it.
PtyRegistry.cull_ready
def cull_ready()->list[str]:
Return names of sessions past cull_timeout seconds of inactivity (empty when culling is disabled).
PtyRegistry.cull
async def cull()->None:
Delete and force-terminate every session reported by cull_ready.
PtyRegistry.shutdown
async def shutdown()->None:
Force-terminate and remove every session in the registry.
cull_loop
async def cull_loop(
reg:PtyRegistry, interval:float=300
)->None:
Periodically call reg.cull() every interval seconds; run as a background asyncio task.