pty

    Cross-platform PTY (pseudo-terminal) spawning for MoonBit native targets, integrated with moonbitlang/async.

    pty
    pseudo-terminal
    async
    native
    Download zip
    Version
    0.4.4
    License
    Apache-2.0
    Last updated
    16 days ago
    Downloads
    47K

    #moonbit-community/pty

    Cross-platform PTY (pseudo-terminal) spawning for MoonBit native targets, integrated with moonbitlang/async so reads and writes go through the async event loop instead of blocking the thread.

    #Usage

    let exit_code = @pty.with_pty(
    "sh", [],
    rows=24, cols=80,
    cwd="/workspace",
    ) <| pty => {
    let pid : Int = pty.pid()
    pty.resize(rows=40, cols=120)
    pty.write(b"ls\nexit\n") // Pty implements @io.Writer
    let text = pty.read_all().text() // ... and @io.Reader
    pty.wait()
    }

    with_pty spawns file with args on a new pseudo-terminal, runs the callback with its Pty, and releases the pty when the callback is done.

    The pty lives exactly as long as the callback. If the child is still running when the callback returns, raises, or is cancelled, it is hung up, given a 5 s grace period, then killed; with_pty returns once it has been reaped. Pty::wait returns the child's exit code; call it inside the callback to let the child finish on its own.

    Do not let the Pty escape the callback: it is closed afterwards, and a task still blocked reading it is not woken up.

    #Spawning into your own task group: spawn

    with_pty opens a task group of its own. When you already have one whose lifetime is the pty's — typically a session with tasks reading and writing concurrently — spawn the pty into it directly with spawn, which takes the group as its first argument and otherwise the same arguments:

    @async.with_task_group() <| session => {
    let pty = @pty.spawn(session, "sh", [])
    session.spawn_bg(no_wait=true, () => forward_input(pty))
    while pty.read_some() is Some(chunk) {
    handle(chunk)
    }
    }

    The pty's resources are released when that group exits. If the group is cancelled, the child gets the same 5 s grace period, then a hard kill.

    By default the group waits for the child to exit. Pass no_wait=true (same semantics as @async/process.spawn) to let the group exit as soon as its own tasks are done, terminating the child instead of waiting for it.

    Because the pty stays open until its group exits, do not spawn many ptys into a single long-lived group: their file descriptors accumulate. Give each pty a group of its own, or use with_pty.

    #Drain the pty concurrently

    Do not wait() first and read() afterwards. A pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Read concurrently while waiting; reading late yields a clean but empty EOF.

    Relatedly, ConPTY output is a screen rendering, not a byte stream: expect VT escape sequences (including an initial clear-screen) surrounding your child's output. Strip or escape them before asserting on pty output in tests — a failing diff that prints raw pty output replays those sequences into your terminal.

    #Further reading

    • docs/internals.md — executable resolution, environment merging, and platform architecture: unix fork/execve, Windows ConPTY startup, argv encoding.
    • docs/invariants.md — hard-won debugging conclusions and decision records that must not regress.

    Pty

    type Pty

    A pseudo-terminal attached to a spawned child process.

    Pty implements @async/io.Reader and @async/io.Writer: writes send input to the child's terminal, reads carry the terminal's output (stdout and stderr merged). On Windows the output is a ConPTY screen rendering, so it is wrapped in VT escape sequences (including an initial clear-screen) rather than being the child's raw bytes.

    The pty's resources are released when the task group passed to spawn exits. If the group is cancelled, the child gets a 5 s grace period, then a hard kill.
    impl Reader for Pty
    impl Writer for Pty

    Pty::drop

    async fn Pty::drop(self : Pty, len : Int) -> Int

    Reads the child's terminal output (stdout and stderr merged). These are the standard @async/io.Reader methods with their usual semantics: read reads what is immediately available, read_some returns as soon as some data arrives, read_all collects until EOF, and read_until / read_exactly / drop behave as documented on @async/io.Reader.

    Read concurrently with Pty::wait — do not wait for the child and only then read: the pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Reading late yields a clean but empty EOF.

    On Windows the output is a ConPTY screen rendering rather than a raw byte stream: expect VT escape sequences (including an initial clear-screen) surrounding the child's output.

    Pty::pid

    fn Pty::pid(self : Pty) -> Int

    The process ID of the spawned child process.

    Pty::read

    async fn Pty::read(self : Pty, dst : FixedArray[Byte], offset? : Int, max_len? : Int) -> Int

    Reads the child's terminal output (stdout and stderr merged). These are the standard @async/io.Reader methods with their usual semantics: read reads what is immediately available, read_some returns as soon as some data arrives, read_all collects until EOF, and read_until / read_exactly / drop behave as documented on @async/io.Reader.

    Read concurrently with Pty::wait — do not wait for the child and only then read: the pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Reading late yields a clean but empty EOF.

    On Windows the output is a ConPTY screen rendering rather than a raw byte stream: expect VT escape sequences (including an initial clear-screen) surrounding the child's output.

    Pty::read_all

    async fn Pty::read_all(self : Pty) -> &
    Data

    Reads the child's terminal output (stdout and stderr merged). These are the standard @async/io.Reader methods with their usual semantics: read reads what is immediately available, read_some returns as soon as some data arrives, read_all collects until EOF, and read_until / read_exactly / drop behave as documented on @async/io.Reader.

    Read concurrently with Pty::wait — do not wait for the child and only then read: the pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Reading late yields a clean but empty EOF.

    On Windows the output is a ConPTY screen rendering rather than a raw byte stream: expect VT escape sequences (including an initial clear-screen) surrounding the child's output.

    Pty::read_exactly

    async fn Pty::read_exactly(self : Pty, len : Int) -> Bytes

    Reads the child's terminal output (stdout and stderr merged). These are the standard @async/io.Reader methods with their usual semantics: read reads what is immediately available, read_some returns as soon as some data arrives, read_all collects until EOF, and read_until / read_exactly / drop behave as documented on @async/io.Reader.

    Read concurrently with Pty::wait — do not wait for the child and only then read: the pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Reading late yields a clean but empty EOF.

    On Windows the output is a ConPTY screen rendering rather than a raw byte stream: expect VT escape sequences (including an initial clear-screen) surrounding the child's output.

    Pty::read_some

    async fn Pty::read_some(self : Pty, max_len? : Int) -> Bytes?

    Reads the child's terminal output (stdout and stderr merged). These are the standard @async/io.Reader methods with their usual semantics: read reads what is immediately available, read_some returns as soon as some data arrives, read_all collects until EOF, and read_until / read_exactly / drop behave as documented on @async/io.Reader.

    Read concurrently with Pty::wait — do not wait for the child and only then read: the pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Reading late yields a clean but empty EOF.

    On Windows the output is a ConPTY screen rendering rather than a raw byte stream: expect VT escape sequences (including an initial clear-screen) surrounding the child's output.

    Pty::read_until

    async fn Pty::read_until(self : Pty, sep : StringView) -> String?

    Reads the child's terminal output (stdout and stderr merged). These are the standard @async/io.Reader methods with their usual semantics: read reads what is immediately available, read_some returns as soon as some data arrives, read_all collects until EOF, and read_until / read_exactly / drop behave as documented on @async/io.Reader.

    Read concurrently with Pty::wait — do not wait for the child and only then read: the pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Reading late yields a clean but empty EOF.

    On Windows the output is a ConPTY screen rendering rather than a raw byte stream: expect VT escape sequences (including an initial clear-screen) surrounding the child's output.

    Pty::resize

    fn Pty::resize(self : Pty, rows~ : Int, cols~ : Int) -> Unit raise
    OSError

    Resizes the child's terminal, in characters. Raises @os_error.OSError if the resize fails, including when the pty has already been closed (for example after the owning task group has exited).

    Pty::wait

    async fn Pty::wait(self : Pty) -> Int

    Waits for the child process to terminate and returns its exit code. If the process was killed by a signal, the result is -signal_number (the same convention as @async/process.wait_pid).

    Do not wait first and read afterwards: the pty master is a bounded kernel queue, and on macOS the kernel discards whatever is still queued a few hundred milliseconds after the child exits. Read concurrently while waiting; reading late yields a clean but empty EOF.

    Pty::write

    async fn Pty::write(self : Pty, data : &
    Data
    ) -> Unit

    Sends input to the child's terminal. These are the standard @async/io.Writer methods with their usual semantics: write_once performs a single write and reports how many bytes were accepted, write writes the whole buffer before returning, and write_reader forwards everything read from another reader.

    Pty::write_once

    async fn Pty::write_once(self : Pty, buf : Bytes, offset~ : Int, len~ : Int) -> Int

    Sends input to the child's terminal. These are the standard @async/io.Writer methods with their usual semantics: write_once performs a single write and reports how many bytes were accepted, write writes the whole buffer before returning, and write_reader forwards everything read from another reader.

    Pty::write_reader

    async fn Pty::write_reader(self : Pty, reader : &
    Reader
    ) -> Unit

    Sends input to the child's terminal. These are the standard @async/io.Writer methods with their usual semantics: write_once performs a single write and reports how many bytes were accepted, write writes the whole buffer before returning, and write_reader forwards everything read from another reader.

    spawn

    async fn[X] spawn(group :
    TaskGroup
    [X], rows? : Int, cols? : Int, file : StringView, args : ArrayView[StringView], extra_env? : Map[String, String], inherit_env? : Bool, cwd? : StringView, no_wait? : Bool) -> Pty

    Spawns a child process attached to a new pseudo-terminal and returns the Pty handle.

    The child runs file with args as its arguments; its argv[0] is file verbatim, so programs that dispatch on argv[0] (busybox-style multi-call binaries, shells checking for a leading -) see what the caller wrote. file is looked up through PATH when it does not contain a path separator, and used directly otherwise.

    • rows and cols set the initial terminal size in characters.
    • extra_env adds or overrides environment variables; by default (inherit_env=true) the child also inherits the current process's environment.
    • cwd sets the child's working directory; by default the child starts in the current directory.
    • no_wait has the same semantics as @async/process.spawn: by default the task group waits for the child to terminate; with no_wait=true the group exits as soon as its own tasks are done, terminating the child.

    The returned Pty implements @async/io.Reader and @async/io.Writer, and its resources are released when group exits. Raises @os_error.OSError if the pty cannot be opened or the child cannot be spawned.

    with_pty

    async fn[T] with_pty(rows? : Int, cols? : Int, file : StringView, args : ArrayView[StringView], extra_env? : Map[String, String], inherit_env? : Bool, cwd? : StringView, f : async (Pty) -> T) -> T

    Spawns a child process attached to a new pseudo-terminal, runs f with its Pty, and releases the pty when f is done.

    The pty lives exactly as long as f. When f returns, raises, or is cancelled, the terminal is closed; a child that is still running is hung up, given the 5 s grace period, then killed, and with_pty only returns once it has been reaped. Call Pty::wait inside f to let the child finish on its own and to get its exit code.

    Prefer this over spawn when the pty's lifetime is a lexical scope and no task group with that lifetime exists yet: spawn keeps the pty open until its task group exits, so a long-lived group that spawns many ptys accumulates their file descriptors.

    rows, cols, file, args, extra_env, inherit_env and cwd are those of spawn, with the same defaults.

    Do not let the Pty escape f: it is closed afterwards, and a task still blocked reading it is not woken up. When tasks need to read or write the pty concurrently, open a task group for them and spawn the pty into that group directly, rather than nesting one inside with_pty.