71 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-11-17 10:07:18 -05:00
import { CommandHandle, Sandbox } from "e2b"
2024-09-05 12:32:32 -07:00
// Terminal class to manage a pseudo-terminal (PTY) in a sandbox environment
export class Terminal {
2024-11-17 10:07:18 -05:00
private pty: CommandHandle | undefined // Holds the PTY process handle
2024-10-19 05:25:26 -06:00
private sandbox: Sandbox // Reference to the sandbox environment
2024-09-05 12:32:32 -07:00
// Constructor initializes the Terminal with a sandbox
constructor(sandbox: Sandbox) {
2024-10-19 05:25:26 -06:00
this.sandbox = sandbox
2024-09-05 12:32:32 -07:00
}
// Initialize the terminal with specified rows, columns, and data handler
async init({
rows = 20,
cols = 80,
onData,
}: {
2024-10-19 05:25:26 -06:00
rows?: number
cols?: number
onData: (responseData: string) => void
2024-09-05 12:32:32 -07:00
}): Promise<void> {
// Create a new PTY process
this.pty = await this.sandbox.pty.create({
rows,
cols,
2024-11-17 10:07:18 -05:00
timeoutMs: 0,
2024-09-05 12:32:32 -07:00
onData: (data: Uint8Array) => {
2024-10-19 05:25:26 -06:00
onData(new TextDecoder().decode(data)) // Convert received data to string and pass to handler
2024-09-05 12:32:32 -07:00
},
2024-10-19 05:25:26 -06:00
})
2024-09-05 12:32:32 -07:00
}
// Send data to the terminal
async sendData(data: string) {
if (this.pty) {
2024-10-19 05:25:26 -06:00
await this.sandbox.pty.sendInput(
this.pty.pid,
new TextEncoder().encode(data)
)
2024-09-05 12:32:32 -07:00
} else {
2024-10-19 05:25:26 -06:00
console.log("Cannot send data because pty is not initialized.")
2024-09-05 12:32:32 -07:00
}
}
// Resize the terminal
async resize(size: { cols: number; rows: number }): Promise<void> {
if (this.pty) {
2024-10-19 05:25:26 -06:00
await this.sandbox.pty.resize(this.pty.pid, size)
2024-09-05 12:32:32 -07:00
} else {
2024-10-19 05:25:26 -06:00
console.log("Cannot resize terminal because pty is not initialized.")
2024-09-05 12:32:32 -07:00
}
}
// Close the terminal, killing the PTY process and stopping the input stream
async close(): Promise<void> {
if (this.pty) {
2024-10-19 05:25:26 -06:00
await this.pty.kill()
2024-09-05 12:32:32 -07:00
} else {
2024-10-19 05:25:26 -06:00
console.log("Cannot kill pty because it is not initialized.")
2024-09-05 12:32:32 -07:00
}
}
}
// Usage example:
// const terminal = new Terminal(sandbox);
// await terminal.init();
// terminal.sendData('ls -la');
// await terminal.resize({ cols: 100, rows: 30 });
2024-10-19 05:25:26 -06:00
// await terminal.close();