---
title: Asyncio sessions
description: Asyncio PTY sessions, offset-tracked output rings, and named session
  registries.
order: 1
---
[`PtySession`](core.md#ptysession) wraps a Rust PTY reader thread (`ptymini._core.PtyCore`) and bounded byte [`Ring`](core.md#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`](core.md) explicitly (`ptymini` does not re-export it at top level).

```python
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`](core.md#ptysession) and [`PtyRegistry`](core.md#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`](bg.md#kill) raises `ProcessLookupError`, and deleting an unknown registry name raises `KeyError`.

## PtySession

```python
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`](core.md#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

```python
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

```python
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

```python
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

```python
def write(
    data:bytes
)->None:
```

*Write raw bytes to the PTY input.*

### PtySession.resize

```python
def resize(
    rows:int, cols:int
)->None:
```

*Resize the PTY window and notify the child process.*

### PtySession.terminate

```python
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

```python
def kill(
    sig:int=<Signals.SIGTERM: 15>
)->None:
```

*Send a signal directly to the child process.*

### PtySession.wait

```python
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

```python
def model()->dict:
```

*Return a dict with `name`, `alive`, and `last_activity`.*

### PtySession.ring

```python
def ring()->PtyCore:
```

*Ring view of the session (`read_from`, `start`, and `end`).*

### PtySession.alive

```python
def alive()->bool:
```

### PtySession.exit\_code

```python
def exit_code()->int | None:
```

*Child exit code once exited (negative for terminating signal), or `None` while running.*

### PtySession.last\_activity

```python
def last_activity()->float:
```

*Unix timestamp of the last read or write on the PTY.*

## Gap

```python
def Gap():
```

*Count of bytes lost to ring trimming between two yields of an `attach(gaps=True)` stream.*

## Ring

```python
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

```python
def append(
    data
):
```

*Append `data`, trimming the oldest bytes to keep at most `max_bytes`.*

### Ring.read\_from

```python
def read_from(
    offset, max_bytes_out=None
):
```

*Read from absolute `offset`, returning `(data, new_offset, dropped)`.*

### Ring.max\_bytes

```python
@property
def max_bytes(self):
```

*The ring bound: how many recent bytes are retained.*

### Ring.end

```python
@property
def end(self):
```

*Total bytes ever appended.*

### Ring.start

```python
@property
def start(self):
```

*The absolute offset of the oldest retained byte.*

## PtyRegistry

```python
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.*

```python
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

```python
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

```python
def get(
    name:str
)->PtySession | None:
```

*Return the session registered under `name`, or `None` if absent.*

### PtyRegistry.values

```python
def values()->Iterable[PtySession]:
```

*Return active [`PtySession`](core.md#ptysession) instances in the registry.*

### PtyRegistry.delete

```python
async def delete(
    name:str
)->None:
```

*Remove session `name` from the registry and force-terminate it.*

### PtyRegistry.cull\_ready

```python
def cull_ready()->list[str]:
```

*Return names of sessions past `cull_timeout` seconds of inactivity (empty when culling is disabled).*

### PtyRegistry.cull

```python
async def cull()->None:
```

*Delete and force-terminate every session reported by `cull_ready`.*

### PtyRegistry.shutdown

```python
async def shutdown()->None:
```

*Force-terminate and remove every session in the registry.*

## cull\_loop

```python
async def cull_loop(
    reg:PtyRegistry, interval:float=300
)->None:
```

*Periodically call `reg.cull()` every `interval` seconds; run as a background asyncio task.*
