PTY Pseudo-Terminal openpty() Master-Slave Redirection & Character Stream Control
Decrypting tools/environments/local.py pseudo-terminal pair allocation, multi-threaded read/write pump details
📊 Fig 9-1-1: Host sandbox controller and isolated environment (PTY master-slave devices) bidirectional redirection pipeline diagram
💻 1. local.py's openpty() Pipe Pump Characters
When the LLM needs to execute interactive commands, the system uses the Unix pty.openpty() to open a pseudo-terminal pair. The slave device is bound to the Bash shell subprocess's stdin/stdout/stderr, and a background daemon thread performs os.read() on the master device in real-time, streaming ANSI control characters to the interface renderer.
📊 Fig 9-1-2: Standard I/O redirection, host directory mount & Docker container sandbox boundary diagram
🔄 2. Bidirectional Redirection Pump Implementation
The main process can write characters through the Master FD to simulate input, while an independent thread streams output from the slave device, handling special keyboard control signals (such as Ctrl+C/Ctrl+D) to ensure consistency with a real terminal during rendering.