1
import type { Connection, Json } from "./connection.ts";3
/** Input larger than this goes to the daemon in several writes; frames are at most 16 MiB. */4
const WRITE_CHUNK = 1024 * 1024;6
export interface TerminalOptions {7
/** Working directory of the program; it must exist. */8
cwd: string;9
/** Program and arguments. Default: the user's shell (`SHELL` in `env` or the daemon's environment) as a login shell. */10
argv?: readonly string[];11
/** Added to the daemon's environment, or the whole environment with `inheritEnv: false`. Set `TERM` here. */12
env?: Record<string, string>;13
inheritEnv?: boolean;14
cols: number;15
rows: number;16
/** The terminal's raw output, in order. */17
onData: (bytes: Uint8Array) => void;18
}20
/** The foreground job of a terminal: its process group id, and its leader's name if the system tells. */21
export interface TerminalForeground {22
pid: number;23
name?: string;24
}26
/**27
* A program running in a pseudo-terminal of a pi-env daemon. It ends when the program exits, `close()` kills it, or28
* the connection is lost (the daemon then kills it).29
*/30
export class RemoteTerminal {31
readonly pid: number;32
/** The exit code; rejects with the daemon's error, with code `aborted` after `close()`. */33
readonly exited: Promise<number>;34
readonly #connection: Connection;35
readonly #id: number;36
readonly #session: number;37
readonly #abort: AbortController;39
constructor(40
connection: Connection,41
id: number,42
session: number,43
pid: number,44
exited: Promise<number>,45
abort: AbortController,46
) {47
this.#connection = connection;48
this.#id = id;49
this.#session = session;50
this.pid = pid;51
this.exited = exited;52
this.#abort = abort;53
}55
/** Send input; once the terminal has ended, input is dropped. */56
write(data: Uint8Array | string): void {57
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;58
for (let offset = 0; offset < bytes.length; offset += WRITE_CHUNK) {59
this.#request("ptyWrite", {}, bytes.subarray(offset, offset + WRITE_CHUNK));60
}61
}63
/** Change the size; the program receives `SIGWINCH`. */64
resize(cols: number, rows: number): void {65
this.#request("ptyResize", { cols, rows });66
}68
/** Kill the program and everything in its session. */69
close(): void {70
this.#abort.abort();71
}73
/**74
* The job in the terminal's foreground when it is not the program itself: what a shell runs, such as an editor.75
* Undefined while the program is in front (a shell at its prompt). Rejects once the terminal has ended.76
*/77
async foreground(): Promise<TerminalForeground | undefined> {78
const reply = await this.#connection.request("ptyForeground", { target: this.#id }, { session: this.#session });79
const foreground = reply.json.foreground as { pid: number; name: string | null } | null;80
if (!foreground) return undefined;81
return { pid: foreground.pid, ...(foreground.name ? { name: foreground.name } : {}) };82
}84
#request(op: string, json: Json, payload?: Uint8Array): void {85
this.#connection86
.request(op, { ...json, target: this.#id }, { session: this.#session, ...(payload ? { payload } : {}) })87
// A terminal that ended or a lost connection: `exited` reports it.88
.catch(() => {});89
}90
}92
/** Start a program in a new pseudo-terminal of the daemon behind `connection`. */93
export function openTerminal(connection: Connection, options: TerminalOptions): Promise<RemoteTerminal> {94
const abort = new AbortController();95
const started = Promise.withResolvers<RemoteTerminal>();96
let request: { id: number; session: number } | undefined;97
const exited = connection98
.request(99
"pty",100
{101
cwd: options.cwd,102
...(options.argv === undefined ? {} : { argv: options.argv }),103
...(options.env === undefined ? {} : { env: options.env }),104
...(options.inheritEnv === undefined ? {} : { inheritEnv: options.inheritEnv }),105
cols: options.cols,106
rows: options.rows,107
},108
{109
signal: abort.signal,110
onStart: (id, session) => {111
request = { id, session };112
},113
onEvent: (json, payload) => {114
if (json.kind === "output") options.onData(payload);115
else if (json.kind === "started" && request) {116
started.resolve(117
new RemoteTerminal(connection, request.id, request.session, Number(json.pid), exited, abort),118
);119
}120
},121
},122
)123
.then((reply) => Number(reply.json.exitCode));124
// Failing before it started rejects the open; afterwards, `exited` carries it.125
exited.catch(started.reject);126
return started.promise;127
}