Skip to content

Pseudo Terminal (PTY)

PTY endpoints let you create interactive terminal sessions with a persistent shell process. Connect via WebSocket for real-time bidirectional I/O, similar to SSH or a browser-based terminal.

Create a terminal session with a shell process.

By default, the shell starts when the PTY session is created. If you set lazy_start: true, Leap0 creates the PTY session first and waits to start the shell until the first WebSocket connection is opened for that session.

from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.create(
session_id="my-terminal",
cols=120,
rows=40,
cwd="/home/user",
envs={"TERM": "xterm-256color"},
)
print(session.id, session.cwd, session.cols, session.rows)

Use lazy_start: true when you want to create the PTY session now but wait to start the shell until the first WebSocket connection.

from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.create(
session_id="lazy-terminal",
cwd="/workspace",
cols=120,
rows=40,
lazy_start=True,
)
print(session.id, session.lazy_start)

Open a WebSocket connection for interactive terminal I/O. All messages are binary frames containing raw terminal bytes.

from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.get("my-terminal")
connection = sandbox.pty.connect(session.id)
try:
connection.send("ls -la
")
print(connection.recv().decode("utf-8", errors="replace"), end="")
finally:
connection.close()

Change the terminal dimensions while connected.

from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.resize("my-terminal", cols=200, rows=50)
print(session.cols, session.rows)
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
for session in sandbox.pty.list():
print(session.id, session.active)

Kill the shell process and remove the session.

from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.pty.delete("my-terminal")