SugarPty
Pseudo-terminal primitives — open / spawn / read / write / resize
Open a master/slave PTY pair, spawn a child process with its stdin/stdout/stderr wired to the slave, and pump bytes / forward resizes between the host terminal and the child. Wraps the libc PTY syscalls (posix_openpt, grantpt, unlockpt, ptsname_r, ioctl(TIOCSWINSZ)) via ext-ffi — no shelling out to /usr/bin/script, no C extension to compile (where FFI cannot answer, fallbacks exist only for termios (stty(1)), macOS size reads (stty(1)), and exit detection (proc_get_status polling) — with ffi.enable=0 the core open/read/write/kill path has no fallback and throws).
Install
composer require sugarcraft/sugar-pty
Requires PHP 8.3+ with ext-ffi. ext-pcntl is optional — the lib polls waitpid() when pcntl is absent and SignalForwarder degrades to a no-op. ext-posix is optional too — kill() signals through Libc::kill(), which uses posix_kill() when it is loaded and libc kill(2) over FFI otherwise.
Open + spawn + drain
use SugarCraft\Pty\PtySystemFactory;
$system = PtySystemFactory::new();
$pair = $system->open(100, 30); // master/slave pair
$child = $pair->slave()->spawn(
['/bin/bash', '-c', 'echo $TERM; date'],
env: [...(array) getenv(), 'TERM' => 'xterm-256color'], // $env REPLACES the child env
);
$master = $pair->master();
$out = '';
while (($chunk = $master->read(4096)) !== '') { // '' = confirmed EOF
if ($chunk !== null) { // null = timed out (0.05 s default)
$out .= $chunk;
}
}
$exit = $child->wait();
$master->close();
Drain until EOF instead of polling exited() first — a fast child's final bytes can sit in the master buffer before the reap, and an exited()-first loop drops them. PosixPump::run() implements this loop (with callbacks) if you prefer not to hand-roll it.
Resize forwarding
use SugarCraft\Pty\SignalForwarder;
use SugarCraft\Core\Util\Tty;
$tty = new Tty(STDIN); // the host terminal
SignalForwarder::attachSigwinch(
$master,
fn () => $tty->size(), // ['cols' => N, 'rows' => N]
);
// Now every host SIGWINCH triggers $master->resize($cols, $rows).
// For raw /dev/tty fds (no MasterPty object):
$ttyFd = \SugarCraft\Pty\Libc::lib()->open('/dev/tty', 0x0002); // O_RDWR
SignalForwarder::attachSigwinchToFd(
$ttyFd,
fn () => $tty->size(),
fn (int $cols, int $rows) => null, // optional post-resize callback
);
What's in the box
PtySystemFactory)Allocates a master/slave pair by delegating to PosixPtySystem::open(), so the facade shares the canonical path exactly. On macOS: openpty(3) first (single call), falls back to posix_openpt + grantpt + unlockpt + ptsname_r on -1. On Linux: the quartet directly (openpty lives in libutil.so.1 on most distros). The master fd is FD_CLOEXEC (children never inherit it, so closing it delivers the hangup) and the requested winsize is applied at open best-effort — a refused ioctl surfaces as 0×0 until the next resize rather than failing the open. Failures close the master fd before throwing — callers never get a half-open Pty.proc_open's [0,1,2] descriptor slots. TIOCSWINSZ is applied before the child starts (throwing, with no child, on failure) and re-asserted best-effort after it, because macOS zeroes the winsize when the child's slave descriptors open. Pass controllingTerminal: true to route through bin/pty-shim.php for Ctrl+C → SIGINT delivery (requires ext-pcntl). Returns a Child with pid() + idempotent wait() + non-blocking exited().Contract\MasterPty has no such member; contract users hold the same lever through stream_set_blocking($master->stream(), $blocking))read($len, $timeout = 0.05) returns null on timeout, '' on confirmed EOF, bytes otherwise; pass null for a mode-governed blocking read. Non-blocking + stream_select with EINTR retry. write returns bytes actually written.size() reads back via TIOCGWINSZ on Linux — on macOS both the set and read directions fall back to stty(1) through a dup’d fd alias (a CLOEXEC master is invisible under /dev/fd there). Platform-aware constants for Linux + macOS.PtySystem contract (open(cols, rows) → pair with master() / slave()). $pair->slave()->spawn() applies an explicit $cols/$rows on every spawn (creack/pty StartWithSize()); omit both to keep the size the pair was opened or last resized with. The parent's slave handle is opened O_CLOEXEC, so the child holds the slave only at fds 0-2. PtySystemFactory::default() remains as a deprecated alias.Pty::resize() via a caller-supplied size provider, plus optional SIGCHLD reaper. Defaults pcntl_async_signals(true); falls back cleanly when pcntl is missing.Child::exited() and Child::wait() use a waitpid(pid, &status, WNOHANG) FFI call as the first exit probe — sub-ms detection instead of the 10 ms proc_get_status poll. If FFI is unavailable, falls back to proc_get_status transparently. Signal-terminated exit codes follow the Unix convention: 128 + signal_number.setsid() + ioctl(fd, TIOCSCTTY, 0) to claim a fd as the session's controlling terminal. Used by the controllingTerminal: true shim path; callable directly from FFI-heavy code that needs the same effect without the PHP shim overhead. Throws PtyException on failure.onIdle (idle tick), onSigwinch (polled size-diff observer on idle ticks — not a signal hook; never fires while the size is 0×0), onChildExit (child exit), and recorder (session tap) callbacks. Wire via PumpOptions::withOnIdle() / withOnSigwinch() / withOnChildExit() / withRecorder(). Back-pressure: when the master accepts only part of a stdin chunk, the pump parks the remainder, stops reading stdin and waits for the master to drain it — input is never reordered or grown without bound, and VEOF is sent only behind the last data byte.libc.so.6 on Linux, /usr/lib/libSystem.B.dylib on macOS. Override via env var for musl, Alpine, or custom sysroots.posix-ffi (default on POSIX; selecting it on Windows silently resolves to conpty — POSIX FFI is not offered there, so you get ConPTY semantics), conpty (auto-resolved on Windows, throws on POSIX), sidecar and pecl (reserved — selecting them throws UnsupportedPlatformException in this release), auto (platform-resolving, same as unset). Unrecognised values throw InvalidArgumentException. See the full backend selection table in the README.Use it for
- In-process SSH session hosting — drives SugarSshServer away from depending on host sshd; spawn the user's shell directly inside the SSH server process with full PTY control.
- Recorded TUI sessions — pair with CandyVcr to capture both the input bytes (typed into the master) and the rendered output (read back from the master).
- Test harnesses for ANSI-emitting CLIs — spawn the binary under test in a controlled PTY, pump fixture input, assert on the captured output via SugarVterm's cell-grid.
- VHS-style demo recorders — run a script in a PTY, capture the byte stream + winsize, replay later.
Controlling terminal (Ctrl+C, job control)
Pass controllingTerminal: true to spawn() when you need Ctrl+C typed at the master to deliver SIGINT to the child — required for interactive shells (bash -i), editors (vim, less), and anything else that uses tty-driven job control.
$system = PtySystemFactory::new();
$pair = $system->open();
$child = $pair->slave()->spawn(
['/bin/bash', '-i'],
env: [...(array) getenv(), 'TERM' => 'xterm-256color'],
controllingTerminal: true, // claim slave as the child's ctty
);
$pair->master()->write("\x03"); // Ctrl+C → SIGINT to the child
Routes the spawn through bin/pty-shim.php, which does setsid() + ioctl(0, TIOCSCTTY, 0) + pcntl_exec() between proc_open and the actual cmd. Requires ext-pcntl. Costs single-digit-to-low-double-digit milliseconds of shim startup per spawn (an unmeasured estimate — treat as order-of-magnitude) — opt-in because non-interactive spawns don't benefit.
Known limitations
- Windows ConPTY caveats. The
Windows\ConPtySystembackend needs Windows 10 1809+ and PHP 8.4+ with ext-ffi; the pseudo console is not a PTY — no controlling terminal, every signal collapses to one job terminate, andstream()/fd()throw, so the pumps stay POSIX-only (pollread($len, $timeout)instead). ffi.enable=0silently disables FFI. Many distributions ship PHP withffi.enable=0inphp.ini; FFI then refuses to load libc and sugar-pty throwsPtyException: Failed to load libc(or, where a fallback exists, transparently uses it: stty Termios, stty macOS size reads,proc_get_statuspolling). Setffi.enable=1(PHP_INI_SYSTEM—ini_set()cannot change it at runtime); PHP 8.3 accepts only0,1,preload, and an unrecognised string such aspeercasts to0. Verify what your PHP actually answered:php -r 'try { FFI::cdef("int getpid(void);"); echo "FFI cdef OK\n"; } catch (Throwable $e) { echo get_class($e), ": ", $e->getMessage(), "\n"; }'
Source & demos
- Source on GitHub (split repo; monorepo home: detain/sugarcraft,
sugar-pty/) - Full README
- Runnable examples
- Originally inspired by charmbracelet/x/xpty (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| Pty (deprecated facade; removed v2.0) | open(cols = 80, rows = 24) | Allocate master/slave PTY pair (FD_CLOEXEC master, winsize applied at open) |
| Pty (deprecated facade; removed v2.0) | spawn(cmd, env, cols = null, rows = null, controllingTerminal = false) | (facade) Spawn child with PTY; explicit geometry applied before the spawn and re-asserted after it, null keeps the pair's current size |
| Pty (deprecated facade; removed v2.0) | read(len, timeout = 0.05) | Read bytes from PTY; null timeout = mode-governed blocking |
| Pty (deprecated facade; removed v2.0) | write(data) | Write bytes to PTY |
| Pty (deprecated facade; removed v2.0) | resize(cols, rows) | Resize terminal window |
| Pty (deprecated facade; removed v2.0) | size() | Get current terminal size |
| Pty (deprecated facade; removed v2.0) | close() | Idempotent; always close(2)s the master fd and throws PtyException if that close (or the stream wrapper's fclose) fails |
| PtySystemFactory | new() | Build the platform PtySystem, honoring SUGARCRAFT_PTY_BACKEND (default() is a deprecated alias) |
| PosixSlavePty | spawn(cmd, env, cols = null, rows = null, controllingTerminal = false) | Spawn on a pair from PtySystem::open(); explicit geometry applied on every spawn, null keeps the pair's current size |
| Libc | kill(pid, signal) | posix_kill() when ext-posix is loaded, libc kill(2) over FFI otherwise |
| TermiosFactory | fallbackCount() | How many times the FFI termios backend fell back to stty (each fallback is also logged) |
| SignalForwarder | attachSigwinch(pty, provider) | Forward SIGWINCH to PTY resize |
| SignalForwarder | attachSigwinchToFd(fd, provider, onResize?) | Forward SIGWINCH to raw /dev/tty fd via TIOCSWINSZ |
| PosixPump | run(master, stdin, stdout, child?, opts?) | Run byte pump with optional PumpOptions callbacks |
| PumpOptions | withOnIdle(fn) | Register idle-tick callback (fires every stream_select timeout) |
| PumpOptions | withOnSigwinch(fn(cols, rows)) | Register resize observer — fires when the pump polls a size change on an idle tick (not a signal hook; silent for 0×0 sessions; MultiPump never delivers it) |
| PumpOptions | withOnChildExit(fn(code)) | Register child-exit callback |
| PumpOptions | withRecorder(recorder) | Attach session recorder (tee stdin/master bytes) |
| PumpOptions | sshDefault() | Identity preset — returns the stock defaults (the values InProcessTransport previously hardcoded — it now consumes the preset); kept for call-site intent |
| Child | pid() | Child process ID — the contract type Contract\Child declares only the method; the public readonly int $pid property exists on the concrete PosixChild/Child classes but fatals behind a contract type |
| Child | exited(), wait() | Check/await child exit (wait() probes via WNOHANG first; signal deaths surface as 128+signo) |
| Child | kill(signal) | Signal the child; no-op once reaped, PtyException when the kill(2) itself fails |
| ControllingTerminal | claim(fd) | Claim a fd as controlling terminal via setsid() + ioctl(TIOCSCTTY) |
| Expect | on(master) / send() / expectAny() / expectPattern() / expectEof() | Bounded scripted automation over a master: needles, regex, stall-protected sends |
| PtyPool | acquire(cols, rows) / release(pair) / drain() | Concurrency ceiling on live pairs (in-flight slots are weak — abandoned pairs free their slot) |
| PtyInputDecoder | readEvents(timeout) / readEventsBlocking(timeout?) / isEof() / remainder() / reset() | Master bytes → key/mouse events via sugar-input's EscapeDecoder; empty readEvents() is ambiguous — isEof() is the only end-of-stream signal |
| AnsiOutputParser + SgrHandler | forMaster(master) / readChunk(timeout) / readChunkWithTransitions(timeout) / state() / reset() | Verbatim byte reads with optimistic SGR state tracking (OSC not tracked); SgrHandler adds drainTransitions() / reset() on a 1024-entry drop-oldest ring |
| PosixProcess | wait() / kill() / exitCode() / stdoutBytes() | Plain proc_open child with pipe capture (no PTY) |
| ReactPump | start() / stop() | The byte pump driven by the ReactPHP event loop instead of a blocking select |
| MultiPump | add(master, stdoutSink, child?, opts?) / tick() / runAsync() | Multiplex many sessions on one loop (sync tick delivers keepalive; callbacks ride PosixPump/ReactPump) |