@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.
Files changed (82) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +26 -1
  2. package/dist/alpd.js +10768 -2592
  3. package/dist/attachments.d.ts +25 -49
  4. package/dist/attachments.js +45 -8
  5. package/dist/build-manifest.json +14 -1
  6. package/dist/conversation.js +18 -2
  7. package/dist/disk.d.ts +67 -0
  8. package/dist/disk.js +152 -0
  9. package/dist/files.d.ts +141 -2
  10. package/dist/files.js +377 -68
  11. package/dist/git.d.ts +8 -2
  12. package/dist/git.js +111 -12
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.js +3 -0
  15. package/dist/main.js +57 -12
  16. package/dist/native-terminal.d.ts +45 -0
  17. package/dist/native-terminal.js +198 -0
  18. package/dist/operations.d.ts +12 -2
  19. package/dist/operations.js +22 -11
  20. package/dist/registry.js +1 -1
  21. package/dist/scheduler.js +8 -2
  22. package/dist/schedules.d.ts +2 -1
  23. package/dist/schedules.js +6 -4
  24. package/dist/server.d.ts +4 -2
  25. package/dist/server.js +171 -43
  26. package/dist/store.d.ts +3 -1
  27. package/dist/store.js +4 -3
  28. package/dist/terminal-native/README.md +201 -0
  29. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  30. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  31. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  32. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  33. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  34. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  35. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  36. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  37. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  38. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  39. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  40. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  41. package/dist/terminal-native/terminal-owner.c +389 -0
  42. package/dist/terminal-screen.d.ts +24 -0
  43. package/dist/terminal-screen.js +99 -0
  44. package/dist/terminals.d.ts +43 -7
  45. package/dist/terminals.js +222 -139
  46. package/dist/windows-terminal.d.ts +29 -0
  47. package/dist/windows-terminal.js +122 -0
  48. package/dist/worktrees.d.ts +25 -1
  49. package/dist/worktrees.js +74 -2
  50. package/native/README.md +201 -0
  51. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  52. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  53. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  54. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  55. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  56. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  57. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  58. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  59. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  60. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  61. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  62. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  63. package/native/terminal-owner.c +389 -0
  64. package/package.json +11 -7
  65. package/src/attachments.ts +46 -8
  66. package/src/conversation.ts +22 -2
  67. package/src/disk.ts +175 -0
  68. package/src/files.ts +505 -80
  69. package/src/git.ts +113 -18
  70. package/src/index.ts +1 -0
  71. package/src/main.ts +53 -13
  72. package/src/native-terminal.ts +122 -0
  73. package/src/operations.ts +28 -12
  74. package/src/registry.ts +1 -1
  75. package/src/scheduler.ts +13 -3
  76. package/src/schedules.ts +5 -2
  77. package/src/server.ts +164 -36
  78. package/src/store.ts +2 -1
  79. package/src/terminal-screen.ts +74 -0
  80. package/src/terminals.ts +205 -155
  81. package/src/windows-terminal.ts +123 -0
  82. package/src/worktrees.ts +97 -2
package/src/terminals.ts CHANGED
@@ -1,20 +1,22 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { execFile } from 'node:child_process';
3
3
  import { constants } from 'node:fs';
4
- import { readFileSync } from 'node:fs';
5
4
  import { access, lstat, readFile } from 'node:fs/promises';
6
- import { createRequire } from 'node:module';
5
+ import { nativePtySpawn, nativeTerminalCapability, type CleanupResult } from './native-terminal.js';
6
+ import { windowsPtySpawn, windowsShell, windowsTerminalCapability } from './windows-terminal.js';
7
7
  import path from 'node:path';
8
8
  import { ERROR, RPC_ERROR, TERMINAL, TERMINAL_LIMIT_KEYS, isTerminalId } from '@anhlp/alp-protocol';
9
9
  import type { TerminalEndReason, TerminalEvent, TerminalInfo, TerminalLimits } from '@anhlp/alp-protocol/rpc';
10
10
  import { RpcError } from './rpc-error.js';
11
+ import { TerminalScreen, SCREEN_LIMITS } from './terminal-screen.js';
11
12
 
12
13
  /**
13
14
  * Terminals (capability `terminal`, docs/protocol/alp-json-rpc-v1.md §12.10, issue #121 H): a real
14
15
  * PTY running a shell on this host **as the daemon's account**. A workspace chooses only where the
15
16
  * shell starts and who sees the terminal; it is not a sandbox. alpd serves terminals only while the
16
17
  * host owner opted in (`<ALP_HOME>/terminal.json` `allowRemoteTerminal`, an owner-private file no RPC
17
- * writes), on macOS and Linux, when the optional `node-pty` module loads. Lifecycle is audited;
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;
18
20
  * input, output and the environment never are.
19
21
  */
20
22
 
@@ -23,7 +25,7 @@ export type TerminalPrincipal = { id: string; epoch: string; roots?: readonly st
23
25
  /** The connection a terminal streams to: alpd's own IPC connection object. */
24
26
  export type TerminalSink = { send(message: unknown): void; socket?: { writableLength: number; destroyed?: boolean } };
25
27
  type Disposable = { dispose(): void };
26
- /** What alpd uses of a node-pty process. */
28
+ /** Native owner interface; injected owners are used only by tests. */
27
29
  export type PtyProcess = {
28
30
  pid: number;
29
31
  /** The PTY's device (node-pty's UnixTerminal), such as /dev/ttys004 or /dev/pts/3. */
@@ -31,10 +33,13 @@ export type PtyProcess = {
31
33
  write(data: string): void;
32
34
  resize(cols: number, rows: number): void;
33
35
  kill(signal?: string): void;
36
+ cleanup?: () => Promise<CleanupResult>;
34
37
  onData(listener: (data: string) => void): Disposable;
35
- onExit(listener: (event: { exitCode: number; signal?: number }) => void): Disposable;
38
+ onExit(listener: (event: { exitCode: number | null; signal?: number }) => void): Disposable;
36
39
  };
37
- export type PtySpawn = (file: string, args: string[], options: { name: string; cols: number; rows: number; cwd: string; env: Record<string, string> }) => PtyProcess;
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>;
38
43
  /** One process: ids, (Linux) session, controlling tty, age, and the terminal markers in its environment. */
39
44
  export type ProcessRow = { pid: number; ppid: number; pgid: number; sid?: number; tty?: string; elapsedMs: number; markers?: string[] };
40
45
  type Log = { info(message: string, fields?: Record<string, unknown>): void; warn(message: string, fields?: Record<string, unknown>): void };
@@ -48,8 +53,10 @@ export type TerminalServiceOptions = {
48
53
  limits?: Partial<TerminalLimits>;
49
54
  now?: () => number;
50
55
  platform?: NodeJS.Platform;
51
- /** Test hook: the PTY spawner; default node-pty, loaded on first use. */
56
+ /** Test hook: the PTY owner; production uses only the identity-bound native owner. */
52
57
  spawn?: PtySpawn;
58
+ /** Test hook: capability result; production always verifies the shipped helper. */
59
+ capability?: typeof nativeTerminalCapability;
53
60
  /** Test hook: the process table; default `ps`. */
54
61
  processes?: () => Promise<ProcessRow[]>;
55
62
  sweepMs?: number;
@@ -64,10 +71,12 @@ type Terminal = {
64
71
  principal: { id: string; epoch: string };
65
72
  workspaceId: string;
66
73
  root: string;
74
+ protection?: TerminalProtection;
67
75
  title: string;
68
76
  cols: number;
69
77
  rows: number;
70
78
  pty: PtyProcess;
79
+ screen: TerminalScreen;
71
80
  pid: number;
72
81
  /** The PTY's device as ps names it (ttys004, pts/3): a controlling terminal outlives double forks. */
73
82
  tty?: string;
@@ -80,11 +89,7 @@ type Terminal = {
80
89
  nextSeq: number;
81
90
  sink?: TerminalSink;
82
91
  detachedAt?: number;
83
- /**
84
- * A random value in the environment of every process the terminal starts (ALP_TERMINAL_ID): it
85
- * finds a job that left the shell's tree (double fork, re-parented, shell already gone) without
86
- * remembering any process or group id that could be reused.
87
- */
92
+ /** Informational terminal marker only; NEVER used to discover or signal processes. */
88
93
  marker: string;
89
94
  ending?: TerminalEndReason;
90
95
  exit?: { seq: number; exitCode: number | null; signal: number | null; reason: TerminalEndReason; at: number };
@@ -106,12 +111,14 @@ const iso = (ms: number) => new Date(ms).toISOString();
106
111
  * The host switch and the operator's lower limits. Anything but a regular, owner-private file of
107
112
  * this user saying `"allowRemoteTerminal": true` is off.
108
113
  */
109
- export async function readTerminalConfig(home: string, log?: Log): Promise<{ enabled: boolean; reason?: string; limits: TerminalLimits; paseo: boolean }> {
114
+ export async function readTerminalConfig(home: string, log?: Log, platform: NodeJS.Platform = process.platform): Promise<{ enabled: boolean; reason?: string; limits: TerminalLimits; paseo: boolean }> {
110
115
  const defaults = Object.fromEntries(TERMINAL_LIMIT_KEYS.map(key => [key, TERMINAL[key as keyof typeof TERMINAL]])) as TerminalLimits;
111
116
  const file = path.join(home, CONFIG_FILE);
112
117
  const info = await lstat(file).catch(() => undefined);
113
118
  if (!info) return { enabled: false, reason: 'missing', limits: defaults, paseo: false };
114
- if (!info.isFile() || (process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077)) {
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))) {
115
122
  log?.warn('terminal.json is not a private file of the daemon user; terminals stay off', { code: 'ALPD_TERMINAL_CONFIG' });
116
123
  return { enabled: false, reason: 'not_private', limits: defaults, paseo: false };
117
124
  }
@@ -153,7 +160,10 @@ const ENTRY = /^ALP_TERMINAL_ID=(atm_[0-9a-f]{32})$/;
153
160
  * markers in each process's environment (macOS: `ps -E`, this user's processes only; Linux:
154
161
  * /proc/<pid>/environ, readable for this user's processes).
155
162
  */
156
- export function psProcesses(platform: NodeJS.Platform = process.platform): () => Promise<ProcessRow[]> {
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[]> {
157
167
  const linux = platform === 'linux';
158
168
  // At most 10 s for each ps, even one that does not die at once.
159
169
  const run = (args: string[]) => new Promise<string | undefined>(resolve => {
@@ -181,7 +191,7 @@ export function psProcesses(platform: NodeJS.Platform = process.platform): () =>
181
191
  const tty = cells[linux ? 4 : 3]!;
182
192
  let markers: string[] = [];
183
193
  // Linux: one entry of the environment, never a marker inside another variable's value.
184
- if (linux) { try { markers = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0').flatMap(entry => ENTRY.exec(entry)?.[1] ?? []); } catch {} }
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 {} }
185
195
  else {
186
196
  // Exactly one space after etime: a command line may itself start with spaces.
187
197
  const full = /^\s*(?:\S+\s+){4}\S+ (.*)$/.exec(line)?.[1] ?? '';
@@ -215,29 +225,46 @@ export function createTerminalService(options: TerminalServiceOptions) {
215
225
  const { home, resolveWorkspace, log } = options;
216
226
  const now = options.now ?? Date.now;
217
227
  const platform = options.platform ?? process.platform;
218
- const supported = platform === 'darwin' || platform === 'linux';
219
- const listProcesses = options.processes ?? psProcesses(platform);
228
+ const supported = platform === 'darwin' || platform === 'linux' || platform === 'win32';
229
+ const windows = platform === 'win32';
220
230
  const killGraceMs = options.killGraceMs ?? KILL_GRACE_MS;
221
231
  const maxBuffered = options.maxBufferedBytes ?? MAX_BUFFERED_BYTES;
222
232
  const terminals = new Map<string, Terminal>();
223
233
  const requests = new Map<string, string>();
224
- let spawner: PtySpawn | undefined = options.spawn;
225
- let loadError: unknown;
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
+ }
226
247
  let closed = false;
227
248
  let enabled = false;
228
-
229
- /** node-pty, loaded once on first need; its absence only turns terminals off. */
230
- function pty(): PtySpawn | undefined {
231
- if (spawner || loadError) return spawner;
232
- try {
233
- const name = 'node-pty';
234
- const module = createRequire(import.meta.url)(name);
235
- spawner = module.spawn as PtySpawn;
236
- } catch (error) {
237
- loadError = error;
238
- log.warn('the optional node-pty module did not load; terminals are unavailable', { code: 'ALPD_TERMINAL_UNAVAILABLE', error });
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');
239
267
  }
240
- return spawner;
241
268
  }
242
269
 
243
270
  /** Effective limits: the operator's, then the caller's lower ones. */
@@ -252,23 +279,25 @@ export function createTerminalService(options: TerminalServiceOptions) {
252
279
 
253
280
  /** The switch now: off kills every terminal (reason `disabled`). */
254
281
  async function state() {
255
- const config = await readTerminalConfig(home, log);
282
+ const config = await readTerminalConfig(home, log, platform);
256
283
  const limits = effective(config.limits);
257
284
  if (enabled && !config.enabled) {
258
285
  log.info('terminals turned off on this host; ending every terminal', { code: 'ALPD_TERMINAL_DISABLED' });
259
- for (const terminal of terminals.values()) if (!terminal.exit) void end(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(() => {});
260
288
  }
261
289
  enabled = config.enabled;
262
290
  return { enabled: config.enabled, limits };
263
291
  }
264
292
 
265
- /** The switch, the platform and the module, or the refusal. */
293
+ /** The switch, the platform and the owner (native helper; node-pty on win32), or the refusal. */
266
294
  async function ready() {
295
+ if (cleanupFault) throw refused('terminal_cleanup_uncertain');
267
296
  if (closed) throw new RpcError(ERROR.unavailable, 'alpd is shutting down', { reason: 'terminal_unsupported' });
268
297
  if (!supported) throw new RpcError(ERROR.unavailable, 'Terminals are not supported on this host\'s platform', { reason: 'terminal_unsupported' });
269
298
  const current = await state();
270
299
  if (!current.enabled) throw new RpcError(ERROR.unavailable, 'The host has not allowed remote terminals (alp terminal allow)', { reason: 'terminal_disabled' });
271
- if (!pty()) throw new RpcError(ERROR.unavailable, 'The terminal module is not installed on this host', { reason: 'terminal_unsupported' });
300
+ if (!pty()) throw new RpcError(ERROR.unavailable, 'The native terminal owner is unavailable on this host', { reason: 'terminal_unsupported' });
272
301
  return current.limits;
273
302
  }
274
303
 
@@ -278,6 +307,7 @@ export function createTerminalService(options: TerminalServiceOptions) {
278
307
  state: terminal.exit ? 'exited' : 'running', attached: !!terminal.sink, createdAt: iso(terminal.createdAt),
279
308
  lastActivityAt: iso(terminal.lastActivityAt), expiresAt: iso(terminal.expiresAt),
280
309
  ...(terminal.exit ? { exitCode: terminal.exit.exitCode, signal: terminal.exit.signal, endReason: terminal.exit.reason } : {}),
310
+ ...(terminal.protection ? { protection: terminal.protection } : {}),
281
311
  };
282
312
  }
283
313
 
@@ -310,11 +340,13 @@ export function createTerminalService(options: TerminalServiceOptions) {
310
340
  terminal.sink = undefined;
311
341
  terminal.detachedAt = now();
312
342
  if (reason !== 'disconnected') sink.send({ jsonrpc: '2.0', method: 'terminal.event', params: { terminalId: terminal.id, type: 'detached', reason } satisfies TerminalEvent });
343
+ changed(terminal);
313
344
  audit('terminal detached', terminal, { code: 'ALPD_TERMINAL_DETACHED', reason });
314
345
  }
315
346
 
316
347
  function output(terminal: Terminal, data: string, limits: TerminalLimits) {
317
348
  terminal.lastActivityAt = now();
349
+ terminal.screen.write(data);
318
350
  for (const piece of frames(data, limits.maxOutputFrameBytes)) {
319
351
  const frame: Frame = { seq: terminal.nextSeq++, data: piece, bytes: Buffer.byteLength(piece) };
320
352
  terminal.ring.push(frame);
@@ -324,72 +356,11 @@ export function createTerminalService(options: TerminalServiceOptions) {
324
356
  }
325
357
  }
326
358
 
327
- /**
328
- * Every process of a terminal still running, identified afresh from the process table, never from
329
- * a remembered pid or group id (one that may have been reused):
330
- * - its marker in the environment (any process the terminal started, wherever it went);
331
- * - while the shell runs: the shell itself and every process whose controlling terminal is its PTY;
332
- * - on Linux, its session (a session id is not reused while the session has members);
333
- * then their descendants, and every member of their process groups (a live group's id is not
334
- * reused either). Never alpd itself or its group, never a process older than the terminal.
335
- */
336
- async function tree(terminal: Terminal): Promise<ProcessRow[]> {
337
- // Whether the shell runs is decided before the snapshot, never after it.
338
- const running = !terminal.exit;
339
- // The terminal's age when the snapshot began: ps (and its /proc reads) may take a while.
340
- const lifetime = now() - terminal.createdAt;
341
- const rows = await listProcesses();
342
- const age = now() - terminal.createdAt + 2_000;
343
- const own = rows.find(row => row.pid === process.pid);
344
- const children = new Map<number, ProcessRow[]>();
345
- for (const row of rows) children.set(row.ppid, [...(children.get(row.ppid) ?? []), row]);
346
- const found = new Map<number, ProcessRow>();
347
- for (const row of rows) if (row.markers?.includes(terminal.marker)) found.set(row.pid, row);
348
- // The process with the shell's pid is our shell only when it is as old as the terminal (etime
349
- // counts whole seconds): a younger one got the pid again after our shell had gone.
350
- const holder = rows.find(row => row.pid === terminal.pid);
351
- const ours = !holder || holder.elapsedMs >= lifetime - 2_000;
352
- const shell = running && ours ? holder : undefined;
353
- if (shell) found.set(shell.pid, shell);
354
- // The PTY's device name counts only while the shell, in this very snapshot, still has it as its
355
- // terminal: once node-pty closed it the name may already be another PTY's.
356
- const tty = shell && terminal.tty && shell.tty === terminal.tty ? terminal.tty : undefined;
357
- // Linux: the session, also once the shell has gone. A pid is not given out again while it is a
358
- // live process's session id, so while our session has members its id stays ours; a younger
359
- // process holding the shell's pid means it was given out again. (Left open: our session emptied,
360
- // and within the reap's second or so a new session leader got the very same pid and exited.)
361
- for (const row of rows) {
362
- if ((tty && row.tty === tty) || (row.sid !== undefined && row.sid === terminal.pid && ours)) found.set(row.pid, row);
363
- }
364
- const queue = [...found.values()];
365
- while (queue.length) {
366
- const row = queue.pop()!;
367
- for (const child of children.get(row.pid) ?? []) if (!found.has(child.pid)) { found.set(child.pid, child); queue.push(child); }
368
- }
369
- const groups = new Set([...found.values()].map(row => row.pgid));
370
- for (const row of rows) if (groups.has(row.pgid)) found.set(row.pid, row);
371
- return [...found.values()].filter(row => row.pid > 1 && row.pid !== process.pid && (!own || row.pgid !== own.pgid) && row.elapsedMs <= age);
372
- }
373
-
374
- function signal(rows: ProcessRow[], name: NodeJS.Signals) {
375
- for (const row of rows) { try { process.kill(row.pid, name); } catch {} }
376
- }
377
-
378
- /**
379
- * Kills what is left of a terminal's tree: SIGHUP, then SIGKILL after the grace. Only processes
380
- * the process table shows in the tree now (never a bare group id that may have been reused).
381
- */
359
+ /** Native owns discovery, identity-bound signals, and exclusive root reap. */
382
360
  function reap(terminal: Terminal) {
383
- terminal.reaped ??= (async () => {
384
- signal(await tree(terminal), 'SIGHUP');
385
- await new Promise(resolve => setTimeout(resolve, killGraceMs));
386
- const left = await tree(terminal);
387
- signal(left, 'SIGKILL');
388
- if (left.length) {
389
- await new Promise(resolve => setTimeout(resolve, 100));
390
- signal(await tree(terminal), 'SIGKILL');
391
- }
392
- })().catch(error => log.warn('could not end every process of a terminal', { code: 'ALPD_TERMINAL_REAP_FAILED', terminalId: terminal.id, error }));
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(() => {});
393
364
  return terminal.reaped;
394
365
  }
395
366
 
@@ -401,8 +372,9 @@ export function createTerminalService(options: TerminalServiceOptions) {
401
372
  for (const disposable of terminal.disposables) { try { disposable.dispose(); } catch {} }
402
373
  requests.delete(terminal.requestKey);
403
374
  send(terminal, { terminalId: terminal.id, type: 'exit', seq: terminal.exit.seq, exitCode, signal: signalNumber, reason });
375
+ changed(terminal);
404
376
  audit('terminal ended', terminal, { code: 'ALPD_TERMINAL_ENDED', reason, exitCode, signal: signalNumber });
405
- void reap(terminal);
377
+ void reap(terminal).catch(() => {});
406
378
  }
407
379
 
408
380
  /** Ends a running terminal for `reason`; resolves once its tree was killed. */
@@ -410,9 +382,8 @@ export function createTerminalService(options: TerminalServiceOptions) {
410
382
  if (terminal.exit) return terminal.reaped;
411
383
  terminal.ending ??= reason;
412
384
  const reaping = reap(terminal);
413
- try { terminal.pty.kill('SIGHUP'); } catch {}
414
385
  await reaping;
415
- // node-pty reports the exit when the PTY closes; do not wait on it for ever.
386
+ // A clean native completion includes the root reap; preserve an exit if no callback arrived.
416
387
  if (!terminal.exit) exited(terminal, null, null);
417
388
  }
418
389
 
@@ -429,12 +400,12 @@ export function createTerminalService(options: TerminalServiceOptions) {
429
400
  const at = now();
430
401
  for (const terminal of [...terminals.values()]) {
431
402
  if (terminal.exit) {
432
- if (at - terminal.exit.at >= limits.reconnectMs) terminals.delete(terminal.id);
403
+ if (at - terminal.exit.at >= limits.reconnectMs) forget(terminal);
433
404
  continue;
434
405
  }
435
- if (at >= terminal.expiresAt) void end(terminal, 'lifetime');
436
- else if (at - terminal.lastActivityAt >= limits.idleMs) void end(terminal, 'idle');
437
- else if (!terminal.sink && terminal.detachedAt !== undefined && at - terminal.detachedAt >= limits.reconnectMs) void end(terminal, 'detached');
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(() => {});
438
409
  }
439
410
  }
440
411
  const timer = setInterval(() => void sweep().catch(() => {}), options.sweepMs ?? SWEEP_MS);
@@ -442,6 +413,7 @@ export function createTerminalService(options: TerminalServiceOptions) {
442
413
 
443
414
  /** The approved shell: the daemon user's login shell when /etc/shells lists it, else /bin/sh. */
444
415
  async function shell() {
416
+ if (windows) return windowsShell();
445
417
  const candidate = process.env.SHELL;
446
418
  if (candidate && path.isAbsolute(candidate)) {
447
419
  const listed = await readFile('/etc/shells', 'utf8').then(text => text.split('\n').map(line => line.trim()).includes(candidate), () => false);
@@ -456,6 +428,12 @@ export function createTerminalService(options: TerminalServiceOptions) {
456
428
  return { ...env, TERM: 'xterm-256color', COLORTERM: 'truecolor', ALP_TERMINAL: '1', ALP_TERMINAL_ID: marker };
457
429
  }
458
430
 
431
+ function forget(terminal: Terminal) {
432
+ terminal.screen.dispose();
433
+ terminals.delete(terminal.id);
434
+ changed(terminal);
435
+ }
436
+
459
437
  const running = (filter: (terminal: Terminal) => boolean) => [...terminals.values()].filter(terminal => !terminal.exit && filter(terminal)).length;
460
438
 
461
439
  return {
@@ -463,56 +441,114 @@ export function createTerminalService(options: TerminalServiceOptions) {
463
441
  async advertised(): Promise<TerminalLimits | undefined> {
464
442
  if (closed || !supported) return undefined;
465
443
  const current = await state().catch(() => undefined);
466
- return current?.enabled && pty() ? current.limits : undefined;
444
+ return !cleanupFault && current?.enabled && pty() ? current.limits : undefined;
467
445
  },
468
446
 
469
- async create(principal: TerminalPrincipal, params: { workspaceId: string; cols: number; rows: number; requestId: string }): Promise<{ terminal: TerminalInfo }> {
470
- const limits = await ready();
447
+ create(principal: TerminalPrincipal, params: { workspaceId: string; cols: number; rows: number; requestId: string; protectionAcknowledgment?: 'linux-root-only-v1' /* deprecated, ignored */ }): Promise<{ terminal: TerminalInfo }> {
471
448
  const requestKey = JSON.stringify([principal.id, principal.epoch, params.requestId]);
472
- let root: string;
473
- try { root = await resolveWorkspace(params.workspaceId); } catch (error: any) {
474
- 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' });
475
- throw error;
476
- }
477
- if (!within(principal, root)) throw new RpcError(ERROR.forbidden, 'The workspace is outside this grant', { reason: 'outside_workspace' });
478
- const file = await shell();
479
- // From here to the spawn nothing awaits: the requestId, both limits and the new terminal are
480
- // checked and recorded in one step, so concurrent creates cannot pass the same check.
481
- if (closed) throw new RpcError(ERROR.unavailable, 'alpd is shutting down', { reason: 'terminal_unsupported' });
482
- const repeated = terminals.get(requests.get(requestKey) ?? '');
483
- if (repeated && !repeated.exit) {
484
- if (repeated.workspaceId !== params.workspaceId) throw new RpcError(ERROR.conflict, 'This requestId created another terminal', { reason: 'request_conflict' });
485
- return { terminal: info(repeated) };
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; });
486
453
  }
487
- if (running(terminal => terminal.principal.id === principal.id) >= limits.maxPerPrincipal) throw new RpcError(ERROR.unavailable, `At most ${limits.maxPerPrincipal} terminals run per principal`, { reason: 'terminal_limit', limit: 'principal' });
488
- if (running(() => true) >= limits.maxPerDaemon) throw new RpcError(ERROR.unavailable, `At most ${limits.maxPerDaemon} terminals run on this host`, { reason: 'terminal_limit', limit: 'daemon' });
489
- const at = now();
490
- const marker = `atm_${randomBytes(16).toString('hex')}`;
491
- const process_ = pty()!(file, [], { name: 'xterm-256color', cols: params.cols, rows: params.rows, cwd: root, env: environment(marker) });
492
- const terminal: Terminal = {
493
- id: `term_${randomBytes(16).toString('hex')}`, principal: { id: principal.id, epoch: principal.epoch }, workspaceId: params.workspaceId,
494
- root, title: path.basename(file).slice(0, 64), cols: params.cols, rows: params.rows, pty: process_, pid: process_.pid,
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
- audit('terminal created', terminal, { code: 'ALPD_TERMINAL_CREATED' });
504
- return { terminal: info(terminal) };
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;
505
523
  },
506
524
 
507
525
  async list(principal: TerminalPrincipal, params: { workspaceId?: string }) {
508
526
  if (supported) await state().catch(() => undefined);
509
- const terminals_ = [...terminals.values()]
510
- .filter(terminal => terminal.principal.id === principal.id && terminal.principal.epoch === principal.epoch && within(principal, terminal.root) && (params.workspaceId === undefined || terminal.workspaceId === params.workspaceId))
511
- .sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1));
512
- return { terminals: terminals_.map(info) };
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;
513
549
  },
514
550
 
515
- async attach(principal: TerminalPrincipal, sink: TerminalSink, params: { terminalId: string; after?: number }) {
551
+ async attach(principal: TerminalPrincipal, sink: TerminalSink, params: { terminalId: string; after?: number; protectionAcknowledgment?: 'linux-root-only-v1' /* deprecated, ignored */ }) {
516
552
  await ready();
517
553
  const terminal = own(principal, params.terminalId);
518
554
  if (terminal.sink && terminal.sink !== sink) detach(terminal, 'replaced');
@@ -524,6 +560,7 @@ export function createTerminalService(options: TerminalServiceOptions) {
524
560
  const gap = after + 1 < first && after < lastOutput ? { fromSeq: after + 1, toSeq: Math.min(first, lastOutput + 1) - 1 } : undefined;
525
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 });
526
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);
527
564
  audit('terminal attached', terminal, { code: 'ALPD_TERMINAL_ATTACHED', after, ...(gap ? { gap: gap.toSeq - gap.fromSeq + 1 } : {}) });
528
565
  return { terminal: info(terminal), nextSeq: terminal.nextSeq, ...(gap ? { gap } : {}) };
529
566
  },
@@ -545,32 +582,39 @@ export function createTerminalService(options: TerminalServiceOptions) {
545
582
  const terminal = own(principal, params.terminalId);
546
583
  if (terminal.sink !== sink) throw new RpcError(ERROR.conflict, 'Attach the terminal on this connection first', { reason: 'not_attached' });
547
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);
548
586
  terminal.pty.resize(params.cols, params.rows);
549
587
  terminal.cols = params.cols;
550
588
  terminal.rows = params.rows;
589
+ changed(terminal);
551
590
  return { cols: terminal.cols, rows: terminal.rows };
552
591
  },
553
592
 
554
593
  async close(principal: TerminalPrincipal, params: { terminalId: string }) {
555
594
  const terminal = own(principal, params.terminalId);
556
- if (terminal.exit) { terminals.delete(terminal.id); return { closed: true as const }; }
595
+ if (terminal.exit) { await terminal.reaped; forget(terminal); return { closed: true as const }; }
557
596
  await end(terminal, 'closed');
558
- terminals.delete(terminal.id);
597
+ forget(terminal);
559
598
  return { closed: true as const };
560
599
  },
561
600
 
562
601
  /** Every terminal of a principal, any epoch: a gateway's revocation. */
563
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');
564
606
  const mine = [...terminals.values()].filter(terminal => terminal.principal.id === principalId);
565
- const live = mine.filter(terminal => !terminal.exit);
566
- await Promise.all(live.map(terminal => end(terminal, 'revoked')));
567
- for (const terminal of mine) terminals.delete(terminal.id);
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);
568
611
  if (mine.length) log.info('revoked the terminals of a principal', { code: 'ALPD_TERMINAL_REVOKED', principal: principalId, closed: live.length });
569
- return { closed: live.length };
612
+ return { closed: live.length + newlyCancelled.length };
570
613
  },
571
614
 
572
615
  /** A connection closed: its terminals keep running for reconnectMs. */
573
616
  disconnect(sink: TerminalSink) {
617
+ watchers.delete(sink);
574
618
  for (const terminal of terminals.values()) if (terminal.sink === sink) detach(terminal, 'disconnected');
575
619
  },
576
620
 
@@ -580,8 +624,14 @@ export function createTerminalService(options: TerminalServiceOptions) {
580
624
  async shutdown() {
581
625
  closed = true;
582
626
  clearInterval(timer);
583
- await Promise.all([...terminals.values()].map(terminal => terminal.exit ? terminal.reaped : end(terminal, 'shutdown')));
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();
584
632
  terminals.clear();
633
+ watchers.clear();
634
+ if (cleanupFault || outcomes.some(result => result.status === 'rejected')) throw refused('terminal_cleanup_uncertain');
585
635
  },
586
636
 
587
637
  /** Test hook: pids of every running terminal's shell. */