@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
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
// packages/daemon/src/terminals.ts
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { constants } from "node:fs";
|
|
5
|
+
import { access, lstat, readFile } from "node:fs/promises";
|
|
6
|
+
import { nativePtySpawn, nativeTerminalCapability } from "./native-terminal.js";
|
|
7
|
+
import { windowsPtySpawn, windowsShell, windowsTerminalCapability } from "./windows-terminal.js";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { ERROR, RPC_ERROR, TERMINAL, TERMINAL_LIMIT_KEYS, isTerminalId } from "@anhlp/alp-protocol";
|
|
10
|
+
import { RpcError } from "./rpc-error.js";
|
|
11
|
+
import { TerminalScreen, SCREEN_LIMITS } from "./terminal-screen.js";
|
|
12
|
+
var SWEEP_MS = 5e3;
|
|
13
|
+
var KILL_GRACE_MS = 1e3;
|
|
14
|
+
var MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
|
|
15
|
+
var CONFIG_FILE = "terminal.json";
|
|
16
|
+
var PRIVATE_ENV = /^(ALP_|npm_)/i;
|
|
17
|
+
var notFound = () => new RpcError(ERROR.notFound, "No such terminal", { reason: "not_found" });
|
|
18
|
+
var iso = (ms) => new Date(ms).toISOString();
|
|
19
|
+
async function readTerminalConfig(home, log, platform = process.platform) {
|
|
20
|
+
const defaults = Object.fromEntries(TERMINAL_LIMIT_KEYS.map((key) => [key, TERMINAL[key]]));
|
|
21
|
+
const file = path.join(home, CONFIG_FILE);
|
|
22
|
+
const info = await lstat(file).catch(() => void 0);
|
|
23
|
+
if (!info) return { enabled: false, reason: "missing", limits: defaults, paseo: false };
|
|
24
|
+
if (!info.isFile() || process.getuid && info.uid !== process.getuid() || platform !== "win32" && info.mode & 63) {
|
|
25
|
+
log?.warn("terminal.json is not a private file of the daemon user; terminals stay off", { code: "ALPD_TERMINAL_CONFIG" });
|
|
26
|
+
return { enabled: false, reason: "not_private", limits: defaults, paseo: false };
|
|
27
|
+
}
|
|
28
|
+
let value;
|
|
29
|
+
try {
|
|
30
|
+
value = JSON.parse(await readFile(file, "utf8"));
|
|
31
|
+
} catch {
|
|
32
|
+
log?.warn("terminal.json is not valid JSON; terminals stay off", { code: "ALPD_TERMINAL_CONFIG" });
|
|
33
|
+
return { enabled: false, reason: "invalid", limits: defaults, paseo: false };
|
|
34
|
+
}
|
|
35
|
+
if (!value || typeof value !== "object" || value.version !== 1) return { enabled: false, reason: "invalid", limits: defaults, paseo: false };
|
|
36
|
+
const limits = { ...defaults };
|
|
37
|
+
if (value.limits && typeof value.limits === "object") {
|
|
38
|
+
for (const [key, raw] of Object.entries(value.limits)) {
|
|
39
|
+
if (!TERMINAL_LIMIT_KEYS.includes(key) || !Number.isSafeInteger(raw) || raw < 1) {
|
|
40
|
+
log?.warn(`terminal.json limit ${key} ignored`, { code: "ALPD_TERMINAL_CONFIG" });
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const k = key;
|
|
44
|
+
if (raw > defaults[k]) {
|
|
45
|
+
log?.warn(`terminal.json limit ${key} is above the maximum; ignored`, { code: "ALPD_TERMINAL_CONFIG" });
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
limits[k] = raw;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return value.allowRemoteTerminal === true ? { enabled: true, limits, paseo: value.allowPaseoTerminal === true } : { enabled: false, reason: "off", limits, paseo: false };
|
|
52
|
+
}
|
|
53
|
+
function elapsed(text) {
|
|
54
|
+
const [days, rest] = text.includes("-") ? text.split("-") : ["0", text];
|
|
55
|
+
const parts = rest.split(":").map(Number);
|
|
56
|
+
while (parts.length < 3) parts.unshift(0);
|
|
57
|
+
const [h, m, s] = parts;
|
|
58
|
+
return (((Number(days) * 24 + h) * 60 + m) * 60 + s) * 1e3;
|
|
59
|
+
}
|
|
60
|
+
var MARKER = /(?:^|\s)ALP_TERMINAL_ID=(atm_[0-9a-f]{32})(?=\s|$)/g;
|
|
61
|
+
var markersOf = (text) => [...text.matchAll(MARKER)].map((match) => match[1]);
|
|
62
|
+
var ENTRY = /^ALP_TERMINAL_ID=(atm_[0-9a-f]{32})$/;
|
|
63
|
+
function psProcesses(platform = process.platform, options = {}) {
|
|
64
|
+
const linux = platform === "linux";
|
|
65
|
+
const run = (args) => new Promise((resolve) => {
|
|
66
|
+
const child = execFile("ps", args, { encoding: "utf8", maxBuffer: 256 * 1024 * 1024, killSignal: "SIGKILL", env: { ...process.env, LC_ALL: "C" } }, (error, stdout) => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
resolve(error ? void 0 : stdout);
|
|
69
|
+
});
|
|
70
|
+
const timer = setTimeout(() => {
|
|
71
|
+
child.kill("SIGKILL");
|
|
72
|
+
resolve(void 0);
|
|
73
|
+
}, 1e4);
|
|
74
|
+
});
|
|
75
|
+
return async () => {
|
|
76
|
+
const columns = linux ? "pid=,ppid=,pgid=,sid=,tty=,etime=" : "pid=,ppid=,pgid=,tty=,etime=,command=";
|
|
77
|
+
const [stdout, plain] = await Promise.all([run(linux ? ["-A", "-o", columns] : ["-A", "-E", "-ww", "-o", columns]), linux ? void 0 : run(["-A", "-ww", "-o", "pid=,command="])]);
|
|
78
|
+
if (stdout === void 0) return [];
|
|
79
|
+
const commands = /* @__PURE__ */ new Map();
|
|
80
|
+
for (const line of plain?.split("\n") ?? []) {
|
|
81
|
+
const match = /^\s*(\d+) (.*)$/.exec(line);
|
|
82
|
+
if (match) commands.set(Number(match[1]), match[2]);
|
|
83
|
+
}
|
|
84
|
+
const rows = [];
|
|
85
|
+
for (const line of stdout.split("\n")) {
|
|
86
|
+
const cells = line.trim().split(/\s+/);
|
|
87
|
+
if (cells.length < 5) continue;
|
|
88
|
+
const [pid, ppid, pgid] = cells.slice(0, 3).map(Number);
|
|
89
|
+
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(ppid) || !Number.isSafeInteger(pgid)) continue;
|
|
90
|
+
const sid = linux ? Number(cells[3]) : void 0;
|
|
91
|
+
const tty = cells[linux ? 4 : 3];
|
|
92
|
+
let markers = [];
|
|
93
|
+
if (linux) {
|
|
94
|
+
try {
|
|
95
|
+
markers = (await (options.readEnvironment ? options.readEnvironment(pid) : readFile(`/proc/${pid}/environ`, "utf8"))).split("\0").flatMap((entry) => ENTRY.exec(entry)?.[1] ?? []);
|
|
96
|
+
} catch {
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
const full = /^\s*(?:\S+\s+){4}\S+ (.*)$/.exec(line)?.[1] ?? "";
|
|
100
|
+
const command = commands.get(pid);
|
|
101
|
+
if (command !== void 0 && full.startsWith(command)) markers = markersOf(full.slice(command.length));
|
|
102
|
+
}
|
|
103
|
+
rows.push({ pid, ppid, pgid, ...sid !== void 0 && Number.isSafeInteger(sid) ? { sid } : {}, .../^[?-]+$/.test(tty) ? {} : { tty }, elapsedMs: elapsed(cells[linux ? 5 : 4]), ...markers.length ? { markers } : {} });
|
|
104
|
+
}
|
|
105
|
+
return rows;
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function frames(data, max) {
|
|
109
|
+
if (Buffer.byteLength(data) <= max) return [data];
|
|
110
|
+
const out = [];
|
|
111
|
+
let current = "";
|
|
112
|
+
let bytes = 0;
|
|
113
|
+
for (const char of data) {
|
|
114
|
+
const size = Buffer.byteLength(char);
|
|
115
|
+
if (bytes + size > max && current) {
|
|
116
|
+
out.push(current);
|
|
117
|
+
current = "";
|
|
118
|
+
bytes = 0;
|
|
119
|
+
}
|
|
120
|
+
current += char;
|
|
121
|
+
bytes += size;
|
|
122
|
+
}
|
|
123
|
+
if (current) out.push(current);
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
function createTerminalService(options) {
|
|
127
|
+
const { home, resolveWorkspace, log } = options;
|
|
128
|
+
const now = options.now ?? Date.now;
|
|
129
|
+
const platform = options.platform ?? process.platform;
|
|
130
|
+
const supported = platform === "darwin" || platform === "linux" || platform === "win32";
|
|
131
|
+
const windows = platform === "win32";
|
|
132
|
+
const killGraceMs = options.killGraceMs ?? KILL_GRACE_MS;
|
|
133
|
+
const maxBuffered = options.maxBufferedBytes ?? MAX_BUFFERED_BYTES;
|
|
134
|
+
const terminals = /* @__PURE__ */ new Map();
|
|
135
|
+
const requests = /* @__PURE__ */ new Map();
|
|
136
|
+
const watchers = /* @__PURE__ */ new Map();
|
|
137
|
+
const token = () => randomBytes(16).toString("hex");
|
|
138
|
+
function changed(terminal) {
|
|
139
|
+
for (const [sink, watch] of watchers) {
|
|
140
|
+
if (watch.principal.id !== terminal.principal.id || watch.principal.epoch !== terminal.principal.epoch || !within(watch.principal, terminal.root) || watch.workspaceId !== void 0 && watch.workspaceId !== terminal.workspaceId) continue;
|
|
141
|
+
watch.cursor = token();
|
|
142
|
+
try {
|
|
143
|
+
sink.send({ jsonrpc: "2.0", method: "terminal.changed", params: { watchId: watch.watchId, cursor: watch.cursor } });
|
|
144
|
+
} catch {
|
|
145
|
+
watchers.delete(sink);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function snapshot(principal, workspaceId) {
|
|
150
|
+
return [...terminals.values()].filter((terminal) => terminal.principal.id === principal.id && terminal.principal.epoch === principal.epoch && within(principal, terminal.root) && (workspaceId === void 0 || terminal.workspaceId === workspaceId)).sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1)).map(info);
|
|
151
|
+
}
|
|
152
|
+
let closed = false;
|
|
153
|
+
let enabled = false;
|
|
154
|
+
let cleanupFault = false;
|
|
155
|
+
const pending = /* @__PURE__ */ new Map();
|
|
156
|
+
const spawner = options.spawn ?? (windows ? windowsPtySpawn : nativePtySpawn);
|
|
157
|
+
let capability;
|
|
158
|
+
function pty() {
|
|
159
|
+
capability ??= options.capability?.() ?? (options.spawn ? { available: true } : windows ? windowsTerminalCapability() : nativeTerminalCapability());
|
|
160
|
+
return capability.available ? spawner : void 0;
|
|
161
|
+
}
|
|
162
|
+
const cancel = (entry, reason) => {
|
|
163
|
+
entry.reason ??= reason;
|
|
164
|
+
entry.controller.abort();
|
|
165
|
+
};
|
|
166
|
+
const refused = (reason) => new RpcError(ERROR.unavailable, "Terminal startup was cancelled or its native owner is unavailable", { reason });
|
|
167
|
+
async function cleanup(owner, id) {
|
|
168
|
+
if (!owner.cleanup) {
|
|
169
|
+
owner.kill();
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const result = await owner.cleanup();
|
|
173
|
+
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 });
|
|
174
|
+
if (result.live || result.uncertain) {
|
|
175
|
+
cleanupFault = true;
|
|
176
|
+
log.warn("native terminal cleanup could not prove all observed processes exited", { code: "ALPD_TERMINAL_REAP_FAILED", terminalId: id, ...result });
|
|
177
|
+
throw refused("terminal_cleanup_uncertain");
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function effective(config) {
|
|
181
|
+
const limits = { ...config };
|
|
182
|
+
for (const key of TERMINAL_LIMIT_KEYS) {
|
|
183
|
+
const lower = options.limits?.[key];
|
|
184
|
+
if (Number.isSafeInteger(lower) && lower > 0 && lower < limits[key]) limits[key] = lower;
|
|
185
|
+
}
|
|
186
|
+
return limits;
|
|
187
|
+
}
|
|
188
|
+
async function state() {
|
|
189
|
+
const config = await readTerminalConfig(home, log, platform);
|
|
190
|
+
const limits = effective(config.limits);
|
|
191
|
+
if (enabled && !config.enabled) {
|
|
192
|
+
log.info("terminals turned off on this host; ending every terminal", { code: "ALPD_TERMINAL_DISABLED" });
|
|
193
|
+
for (const entry of pending.values()) cancel(entry, "terminal_disabled");
|
|
194
|
+
for (const terminal of terminals.values()) if (!terminal.exit) void end(terminal, "disabled").catch(() => {
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
enabled = config.enabled;
|
|
198
|
+
return { enabled: config.enabled, limits };
|
|
199
|
+
}
|
|
200
|
+
async function ready() {
|
|
201
|
+
if (cleanupFault) throw refused("terminal_cleanup_uncertain");
|
|
202
|
+
if (closed) throw new RpcError(ERROR.unavailable, "alpd is shutting down", { reason: "terminal_unsupported" });
|
|
203
|
+
if (!supported) throw new RpcError(ERROR.unavailable, "Terminals are not supported on this host's platform", { reason: "terminal_unsupported" });
|
|
204
|
+
const current = await state();
|
|
205
|
+
if (!current.enabled) throw new RpcError(ERROR.unavailable, "The host has not allowed remote terminals (alp terminal allow)", { reason: "terminal_disabled" });
|
|
206
|
+
if (!pty()) throw new RpcError(ERROR.unavailable, "The native terminal owner is unavailable on this host", { reason: "terminal_unsupported" });
|
|
207
|
+
return current.limits;
|
|
208
|
+
}
|
|
209
|
+
function info(terminal) {
|
|
210
|
+
return {
|
|
211
|
+
terminalId: terminal.id,
|
|
212
|
+
workspaceId: terminal.workspaceId,
|
|
213
|
+
title: terminal.title,
|
|
214
|
+
cols: terminal.cols,
|
|
215
|
+
rows: terminal.rows,
|
|
216
|
+
state: terminal.exit ? "exited" : "running",
|
|
217
|
+
attached: !!terminal.sink,
|
|
218
|
+
createdAt: iso(terminal.createdAt),
|
|
219
|
+
lastActivityAt: iso(terminal.lastActivityAt),
|
|
220
|
+
expiresAt: iso(terminal.expiresAt),
|
|
221
|
+
...terminal.exit ? { exitCode: terminal.exit.exitCode, signal: terminal.exit.signal, endReason: terminal.exit.reason } : {},
|
|
222
|
+
...terminal.protection ? { protection: terminal.protection } : {}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const audit = (message, terminal, fields = {}) => log.info(message, { terminalId: terminal.id, workspaceId: terminal.workspaceId, principal: terminal.principal.id, ...fields });
|
|
226
|
+
function own(principal, terminalId) {
|
|
227
|
+
const terminal = isTerminalId(terminalId) ? terminals.get(terminalId) : void 0;
|
|
228
|
+
if (!terminal || terminal.principal.id !== principal.id || terminal.principal.epoch !== principal.epoch || !within(principal, terminal.root)) throw notFound();
|
|
229
|
+
return terminal;
|
|
230
|
+
}
|
|
231
|
+
function within(principal, root) {
|
|
232
|
+
if (principal.roots === void 0) return true;
|
|
233
|
+
return principal.roots.some((granted) => root === granted || root.startsWith(granted.endsWith(path.sep) ? granted : granted + path.sep));
|
|
234
|
+
}
|
|
235
|
+
function send(terminal, event) {
|
|
236
|
+
const sink = terminal.sink;
|
|
237
|
+
if (!sink) return;
|
|
238
|
+
sink.send({ jsonrpc: "2.0", method: "terminal.event", params: event });
|
|
239
|
+
if (event.type === "output" && (sink.socket?.writableLength ?? 0) > maxBuffered) detach(terminal, "slow_consumer");
|
|
240
|
+
}
|
|
241
|
+
function detach(terminal, reason) {
|
|
242
|
+
const sink = terminal.sink;
|
|
243
|
+
if (!sink) return;
|
|
244
|
+
terminal.sink = void 0;
|
|
245
|
+
terminal.detachedAt = now();
|
|
246
|
+
if (reason !== "disconnected") sink.send({ jsonrpc: "2.0", method: "terminal.event", params: { terminalId: terminal.id, type: "detached", reason } });
|
|
247
|
+
changed(terminal);
|
|
248
|
+
audit("terminal detached", terminal, { code: "ALPD_TERMINAL_DETACHED", reason });
|
|
249
|
+
}
|
|
250
|
+
function output(terminal, data, limits) {
|
|
251
|
+
terminal.lastActivityAt = now();
|
|
252
|
+
terminal.screen.write(data);
|
|
253
|
+
for (const piece of frames(data, limits.maxOutputFrameBytes)) {
|
|
254
|
+
const frame = { seq: terminal.nextSeq++, data: piece, bytes: Buffer.byteLength(piece) };
|
|
255
|
+
terminal.ring.push(frame);
|
|
256
|
+
terminal.ringBytes += frame.bytes;
|
|
257
|
+
while (terminal.ringBytes > limits.replayBytes && terminal.ring.length > 1) terminal.ringBytes -= terminal.ring.shift().bytes;
|
|
258
|
+
send(terminal, { terminalId: terminal.id, type: "output", seq: frame.seq, data: frame.data });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function reap(terminal) {
|
|
262
|
+
terminal.reaped ??= cleanup(terminal.pty, terminal.id);
|
|
263
|
+
void terminal.reaped.catch(() => {
|
|
264
|
+
});
|
|
265
|
+
return terminal.reaped;
|
|
266
|
+
}
|
|
267
|
+
function exited(terminal, exitCode, signalNumber) {
|
|
268
|
+
if (terminal.exit) return;
|
|
269
|
+
const reason = terminal.ending ?? "exited";
|
|
270
|
+
terminal.exit = { seq: terminal.nextSeq++, exitCode, signal: signalNumber, reason, at: now() };
|
|
271
|
+
for (const disposable of terminal.disposables) {
|
|
272
|
+
try {
|
|
273
|
+
disposable.dispose();
|
|
274
|
+
} catch {
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
requests.delete(terminal.requestKey);
|
|
278
|
+
send(terminal, { terminalId: terminal.id, type: "exit", seq: terminal.exit.seq, exitCode, signal: signalNumber, reason });
|
|
279
|
+
changed(terminal);
|
|
280
|
+
audit("terminal ended", terminal, { code: "ALPD_TERMINAL_ENDED", reason, exitCode, signal: signalNumber });
|
|
281
|
+
void reap(terminal).catch(() => {
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
async function end(terminal, reason) {
|
|
285
|
+
if (terminal.exit) return terminal.reaped;
|
|
286
|
+
terminal.ending ??= reason;
|
|
287
|
+
const reaping = reap(terminal);
|
|
288
|
+
await reaping;
|
|
289
|
+
if (!terminal.exit) exited(terminal, null, null);
|
|
290
|
+
}
|
|
291
|
+
let sweeping = false;
|
|
292
|
+
async function sweep() {
|
|
293
|
+
if (closed || sweeping) return;
|
|
294
|
+
sweeping = true;
|
|
295
|
+
try {
|
|
296
|
+
await sweepOnce();
|
|
297
|
+
} finally {
|
|
298
|
+
sweeping = false;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async function sweepOnce() {
|
|
302
|
+
const current = await state().catch(() => void 0);
|
|
303
|
+
if (!current) return;
|
|
304
|
+
const { limits } = current;
|
|
305
|
+
const at = now();
|
|
306
|
+
for (const terminal of [...terminals.values()]) {
|
|
307
|
+
if (terminal.exit) {
|
|
308
|
+
if (at - terminal.exit.at >= limits.reconnectMs) forget(terminal);
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (at >= terminal.expiresAt) void end(terminal, "lifetime").catch(() => {
|
|
312
|
+
});
|
|
313
|
+
else if (at - terminal.lastActivityAt >= limits.idleMs) void end(terminal, "idle").catch(() => {
|
|
314
|
+
});
|
|
315
|
+
else if (!terminal.sink && terminal.detachedAt !== void 0 && at - terminal.detachedAt >= limits.reconnectMs) void end(terminal, "detached").catch(() => {
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const timer = setInterval(() => void sweep().catch(() => {
|
|
320
|
+
}), options.sweepMs ?? SWEEP_MS);
|
|
321
|
+
timer.unref?.();
|
|
322
|
+
async function shell() {
|
|
323
|
+
if (windows) return windowsShell();
|
|
324
|
+
const candidate = process.env.SHELL;
|
|
325
|
+
if (candidate && path.isAbsolute(candidate)) {
|
|
326
|
+
const listed = await readFile("/etc/shells", "utf8").then((text) => text.split("\n").map((line) => line.trim()).includes(candidate), () => false);
|
|
327
|
+
if (listed && await access(candidate, constants.X_OK).then(() => true, () => false)) return candidate;
|
|
328
|
+
}
|
|
329
|
+
return "/bin/sh";
|
|
330
|
+
}
|
|
331
|
+
function environment(marker) {
|
|
332
|
+
const env = {};
|
|
333
|
+
for (const [key, value] of Object.entries(process.env)) if (value !== void 0 && !PRIVATE_ENV.test(key)) env[key] = value;
|
|
334
|
+
return { ...env, TERM: "xterm-256color", COLORTERM: "truecolor", ALP_TERMINAL: "1", ALP_TERMINAL_ID: marker };
|
|
335
|
+
}
|
|
336
|
+
function forget(terminal) {
|
|
337
|
+
terminal.screen.dispose();
|
|
338
|
+
terminals.delete(terminal.id);
|
|
339
|
+
changed(terminal);
|
|
340
|
+
}
|
|
341
|
+
const running = (filter) => [...terminals.values()].filter((terminal) => !terminal.exit && filter(terminal)).length;
|
|
342
|
+
return {
|
|
343
|
+
/** `terminalLimits` for daemon.hello while terminals are served, else undefined. */
|
|
344
|
+
async advertised() {
|
|
345
|
+
if (closed || !supported) return void 0;
|
|
346
|
+
const current = await state().catch(() => void 0);
|
|
347
|
+
return !cleanupFault && current?.enabled && pty() ? current.limits : void 0;
|
|
348
|
+
},
|
|
349
|
+
create(principal, params) {
|
|
350
|
+
const requestKey = JSON.stringify([principal.id, principal.epoch, params.requestId]);
|
|
351
|
+
const existing = pending.get(requestKey);
|
|
352
|
+
if (existing) {
|
|
353
|
+
if (existing.workspaceId !== params.workspaceId) return Promise.reject(new RpcError(ERROR.conflict, "This requestId created another terminal", { reason: "request_conflict" }));
|
|
354
|
+
return existing.promise.then((result) => {
|
|
355
|
+
own(principal, result.terminal.terminalId);
|
|
356
|
+
return result;
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
if (pending.size >= TERMINAL.maxPerDaemon * 2) return Promise.reject(refused("terminal_limit"));
|
|
360
|
+
const entry = { principal: { ...principal }, workspaceId: params.workspaceId, controller: new AbortController(), admitted: false, promise: void 0 };
|
|
361
|
+
pending.set(requestKey, entry);
|
|
362
|
+
entry.promise = (async () => {
|
|
363
|
+
let process_;
|
|
364
|
+
try {
|
|
365
|
+
const limits = await ready();
|
|
366
|
+
const root = await resolveWorkspace(params.workspaceId).catch((error) => {
|
|
367
|
+
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" });
|
|
368
|
+
throw error;
|
|
369
|
+
});
|
|
370
|
+
if (!within(principal, root)) throw new RpcError(ERROR.forbidden, "The workspace is outside this grant", { reason: "outside_workspace" });
|
|
371
|
+
const protection = capability?.protection;
|
|
372
|
+
const file = await shell();
|
|
373
|
+
if (cleanupFault) throw refused("terminal_cleanup_uncertain");
|
|
374
|
+
if (entry.reason || closed) throw refused(entry.reason ?? "terminal_unsupported");
|
|
375
|
+
const repeated = terminals.get(requests.get(requestKey) ?? "");
|
|
376
|
+
if (repeated && !repeated.exit) {
|
|
377
|
+
if (repeated.workspaceId !== params.workspaceId) throw new RpcError(ERROR.conflict, "This requestId created another terminal", { reason: "request_conflict" });
|
|
378
|
+
return { terminal: info(repeated) };
|
|
379
|
+
}
|
|
380
|
+
const reserved = (id) => [...pending.values()].filter((other) => other.admitted && (id === void 0 || other.principal.id === id)).length;
|
|
381
|
+
if (running((terminal2) => terminal2.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" });
|
|
382
|
+
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" });
|
|
383
|
+
entry.admitted = true;
|
|
384
|
+
const at = now();
|
|
385
|
+
const marker = `atm_${randomBytes(16).toString("hex")}`;
|
|
386
|
+
process_ = await spawner(file, [], { name: "xterm-256color", cols: params.cols, rows: params.rows, cwd: root, env: environment(marker), killGraceMs, signal: entry.controller.signal, protection });
|
|
387
|
+
const current = await state();
|
|
388
|
+
if (cleanupFault) throw refused("terminal_cleanup_uncertain");
|
|
389
|
+
if (entry.reason || closed || !current.enabled) throw refused(entry.reason ?? (closed ? "terminal_unsupported" : "terminal_disabled"));
|
|
390
|
+
const screens = [...terminals.values()].filter((terminal2) => terminal2.screen.available);
|
|
391
|
+
while (screens.length >= SCREEN_LIMITS.retained) {
|
|
392
|
+
const oldest = screens.findIndex((terminal2) => !!terminal2.exit);
|
|
393
|
+
if (oldest < 0) break;
|
|
394
|
+
screens.splice(oldest, 1)[0].screen.dispose();
|
|
395
|
+
}
|
|
396
|
+
const terminal = {
|
|
397
|
+
id: `term_${randomBytes(16).toString("hex")}`,
|
|
398
|
+
principal: { id: principal.id, epoch: principal.epoch },
|
|
399
|
+
workspaceId: params.workspaceId,
|
|
400
|
+
root,
|
|
401
|
+
...protection ? { protection } : {},
|
|
402
|
+
title: path.basename(file).slice(0, 64),
|
|
403
|
+
cols: params.cols,
|
|
404
|
+
rows: params.rows,
|
|
405
|
+
pty: process_,
|
|
406
|
+
pid: process_.pid,
|
|
407
|
+
screen: new TerminalScreen(params.cols, params.rows),
|
|
408
|
+
...typeof process_.ptsName === "string" && process_.ptsName.startsWith("/dev/") ? { tty: process_.ptsName.slice("/dev/".length) } : {},
|
|
409
|
+
createdAt: at,
|
|
410
|
+
lastActivityAt: at,
|
|
411
|
+
expiresAt: at + limits.maxLifetimeMs,
|
|
412
|
+
requestKey,
|
|
413
|
+
ring: [],
|
|
414
|
+
ringBytes: 0,
|
|
415
|
+
nextSeq: 1,
|
|
416
|
+
detachedAt: at,
|
|
417
|
+
marker,
|
|
418
|
+
disposables: []
|
|
419
|
+
};
|
|
420
|
+
terminals.set(terminal.id, terminal);
|
|
421
|
+
requests.set(requestKey, terminal.id);
|
|
422
|
+
terminal.disposables.push(process_.onData((data) => output(terminal, data, limits)));
|
|
423
|
+
terminal.disposables.push(process_.onExit(({ exitCode, signal: number }) => exited(terminal, terminal.ending ? null : exitCode, number || null)));
|
|
424
|
+
entry.admitted = false;
|
|
425
|
+
changed(terminal);
|
|
426
|
+
audit("terminal created", terminal, { code: "ALPD_TERMINAL_CREATED" });
|
|
427
|
+
return { terminal: info(terminal) };
|
|
428
|
+
} catch (error) {
|
|
429
|
+
if (process_) await cleanup(process_);
|
|
430
|
+
const failedCleanup = error?.cleanupResult;
|
|
431
|
+
if (failedCleanup && (failedCleanup.live || failedCleanup.uncertain)) {
|
|
432
|
+
cleanupFault = true;
|
|
433
|
+
log.warn("native startup cleanup was uncertain", { code: "ALPD_TERMINAL_REAP_FAILED", ...failedCleanup });
|
|
434
|
+
throw refused("terminal_cleanup_uncertain");
|
|
435
|
+
}
|
|
436
|
+
if (entry.reason) throw refused(entry.reason);
|
|
437
|
+
if (error?.terminalReason) {
|
|
438
|
+
capability = void 0;
|
|
439
|
+
throw refused("terminal_unsupported");
|
|
440
|
+
}
|
|
441
|
+
if (entry.admitted && !(error instanceof RpcError)) throw refused("terminal_unsupported");
|
|
442
|
+
throw error;
|
|
443
|
+
} finally {
|
|
444
|
+
pending.delete(requestKey);
|
|
445
|
+
}
|
|
446
|
+
})();
|
|
447
|
+
return entry.promise;
|
|
448
|
+
},
|
|
449
|
+
async list(principal, params) {
|
|
450
|
+
if (supported) await state().catch(() => void 0);
|
|
451
|
+
return { terminals: snapshot(principal, params.workspaceId) };
|
|
452
|
+
},
|
|
453
|
+
async watch(principal, sink, params) {
|
|
454
|
+
await ready();
|
|
455
|
+
const old = watchers.get(sink);
|
|
456
|
+
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;
|
|
457
|
+
const watch = same ? old : { principal: { ...principal, ...principal.roots ? { roots: [...principal.roots] } : {} }, workspaceId: params.workspaceId, watchId: token(), cursor: token() };
|
|
458
|
+
watchers.set(sink, watch);
|
|
459
|
+
return { terminals: snapshot(principal, params.workspaceId), watchId: watch.watchId, cursor: watch.cursor, reset: params.after !== watch.cursor };
|
|
460
|
+
},
|
|
461
|
+
async unwatch(sink) {
|
|
462
|
+
watchers.delete(sink);
|
|
463
|
+
return { closed: true };
|
|
464
|
+
},
|
|
465
|
+
async capture(principal, params) {
|
|
466
|
+
await ready();
|
|
467
|
+
const terminal = own(principal, params.terminalId);
|
|
468
|
+
const result = await terminal.screen.capture(params);
|
|
469
|
+
await ready();
|
|
470
|
+
if (own(principal, params.terminalId) !== terminal) throw notFound();
|
|
471
|
+
return result;
|
|
472
|
+
},
|
|
473
|
+
async attach(principal, sink, params) {
|
|
474
|
+
await ready();
|
|
475
|
+
const terminal = own(principal, params.terminalId);
|
|
476
|
+
if (terminal.sink && terminal.sink !== sink) detach(terminal, "replaced");
|
|
477
|
+
terminal.sink = sink;
|
|
478
|
+
terminal.detachedAt = void 0;
|
|
479
|
+
const after = Math.min(params.after ?? 0, terminal.nextSeq - 1);
|
|
480
|
+
const first = terminal.ring[0]?.seq ?? terminal.nextSeq;
|
|
481
|
+
const lastOutput = terminal.exit ? terminal.exit.seq - 1 : terminal.nextSeq - 1;
|
|
482
|
+
const gap = after + 1 < first && after < lastOutput ? { fromSeq: after + 1, toSeq: Math.min(first, lastOutput + 1) - 1 } : void 0;
|
|
483
|
+
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 } });
|
|
484
|
+
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 } });
|
|
485
|
+
changed(terminal);
|
|
486
|
+
audit("terminal attached", terminal, { code: "ALPD_TERMINAL_ATTACHED", after, ...gap ? { gap: gap.toSeq - gap.fromSeq + 1 } : {} });
|
|
487
|
+
return { terminal: info(terminal), nextSeq: terminal.nextSeq, ...gap ? { gap } : {} };
|
|
488
|
+
},
|
|
489
|
+
async input(principal, sink, params) {
|
|
490
|
+
const limits = await ready();
|
|
491
|
+
const terminal = own(principal, params.terminalId);
|
|
492
|
+
if (terminal.sink !== sink) throw new RpcError(ERROR.conflict, "Attach the terminal on this connection first", { reason: "not_attached" });
|
|
493
|
+
if (terminal.exit || terminal.ending) throw new RpcError(ERROR.conflict, "The terminal has ended", { reason: "terminal_exited" });
|
|
494
|
+
const bytes = Buffer.byteLength(params.data);
|
|
495
|
+
if (bytes > limits.maxInputBytes) throw new RpcError(RPC_ERROR.invalidParams, `At most ${limits.maxInputBytes} bytes of input at once`, { reason: "input_too_large" });
|
|
496
|
+
terminal.pty.write(params.data);
|
|
497
|
+
terminal.lastActivityAt = now();
|
|
498
|
+
return { bytes };
|
|
499
|
+
},
|
|
500
|
+
async resize(principal, sink, params) {
|
|
501
|
+
await ready();
|
|
502
|
+
const terminal = own(principal, params.terminalId);
|
|
503
|
+
if (terminal.sink !== sink) throw new RpcError(ERROR.conflict, "Attach the terminal on this connection first", { reason: "not_attached" });
|
|
504
|
+
if (terminal.exit || terminal.ending) throw new RpcError(ERROR.conflict, "The terminal has ended", { reason: "terminal_exited" });
|
|
505
|
+
terminal.screen.resize(params.cols, params.rows);
|
|
506
|
+
terminal.pty.resize(params.cols, params.rows);
|
|
507
|
+
terminal.cols = params.cols;
|
|
508
|
+
terminal.rows = params.rows;
|
|
509
|
+
changed(terminal);
|
|
510
|
+
return { cols: terminal.cols, rows: terminal.rows };
|
|
511
|
+
},
|
|
512
|
+
async close(principal, params) {
|
|
513
|
+
const terminal = own(principal, params.terminalId);
|
|
514
|
+
if (terminal.exit) {
|
|
515
|
+
await terminal.reaped;
|
|
516
|
+
forget(terminal);
|
|
517
|
+
return { closed: true };
|
|
518
|
+
}
|
|
519
|
+
await end(terminal, "closed");
|
|
520
|
+
forget(terminal);
|
|
521
|
+
return { closed: true };
|
|
522
|
+
},
|
|
523
|
+
/** Every terminal of a principal, any epoch: a gateway's revocation. */
|
|
524
|
+
async revoke(principalId) {
|
|
525
|
+
const starting = [...pending.values()].filter((entry) => entry.principal.id === principalId);
|
|
526
|
+
const newlyCancelled = starting.filter((entry) => !entry.reason);
|
|
527
|
+
for (const entry of newlyCancelled) cancel(entry, "terminal_revoked");
|
|
528
|
+
const mine = [...terminals.values()].filter((terminal) => terminal.principal.id === principalId);
|
|
529
|
+
const live = mine.filter((terminal) => !terminal.exit && !terminal.ending);
|
|
530
|
+
const outcomes = await Promise.allSettled([...mine.map((terminal) => terminal.exit ? terminal.reaped : end(terminal, "revoked")), ...starting.map((entry) => entry.promise.then(() => {
|
|
531
|
+
}, () => {
|
|
532
|
+
}))]);
|
|
533
|
+
if (cleanupFault || outcomes.some((result) => result.status === "rejected")) throw refused("terminal_cleanup_uncertain");
|
|
534
|
+
for (const terminal of mine) forget(terminal);
|
|
535
|
+
if (mine.length) log.info("revoked the terminals of a principal", { code: "ALPD_TERMINAL_REVOKED", principal: principalId, closed: live.length });
|
|
536
|
+
return { closed: live.length + newlyCancelled.length };
|
|
537
|
+
},
|
|
538
|
+
/** A connection closed: its terminals keep running for reconnectMs. */
|
|
539
|
+
disconnect(sink) {
|
|
540
|
+
watchers.delete(sink);
|
|
541
|
+
for (const terminal of terminals.values()) if (terminal.sink === sink) detach(terminal, "disconnected");
|
|
542
|
+
},
|
|
543
|
+
sweep,
|
|
544
|
+
/** alpd stops: every terminal ends (reason `shutdown`) and its tree is killed. */
|
|
545
|
+
async shutdown() {
|
|
546
|
+
closed = true;
|
|
547
|
+
clearInterval(timer);
|
|
548
|
+
const starting = [...pending.values()];
|
|
549
|
+
for (const entry of starting) cancel(entry, "terminal_unsupported");
|
|
550
|
+
await Promise.all(starting.map((entry) => entry.promise.then(() => {
|
|
551
|
+
}, () => {
|
|
552
|
+
})));
|
|
553
|
+
const outcomes = await Promise.allSettled([...terminals.values()].map((terminal) => terminal.exit ? terminal.reaped : end(terminal, "shutdown")));
|
|
554
|
+
for (const terminal of terminals.values()) terminal.screen.dispose();
|
|
555
|
+
terminals.clear();
|
|
556
|
+
watchers.clear();
|
|
557
|
+
if (cleanupFault || outcomes.some((result) => result.status === "rejected")) throw refused("terminal_cleanup_uncertain");
|
|
558
|
+
},
|
|
559
|
+
/** Test hook: pids of every running terminal's shell. */
|
|
560
|
+
pids() {
|
|
561
|
+
return [...terminals.values()].filter((terminal) => !terminal.exit).map((terminal) => terminal.pid);
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
export {
|
|
566
|
+
createTerminalService,
|
|
567
|
+
frames,
|
|
568
|
+
psProcesses,
|
|
569
|
+
readTerminalConfig
|
|
570
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { PtySpawn } from './terminals.js';
|
|
2
|
+
type NodePty = {
|
|
3
|
+
spawn(file: string, args: string[], options: Record<string, unknown>): {
|
|
4
|
+
pid: number;
|
|
5
|
+
write(data: string): void;
|
|
6
|
+
resize(cols: number, rows: number): void;
|
|
7
|
+
kill(signal?: string): void;
|
|
8
|
+
onData(listener: (data: string) => void): {
|
|
9
|
+
dispose(): void;
|
|
10
|
+
};
|
|
11
|
+
onExit(listener: (event: {
|
|
12
|
+
exitCode: number;
|
|
13
|
+
signal?: number;
|
|
14
|
+
}) => void): {
|
|
15
|
+
dispose(): void;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/** node-pty, or undefined when it cannot load on this host. */
|
|
20
|
+
export declare function loadNodePty(): NodePty | undefined;
|
|
21
|
+
export declare function windowsTerminalCapability(): {
|
|
22
|
+
available: boolean;
|
|
23
|
+
protection?: 'none';
|
|
24
|
+
reason?: string;
|
|
25
|
+
};
|
|
26
|
+
/** The shell for a Windows terminal: COMSPEC when absolute, else cmd.exe. */
|
|
27
|
+
export declare function windowsShell(env?: NodeJS.ProcessEnv): string;
|
|
28
|
+
export declare const windowsPtySpawn: PtySpawn;
|
|
29
|
+
export {};
|