@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/alpd.js +29928 -14898
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +34 -1
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +154 -2
- package/dist/files.js +392 -68
- package/dist/git.d.ts +93 -0
- package/dist/git.js +1192 -0
- package/dist/gitignore.d.ts +5 -0
- package/dist/gitignore.js +7 -1
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +21 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +43 -11
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +198 -0
- package/dist/operations.d.ts +8 -2
- package/dist/operations.js +20 -10
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +296 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +14 -2
- package/dist/server.js +836 -90
- package/dist/store.d.ts +72 -2
- package/dist/store.js +111 -4
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +193 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +29 -0
- package/dist/windows-terminal.js +122 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +70 -7
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +528 -82
- package/src/git.ts +1140 -0
- package/src/gitignore.ts +10 -0
- package/src/history.ts +118 -0
- package/src/index.ts +7 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +37 -12
- package/src/native-terminal.ts +122 -0
- package/src/operations.ts +27 -11
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +432 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +948 -102
- package/src/store.ts +117 -4
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +641 -0
- package/src/windows-terminal.ts +123 -0
- package/src/worktrees.ts +382 -0
package/src/terminals.ts
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { access, lstat, readFile } from 'node:fs/promises';
|
|
5
|
+
import { nativePtySpawn, nativeTerminalCapability, type CleanupResult } from './native-terminal.js';
|
|
6
|
+
import { windowsPtySpawn, windowsShell, windowsTerminalCapability } from './windows-terminal.js';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { ERROR, RPC_ERROR, TERMINAL, TERMINAL_LIMIT_KEYS, isTerminalId } from '@anhlp/alp-protocol';
|
|
9
|
+
import type { TerminalEndReason, TerminalEvent, TerminalInfo, TerminalLimits } from '@anhlp/alp-protocol/rpc';
|
|
10
|
+
import { RpcError } from './rpc-error.js';
|
|
11
|
+
import { TerminalScreen, SCREEN_LIMITS } from './terminal-screen.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Terminals (capability `terminal`, docs/protocol/alp-json-rpc-v1.md §12.10, issue #121 H): a real
|
|
15
|
+
* PTY running a shell on this host **as the daemon's account**. A workspace chooses only where the
|
|
16
|
+
* shell starts and who sees the terminal; it is not a sandbox. alpd serves terminals only while the
|
|
17
|
+
* host owner opted in (`<ALP_HOME>/terminal.json` `allowRemoteTerminal`, an owner-private file no RPC
|
|
18
|
+
* writes), on macOS and Linux when the shipped native owner validates its capability (Linux may be
|
|
19
|
+
* best-effort `root-only`), and on Windows through node-pty/ConPTY (best-effort, `protection: 'none'`). Lifecycle is audited;
|
|
20
|
+
* input, output and the environment never are.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Who a call acts for, as for attachments: a gateway's credential and grant epoch, or the owner. */
|
|
24
|
+
export type TerminalPrincipal = { id: string; epoch: string; roots?: readonly string[] };
|
|
25
|
+
/** The connection a terminal streams to: alpd's own IPC connection object. */
|
|
26
|
+
export type TerminalSink = { send(message: unknown): void; socket?: { writableLength: number; destroyed?: boolean } };
|
|
27
|
+
type Disposable = { dispose(): void };
|
|
28
|
+
/** Native owner interface; injected owners are used only by tests. */
|
|
29
|
+
export type PtyProcess = {
|
|
30
|
+
pid: number;
|
|
31
|
+
/** The PTY's device (node-pty's UnixTerminal), such as /dev/ttys004 or /dev/pts/3. */
|
|
32
|
+
readonly ptsName?: string;
|
|
33
|
+
write(data: string): void;
|
|
34
|
+
resize(cols: number, rows: number): void;
|
|
35
|
+
kill(signal?: string): void;
|
|
36
|
+
cleanup?: () => Promise<CleanupResult>;
|
|
37
|
+
onData(listener: (data: string) => void): Disposable;
|
|
38
|
+
onExit(listener: (event: { exitCode: number | null; signal?: number }) => void): Disposable;
|
|
39
|
+
};
|
|
40
|
+
/** Absent: full native protection. root-only: best-effort Linux. none: Windows platform PTY. */
|
|
41
|
+
export type TerminalProtection = 'root-only' | 'none';
|
|
42
|
+
export type PtySpawn = (file: string, args: string[], options: { name: string; cols: number; rows: number; cwd: string; env: Record<string, string>; killGraceMs?: number; signal?: AbortSignal; protection?: TerminalProtection }) => PtyProcess | Promise<PtyProcess>;
|
|
43
|
+
/** One process: ids, (Linux) session, controlling tty, age, and the terminal markers in its environment. */
|
|
44
|
+
export type ProcessRow = { pid: number; ppid: number; pgid: number; sid?: number; tty?: string; elapsedMs: number; markers?: string[] };
|
|
45
|
+
type Log = { info(message: string, fields?: Record<string, unknown>): void; warn(message: string, fields?: Record<string, unknown>): void };
|
|
46
|
+
|
|
47
|
+
export type TerminalServiceOptions = {
|
|
48
|
+
home: string;
|
|
49
|
+
/** The canonical directory of a registry workspace, or a RegistryError-like refusal. */
|
|
50
|
+
resolveWorkspace(workspaceId: string): Promise<string>;
|
|
51
|
+
log: Log;
|
|
52
|
+
/** Lower limits (tests, an embedding host); never higher than TERMINAL. */
|
|
53
|
+
limits?: Partial<TerminalLimits>;
|
|
54
|
+
now?: () => number;
|
|
55
|
+
platform?: NodeJS.Platform;
|
|
56
|
+
/** Test hook: the PTY owner; production uses only the identity-bound native owner. */
|
|
57
|
+
spawn?: PtySpawn;
|
|
58
|
+
/** Test hook: capability result; production always verifies the shipped helper. */
|
|
59
|
+
capability?: typeof nativeTerminalCapability;
|
|
60
|
+
/** Test hook: the process table; default `ps`. */
|
|
61
|
+
processes?: () => Promise<ProcessRow[]>;
|
|
62
|
+
sweepMs?: number;
|
|
63
|
+
killGraceMs?: number;
|
|
64
|
+
/** Bytes of terminal events waiting on a connection's socket before it counts as a slow consumer. */
|
|
65
|
+
maxBufferedBytes?: number;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
type Frame = { seq: number; data: string; bytes: number };
|
|
69
|
+
type Terminal = {
|
|
70
|
+
id: string;
|
|
71
|
+
principal: { id: string; epoch: string };
|
|
72
|
+
workspaceId: string;
|
|
73
|
+
root: string;
|
|
74
|
+
protection?: TerminalProtection;
|
|
75
|
+
title: string;
|
|
76
|
+
cols: number;
|
|
77
|
+
rows: number;
|
|
78
|
+
pty: PtyProcess;
|
|
79
|
+
screen: TerminalScreen;
|
|
80
|
+
pid: number;
|
|
81
|
+
/** The PTY's device as ps names it (ttys004, pts/3): a controlling terminal outlives double forks. */
|
|
82
|
+
tty?: string;
|
|
83
|
+
createdAt: number;
|
|
84
|
+
lastActivityAt: number;
|
|
85
|
+
expiresAt: number;
|
|
86
|
+
requestKey: string;
|
|
87
|
+
ring: Frame[];
|
|
88
|
+
ringBytes: number;
|
|
89
|
+
nextSeq: number;
|
|
90
|
+
sink?: TerminalSink;
|
|
91
|
+
detachedAt?: number;
|
|
92
|
+
/** Informational terminal marker only; NEVER used to discover or signal processes. */
|
|
93
|
+
marker: string;
|
|
94
|
+
ending?: TerminalEndReason;
|
|
95
|
+
exit?: { seq: number; exitCode: number | null; signal: number | null; reason: TerminalEndReason; at: number };
|
|
96
|
+
disposables: Disposable[];
|
|
97
|
+
reaped?: Promise<void>;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const SWEEP_MS = 5_000;
|
|
101
|
+
const KILL_GRACE_MS = 1_000;
|
|
102
|
+
const MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
|
|
103
|
+
const CONFIG_FILE = 'terminal.json';
|
|
104
|
+
/** Variables of alpd's own environment a terminal does not inherit. */
|
|
105
|
+
const PRIVATE_ENV = /^(ALP_|npm_)/i;
|
|
106
|
+
|
|
107
|
+
const notFound = () => new RpcError(ERROR.notFound, 'No such terminal', { reason: 'not_found' });
|
|
108
|
+
const iso = (ms: number) => new Date(ms).toISOString();
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The host switch and the operator's lower limits. Anything but a regular, owner-private file of
|
|
112
|
+
* this user saying `"allowRemoteTerminal": true` is off.
|
|
113
|
+
*/
|
|
114
|
+
export async function readTerminalConfig(home: string, log?: Log, platform: NodeJS.Platform = process.platform): Promise<{ enabled: boolean; reason?: string; limits: TerminalLimits; paseo: boolean }> {
|
|
115
|
+
const defaults = Object.fromEntries(TERMINAL_LIMIT_KEYS.map(key => [key, TERMINAL[key as keyof typeof TERMINAL]])) as TerminalLimits;
|
|
116
|
+
const file = path.join(home, CONFIG_FILE);
|
|
117
|
+
const info = await lstat(file).catch(() => undefined);
|
|
118
|
+
if (!info) return { enabled: false, reason: 'missing', limits: defaults, paseo: false };
|
|
119
|
+
// Windows reports regular files as 0o666/0o444 (no POSIX group/other bits), so the mode check is POSIX-only;
|
|
120
|
+
// there the file lives in the owner's profile, as do the gateway credentials.
|
|
121
|
+
if (!info.isFile() || (process.getuid && info.uid !== process.getuid()) || (platform !== 'win32' && (info.mode & 0o077))) {
|
|
122
|
+
log?.warn('terminal.json is not a private file of the daemon user; terminals stay off', { code: 'ALPD_TERMINAL_CONFIG' });
|
|
123
|
+
return { enabled: false, reason: 'not_private', limits: defaults, paseo: false };
|
|
124
|
+
}
|
|
125
|
+
let value: any;
|
|
126
|
+
try { value = JSON.parse(await readFile(file, 'utf8')); } catch {
|
|
127
|
+
log?.warn('terminal.json is not valid JSON; terminals stay off', { code: 'ALPD_TERMINAL_CONFIG' });
|
|
128
|
+
return { enabled: false, reason: 'invalid', limits: defaults, paseo: false };
|
|
129
|
+
}
|
|
130
|
+
if (!value || typeof value !== 'object' || value.version !== 1) return { enabled: false, reason: 'invalid', limits: defaults, paseo: false };
|
|
131
|
+
const limits = { ...defaults };
|
|
132
|
+
if (value.limits && typeof value.limits === 'object') {
|
|
133
|
+
for (const [key, raw] of Object.entries(value.limits)) {
|
|
134
|
+
if (!(TERMINAL_LIMIT_KEYS as readonly string[]).includes(key) || !Number.isSafeInteger(raw) || (raw as number) < 1) { log?.warn(`terminal.json limit ${key} ignored`, { code: 'ALPD_TERMINAL_CONFIG' }); continue; }
|
|
135
|
+
const k = key as keyof TerminalLimits;
|
|
136
|
+
if ((raw as number) > defaults[k]) { log?.warn(`terminal.json limit ${key} is above the maximum; ignored`, { code: 'ALPD_TERMINAL_CONFIG' }); continue; }
|
|
137
|
+
limits[k] = raw as number;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// allowPaseoTerminal: Paseo app devices paired through the relay act as the owner and hold no
|
|
141
|
+
// terminal.exec; the Paseo bridge offers terminals only with this second, separate opt-in.
|
|
142
|
+
return value.allowRemoteTerminal === true ? { enabled: true, limits, paseo: value.allowPaseoTerminal === true } : { enabled: false, reason: 'off', limits, paseo: false };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** `[[dd-]hh:]mm:ss` of ps etime, in milliseconds. */
|
|
146
|
+
function elapsed(text: string) {
|
|
147
|
+
const [days, rest] = text.includes('-') ? text.split('-') : ['0', text];
|
|
148
|
+
const parts = rest!.split(':').map(Number);
|
|
149
|
+
while (parts.length < 3) parts.unshift(0);
|
|
150
|
+
const [h, m, s] = parts as [number, number, number];
|
|
151
|
+
return (((Number(days) * 24 + h) * 60 + m) * 60 + s) * 1000;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const MARKER = /(?:^|\s)ALP_TERMINAL_ID=(atm_[0-9a-f]{32})(?=\s|$)/g;
|
|
155
|
+
const markersOf = (text: string) => [...text.matchAll(MARKER)].map(match => match[1]!);
|
|
156
|
+
const ENTRY = /^ALP_TERMINAL_ID=(atm_[0-9a-f]{32})$/;
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The process table: pid, parent, group, (Linux) session, controlling tty, age, and the terminal
|
|
160
|
+
* markers in each process's environment (macOS: `ps -E`, this user's processes only; Linux:
|
|
161
|
+
* /proc/<pid>/environ, readable for this user's processes).
|
|
162
|
+
*/
|
|
163
|
+
export function psProcesses(platform: NodeJS.Platform = process.platform, options: {
|
|
164
|
+
/** Controlled filesystem seam; production always reads the actual proc entry asynchronously. */
|
|
165
|
+
readEnvironment?: (pid: number) => Promise<string>;
|
|
166
|
+
} = {}): () => Promise<ProcessRow[]> {
|
|
167
|
+
const linux = platform === 'linux';
|
|
168
|
+
// At most 10 s for each ps, even one that does not die at once.
|
|
169
|
+
const run = (args: string[]) => new Promise<string | undefined>(resolve => {
|
|
170
|
+
const child = execFile('ps', args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, killSignal: 'SIGKILL', env: { ...process.env, LC_ALL: 'C' } }, (error, stdout) => { clearTimeout(timer); resolve(error ? undefined : stdout); });
|
|
171
|
+
const timer = setTimeout(() => { child.kill('SIGKILL'); resolve(undefined); }, 10_000);
|
|
172
|
+
});
|
|
173
|
+
return async () => {
|
|
174
|
+
const columns = linux ? 'pid=,ppid=,pgid=,sid=,tty=,etime=' : 'pid=,ppid=,pgid=,tty=,etime=,command=';
|
|
175
|
+
// macOS: `ps -E` appends the environment to the command line (escaping newlines as \012); the
|
|
176
|
+
// command line alone, from a second pass, is cut off first so a marker in arguments never counts.
|
|
177
|
+
const [stdout, plain] = await Promise.all([run(linux ? ['-A', '-o', columns] : ['-A', '-E', '-ww', '-o', columns]), linux ? undefined : run(['-A', '-ww', '-o', 'pid=,command='])]);
|
|
178
|
+
if (stdout === undefined) return [];
|
|
179
|
+
const commands = new Map<number, string>();
|
|
180
|
+
for (const line of plain?.split('\n') ?? []) {
|
|
181
|
+
const match = /^\s*(\d+) (.*)$/.exec(line);
|
|
182
|
+
if (match) commands.set(Number(match[1]), match[2]!);
|
|
183
|
+
}
|
|
184
|
+
const rows: ProcessRow[] = [];
|
|
185
|
+
for (const line of stdout.split('\n')) {
|
|
186
|
+
const cells = line.trim().split(/\s+/);
|
|
187
|
+
if (cells.length < 5) continue;
|
|
188
|
+
const [pid, ppid, pgid] = cells.slice(0, 3).map(Number) as [number, number, number];
|
|
189
|
+
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(ppid) || !Number.isSafeInteger(pgid)) continue;
|
|
190
|
+
const sid = linux ? Number(cells[3]) : undefined;
|
|
191
|
+
const tty = cells[linux ? 4 : 3]!;
|
|
192
|
+
let markers: string[] = [];
|
|
193
|
+
// Linux: one entry of the environment, never a marker inside another variable's value.
|
|
194
|
+
if (linux) { try { markers = (await (options.readEnvironment ? options.readEnvironment(pid) : readFile(`/proc/${pid}/environ`, 'utf8'))).split('\0').flatMap(entry => ENTRY.exec(entry)?.[1] ?? []); } catch {} }
|
|
195
|
+
else {
|
|
196
|
+
// Exactly one space after etime: a command line may itself start with spaces.
|
|
197
|
+
const full = /^\s*(?:\S+\s+){4}\S+ (.*)$/.exec(line)?.[1] ?? '';
|
|
198
|
+
const command = commands.get(pid);
|
|
199
|
+
// The environment is what follows the command line; when the two passes disagree, none.
|
|
200
|
+
if (command !== undefined && full.startsWith(command)) markers = markersOf(full.slice(command.length));
|
|
201
|
+
}
|
|
202
|
+
rows.push({ pid, ppid, pgid, ...(sid !== undefined && Number.isSafeInteger(sid) ? { sid } : {}), ...(/^[?-]+$/.test(tty) ? {} : { tty }), elapsedMs: elapsed(cells[linux ? 5 : 4]!), ...(markers.length ? { markers } : {}) });
|
|
203
|
+
}
|
|
204
|
+
return rows;
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Splits output into frames of at most `max` UTF-8 bytes, never inside a character. */
|
|
209
|
+
export function frames(data: string, max: number): string[] {
|
|
210
|
+
if (Buffer.byteLength(data) <= max) return [data];
|
|
211
|
+
const out: string[] = [];
|
|
212
|
+
let current = '';
|
|
213
|
+
let bytes = 0;
|
|
214
|
+
for (const char of data) {
|
|
215
|
+
const size = Buffer.byteLength(char);
|
|
216
|
+
if (bytes + size > max && current) { out.push(current); current = ''; bytes = 0; }
|
|
217
|
+
current += char;
|
|
218
|
+
bytes += size;
|
|
219
|
+
}
|
|
220
|
+
if (current) out.push(current);
|
|
221
|
+
return out;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function createTerminalService(options: TerminalServiceOptions) {
|
|
225
|
+
const { home, resolveWorkspace, log } = options;
|
|
226
|
+
const now = options.now ?? Date.now;
|
|
227
|
+
const platform = options.platform ?? process.platform;
|
|
228
|
+
const supported = platform === 'darwin' || platform === 'linux' || platform === 'win32';
|
|
229
|
+
const windows = platform === 'win32';
|
|
230
|
+
const killGraceMs = options.killGraceMs ?? KILL_GRACE_MS;
|
|
231
|
+
const maxBuffered = options.maxBufferedBytes ?? MAX_BUFFERED_BYTES;
|
|
232
|
+
const terminals = new Map<string, Terminal>();
|
|
233
|
+
const requests = new Map<string, string>();
|
|
234
|
+
const watchers = new Map<TerminalSink, { principal: TerminalPrincipal; workspaceId?: string; watchId: string; cursor: string }>();
|
|
235
|
+
const token = () => randomBytes(16).toString('hex');
|
|
236
|
+
function changed(terminal: Terminal) {
|
|
237
|
+
for (const [sink, watch] of watchers) {
|
|
238
|
+
if (watch.principal.id !== terminal.principal.id || watch.principal.epoch !== terminal.principal.epoch || !within(watch.principal, terminal.root) || (watch.workspaceId !== undefined && watch.workspaceId !== terminal.workspaceId)) continue;
|
|
239
|
+
watch.cursor = token();
|
|
240
|
+
try { sink.send({ jsonrpc: '2.0', method: 'terminal.changed', params: { watchId: watch.watchId, cursor: watch.cursor } }); } catch { watchers.delete(sink); }
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function snapshot(principal: TerminalPrincipal, workspaceId?: string) {
|
|
244
|
+
return [...terminals.values()].filter(terminal => terminal.principal.id === principal.id && terminal.principal.epoch === principal.epoch && within(principal, terminal.root) && (workspaceId === undefined || terminal.workspaceId === workspaceId))
|
|
245
|
+
.sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1)).map(info);
|
|
246
|
+
}
|
|
247
|
+
let closed = false;
|
|
248
|
+
let enabled = false;
|
|
249
|
+
let cleanupFault = false;
|
|
250
|
+
type Pending = { principal: TerminalPrincipal; workspaceId: string; controller: AbortController; admitted: boolean; reason?: string; promise: Promise<{ terminal: TerminalInfo }> };
|
|
251
|
+
const pending = new Map<string, Pending>();
|
|
252
|
+
// Explicit injected test owners need no host capability. Production never falls back to node-pty,
|
|
253
|
+
// except on win32: there is no protection helper, so Windows uses node-pty (ConPTY), best-effort.
|
|
254
|
+
const spawner: PtySpawn = options.spawn ?? (windows ? windowsPtySpawn : nativePtySpawn);
|
|
255
|
+
let capability: { available: boolean; protection?: TerminalProtection; reason?: string } | undefined;
|
|
256
|
+
function pty() { capability ??= options.capability?.() ?? (options.spawn ? { available: true } : windows ? windowsTerminalCapability() : nativeTerminalCapability()); return capability.available ? spawner : undefined; }
|
|
257
|
+
const cancel = (entry: Pending, reason: string) => { entry.reason ??= reason; entry.controller.abort(); };
|
|
258
|
+
const refused = (reason: string) => new RpcError(ERROR.unavailable, 'Terminal startup was cancelled or its native owner is unavailable', { reason });
|
|
259
|
+
async function cleanup(owner: PtyProcess, id?: string) {
|
|
260
|
+
if (!owner.cleanup) { owner.kill(); return; } // test owners and the win32 node-pty owner (best-effort)
|
|
261
|
+
const result = await owner.cleanup();
|
|
262
|
+
if (result.coverage === 'root-only') log.info('terminal shell cleanup has reduced coverage; descendants are unmanaged', { code: 'ALPD_TERMINAL_ROOT_ONLY_CLEANUP', terminalId: id, outputOpen: result.outputOpen === true });
|
|
263
|
+
if (result.live || result.uncertain) {
|
|
264
|
+
cleanupFault = true;
|
|
265
|
+
log.warn('native terminal cleanup could not prove all observed processes exited', { code: 'ALPD_TERMINAL_REAP_FAILED', terminalId: id, ...result });
|
|
266
|
+
throw refused('terminal_cleanup_uncertain');
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Effective limits: the operator's, then the caller's lower ones. */
|
|
271
|
+
function effective(config: TerminalLimits): TerminalLimits {
|
|
272
|
+
const limits = { ...config };
|
|
273
|
+
for (const key of TERMINAL_LIMIT_KEYS as readonly (keyof TerminalLimits)[]) {
|
|
274
|
+
const lower = options.limits?.[key];
|
|
275
|
+
if (Number.isSafeInteger(lower) && lower! > 0 && lower! < limits[key]) limits[key] = lower!;
|
|
276
|
+
}
|
|
277
|
+
return limits;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The switch now: off kills every terminal (reason `disabled`). */
|
|
281
|
+
async function state() {
|
|
282
|
+
const config = await readTerminalConfig(home, log, platform);
|
|
283
|
+
const limits = effective(config.limits);
|
|
284
|
+
if (enabled && !config.enabled) {
|
|
285
|
+
log.info('terminals turned off on this host; ending every terminal', { code: 'ALPD_TERMINAL_DISABLED' });
|
|
286
|
+
for (const entry of pending.values()) cancel(entry, 'terminal_disabled');
|
|
287
|
+
for (const terminal of terminals.values()) if (!terminal.exit) void end(terminal, 'disabled').catch(() => {});
|
|
288
|
+
}
|
|
289
|
+
enabled = config.enabled;
|
|
290
|
+
return { enabled: config.enabled, limits };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** The switch, the platform and the owner (native helper; node-pty on win32), or the refusal. */
|
|
294
|
+
async function ready() {
|
|
295
|
+
if (cleanupFault) throw refused('terminal_cleanup_uncertain');
|
|
296
|
+
if (closed) throw new RpcError(ERROR.unavailable, 'alpd is shutting down', { reason: 'terminal_unsupported' });
|
|
297
|
+
if (!supported) throw new RpcError(ERROR.unavailable, 'Terminals are not supported on this host\'s platform', { reason: 'terminal_unsupported' });
|
|
298
|
+
const current = await state();
|
|
299
|
+
if (!current.enabled) throw new RpcError(ERROR.unavailable, 'The host has not allowed remote terminals (alp terminal allow)', { reason: 'terminal_disabled' });
|
|
300
|
+
if (!pty()) throw new RpcError(ERROR.unavailable, 'The native terminal owner is unavailable on this host', { reason: 'terminal_unsupported' });
|
|
301
|
+
return current.limits;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function info(terminal: Terminal): TerminalInfo {
|
|
305
|
+
return {
|
|
306
|
+
terminalId: terminal.id, workspaceId: terminal.workspaceId, title: terminal.title, cols: terminal.cols, rows: terminal.rows,
|
|
307
|
+
state: terminal.exit ? 'exited' : 'running', attached: !!terminal.sink, createdAt: iso(terminal.createdAt),
|
|
308
|
+
lastActivityAt: iso(terminal.lastActivityAt), expiresAt: iso(terminal.expiresAt),
|
|
309
|
+
...(terminal.exit ? { exitCode: terminal.exit.exitCode, signal: terminal.exit.signal, endReason: terminal.exit.reason } : {}),
|
|
310
|
+
...(terminal.protection ? { protection: terminal.protection } : {}),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const audit = (message: string, terminal: Terminal, fields: Record<string, unknown> = {}) =>
|
|
315
|
+
log.info(message, { terminalId: terminal.id, workspaceId: terminal.workspaceId, principal: terminal.principal.id, ...fields });
|
|
316
|
+
|
|
317
|
+
/** The caller's own terminal, in its roots; anything else is the same not_found. */
|
|
318
|
+
function own(principal: TerminalPrincipal, terminalId: unknown): Terminal {
|
|
319
|
+
const terminal = isTerminalId(terminalId) ? terminals.get(terminalId as string) : undefined;
|
|
320
|
+
if (!terminal || terminal.principal.id !== principal.id || terminal.principal.epoch !== principal.epoch || !within(principal, terminal.root)) throw notFound();
|
|
321
|
+
return terminal;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function within(principal: TerminalPrincipal, root: string) {
|
|
325
|
+
if (principal.roots === undefined) return true;
|
|
326
|
+
return principal.roots.some(granted => root === granted || root.startsWith(granted.endsWith(path.sep) ? granted : granted + path.sep));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function send(terminal: Terminal, event: TerminalEvent) {
|
|
330
|
+
const sink = terminal.sink;
|
|
331
|
+
if (!sink) return;
|
|
332
|
+
sink.send({ jsonrpc: '2.0', method: 'terminal.event', params: event });
|
|
333
|
+
if (event.type === 'output' && (sink.socket?.writableLength ?? 0) > maxBuffered) detach(terminal, 'slow_consumer');
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Ends the stream of a terminal (it keeps running for reconnectMs). */
|
|
337
|
+
function detach(terminal: Terminal, reason: 'replaced' | 'slow_consumer' | 'disconnected') {
|
|
338
|
+
const sink = terminal.sink;
|
|
339
|
+
if (!sink) return;
|
|
340
|
+
terminal.sink = undefined;
|
|
341
|
+
terminal.detachedAt = now();
|
|
342
|
+
if (reason !== 'disconnected') sink.send({ jsonrpc: '2.0', method: 'terminal.event', params: { terminalId: terminal.id, type: 'detached', reason } satisfies TerminalEvent });
|
|
343
|
+
changed(terminal);
|
|
344
|
+
audit('terminal detached', terminal, { code: 'ALPD_TERMINAL_DETACHED', reason });
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function output(terminal: Terminal, data: string, limits: TerminalLimits) {
|
|
348
|
+
terminal.lastActivityAt = now();
|
|
349
|
+
terminal.screen.write(data);
|
|
350
|
+
for (const piece of frames(data, limits.maxOutputFrameBytes)) {
|
|
351
|
+
const frame: Frame = { seq: terminal.nextSeq++, data: piece, bytes: Buffer.byteLength(piece) };
|
|
352
|
+
terminal.ring.push(frame);
|
|
353
|
+
terminal.ringBytes += frame.bytes;
|
|
354
|
+
while (terminal.ringBytes > limits.replayBytes && terminal.ring.length > 1) terminal.ringBytes -= terminal.ring.shift()!.bytes;
|
|
355
|
+
send(terminal, { terminalId: terminal.id, type: 'output', seq: frame.seq, data: frame.data });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Native owns discovery, identity-bound signals, and exclusive root reap. */
|
|
360
|
+
function reap(terminal: Terminal) {
|
|
361
|
+
terminal.reaped ??= cleanup(terminal.pty, terminal.id);
|
|
362
|
+
// Preserve rejection for close/revoke/shutdown while avoiding unhandled natural-exit errors.
|
|
363
|
+
void terminal.reaped.catch(() => {});
|
|
364
|
+
return terminal.reaped;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** The shell ended: the exit event, the rest of its tree killed, the record kept for reconnectMs. */
|
|
368
|
+
function exited(terminal: Terminal, exitCode: number | null, signalNumber: number | null) {
|
|
369
|
+
if (terminal.exit) return;
|
|
370
|
+
const reason = terminal.ending ?? 'exited';
|
|
371
|
+
terminal.exit = { seq: terminal.nextSeq++, exitCode, signal: signalNumber, reason, at: now() };
|
|
372
|
+
for (const disposable of terminal.disposables) { try { disposable.dispose(); } catch {} }
|
|
373
|
+
requests.delete(terminal.requestKey);
|
|
374
|
+
send(terminal, { terminalId: terminal.id, type: 'exit', seq: terminal.exit.seq, exitCode, signal: signalNumber, reason });
|
|
375
|
+
changed(terminal);
|
|
376
|
+
audit('terminal ended', terminal, { code: 'ALPD_TERMINAL_ENDED', reason, exitCode, signal: signalNumber });
|
|
377
|
+
void reap(terminal).catch(() => {});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Ends a running terminal for `reason`; resolves once its tree was killed. */
|
|
381
|
+
async function end(terminal: Terminal, reason: TerminalEndReason) {
|
|
382
|
+
if (terminal.exit) return terminal.reaped;
|
|
383
|
+
terminal.ending ??= reason;
|
|
384
|
+
const reaping = reap(terminal);
|
|
385
|
+
await reaping;
|
|
386
|
+
// A clean native completion includes the root reap; preserve an exit if no callback arrived.
|
|
387
|
+
if (!terminal.exit) exited(terminal, null, null);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
let sweeping = false;
|
|
391
|
+
async function sweep() {
|
|
392
|
+
if (closed || sweeping) return;
|
|
393
|
+
sweeping = true;
|
|
394
|
+
try { await sweepOnce(); } finally { sweeping = false; }
|
|
395
|
+
}
|
|
396
|
+
async function sweepOnce() {
|
|
397
|
+
const current = await state().catch(() => undefined);
|
|
398
|
+
if (!current) return;
|
|
399
|
+
const { limits } = current;
|
|
400
|
+
const at = now();
|
|
401
|
+
for (const terminal of [...terminals.values()]) {
|
|
402
|
+
if (terminal.exit) {
|
|
403
|
+
if (at - terminal.exit.at >= limits.reconnectMs) forget(terminal);
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
if (at >= terminal.expiresAt) void end(terminal, 'lifetime').catch(() => {});
|
|
407
|
+
else if (at - terminal.lastActivityAt >= limits.idleMs) void end(terminal, 'idle').catch(() => {});
|
|
408
|
+
else if (!terminal.sink && terminal.detachedAt !== undefined && at - terminal.detachedAt >= limits.reconnectMs) void end(terminal, 'detached').catch(() => {});
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const timer = setInterval(() => void sweep().catch(() => {}), options.sweepMs ?? SWEEP_MS);
|
|
412
|
+
timer.unref?.();
|
|
413
|
+
|
|
414
|
+
/** The approved shell: the daemon user's login shell when /etc/shells lists it, else /bin/sh. */
|
|
415
|
+
async function shell() {
|
|
416
|
+
if (windows) return windowsShell();
|
|
417
|
+
const candidate = process.env.SHELL;
|
|
418
|
+
if (candidate && path.isAbsolute(candidate)) {
|
|
419
|
+
const listed = await readFile('/etc/shells', 'utf8').then(text => text.split('\n').map(line => line.trim()).includes(candidate), () => false);
|
|
420
|
+
if (listed && await access(candidate, constants.X_OK).then(() => true, () => false)) return candidate;
|
|
421
|
+
}
|
|
422
|
+
return '/bin/sh';
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function environment(marker: string) {
|
|
426
|
+
const env: Record<string, string> = {};
|
|
427
|
+
for (const [key, value] of Object.entries(process.env)) if (value !== undefined && !PRIVATE_ENV.test(key)) env[key] = value;
|
|
428
|
+
return { ...env, TERM: 'xterm-256color', COLORTERM: 'truecolor', ALP_TERMINAL: '1', ALP_TERMINAL_ID: marker };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function forget(terminal: Terminal) {
|
|
432
|
+
terminal.screen.dispose();
|
|
433
|
+
terminals.delete(terminal.id);
|
|
434
|
+
changed(terminal);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const running = (filter: (terminal: Terminal) => boolean) => [...terminals.values()].filter(terminal => !terminal.exit && filter(terminal)).length;
|
|
438
|
+
|
|
439
|
+
return {
|
|
440
|
+
/** `terminalLimits` for daemon.hello while terminals are served, else undefined. */
|
|
441
|
+
async advertised(): Promise<TerminalLimits | undefined> {
|
|
442
|
+
if (closed || !supported) return undefined;
|
|
443
|
+
const current = await state().catch(() => undefined);
|
|
444
|
+
return !cleanupFault && current?.enabled && pty() ? current.limits : undefined;
|
|
445
|
+
},
|
|
446
|
+
|
|
447
|
+
create(principal: TerminalPrincipal, params: { workspaceId: string; cols: number; rows: number; requestId: string; protectionAcknowledgment?: 'linux-root-only-v1' /* deprecated, ignored */ }): Promise<{ terminal: TerminalInfo }> {
|
|
448
|
+
const requestKey = JSON.stringify([principal.id, principal.epoch, params.requestId]);
|
|
449
|
+
const existing = pending.get(requestKey);
|
|
450
|
+
if (existing) {
|
|
451
|
+
if (existing.workspaceId !== params.workspaceId) return Promise.reject(new RpcError(ERROR.conflict, 'This requestId created another terminal', { reason: 'request_conflict' }));
|
|
452
|
+
return existing.promise.then(result => { own(principal, result.terminal.terminalId); return result; });
|
|
453
|
+
}
|
|
454
|
+
if (pending.size >= TERMINAL.maxPerDaemon * 2) return Promise.reject(refused('terminal_limit'));
|
|
455
|
+
const entry: Pending = { principal: { ...principal }, workspaceId: params.workspaceId, controller: new AbortController(), admitted: false, promise: undefined! };
|
|
456
|
+
pending.set(requestKey, entry);
|
|
457
|
+
entry.promise = (async () => {
|
|
458
|
+
let process_: PtyProcess | undefined;
|
|
459
|
+
try {
|
|
460
|
+
const limits = await ready();
|
|
461
|
+
const root = await resolveWorkspace(params.workspaceId).catch((error: any) => {
|
|
462
|
+
if (typeof error?.code === 'number' && error.code !== ERROR.failed) throw new RpcError(error.code === ERROR.forbidden ? ERROR.forbidden : ERROR.notFound, error.code === ERROR.forbidden ? 'The workspace directory changed' : 'No workspace with this workspaceId', { reason: error.data?.reason ?? 'not_found' });
|
|
463
|
+
throw error;
|
|
464
|
+
});
|
|
465
|
+
if (!within(principal, root)) throw new RpcError(ERROR.forbidden, 'The workspace is outside this grant', { reason: 'outside_workspace' });
|
|
466
|
+
// Reduced protection (Linux root-only, Windows none) opens directly; clients disclose `protection`.
|
|
467
|
+
const protection = capability?.protection;
|
|
468
|
+
const file = await shell();
|
|
469
|
+
if (cleanupFault) throw refused('terminal_cleanup_uncertain');
|
|
470
|
+
if (entry.reason || closed) throw refused(entry.reason ?? 'terminal_unsupported');
|
|
471
|
+
const repeated = terminals.get(requests.get(requestKey) ?? '');
|
|
472
|
+
if (repeated && !repeated.exit) {
|
|
473
|
+
if (repeated.workspaceId !== params.workspaceId) throw new RpcError(ERROR.conflict, 'This requestId created another terminal', { reason: 'request_conflict' });
|
|
474
|
+
return { terminal: info(repeated) };
|
|
475
|
+
}
|
|
476
|
+
const reserved = (id?: string) => [...pending.values()].filter(other => other.admitted && (id === undefined || other.principal.id === id)).length;
|
|
477
|
+
if (running(terminal => terminal.principal.id === principal.id) + reserved(principal.id) >= limits.maxPerPrincipal) throw new RpcError(ERROR.unavailable, `At most ${limits.maxPerPrincipal} terminals run per principal`, { reason: 'terminal_limit', limit: 'principal' });
|
|
478
|
+
if (running(() => true) + reserved() >= limits.maxPerDaemon) throw new RpcError(ERROR.unavailable, `At most ${limits.maxPerDaemon} terminals run on this host`, { reason: 'terminal_limit', limit: 'daemon' });
|
|
479
|
+
entry.admitted = true;
|
|
480
|
+
const at = now();
|
|
481
|
+
const marker = `atm_${randomBytes(16).toString('hex')}`;
|
|
482
|
+
process_ = await spawner(file, [], { name: 'xterm-256color', cols: params.cols, rows: params.rows, cwd: root, env: environment(marker), killGraceMs, signal: entry.controller.signal, protection });
|
|
483
|
+
const current = await state();
|
|
484
|
+
if (cleanupFault) throw refused('terminal_cleanup_uncertain');
|
|
485
|
+
if (entry.reason || closed || !current.enabled) throw refused(entry.reason ?? (closed ? 'terminal_unsupported' : 'terminal_disabled'));
|
|
486
|
+
const screens = [...terminals.values()].filter(terminal => terminal.screen.available);
|
|
487
|
+
while (screens.length >= SCREEN_LIMITS.retained) {
|
|
488
|
+
const oldest = screens.findIndex(terminal => !!terminal.exit);
|
|
489
|
+
if (oldest < 0) break;
|
|
490
|
+
screens.splice(oldest, 1)[0]!.screen.dispose();
|
|
491
|
+
}
|
|
492
|
+
const terminal: Terminal = {
|
|
493
|
+
id: `term_${randomBytes(16).toString('hex')}`, principal: { id: principal.id, epoch: principal.epoch }, workspaceId: params.workspaceId,
|
|
494
|
+
root, ...(protection ? { protection } : {}), title: path.basename(file).slice(0, 64), cols: params.cols, rows: params.rows, pty: process_, pid: process_.pid, screen: new TerminalScreen(params.cols, params.rows),
|
|
495
|
+
...(typeof process_.ptsName === 'string' && process_.ptsName.startsWith('/dev/') ? { tty: process_.ptsName.slice('/dev/'.length) } : {}),
|
|
496
|
+
createdAt: at, lastActivityAt: at, expiresAt: at + limits.maxLifetimeMs, requestKey, ring: [], ringBytes: 0, nextSeq: 1,
|
|
497
|
+
detachedAt: at, marker, disposables: [],
|
|
498
|
+
};
|
|
499
|
+
terminals.set(terminal.id, terminal);
|
|
500
|
+
requests.set(requestKey, terminal.id);
|
|
501
|
+
terminal.disposables.push(process_.onData(data => output(terminal, data, limits)));
|
|
502
|
+
terminal.disposables.push(process_.onExit(({ exitCode, signal: number }) => exited(terminal, terminal.ending ? null : exitCode, number || null)));
|
|
503
|
+
entry.admitted = false;
|
|
504
|
+
changed(terminal);
|
|
505
|
+
audit('terminal created', terminal, { code: 'ALPD_TERMINAL_CREATED' });
|
|
506
|
+
return { terminal: info(terminal) };
|
|
507
|
+
} catch (error) {
|
|
508
|
+
if (process_) await cleanup(process_);
|
|
509
|
+
const failedCleanup = (error as { cleanupResult?: CleanupResult })?.cleanupResult;
|
|
510
|
+
if (failedCleanup && (failedCleanup.live || failedCleanup.uncertain)) {
|
|
511
|
+
cleanupFault = true;
|
|
512
|
+
log.warn('native startup cleanup was uncertain', { code: 'ALPD_TERMINAL_REAP_FAILED', ...failedCleanup });
|
|
513
|
+
throw refused('terminal_cleanup_uncertain');
|
|
514
|
+
}
|
|
515
|
+
if (entry.reason) throw refused(entry.reason);
|
|
516
|
+
// The helper's capability changed since the probe: re-probe on the next create.
|
|
517
|
+
if ((error as { terminalReason?: string })?.terminalReason) { capability = undefined; throw refused('terminal_unsupported'); }
|
|
518
|
+
if (entry.admitted && !(error instanceof RpcError)) throw refused('terminal_unsupported');
|
|
519
|
+
throw error;
|
|
520
|
+
} finally { pending.delete(requestKey); }
|
|
521
|
+
})();
|
|
522
|
+
return entry.promise;
|
|
523
|
+
},
|
|
524
|
+
|
|
525
|
+
async list(principal: TerminalPrincipal, params: { workspaceId?: string }) {
|
|
526
|
+
if (supported) await state().catch(() => undefined);
|
|
527
|
+
return { terminals: snapshot(principal, params.workspaceId) };
|
|
528
|
+
},
|
|
529
|
+
|
|
530
|
+
async watch(principal: TerminalPrincipal, sink: TerminalSink, params: { workspaceId?: string; after?: string }) {
|
|
531
|
+
await ready();
|
|
532
|
+
const old = watchers.get(sink);
|
|
533
|
+
const same = old && old.principal.id === principal.id && old.principal.epoch === principal.epoch && JSON.stringify(old.principal.roots) === JSON.stringify(principal.roots) && old.workspaceId === params.workspaceId;
|
|
534
|
+
const watch = same ? old : { principal: { ...principal, ...(principal.roots ? { roots: [...principal.roots] } : {}) }, workspaceId: params.workspaceId, watchId: token(), cursor: token() };
|
|
535
|
+
// Register and snapshot in one synchronous step after all configuration awaits.
|
|
536
|
+
watchers.set(sink, watch);
|
|
537
|
+
return { terminals: snapshot(principal, params.workspaceId), watchId: watch.watchId, cursor: watch.cursor, reset: params.after !== watch.cursor };
|
|
538
|
+
},
|
|
539
|
+
async unwatch(sink: TerminalSink) { watchers.delete(sink); return { closed: true as const }; },
|
|
540
|
+
|
|
541
|
+
async capture(principal: TerminalPrincipal, params: { terminalId: string; start?: number; end?: number; stripAnsi?: boolean }) {
|
|
542
|
+
await ready();
|
|
543
|
+
const terminal = own(principal, params.terminalId);
|
|
544
|
+
const result = await terminal.screen.capture(params);
|
|
545
|
+
// Permission/config and record lifetime may have changed while the parser flushed.
|
|
546
|
+
await ready();
|
|
547
|
+
if (own(principal, params.terminalId) !== terminal) throw notFound();
|
|
548
|
+
return result;
|
|
549
|
+
},
|
|
550
|
+
|
|
551
|
+
async attach(principal: TerminalPrincipal, sink: TerminalSink, params: { terminalId: string; after?: number; protectionAcknowledgment?: 'linux-root-only-v1' /* deprecated, ignored */ }) {
|
|
552
|
+
await ready();
|
|
553
|
+
const terminal = own(principal, params.terminalId);
|
|
554
|
+
if (terminal.sink && terminal.sink !== sink) detach(terminal, 'replaced');
|
|
555
|
+
terminal.sink = sink;
|
|
556
|
+
terminal.detachedAt = undefined;
|
|
557
|
+
const after = Math.min(params.after ?? 0, terminal.nextSeq - 1);
|
|
558
|
+
const first = terminal.ring[0]?.seq ?? terminal.nextSeq;
|
|
559
|
+
const lastOutput = terminal.exit ? terminal.exit.seq - 1 : terminal.nextSeq - 1;
|
|
560
|
+
const gap = after + 1 < first && after < lastOutput ? { fromSeq: after + 1, toSeq: Math.min(first, lastOutput + 1) - 1 } : undefined;
|
|
561
|
+
for (const frame of terminal.ring) if (frame.seq > after) sink.send({ jsonrpc: '2.0', method: 'terminal.event', params: { terminalId: terminal.id, type: 'output', seq: frame.seq, data: frame.data } satisfies TerminalEvent });
|
|
562
|
+
if (terminal.exit && terminal.exit.seq > after) sink.send({ jsonrpc: '2.0', method: 'terminal.event', params: { terminalId: terminal.id, type: 'exit', seq: terminal.exit.seq, exitCode: terminal.exit.exitCode, signal: terminal.exit.signal, reason: terminal.exit.reason } satisfies TerminalEvent });
|
|
563
|
+
changed(terminal);
|
|
564
|
+
audit('terminal attached', terminal, { code: 'ALPD_TERMINAL_ATTACHED', after, ...(gap ? { gap: gap.toSeq - gap.fromSeq + 1 } : {}) });
|
|
565
|
+
return { terminal: info(terminal), nextSeq: terminal.nextSeq, ...(gap ? { gap } : {}) };
|
|
566
|
+
},
|
|
567
|
+
|
|
568
|
+
async input(principal: TerminalPrincipal, sink: TerminalSink, params: { terminalId: string; data: string }) {
|
|
569
|
+
const limits = await ready();
|
|
570
|
+
const terminal = own(principal, params.terminalId);
|
|
571
|
+
if (terminal.sink !== sink) throw new RpcError(ERROR.conflict, 'Attach the terminal on this connection first', { reason: 'not_attached' });
|
|
572
|
+
if (terminal.exit || terminal.ending) throw new RpcError(ERROR.conflict, 'The terminal has ended', { reason: 'terminal_exited' });
|
|
573
|
+
const bytes = Buffer.byteLength(params.data);
|
|
574
|
+
if (bytes > limits.maxInputBytes) throw new RpcError(RPC_ERROR.invalidParams, `At most ${limits.maxInputBytes} bytes of input at once`, { reason: 'input_too_large' });
|
|
575
|
+
terminal.pty.write(params.data);
|
|
576
|
+
terminal.lastActivityAt = now();
|
|
577
|
+
return { bytes };
|
|
578
|
+
},
|
|
579
|
+
|
|
580
|
+
async resize(principal: TerminalPrincipal, sink: TerminalSink, params: { terminalId: string; cols: number; rows: number }) {
|
|
581
|
+
await ready();
|
|
582
|
+
const terminal = own(principal, params.terminalId);
|
|
583
|
+
if (terminal.sink !== sink) throw new RpcError(ERROR.conflict, 'Attach the terminal on this connection first', { reason: 'not_attached' });
|
|
584
|
+
if (terminal.exit || terminal.ending) throw new RpcError(ERROR.conflict, 'The terminal has ended', { reason: 'terminal_exited' });
|
|
585
|
+
terminal.screen.resize(params.cols, params.rows);
|
|
586
|
+
terminal.pty.resize(params.cols, params.rows);
|
|
587
|
+
terminal.cols = params.cols;
|
|
588
|
+
terminal.rows = params.rows;
|
|
589
|
+
changed(terminal);
|
|
590
|
+
return { cols: terminal.cols, rows: terminal.rows };
|
|
591
|
+
},
|
|
592
|
+
|
|
593
|
+
async close(principal: TerminalPrincipal, params: { terminalId: string }) {
|
|
594
|
+
const terminal = own(principal, params.terminalId);
|
|
595
|
+
if (terminal.exit) { await terminal.reaped; forget(terminal); return { closed: true as const }; }
|
|
596
|
+
await end(terminal, 'closed');
|
|
597
|
+
forget(terminal);
|
|
598
|
+
return { closed: true as const };
|
|
599
|
+
},
|
|
600
|
+
|
|
601
|
+
/** Every terminal of a principal, any epoch: a gateway's revocation. */
|
|
602
|
+
async revoke(principalId: string) {
|
|
603
|
+
const starting = [...pending.values()].filter(entry => entry.principal.id === principalId);
|
|
604
|
+
const newlyCancelled = starting.filter(entry => !entry.reason);
|
|
605
|
+
for (const entry of newlyCancelled) cancel(entry, 'terminal_revoked');
|
|
606
|
+
const mine = [...terminals.values()].filter(terminal => terminal.principal.id === principalId);
|
|
607
|
+
const live = mine.filter(terminal => !terminal.exit && !terminal.ending);
|
|
608
|
+
const outcomes = await Promise.allSettled([...mine.map(terminal => terminal.exit ? terminal.reaped : end(terminal, 'revoked')), ...starting.map(entry => entry.promise.then(() => {}, () => {}))]);
|
|
609
|
+
if (cleanupFault || outcomes.some(result => result.status === 'rejected')) throw refused('terminal_cleanup_uncertain');
|
|
610
|
+
for (const terminal of mine) forget(terminal);
|
|
611
|
+
if (mine.length) log.info('revoked the terminals of a principal', { code: 'ALPD_TERMINAL_REVOKED', principal: principalId, closed: live.length });
|
|
612
|
+
return { closed: live.length + newlyCancelled.length };
|
|
613
|
+
},
|
|
614
|
+
|
|
615
|
+
/** A connection closed: its terminals keep running for reconnectMs. */
|
|
616
|
+
disconnect(sink: TerminalSink) {
|
|
617
|
+
watchers.delete(sink);
|
|
618
|
+
for (const terminal of terminals.values()) if (terminal.sink === sink) detach(terminal, 'disconnected');
|
|
619
|
+
},
|
|
620
|
+
|
|
621
|
+
sweep,
|
|
622
|
+
|
|
623
|
+
/** alpd stops: every terminal ends (reason `shutdown`) and its tree is killed. */
|
|
624
|
+
async shutdown() {
|
|
625
|
+
closed = true;
|
|
626
|
+
clearInterval(timer);
|
|
627
|
+
const starting = [...pending.values()];
|
|
628
|
+
for (const entry of starting) cancel(entry, 'terminal_unsupported');
|
|
629
|
+
await Promise.all(starting.map(entry => entry.promise.then(() => {}, () => {})));
|
|
630
|
+
const outcomes = await Promise.allSettled([...terminals.values()].map(terminal => terminal.exit ? terminal.reaped : end(terminal, 'shutdown')));
|
|
631
|
+
for (const terminal of terminals.values()) terminal.screen.dispose();
|
|
632
|
+
terminals.clear();
|
|
633
|
+
watchers.clear();
|
|
634
|
+
if (cleanupFault || outcomes.some(result => result.status === 'rejected')) throw refused('terminal_cleanup_uncertain');
|
|
635
|
+
},
|
|
636
|
+
|
|
637
|
+
/** Test hook: pids of every running terminal's shell. */
|
|
638
|
+
pids() { return [...terminals.values()].filter(terminal => !terminal.exit).map(terminal => terminal.pid); },
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
export type TerminalService = ReturnType<typeof createTerminalService>;
|