@anhlp/alp-daemon 0.0.1-beta.4 → 0.0.1-beta.6
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/dist/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/alpd.js +10768 -2592
- package/dist/attachments.d.ts +25 -49
- package/dist/attachments.js +45 -8
- package/dist/build-manifest.json +14 -1
- package/dist/conversation.js +18 -2
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +141 -2
- package/dist/files.js +377 -68
- package/dist/git.d.ts +8 -2
- package/dist/git.js +111 -12
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/dist/main.js +57 -12
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +198 -0
- package/dist/operations.d.ts +12 -2
- package/dist/operations.js +22 -11
- package/dist/registry.js +1 -1
- package/dist/scheduler.js +8 -2
- package/dist/schedules.d.ts +2 -1
- package/dist/schedules.js +6 -4
- package/dist/server.d.ts +4 -2
- package/dist/server.js +171 -43
- package/dist/store.d.ts +3 -1
- package/dist/store.js +4 -3
- 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 +43 -7
- package/dist/terminals.js +222 -139
- package/dist/windows-terminal.d.ts +29 -0
- package/dist/windows-terminal.js +122 -0
- package/dist/worktrees.d.ts +25 -1
- package/dist/worktrees.js +74 -2
- 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 +11 -7
- package/src/attachments.ts +46 -8
- package/src/conversation.ts +22 -2
- package/src/disk.ts +175 -0
- package/src/files.ts +505 -80
- package/src/git.ts +113 -18
- package/src/index.ts +1 -0
- package/src/main.ts +53 -13
- package/src/native-terminal.ts +122 -0
- package/src/operations.ts +28 -12
- package/src/registry.ts +1 -1
- package/src/scheduler.ts +13 -3
- package/src/schedules.ts +5 -2
- package/src/server.ts +164 -36
- package/src/store.ts +2 -1
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +205 -155
- package/src/windows-terminal.ts +123 -0
- package/src/worktrees.ts +97 -2
package/dist/terminals.js
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
3
|
import { execFile } from "node:child_process";
|
|
4
4
|
import { constants } from "node:fs";
|
|
5
|
-
import { readFileSync } from "node:fs";
|
|
6
5
|
import { access, lstat, readFile } from "node:fs/promises";
|
|
7
|
-
import {
|
|
6
|
+
import { nativePtySpawn, nativeTerminalCapability } from "./native-terminal.js";
|
|
7
|
+
import { windowsPtySpawn, windowsShell, windowsTerminalCapability } from "./windows-terminal.js";
|
|
8
8
|
import path from "node:path";
|
|
9
9
|
import { ERROR, RPC_ERROR, TERMINAL, TERMINAL_LIMIT_KEYS, isTerminalId } from "@anhlp/alp-protocol";
|
|
10
10
|
import { RpcError } from "./rpc-error.js";
|
|
11
|
+
import { TerminalScreen, SCREEN_LIMITS } from "./terminal-screen.js";
|
|
11
12
|
var SWEEP_MS = 5e3;
|
|
12
13
|
var KILL_GRACE_MS = 1e3;
|
|
13
14
|
var MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
|
|
@@ -15,12 +16,12 @@ var CONFIG_FILE = "terminal.json";
|
|
|
15
16
|
var PRIVATE_ENV = /^(ALP_|npm_)/i;
|
|
16
17
|
var notFound = () => new RpcError(ERROR.notFound, "No such terminal", { reason: "not_found" });
|
|
17
18
|
var iso = (ms) => new Date(ms).toISOString();
|
|
18
|
-
async function readTerminalConfig(home, log) {
|
|
19
|
+
async function readTerminalConfig(home, log, platform = process.platform) {
|
|
19
20
|
const defaults = Object.fromEntries(TERMINAL_LIMIT_KEYS.map((key) => [key, TERMINAL[key]]));
|
|
20
21
|
const file = path.join(home, CONFIG_FILE);
|
|
21
22
|
const info = await lstat(file).catch(() => void 0);
|
|
22
23
|
if (!info) return { enabled: false, reason: "missing", limits: defaults, paseo: false };
|
|
23
|
-
if (!info.isFile() || process.getuid && info.uid !== process.getuid() || info.mode & 63) {
|
|
24
|
+
if (!info.isFile() || process.getuid && info.uid !== process.getuid() || platform !== "win32" && info.mode & 63) {
|
|
24
25
|
log?.warn("terminal.json is not a private file of the daemon user; terminals stay off", { code: "ALPD_TERMINAL_CONFIG" });
|
|
25
26
|
return { enabled: false, reason: "not_private", limits: defaults, paseo: false };
|
|
26
27
|
}
|
|
@@ -59,7 +60,7 @@ function elapsed(text) {
|
|
|
59
60
|
var MARKER = /(?:^|\s)ALP_TERMINAL_ID=(atm_[0-9a-f]{32})(?=\s|$)/g;
|
|
60
61
|
var markersOf = (text) => [...text.matchAll(MARKER)].map((match) => match[1]);
|
|
61
62
|
var ENTRY = /^ALP_TERMINAL_ID=(atm_[0-9a-f]{32})$/;
|
|
62
|
-
function psProcesses(platform = process.platform) {
|
|
63
|
+
function psProcesses(platform = process.platform, options = {}) {
|
|
63
64
|
const linux = platform === "linux";
|
|
64
65
|
const run = (args) => new Promise((resolve) => {
|
|
65
66
|
const child = execFile("ps", args, { encoding: "utf8", maxBuffer: 256 * 1024 * 1024, killSignal: "SIGKILL", env: { ...process.env, LC_ALL: "C" } }, (error, stdout) => {
|
|
@@ -91,7 +92,7 @@ function psProcesses(platform = process.platform) {
|
|
|
91
92
|
let markers = [];
|
|
92
93
|
if (linux) {
|
|
93
94
|
try {
|
|
94
|
-
markers =
|
|
95
|
+
markers = (await (options.readEnvironment ? options.readEnvironment(pid) : readFile(`/proc/${pid}/environ`, "utf8"))).split("\0").flatMap((entry) => ENTRY.exec(entry)?.[1] ?? []);
|
|
95
96
|
} catch {
|
|
96
97
|
}
|
|
97
98
|
} else {
|
|
@@ -126,27 +127,55 @@ function createTerminalService(options) {
|
|
|
126
127
|
const { home, resolveWorkspace, log } = options;
|
|
127
128
|
const now = options.now ?? Date.now;
|
|
128
129
|
const platform = options.platform ?? process.platform;
|
|
129
|
-
const supported = platform === "darwin" || platform === "linux";
|
|
130
|
-
const
|
|
130
|
+
const supported = platform === "darwin" || platform === "linux" || platform === "win32";
|
|
131
|
+
const windows = platform === "win32";
|
|
131
132
|
const killGraceMs = options.killGraceMs ?? KILL_GRACE_MS;
|
|
132
133
|
const maxBuffered = options.maxBufferedBytes ?? MAX_BUFFERED_BYTES;
|
|
133
134
|
const terminals = /* @__PURE__ */ new Map();
|
|
134
135
|
const requests = /* @__PURE__ */ new Map();
|
|
135
|
-
|
|
136
|
-
|
|
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
|
+
}
|
|
137
152
|
let closed = false;
|
|
138
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;
|
|
139
158
|
function pty() {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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");
|
|
148
178
|
}
|
|
149
|
-
return spawner;
|
|
150
179
|
}
|
|
151
180
|
function effective(config) {
|
|
152
181
|
const limits = { ...config };
|
|
@@ -157,21 +186,24 @@ function createTerminalService(options) {
|
|
|
157
186
|
return limits;
|
|
158
187
|
}
|
|
159
188
|
async function state() {
|
|
160
|
-
const config = await readTerminalConfig(home, log);
|
|
189
|
+
const config = await readTerminalConfig(home, log, platform);
|
|
161
190
|
const limits = effective(config.limits);
|
|
162
191
|
if (enabled && !config.enabled) {
|
|
163
192
|
log.info("terminals turned off on this host; ending every terminal", { code: "ALPD_TERMINAL_DISABLED" });
|
|
164
|
-
for (const
|
|
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
|
+
});
|
|
165
196
|
}
|
|
166
197
|
enabled = config.enabled;
|
|
167
198
|
return { enabled: config.enabled, limits };
|
|
168
199
|
}
|
|
169
200
|
async function ready() {
|
|
201
|
+
if (cleanupFault) throw refused("terminal_cleanup_uncertain");
|
|
170
202
|
if (closed) throw new RpcError(ERROR.unavailable, "alpd is shutting down", { reason: "terminal_unsupported" });
|
|
171
203
|
if (!supported) throw new RpcError(ERROR.unavailable, "Terminals are not supported on this host's platform", { reason: "terminal_unsupported" });
|
|
172
204
|
const current = await state();
|
|
173
205
|
if (!current.enabled) throw new RpcError(ERROR.unavailable, "The host has not allowed remote terminals (alp terminal allow)", { reason: "terminal_disabled" });
|
|
174
|
-
if (!pty()) throw new RpcError(ERROR.unavailable, "The terminal
|
|
206
|
+
if (!pty()) throw new RpcError(ERROR.unavailable, "The native terminal owner is unavailable on this host", { reason: "terminal_unsupported" });
|
|
175
207
|
return current.limits;
|
|
176
208
|
}
|
|
177
209
|
function info(terminal) {
|
|
@@ -186,7 +218,8 @@ function createTerminalService(options) {
|
|
|
186
218
|
createdAt: iso(terminal.createdAt),
|
|
187
219
|
lastActivityAt: iso(terminal.lastActivityAt),
|
|
188
220
|
expiresAt: iso(terminal.expiresAt),
|
|
189
|
-
...terminal.exit ? { exitCode: terminal.exit.exitCode, signal: terminal.exit.signal, endReason: terminal.exit.reason } : {}
|
|
221
|
+
...terminal.exit ? { exitCode: terminal.exit.exitCode, signal: terminal.exit.signal, endReason: terminal.exit.reason } : {},
|
|
222
|
+
...terminal.protection ? { protection: terminal.protection } : {}
|
|
190
223
|
};
|
|
191
224
|
}
|
|
192
225
|
const audit = (message, terminal, fields = {}) => log.info(message, { terminalId: terminal.id, workspaceId: terminal.workspaceId, principal: terminal.principal.id, ...fields });
|
|
@@ -211,10 +244,12 @@ function createTerminalService(options) {
|
|
|
211
244
|
terminal.sink = void 0;
|
|
212
245
|
terminal.detachedAt = now();
|
|
213
246
|
if (reason !== "disconnected") sink.send({ jsonrpc: "2.0", method: "terminal.event", params: { terminalId: terminal.id, type: "detached", reason } });
|
|
247
|
+
changed(terminal);
|
|
214
248
|
audit("terminal detached", terminal, { code: "ALPD_TERMINAL_DETACHED", reason });
|
|
215
249
|
}
|
|
216
250
|
function output(terminal, data, limits) {
|
|
217
251
|
terminal.lastActivityAt = now();
|
|
252
|
+
terminal.screen.write(data);
|
|
218
253
|
for (const piece of frames(data, limits.maxOutputFrameBytes)) {
|
|
219
254
|
const frame = { seq: terminal.nextSeq++, data: piece, bytes: Buffer.byteLength(piece) };
|
|
220
255
|
terminal.ring.push(frame);
|
|
@@ -223,55 +258,10 @@ function createTerminalService(options) {
|
|
|
223
258
|
send(terminal, { terminalId: terminal.id, type: "output", seq: frame.seq, data: frame.data });
|
|
224
259
|
}
|
|
225
260
|
}
|
|
226
|
-
async function tree(terminal) {
|
|
227
|
-
const running2 = !terminal.exit;
|
|
228
|
-
const lifetime = now() - terminal.createdAt;
|
|
229
|
-
const rows = await listProcesses();
|
|
230
|
-
const age = now() - terminal.createdAt + 2e3;
|
|
231
|
-
const own2 = rows.find((row) => row.pid === process.pid);
|
|
232
|
-
const children = /* @__PURE__ */ new Map();
|
|
233
|
-
for (const row of rows) children.set(row.ppid, [...children.get(row.ppid) ?? [], row]);
|
|
234
|
-
const found = /* @__PURE__ */ new Map();
|
|
235
|
-
for (const row of rows) if (row.markers?.includes(terminal.marker)) found.set(row.pid, row);
|
|
236
|
-
const holder = rows.find((row) => row.pid === terminal.pid);
|
|
237
|
-
const ours = !holder || holder.elapsedMs >= lifetime - 2e3;
|
|
238
|
-
const shell2 = running2 && ours ? holder : void 0;
|
|
239
|
-
if (shell2) found.set(shell2.pid, shell2);
|
|
240
|
-
const tty = shell2 && terminal.tty && shell2.tty === terminal.tty ? terminal.tty : void 0;
|
|
241
|
-
for (const row of rows) {
|
|
242
|
-
if (tty && row.tty === tty || row.sid !== void 0 && row.sid === terminal.pid && ours) found.set(row.pid, row);
|
|
243
|
-
}
|
|
244
|
-
const queue = [...found.values()];
|
|
245
|
-
while (queue.length) {
|
|
246
|
-
const row = queue.pop();
|
|
247
|
-
for (const child of children.get(row.pid) ?? []) if (!found.has(child.pid)) {
|
|
248
|
-
found.set(child.pid, child);
|
|
249
|
-
queue.push(child);
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
const groups = new Set([...found.values()].map((row) => row.pgid));
|
|
253
|
-
for (const row of rows) if (groups.has(row.pgid)) found.set(row.pid, row);
|
|
254
|
-
return [...found.values()].filter((row) => row.pid > 1 && row.pid !== process.pid && (!own2 || row.pgid !== own2.pgid) && row.elapsedMs <= age);
|
|
255
|
-
}
|
|
256
|
-
function signal(rows, name) {
|
|
257
|
-
for (const row of rows) {
|
|
258
|
-
try {
|
|
259
|
-
process.kill(row.pid, name);
|
|
260
|
-
} catch {
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
261
|
function reap(terminal) {
|
|
265
|
-
terminal.reaped ??= (
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
const left = await tree(terminal);
|
|
269
|
-
signal(left, "SIGKILL");
|
|
270
|
-
if (left.length) {
|
|
271
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
272
|
-
signal(await tree(terminal), "SIGKILL");
|
|
273
|
-
}
|
|
274
|
-
})().catch((error) => log.warn("could not end every process of a terminal", { code: "ALPD_TERMINAL_REAP_FAILED", terminalId: terminal.id, error }));
|
|
262
|
+
terminal.reaped ??= cleanup(terminal.pty, terminal.id);
|
|
263
|
+
void terminal.reaped.catch(() => {
|
|
264
|
+
});
|
|
275
265
|
return terminal.reaped;
|
|
276
266
|
}
|
|
277
267
|
function exited(terminal, exitCode, signalNumber) {
|
|
@@ -286,17 +276,15 @@ function createTerminalService(options) {
|
|
|
286
276
|
}
|
|
287
277
|
requests.delete(terminal.requestKey);
|
|
288
278
|
send(terminal, { terminalId: terminal.id, type: "exit", seq: terminal.exit.seq, exitCode, signal: signalNumber, reason });
|
|
279
|
+
changed(terminal);
|
|
289
280
|
audit("terminal ended", terminal, { code: "ALPD_TERMINAL_ENDED", reason, exitCode, signal: signalNumber });
|
|
290
|
-
void reap(terminal)
|
|
281
|
+
void reap(terminal).catch(() => {
|
|
282
|
+
});
|
|
291
283
|
}
|
|
292
284
|
async function end(terminal, reason) {
|
|
293
285
|
if (terminal.exit) return terminal.reaped;
|
|
294
286
|
terminal.ending ??= reason;
|
|
295
287
|
const reaping = reap(terminal);
|
|
296
|
-
try {
|
|
297
|
-
terminal.pty.kill("SIGHUP");
|
|
298
|
-
} catch {
|
|
299
|
-
}
|
|
300
288
|
await reaping;
|
|
301
289
|
if (!terminal.exit) exited(terminal, null, null);
|
|
302
290
|
}
|
|
@@ -317,18 +305,22 @@ function createTerminalService(options) {
|
|
|
317
305
|
const at = now();
|
|
318
306
|
for (const terminal of [...terminals.values()]) {
|
|
319
307
|
if (terminal.exit) {
|
|
320
|
-
if (at - terminal.exit.at >= limits.reconnectMs)
|
|
308
|
+
if (at - terminal.exit.at >= limits.reconnectMs) forget(terminal);
|
|
321
309
|
continue;
|
|
322
310
|
}
|
|
323
|
-
if (at >= terminal.expiresAt) void end(terminal, "lifetime")
|
|
324
|
-
|
|
325
|
-
else if (
|
|
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
|
+
});
|
|
326
317
|
}
|
|
327
318
|
}
|
|
328
319
|
const timer = setInterval(() => void sweep().catch(() => {
|
|
329
320
|
}), options.sweepMs ?? SWEEP_MS);
|
|
330
321
|
timer.unref?.();
|
|
331
322
|
async function shell() {
|
|
323
|
+
if (windows) return windowsShell();
|
|
332
324
|
const candidate = process.env.SHELL;
|
|
333
325
|
if (candidate && path.isAbsolute(candidate)) {
|
|
334
326
|
const listed = await readFile("/etc/shells", "utf8").then((text) => text.split("\n").map((line) => line.trim()).includes(candidate), () => false);
|
|
@@ -341,70 +333,142 @@ function createTerminalService(options) {
|
|
|
341
333
|
for (const [key, value] of Object.entries(process.env)) if (value !== void 0 && !PRIVATE_ENV.test(key)) env[key] = value;
|
|
342
334
|
return { ...env, TERM: "xterm-256color", COLORTERM: "truecolor", ALP_TERMINAL: "1", ALP_TERMINAL_ID: marker };
|
|
343
335
|
}
|
|
336
|
+
function forget(terminal) {
|
|
337
|
+
terminal.screen.dispose();
|
|
338
|
+
terminals.delete(terminal.id);
|
|
339
|
+
changed(terminal);
|
|
340
|
+
}
|
|
344
341
|
const running = (filter) => [...terminals.values()].filter((terminal) => !terminal.exit && filter(terminal)).length;
|
|
345
342
|
return {
|
|
346
343
|
/** `terminalLimits` for daemon.hello while terminals are served, else undefined. */
|
|
347
344
|
async advertised() {
|
|
348
345
|
if (closed || !supported) return void 0;
|
|
349
346
|
const current = await state().catch(() => void 0);
|
|
350
|
-
return current?.enabled && pty() ? current.limits : void 0;
|
|
347
|
+
return !cleanupFault && current?.enabled && pty() ? current.limits : void 0;
|
|
351
348
|
},
|
|
352
|
-
|
|
353
|
-
const limits = await ready();
|
|
349
|
+
create(principal, params) {
|
|
354
350
|
const requestKey = JSON.stringify([principal.id, principal.epoch, params.requestId]);
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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
|
+
});
|
|
361
358
|
}
|
|
362
|
-
if (
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
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;
|
|
403
448
|
},
|
|
404
449
|
async list(principal, params) {
|
|
405
450
|
if (supported) await state().catch(() => void 0);
|
|
406
|
-
|
|
407
|
-
|
|
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;
|
|
408
472
|
},
|
|
409
473
|
async attach(principal, sink, params) {
|
|
410
474
|
await ready();
|
|
@@ -418,6 +482,7 @@ function createTerminalService(options) {
|
|
|
418
482
|
const gap = after + 1 < first && after < lastOutput ? { fromSeq: after + 1, toSeq: Math.min(first, lastOutput + 1) - 1 } : void 0;
|
|
419
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 } });
|
|
420
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);
|
|
421
486
|
audit("terminal attached", terminal, { code: "ALPD_TERMINAL_ATTACHED", after, ...gap ? { gap: gap.toSeq - gap.fromSeq + 1 } : {} });
|
|
422
487
|
return { terminal: info(terminal), nextSeq: terminal.nextSeq, ...gap ? { gap } : {} };
|
|
423
488
|
},
|
|
@@ -437,32 +502,42 @@ function createTerminalService(options) {
|
|
|
437
502
|
const terminal = own(principal, params.terminalId);
|
|
438
503
|
if (terminal.sink !== sink) throw new RpcError(ERROR.conflict, "Attach the terminal on this connection first", { reason: "not_attached" });
|
|
439
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);
|
|
440
506
|
terminal.pty.resize(params.cols, params.rows);
|
|
441
507
|
terminal.cols = params.cols;
|
|
442
508
|
terminal.rows = params.rows;
|
|
509
|
+
changed(terminal);
|
|
443
510
|
return { cols: terminal.cols, rows: terminal.rows };
|
|
444
511
|
},
|
|
445
512
|
async close(principal, params) {
|
|
446
513
|
const terminal = own(principal, params.terminalId);
|
|
447
514
|
if (terminal.exit) {
|
|
448
|
-
|
|
515
|
+
await terminal.reaped;
|
|
516
|
+
forget(terminal);
|
|
449
517
|
return { closed: true };
|
|
450
518
|
}
|
|
451
519
|
await end(terminal, "closed");
|
|
452
|
-
|
|
520
|
+
forget(terminal);
|
|
453
521
|
return { closed: true };
|
|
454
522
|
},
|
|
455
523
|
/** Every terminal of a principal, any epoch: a gateway's revocation. */
|
|
456
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");
|
|
457
528
|
const mine = [...terminals.values()].filter((terminal) => terminal.principal.id === principalId);
|
|
458
|
-
const live = mine.filter((terminal) => !terminal.exit);
|
|
459
|
-
await Promise.
|
|
460
|
-
|
|
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);
|
|
461
535
|
if (mine.length) log.info("revoked the terminals of a principal", { code: "ALPD_TERMINAL_REVOKED", principal: principalId, closed: live.length });
|
|
462
|
-
return { closed: live.length };
|
|
536
|
+
return { closed: live.length + newlyCancelled.length };
|
|
463
537
|
},
|
|
464
538
|
/** A connection closed: its terminals keep running for reconnectMs. */
|
|
465
539
|
disconnect(sink) {
|
|
540
|
+
watchers.delete(sink);
|
|
466
541
|
for (const terminal of terminals.values()) if (terminal.sink === sink) detach(terminal, "disconnected");
|
|
467
542
|
},
|
|
468
543
|
sweep,
|
|
@@ -470,8 +545,16 @@ function createTerminalService(options) {
|
|
|
470
545
|
async shutdown() {
|
|
471
546
|
closed = true;
|
|
472
547
|
clearInterval(timer);
|
|
473
|
-
|
|
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();
|
|
474
555
|
terminals.clear();
|
|
556
|
+
watchers.clear();
|
|
557
|
+
if (cleanupFault || outcomes.some((result) => result.status === "rejected")) throw refused("terminal_cleanup_uncertain");
|
|
475
558
|
},
|
|
476
559
|
/** Test hook: pids of every running terminal's shell. */
|
|
477
560
|
pids() {
|
|
@@ -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 {};
|