Background terminal sessions

Synchronous, cursor-paged PTY sessions for scripts, kernel tools, and LLM agents.

ptymini.bg calls the Rust PTY core directly with the GIL released and requires no asyncio event loop. Sessions live in-process and end when the Python process exits. Import ptymini.bg explicitly (ptymini does not re-export it at top level).

sid = start_bgterm("python3 -q")
res = write_stdin(sid, "print(6 * 7)\n", wait_ms=2000, until=r"42")
print(res.text)
close_bgterm(sid)

write_stdin and poll share three bounded wait parameters: wait_ms caps waiting for new output (or for an until regex match against unread text produced since the previous read), and settle_ms continues collecting until output pauses (up to settle_ms past the wait_ms deadline). Process exit ends any wait immediately. Unknown or unwritable sessions raise BgtermError, negative max_output_bytes or non-positive max_buffer_bytes raise ValueError, and PTY spawn failures raise OSError.

Starting and driving sessions

start_bgterm spawns a child process and returns an integer session ID (sid). write_stdin, poll, and read advance the session cursor and return a PollResult.

start_bgterm

def start_bgterm(
    cmd:Cmd=None, # Command argv, or a string command line; None spawns `$SHELL`
    cwd:str=None, # Working directory for the child
    env:dict=None, # Child environment; None inherits this process's; `term` replaces its `TERM`
    shell:bool=None, # Run a string `cmd` via `/bin/sh -c`? None: yes when `cmd` is a string
    encoding:str='utf-8', # Decoding for `PollResult.text`
    errors:str='replace', # Decode error handling
    max_buffer_bytes:int=1000000, # Ring bound: how much unread output is retained
    term:str='dumb', # The child's `TERM`; `'dumb'` turns off colours and line editing in most programs
)->int: # Integer session ID for subsequent calls

Start a PTY-backed session and return its integer session ID.

write_stdin

def write_stdin(
    sid:int, # Session ID from `start_bgterm`
    chars:str | bytes='', # Input to write; str encodes with the session's encoding, bytes pass through
    wait_ms:int=0, # Max ms to wait for output when none is unread (with `until`: for the match)
    max_output_bytes:int=65536, # Page size cap on returned bytes; None returns everything unread
    until:str=None, # Regex; return as soon as this call's accumulated unread text matches
    settle_ms:int=0, # Keep collecting until output stops for this long (at most `settle_ms` past the deadline)
)->PollResult:

Write to a session PTY, wait as poll does, and return unread output.

poll

def poll(
    sid:int, # Session ID from `start_bgterm`
    wait_ms:int=0, # Max ms to wait for output when none is unread (with `until`: for the match)
    max_output_bytes:int=65536, # Page size cap on returned bytes; None returns everything unread
    until:str=None, # Regex; return as soon as this call's accumulated unread text matches
    settle_ms:int=0, # Keep collecting until output stops for this long (at most `settle_ms` past the deadline)
)->PollResult:

Wait for unread session output (or an until match, or settling), then return it without writing input.

read

def read(
    sid:int, # Session ID from `start_bgterm`
    max_output_bytes:int=65536, # Page size cap on returned bytes; None returns everything unread
)->PollResult:

Return unread session output immediately.

wait

def wait(
    sid:int, timeout_ms:int=None
)->int | None:

Wait up to timeout_ms (or indefinitely) for a session to exit; returns exit code (negative for signal) or None on timeout.

Lifecycle and cleanup

list_sessions

def list_sessions()->tuple[int, ...]:

List active in-process bgterm session IDs in ascending order.

terminate

def terminate(
    sid:int
)->None:

Send SIGTERM to the session child process (no-op if already exited).

kill

def kill(
    sid:int
)->None:

Send SIGKILL to the session child process (no-op if already exited).

close_bgterm

def close_bgterm(
    sid:int, # Session ID from `start_bgterm`
    terminate:bool=True, # Ask the child to exit (`SIGTERM`, then `SIGKILL`) before closing?
    kill_after_ms:int=1000, # Ms to wait after each signal before escalating
)->None:

Close a session and remove it from the in-process registry (no-op if already closed).

Object wrapper and results

PollResult

def PollResult(
    text:str, # `data` decoded with the session's encoding
    data:bytes, # The unread bytes returned by this call
    start_offset:int, # Absolute offset of the first returned byte
    end_offset:int, # Absolute offset just past the last returned byte (the new cursor)
    buffer_start_offset:int, # Absolute offset of the oldest byte the ring retains
    buffer_end_offset:int, # Total bytes the session has ever output
    bytes_returned:int, # Length of `data`
    remaining_bytes:int, # Unread bytes still in the ring after this page
    dropped_bytes:int, # Unread bytes lost to ring trimming before this read
    running:bool, # Was the child still alive at read time?
    exit_code:int | None, # Exit code once dead (negative: terminating signal number)
):

Unread output, cursor offsets, drop counts, and process status returned by write_stdin, poll, or read.

PollResult.truncated

def truncated()->bool:

True when output was paged (remaining_bytes > 0) or older unread bytes were dropped (dropped_bytes > 0).

BgtermError

def BgtermError(
    *args, **kwargs
):

Raised when a bgterm session cannot be started, found, or controlled.

Session

def Session(
    sid:int, # Session ID from `start_bgterm`
    close_on_exit:bool=True, # Close the session when a `with` block exits?
):

Context-manager wrapper around the sid-based bgterm API.

with Session.start(["/bin/sh"]) as sess:
    out = sess.write_stdin("echo ready\n", wait_ms=500, until="ready")
    assert out.running

Session.start

def start(
    cmd:Cmd=None, # Command argv, or a string command line; None spawns `$SHELL`
    cwd:str=None, # Working directory for the child
    env:dict=None, # Child environment; None inherits this process's; `term` replaces its `TERM`
    shell:bool=None, # Run a string `cmd` via `/bin/sh -c`? None: yes when `cmd` is a string
    encoding:str='utf-8', # Decoding for `PollResult.text`
    errors:str='replace', # Decode error handling
    max_buffer_bytes:int=1000000, # Ring bound: how much unread output is retained
    close_on_exit:bool=True, # Close the session when a `with` block exits?
    term:str='dumb', # The child's `TERM`; `'dumb'` turns off colours and line editing in most programs
)->Session:

Start a PTY-backed session and wrap it in Session.

Session.open

def open(
    sid:int, # Existing session ID to wrap
    close_on_exit:bool=False, # Close the session when a `with` block exits?
)->Session:

Wrap an existing session ID (verifying it is registered).

Session.running

def running()->bool:

Return whether the wrapped session is still running (False once closed).

Session.exit_code

def exit_code()->int | None:

Return the wrapped session's exit code (None while running or once closed).

Session.write_stdin

def write_stdin(
    chars:str | bytes='', # Input to write; str encodes with the session's encoding, bytes pass through
    wait_ms:int=0, # Max ms to wait for output when none is unread (with `until`: for the match)
    max_output_bytes:int=65536, # Page size cap on returned bytes; None returns everything unread
    until:str=None, # Regex; return as soon as this call's accumulated unread text matches
    settle_ms:int=0, # Keep collecting until output stops for this long (at most `settle_ms` past the deadline)
)->PollResult:

Write to this session PTY, wait as poll does, and return unread output.

Session.poll

def poll(
    wait_ms:int=0, # Max ms to wait for output when none is unread (with `until`: for the match)
    max_output_bytes:int=65536, # Page size cap on returned bytes; None returns everything unread
    until:str=None, # Regex; return as soon as this call's accumulated unread text matches
    settle_ms:int=0, # Keep collecting until output stops for this long (at most `settle_ms` past the deadline)
)->PollResult:

Wait for unread output from this session, then return it.

Session.read

def read(
    max_output_bytes:int=65536, # Page size cap on returned bytes; None returns everything unread
)->PollResult:

Return unread output from this session immediately.

Session.wait

def wait(
    timeout_ms:int=None
)->int | None:

Wait up to timeout_ms (or indefinitely) for this session to exit; returns exit code (negative for signal) or None on timeout.

Session.terminate

def terminate()->None:

Send SIGTERM to this session child process.

Session.kill

def kill()->None:

Send SIGKILL to this session child process.

Session.close

def close(
    terminate:bool=True, # Ask the child to exit (`SIGTERM`, then `SIGKILL`) before closing?
    kill_after_ms:int=1000, # Ms to wait after each signal before escalating
)->None:

Close this session and make repeated closes a no-op.