shellpuppet 0.0.1 → 0.2.0
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/LICENSE +202 -0
- package/NOTICE +31 -0
- package/README.md +499 -8
- package/dist/cli/desktopShortcut.d.ts +22 -0
- package/dist/cli/desktopShortcut.js +157 -0
- package/dist/cli/desktopShortcut.js.map +1 -0
- package/dist/cli/index.d.ts +13 -0
- package/dist/cli/index.js +846 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/client/http.d.ts +143 -0
- package/dist/client/http.js +581 -0
- package/dist/client/http.js.map +1 -0
- package/dist/core/dialogs.d.ts +96 -0
- package/dist/core/dialogs.js +226 -0
- package/dist/core/dialogs.js.map +1 -0
- package/dist/core/echo.d.ts +71 -0
- package/dist/core/echo.js +249 -0
- package/dist/core/echo.js.map +1 -0
- package/dist/core/find.d.ts +34 -0
- package/dist/core/find.js +41 -0
- package/dist/core/find.js.map +1 -0
- package/dist/core/keys.d.ts +22 -0
- package/dist/core/keys.js +80 -0
- package/dist/core/keys.js.map +1 -0
- package/dist/core/manager.d.ts +96 -0
- package/dist/core/manager.js +271 -0
- package/dist/core/manager.js.map +1 -0
- package/dist/core/nativePty.d.ts +73 -0
- package/dist/core/nativePty.js +161 -0
- package/dist/core/nativePty.js.map +1 -0
- package/dist/core/policy.d.ts +61 -0
- package/dist/core/policy.js +143 -0
- package/dist/core/policy.js.map +1 -0
- package/dist/core/promptDetector.d.ts +109 -0
- package/dist/core/promptDetector.js +897 -0
- package/dist/core/promptDetector.js.map +1 -0
- package/dist/core/reasoning.d.ts +265 -0
- package/dist/core/reasoning.js +933 -0
- package/dist/core/reasoning.js.map +1 -0
- package/dist/core/regexBudget.d.ts +64 -0
- package/dist/core/regexBudget.js +103 -0
- package/dist/core/regexBudget.js.map +1 -0
- package/dist/core/renderer.d.ts +127 -0
- package/dist/core/renderer.js +316 -0
- package/dist/core/renderer.js.map +1 -0
- package/dist/core/selection.d.ts +6 -0
- package/dist/core/selection.js +48 -0
- package/dist/core/selection.js.map +1 -0
- package/dist/core/session.d.ts +565 -0
- package/dist/core/session.js +1450 -0
- package/dist/core/session.js.map +1 -0
- package/dist/core/types.d.ts +316 -0
- package/dist/core/types.js +71 -0
- package/dist/core/types.js.map +1 -0
- package/dist/core/waiter.d.ts +94 -0
- package/dist/core/waiter.js +310 -0
- package/dist/core/waiter.js.map +1 -0
- package/dist/core/windowsConsoleHost.d.ts +147 -0
- package/dist/core/windowsConsoleHost.js +588 -0
- package/dist/core/windowsConsoleHost.js.map +1 -0
- package/dist/core/windowsPtyStart.d.ts +161 -0
- package/dist/core/windowsPtyStart.js +236 -0
- package/dist/core/windowsPtyStart.js.map +1 -0
- package/dist/daemon/audit.d.ts +23 -0
- package/dist/daemon/audit.js +51 -0
- package/dist/daemon/audit.js.map +1 -0
- package/dist/daemon/auth.d.ts +197 -0
- package/dist/daemon/auth.js +366 -0
- package/dist/daemon/auth.js.map +1 -0
- package/dist/daemon/config.d.ts +119 -0
- package/dist/daemon/config.js +568 -0
- package/dist/daemon/config.js.map +1 -0
- package/dist/daemon/folderPicker.d.ts +27 -0
- package/dist/daemon/folderPicker.js +115 -0
- package/dist/daemon/folderPicker.js.map +1 -0
- package/dist/daemon/index.d.ts +7 -0
- package/dist/daemon/index.js +88 -0
- package/dist/daemon/index.js.map +1 -0
- package/dist/daemon/launchProfiles.d.ts +155 -0
- package/dist/daemon/launchProfiles.js +554 -0
- package/dist/daemon/launchProfiles.js.map +1 -0
- package/dist/daemon/liveness.d.ts +36 -0
- package/dist/daemon/liveness.js +71 -0
- package/dist/daemon/liveness.js.map +1 -0
- package/dist/daemon/logger.d.ts +7 -0
- package/dist/daemon/logger.js +29 -0
- package/dist/daemon/logger.js.map +1 -0
- package/dist/daemon/meta.d.ts +9 -0
- package/dist/daemon/meta.js +24 -0
- package/dist/daemon/meta.js.map +1 -0
- package/dist/daemon/paths.d.ts +85 -0
- package/dist/daemon/paths.js +154 -0
- package/dist/daemon/paths.js.map +1 -0
- package/dist/daemon/screenshot.d.ts +144 -0
- package/dist/daemon/screenshot.js +402 -0
- package/dist/daemon/screenshot.js.map +1 -0
- package/dist/daemon/server.d.ts +453 -0
- package/dist/daemon/server.js +3954 -0
- package/dist/daemon/server.js.map +1 -0
- package/dist/daemon/sessionFeed.d.ts +48 -0
- package/dist/daemon/sessionFeed.js +101 -0
- package/dist/daemon/sessionFeed.js.map +1 -0
- package/dist/daemon/terminalReports.d.ts +38 -0
- package/dist/daemon/terminalReports.js +84 -0
- package/dist/daemon/terminalReports.js.map +1 -0
- package/dist/daemon/viewerLauncher.d.ts +226 -0
- package/dist/daemon/viewerLauncher.js +562 -0
- package/dist/daemon/viewerLauncher.js.map +1 -0
- package/dist/daemon/viewerSync.d.ts +38 -0
- package/dist/daemon/viewerSync.js +83 -0
- package/dist/daemon/viewerSync.js.map +1 -0
- package/dist/mcp/config.d.ts +50 -0
- package/dist/mcp/config.js +95 -0
- package/dist/mcp/config.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +78 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/tools.d.ts +66 -0
- package/dist/mcp/tools.js +638 -0
- package/dist/mcp/tools.js.map +1 -0
- package/dist/viewer/dashboard-folders.js +20 -0
- package/dist/viewer/dashboard-layout.js +52 -0
- package/dist/viewer/dashboard.css +67 -0
- package/dist/viewer/dashboard.html +44 -0
- package/dist/viewer/dashboard.js +1518 -0
- package/dist/viewer/icon-16.png +0 -0
- package/dist/viewer/icon-180.png +0 -0
- package/dist/viewer/icon-32.png +0 -0
- package/dist/viewer/icon-512.png +0 -0
- package/dist/viewer/icon.ico +0 -0
- package/dist/viewer/icon.svg +66 -0
- package/dist/viewer/index.html +61 -0
- package/dist/viewer/pane.js +736 -0
- package/dist/viewer/viewer.css +95 -0
- package/dist/viewer/viewer.js +84 -0
- package/package.json +66 -7
- package/index.js +0 -4
|
@@ -0,0 +1,1450 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One PTY session: process + renderer + lifecycle (design §2.4).
|
|
3
|
+
*
|
|
4
|
+
* The session owns the real PTY (ConPTY on Windows), keeps the headless
|
|
5
|
+
* renderer current, serialises that renderer for viewers, tracks readiness
|
|
6
|
+
* and kills the whole process tree on demand (design §3.1), not just the PTY
|
|
7
|
+
* child.
|
|
8
|
+
*
|
|
9
|
+
* Shell wrapping happens HERE, after the caller has already made its policy
|
|
10
|
+
* decision against the pre-wrap command (design §4.3). Callers pass
|
|
11
|
+
* `goose session`; this module turns it into `cmd.exe /c goose session` on
|
|
12
|
+
* Windows because direct ConPTY spawns of single-file binaries hang (§7).
|
|
13
|
+
*
|
|
14
|
+
* No stdout/stderr: logging via the injected Logger only (lint-enforced).
|
|
15
|
+
*/
|
|
16
|
+
import { execFile } from 'node:child_process';
|
|
17
|
+
import * as fs from 'node:fs';
|
|
18
|
+
import * as os from 'node:os';
|
|
19
|
+
import * as path from 'node:path';
|
|
20
|
+
import { ensureSpawnHelperExecutable, explainSpawnFailure, loadNodePty } from './nativePty.js';
|
|
21
|
+
import { ScreenRenderer } from './renderer.js';
|
|
22
|
+
import { commandLine } from './policy.js';
|
|
23
|
+
import { detectPrompt, MusePromptSettler, StalePromptGuard } from './promptDetector.js';
|
|
24
|
+
import { waitFor } from './waiter.js';
|
|
25
|
+
import { canReadExitCode, listenForTerminalErrors, observeConptyStartError, recordedExitCode, releaseFailedStarts, } from './windowsPtyStart.js';
|
|
26
|
+
import { queueConsoleHostEnd, registerConsoleHostWindow } from './windowsConsoleHost.js';
|
|
27
|
+
import { DEFAULT_COLS, DEFAULT_ROWS, DEFAULT_SCROLLBACK, MAX_WAIT_TIMEOUT_MS, NULL_LOGGER, RESERVED_FEATURE_CREDENTIALS, } from './types.js';
|
|
28
|
+
/**
|
|
29
|
+
* Hard cap on `taskkill`. Without it a wedged kill never calls back, so
|
|
30
|
+
* `kill()` never resolves, `killAll()` never resolves and daemon shutdown
|
|
31
|
+
* never completes. The daemon then becomes an immortal, undiscoverable
|
|
32
|
+
* process the user can only end via Task Manager.
|
|
33
|
+
*
|
|
34
|
+
* **Why 30 s.** On a real Qoder CLI tree (78 descendants, because it spawns
|
|
35
|
+
* an MCP-server fleet) `taskkill /T /F` took **5,433 ms**. A cap tighter than
|
|
36
|
+
* a normal kill cuts the walk short and leaves the tree to the `pty.kill()`
|
|
37
|
+
* fallback below, the path that cannot reach console-detached descendants.
|
|
38
|
+
* The cap exists to bound the wedged case, not to be tighter than the normal
|
|
39
|
+
* case.
|
|
40
|
+
*/
|
|
41
|
+
export const TREE_KILL_TIMEOUT_MS = 30_000;
|
|
42
|
+
/** Quote one literal argument for the Windows C runtime's argv parser. */
|
|
43
|
+
export function windowsArgument(arg) {
|
|
44
|
+
let result = '"';
|
|
45
|
+
let backslashes = 0;
|
|
46
|
+
for (const character of arg) {
|
|
47
|
+
if (character === '\\') {
|
|
48
|
+
backslashes++;
|
|
49
|
+
}
|
|
50
|
+
else if (character === '"') {
|
|
51
|
+
result += '\\'.repeat(backslashes * 2 + 1) + '"';
|
|
52
|
+
backslashes = 0;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
result += '\\'.repeat(backslashes) + character;
|
|
56
|
+
backslashes = 0;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return result + '\\'.repeat(backslashes * 2) + '"';
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* How long a kill waits for node-pty's deferred program creation (Windows):
|
|
63
|
+
* the pid is 0 from the spawn until the output worker has connected and the
|
|
64
|
+
* program exists. node-pty gives the connection up after five seconds of its
|
|
65
|
+
* own and reports an exit instead, so this bound is never what ends the wait:
|
|
66
|
+
* either the pid arrives, or the session does.
|
|
67
|
+
*/
|
|
68
|
+
const PROGRAM_PID_WAIT_MS = 8_000;
|
|
69
|
+
/**
|
|
70
|
+
* One `taskkill` run for any number of trees. Every run enumerates every
|
|
71
|
+
* process on the machine before it kills anything, and that is most of its
|
|
72
|
+
* cost. Measured on a Windows machine running about 2,700 processes: 9 to
|
|
73
|
+
* 13 s for one lone process; thirty concurrent runs, one per session, each
|
|
74
|
+
* overran the 30 s cap; one run given all thirty pids took 10 s. So daemon
|
|
75
|
+
* shutdown kills every tree in one run (`SessionManager.killAll`).
|
|
76
|
+
*/
|
|
77
|
+
export const taskkillTrees = (pids) => new Promise((resolve) => {
|
|
78
|
+
const startedAt = Date.now();
|
|
79
|
+
execFile('taskkill', ['/T', '/F', ...pids.flatMap((pid) => ['/PID', String(pid)])],
|
|
80
|
+
// A line of output per process killed, descendants included.
|
|
81
|
+
{ windowsHide: true, timeout: TREE_KILL_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 }, (error) => {
|
|
82
|
+
resolve(error
|
|
83
|
+
? {
|
|
84
|
+
// Node also kills a child whose output overruns maxBuffer. Only
|
|
85
|
+
// our timeout counts here, so that case is excluded explicitly:
|
|
86
|
+
// Node 22 leaves `killed` off it, but that is its detail, not a
|
|
87
|
+
// promise.
|
|
88
|
+
timedOut: error.killed === true && error.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER',
|
|
89
|
+
exitCode: error.code ?? null,
|
|
90
|
+
elapsedMs: Date.now() - startedAt,
|
|
91
|
+
}
|
|
92
|
+
: null);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
/**
|
|
96
|
+
* Very large input is written to the PTY in chunks of this size, with
|
|
97
|
+
* WRITE_CHUNK_DELAY_MS between them (see Session.write), but ONLY when the app
|
|
98
|
+
* has not enabled bracketed paste (see PASTE_START below).
|
|
99
|
+
*
|
|
100
|
+
* The threshold is deliberately well above a normal prompt. Chunking exists for
|
|
101
|
+
* the OS limit underneath: a terminal's input buffer is finite (4 KB in
|
|
102
|
+
* canonical mode on Linux), so one multi-kilobyte write to a line-buffered
|
|
103
|
+
* program genuinely can be truncated. Below the threshold nothing changes, so
|
|
104
|
+
* ordinary typing and single keys are untouched.
|
|
105
|
+
*/
|
|
106
|
+
const WRITE_CHUNK_CHARS = 1024;
|
|
107
|
+
const WRITE_CHUNK_DELAY_MS = 8;
|
|
108
|
+
/** Muse needs a short pause after text before its submitting Enter. */
|
|
109
|
+
export const MUSE_SUBMIT_DELAY_MS = 400;
|
|
110
|
+
function museSubmittingText(data) {
|
|
111
|
+
if (!data.endsWith('\r'))
|
|
112
|
+
return false;
|
|
113
|
+
const body = data.slice(0, -1);
|
|
114
|
+
return !/[\r\n]/.test(body) &&
|
|
115
|
+
Array.from(body).some((character) => character > ' ' && character !== '\x7f');
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Bracketed paste (DEC private mode 2004). A TUI that enables it is telling us
|
|
119
|
+
* it wants multi-character input delivered as ONE paste event rather than as a
|
|
120
|
+
* stream of keystrokes, and every real terminal obliges.
|
|
121
|
+
*
|
|
122
|
+
* This matters because chunking and TUIs are actively incompatible. Sent in
|
|
123
|
+
* chunks, a 1,079-character prompt reached Qoder's input box with only its
|
|
124
|
+
* TAIL, while a raw-mode PTY sink received all 1,315 bytes of a
|
|
125
|
+
* marker-bracketed probe across two chunks, front marker and tail marker both
|
|
126
|
+
* present. So the bytes always arrive, and it is the receiving widget that
|
|
127
|
+
* discards everything before the last burst. Chunking a TUI's input is
|
|
128
|
+
* how the loss happens.
|
|
129
|
+
*
|
|
130
|
+
* So: track what the app asks for (it emits `ESC[?2004h` / `ESC[?2004l` on its
|
|
131
|
+
* output stream) and match it. Bracketed paste on → wrap and write once, no
|
|
132
|
+
* chunking, no delay. Off → the OS-limit chunking above still applies, because
|
|
133
|
+
* a line-buffered program has no paste concept and a 4 KB write really can be
|
|
134
|
+
* cut.
|
|
135
|
+
*/
|
|
136
|
+
const PASTE_START = '\x1b[200~';
|
|
137
|
+
const PASTE_END = '\x1b[201~';
|
|
138
|
+
const PASTE_MODE_ON = '\x1b[?2004h';
|
|
139
|
+
const PASTE_MODE_OFF = '\x1b[?2004l';
|
|
140
|
+
/** DECTCEM: tracked because xterm's serialisation omits it. See viewerState(). */
|
|
141
|
+
const CURSOR_HIDE = '\x1b[?25l';
|
|
142
|
+
const CURSOR_SHOW = '\x1b[?25h';
|
|
143
|
+
/** A full terminal reset (RIS) and a soft one (DECSTR): both show the cursor. */
|
|
144
|
+
const TERMINAL_RESET = '\x1bc';
|
|
145
|
+
const SOFT_RESET = '\x1b[!p';
|
|
146
|
+
/**
|
|
147
|
+
* Whether the cursor is hidden after this chunk of program output, given
|
|
148
|
+
* whether it was before. The LAST transition in the chunk wins (a TUI
|
|
149
|
+
* re-asserts its modes on every redraw). A reset counts as showing, because
|
|
150
|
+
* both kinds show the cursor (see TERMINAL_RESET).
|
|
151
|
+
*/
|
|
152
|
+
export function cursorHiddenAfter(scan, current) {
|
|
153
|
+
const hide = scan.lastIndexOf(CURSOR_HIDE);
|
|
154
|
+
const show = Math.max(scan.lastIndexOf(CURSOR_SHOW), scan.lastIndexOf(TERMINAL_RESET), scan.lastIndexOf(SOFT_RESET));
|
|
155
|
+
if (hide === -1 && show === -1)
|
|
156
|
+
return current;
|
|
157
|
+
return hide > show;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Whether bracketed paste (DEC 2004) is on after this chunk of program
|
|
161
|
+
* output, given whether it was before. The twin of `cursorHiddenAfter`, and
|
|
162
|
+
* for the same reason: the emulator the daemon mirrors turns the mode OFF on
|
|
163
|
+
* a reset, so this scan does too. In @xterm/headless both RIS (`ESC c`) and
|
|
164
|
+
* DECSTR (`ESC [ ! p`) reach `CoreService.reset()`, which puts the DEC
|
|
165
|
+
* private modes back to their defaults, where bracketed paste is false.
|
|
166
|
+
*
|
|
167
|
+
* After a reset the program does not expect paste markers, and would read
|
|
168
|
+
* `ESC[200~` and `ESC[201~` around a long write as literal input. The last
|
|
169
|
+
* transition in the chunk wins, as above: a TUI re-asserts its modes on
|
|
170
|
+
* every redraw.
|
|
171
|
+
*/
|
|
172
|
+
export function bracketedPasteAfter(scan, current) {
|
|
173
|
+
const on = scan.lastIndexOf(PASTE_MODE_ON);
|
|
174
|
+
const off = Math.max(scan.lastIndexOf(PASTE_MODE_OFF), scan.lastIndexOf(TERMINAL_RESET), scan.lastIndexOf(SOFT_RESET));
|
|
175
|
+
if (on === -1 && off === -1)
|
|
176
|
+
return current;
|
|
177
|
+
return on > off;
|
|
178
|
+
}
|
|
179
|
+
/** One short of the longest mode sequence: enough to rejoin any split of one. */
|
|
180
|
+
const MODE_SCAN_TAIL_CHARS = PASTE_MODE_ON.length - 1;
|
|
181
|
+
/**
|
|
182
|
+
* A command that cannot be started as given: a bare name not on PATH, a path
|
|
183
|
+
* that is not an executable file, or on Windows a script started without the
|
|
184
|
+
* shell. A caller error, mapped to 400.
|
|
185
|
+
*/
|
|
186
|
+
export class CommandNotFoundError extends Error {
|
|
187
|
+
constructor(message) {
|
|
188
|
+
super(message);
|
|
189
|
+
this.name = 'CommandNotFoundError';
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* The Windows build number of an `os.release()` string (`10.0.19045` → 19045),
|
|
194
|
+
* or 0 when the string names none.
|
|
195
|
+
*/
|
|
196
|
+
export function windowsBuildNumber(release) {
|
|
197
|
+
const parts = /(\d+)\.(\d+)\.(\d+)/.exec(release);
|
|
198
|
+
return parts === null ? 0 : Number(parts[3]);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* The first Windows build with ConPTY, as node-pty's own README states:
|
|
202
|
+
* Windows 10 version 1809, build 18309. node-pty 1.2.0 removed its winpty
|
|
203
|
+
* fallback, so a session cannot start on a build below this.
|
|
204
|
+
*/
|
|
205
|
+
export const CONPTY_MINIMUM_BUILD = 18309;
|
|
206
|
+
/**
|
|
207
|
+
* A start on a Windows build with no ConPTY, which node-pty 1.2.0 cannot run
|
|
208
|
+
* a terminal on (it removed the winpty fallback). A caller error, mapped to
|
|
209
|
+
* 400: nothing about the daemon is wrong, and the message names the floor.
|
|
210
|
+
*/
|
|
211
|
+
export class WindowsWithoutConPTYError extends Error {
|
|
212
|
+
constructor(build) {
|
|
213
|
+
super(`This Windows build (${String(build)}) has no ConPTY, which node-pty 1.2.0 needs for every terminal: ` +
|
|
214
|
+
`Windows 10 version 1809 (build ${String(CONPTY_MINIMUM_BUILD)}) or later is required to start a session.`);
|
|
215
|
+
this.name = 'WindowsWithoutConPTYError';
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Input for a session whose input pipe has failed (Windows): refused, because
|
|
220
|
+
* written it would be lost. The daemon answers it with a 409.
|
|
221
|
+
*/
|
|
222
|
+
export class SessionInputFailedError extends Error {
|
|
223
|
+
constructor(id, cause) {
|
|
224
|
+
super(`Session ${id}'s input pipe has failed (${String(cause)}), so input cannot reach its program. ` +
|
|
225
|
+
'Kill the session and start it again.', { cause });
|
|
226
|
+
this.name = 'SessionInputFailedError';
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* A resize of a session whose program node-pty has seen end: refused, as there
|
|
231
|
+
* is no terminal left to resize. It can be asked for in the moment between that
|
|
232
|
+
* end and the session's exit, which follows once node-pty has flushed the last
|
|
233
|
+
* output. The daemon answers it with the 409 a session that has exited gets.
|
|
234
|
+
*/
|
|
235
|
+
export class SessionProgramEndedError extends Error {
|
|
236
|
+
sessionId;
|
|
237
|
+
exitCode;
|
|
238
|
+
constructor(sessionId, exitCode) {
|
|
239
|
+
super(`Cannot resize session ${sessionId}: its program has exited (code ${String(exitCode)}).`);
|
|
240
|
+
this.sessionId = sessionId;
|
|
241
|
+
this.exitCode = exitCode;
|
|
242
|
+
this.name = 'SessionProgramEndedError';
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Resolve a command to a concrete executable path before spawning directly
|
|
247
|
+
* (`shell: false`). Necessary on **every** platform, for different reasons:
|
|
248
|
+
*
|
|
249
|
+
* - **Windows:** node-pty does not search PATH at all, and fails with a bare
|
|
250
|
+
* `File not found:` naming nothing.
|
|
251
|
+
* - **POSIX:** this is worse, because `pty.spawn` of a nonexistent command
|
|
252
|
+
* *succeeds*. execvp fails inside the forked child, the parent never learns
|
|
253
|
+
* and the caller gets a healthy-looking session that is silently dead. An
|
|
254
|
+
* agent would then wait out its full timeout for output that can never
|
|
255
|
+
* arrive.
|
|
256
|
+
*
|
|
257
|
+
* Resolving up front turns both into an immediate, actionable error.
|
|
258
|
+
*
|
|
259
|
+
* On Windows the file found must be a program Windows starts as one: an
|
|
260
|
+
* `.exe` or a `.com`. A batch file (`.bat`, `.cmd`) is refused, because
|
|
261
|
+
* Windows would hand it to cmd.exe with the arguments quoted for a program's
|
|
262
|
+
* parser, which cmd reads by different rules. A `.ps1` or an extensionless
|
|
263
|
+
* script is refused too. A path whose file name contains `:` names an
|
|
264
|
+
* alternate data stream and is refused before anything is opened. A command
|
|
265
|
+
* that contains a path separator and is not absolute is resolved from the
|
|
266
|
+
* session's working directory, and that absolute path is what is checked and
|
|
267
|
+
* what is started.
|
|
268
|
+
*/
|
|
269
|
+
/**
|
|
270
|
+
* Whether a Windows path's file name names an alternate data stream.
|
|
271
|
+
* The last path component holds the stream (`run.cmd:payload.exe`). A drive
|
|
272
|
+
* prefix (`C:`) is never in that component, so `C:\dir\app.exe` and the
|
|
273
|
+
* drive-relative `C:app.exe` are false. Strings only: nothing is opened.
|
|
274
|
+
*/
|
|
275
|
+
export function windowsCandidateNamesStream(candidate) {
|
|
276
|
+
return path.win32.basename(candidate).includes(':');
|
|
277
|
+
}
|
|
278
|
+
function resolveExecutable(command, platform, cwd) {
|
|
279
|
+
const isWindows = platform === 'win32';
|
|
280
|
+
const usable = (candidate) => {
|
|
281
|
+
try {
|
|
282
|
+
if (!fs.statSync(candidate).isFile())
|
|
283
|
+
return false;
|
|
284
|
+
if (!isWindows)
|
|
285
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
286
|
+
return true;
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
// On Windows a bare name usually needs a PATHEXT suffix; try suffixed forms
|
|
293
|
+
// first unless the caller already supplied one.
|
|
294
|
+
const extensions = isWindows
|
|
295
|
+
? (process.env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD').split(';').filter((e) => e !== '')
|
|
296
|
+
: [];
|
|
297
|
+
const candidatesFor = (base) => {
|
|
298
|
+
if (!isWindows)
|
|
299
|
+
return [base];
|
|
300
|
+
const alreadyExtended = extensions.some((e) => base.toLowerCase().endsWith(e.toLowerCase()));
|
|
301
|
+
return alreadyExtended
|
|
302
|
+
? [base, ...extensions.map((e) => base + e)]
|
|
303
|
+
: [...extensions.map((e) => base + e), base];
|
|
304
|
+
};
|
|
305
|
+
const explicitPath = /[\\/]/.test(command) || (isWindows && /^[a-z]:/i.test(command));
|
|
306
|
+
// A relative command that names a path is taken from the session's cwd, so
|
|
307
|
+
// the file checked is the file started. A drive-relative command (`D:app.exe`,
|
|
308
|
+
// `D:dir\app.exe`) keeps its drive and is not rewritten. A bare name is found
|
|
309
|
+
// on PATH.
|
|
310
|
+
const rooted = /[\\/]/.test(command) && !path.isAbsolute(command) && !(isWindows && /^[a-z]:/i.test(command))
|
|
311
|
+
? path.resolve(cwd, command)
|
|
312
|
+
: command;
|
|
313
|
+
const searchBases = explicitPath
|
|
314
|
+
? [rooted]
|
|
315
|
+
: (process.env['PATH'] ?? '')
|
|
316
|
+
.split(path.delimiter)
|
|
317
|
+
.filter((d) => d !== '')
|
|
318
|
+
.map((dir) => path.join(dir, command));
|
|
319
|
+
const described = (candidate) => candidate === command ? command : `${command} (${candidate})`;
|
|
320
|
+
for (const base of searchBases) {
|
|
321
|
+
for (const candidate of candidatesFor(base)) {
|
|
322
|
+
// Before the file is opened: a stream's stat would succeed and report
|
|
323
|
+
// a file, and a name ending in `.exe` would then pass the suffix check.
|
|
324
|
+
if (isWindows && windowsCandidateNamesStream(candidate)) {
|
|
325
|
+
throw new CommandNotFoundError(`Not a program Windows can start directly: ${described(candidate)}. ` +
|
|
326
|
+
`With shell:false (--no-shell) a path whose file name contains ':' names an ` +
|
|
327
|
+
`alternate data stream, and that is refused. The command must be an .exe or .com file.`);
|
|
328
|
+
}
|
|
329
|
+
if (!usable(candidate))
|
|
330
|
+
continue;
|
|
331
|
+
if (isWindows && !/\.(exe|com)$/i.test(candidate)) {
|
|
332
|
+
throw new CommandNotFoundError(`Not a program Windows can start directly: ${described(candidate)}. With shell:false (--no-shell) ` +
|
|
333
|
+
`the command must be an .exe or .com file. Drop shell:false to run it through the ` +
|
|
334
|
+
`shell, or give its interpreter as the command and the file as an argument.`);
|
|
335
|
+
}
|
|
336
|
+
return candidate;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
const shown = rooted === command ? command : `${command} (${rooted})`;
|
|
340
|
+
throw new CommandNotFoundError(explicitPath
|
|
341
|
+
? `Not an executable file: ${shown}.`
|
|
342
|
+
: `Command not found on PATH: ${command}. Give an absolute path, or drop ` +
|
|
343
|
+
`shell:false (--no-shell) and let the shell wrapper resolve it.`);
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* A session gets the clean baseline unless the configuration says otherwise
|
|
347
|
+
* (ADR-008): the daemon's environment is whatever the client that auto-started
|
|
348
|
+
* it had, so passing it on would hand that client's secrets to every session.
|
|
349
|
+
*/
|
|
350
|
+
export const DEFAULT_SESSION_ENV = 'clean';
|
|
351
|
+
/**
|
|
352
|
+
* The minimal functional variable set for `sessionEnv: "clean"`: enough for
|
|
353
|
+
* shells and ordinary programs to work, without the daemon's secrets. Windows
|
|
354
|
+
* needs rather more scaffolding than POSIX to be usable at all: the standard
|
|
355
|
+
* variables below carry no secrets, and toolchains such as MSBuild, the .NET
|
|
356
|
+
* SDK, PowerShell modules and Git for Windows look for them. POSIX keeps the
|
|
357
|
+
* locale, without which terminal programs lose UTF-8.
|
|
358
|
+
*/
|
|
359
|
+
const CLEAN_ENV_KEYS = {
|
|
360
|
+
win32: [
|
|
361
|
+
'PATH',
|
|
362
|
+
'PATHEXT',
|
|
363
|
+
'SYSTEMROOT',
|
|
364
|
+
'SYSTEMDRIVE',
|
|
365
|
+
'COMSPEC',
|
|
366
|
+
'WINDIR',
|
|
367
|
+
'TEMP',
|
|
368
|
+
'TMP',
|
|
369
|
+
'USERPROFILE',
|
|
370
|
+
'USERNAME',
|
|
371
|
+
'HOMEDRIVE',
|
|
372
|
+
'HOMEPATH',
|
|
373
|
+
'APPDATA',
|
|
374
|
+
'LOCALAPPDATA',
|
|
375
|
+
'PROGRAMFILES',
|
|
376
|
+
'PROGRAMDATA',
|
|
377
|
+
'NUMBER_OF_PROCESSORS',
|
|
378
|
+
'PROCESSOR_ARCHITECTURE',
|
|
379
|
+
'PROCESSOR_IDENTIFIER',
|
|
380
|
+
'PROCESSOR_LEVEL',
|
|
381
|
+
'PROCESSOR_REVISION',
|
|
382
|
+
'OS',
|
|
383
|
+
'ProgramFiles(x86)',
|
|
384
|
+
'ProgramW6432',
|
|
385
|
+
'CommonProgramFiles',
|
|
386
|
+
'CommonProgramFiles(x86)',
|
|
387
|
+
'CommonProgramW6432',
|
|
388
|
+
'ALLUSERSPROFILE',
|
|
389
|
+
'PUBLIC',
|
|
390
|
+
'COMPUTERNAME',
|
|
391
|
+
'USERDOMAIN',
|
|
392
|
+
'USERDOMAIN_ROAMINGPROFILE',
|
|
393
|
+
'LOGONSERVER',
|
|
394
|
+
'PSModulePath',
|
|
395
|
+
'NoDefaultCurrentDirectoryInExePath',
|
|
396
|
+
],
|
|
397
|
+
posix: ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TMPDIR'],
|
|
398
|
+
};
|
|
399
|
+
// Words that mark a variable name as holding a credential. A name is split into
|
|
400
|
+
// words at underscores, at lower-to-upper case changes and before the last
|
|
401
|
+
// capital of a run of capitals, so `PAYMENT_API_KEY`, `GithubToken`, `GHToken`,
|
|
402
|
+
// `S3Key` and `SSH_AUTH_SOCK` match while `MAX_TOKENS`, `PWD` and
|
|
403
|
+
// `GIT_AUTHOR_NAME` do not. A word ending in one of CREDENTIAL_SUFFIXES matches
|
|
404
|
+
// too, for names written as one word (`GITHUBTOKEN`, `PGPASSWORD`). The list is
|
|
405
|
+
// advisory: a name need say nothing of what it holds (`DATABASE_URL`), which is
|
|
406
|
+
// why sessions start clean rather than relying on it.
|
|
407
|
+
const CREDENTIAL_WORDS = new Set([
|
|
408
|
+
'KEY',
|
|
409
|
+
'KEYS',
|
|
410
|
+
'APIKEY',
|
|
411
|
+
'TOKEN',
|
|
412
|
+
'SECRET',
|
|
413
|
+
'SECRETS',
|
|
414
|
+
'PASSWORD',
|
|
415
|
+
'PASSWORDS',
|
|
416
|
+
'PASSWD',
|
|
417
|
+
'PASS',
|
|
418
|
+
'PW',
|
|
419
|
+
'PASSPHRASE',
|
|
420
|
+
'CREDENTIAL',
|
|
421
|
+
'CREDENTIALS',
|
|
422
|
+
'CREDS',
|
|
423
|
+
'COOKIE',
|
|
424
|
+
'AUTH',
|
|
425
|
+
'AUTHORIZATION',
|
|
426
|
+
'BEARER',
|
|
427
|
+
'JWT',
|
|
428
|
+
'PAT',
|
|
429
|
+
'SAS',
|
|
430
|
+
'DSN',
|
|
431
|
+
'WEBHOOK',
|
|
432
|
+
]);
|
|
433
|
+
const CREDENTIAL_SUFFIXES = [
|
|
434
|
+
'TOKEN',
|
|
435
|
+
'SECRET',
|
|
436
|
+
'PASSWORD',
|
|
437
|
+
'PASSWD',
|
|
438
|
+
'PASSPHRASE',
|
|
439
|
+
'APIKEY',
|
|
440
|
+
'ACCESSKEY',
|
|
441
|
+
'SECRETKEY',
|
|
442
|
+
'PRIVATEKEY',
|
|
443
|
+
];
|
|
444
|
+
function looksLikeCredential(name) {
|
|
445
|
+
return name
|
|
446
|
+
// A lookahead, not `([A-Z]+)([A-Z][a-z])`: that backtracks quadratically on
|
|
447
|
+
// a long run of capitals, and a name can be as long as the environment.
|
|
448
|
+
.replace(/([A-Z])(?=[A-Z][a-z])/g, '$1_')
|
|
449
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
450
|
+
.toUpperCase()
|
|
451
|
+
.split(/_+/)
|
|
452
|
+
.some((word) => CREDENTIAL_WORDS.has(word) || CREDENTIAL_SUFFIXES.some((suffix) => word.endsWith(suffix)));
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* The names (never the values) of variables in `source` whose names look like
|
|
456
|
+
* credentials, sorted: part of what `passthrough` would hand every session.
|
|
457
|
+
*/
|
|
458
|
+
export function credentialShapedNames(source = process.env) {
|
|
459
|
+
return Object.keys(source)
|
|
460
|
+
.filter((name) => source[name] !== undefined && source[name] !== '')
|
|
461
|
+
.filter(looksLikeCredential)
|
|
462
|
+
.sort((a, b) => a.localeCompare(b));
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Build the PTY environment for a session. Variable-name matching is
|
|
466
|
+
* case-insensitive on every platform: Windows environment names are, and a
|
|
467
|
+
* list in the configuration means the same wherever the daemon runs.
|
|
468
|
+
*
|
|
469
|
+
* An explicit allowlist is the CLEAN baseline plus the listed names: a bare
|
|
470
|
+
* list would strip system scaffolding that processes need to start at all
|
|
471
|
+
* (verified: node.exe aborts in CSPRNG initialisation without `SystemRoot` on
|
|
472
|
+
* Windows), and "functional minimum plus exactly what you name" is the intent
|
|
473
|
+
* of the mode: naming secrets in, not naming plumbing.
|
|
474
|
+
*
|
|
475
|
+
* `passed` is the session's own variables from the client that started it
|
|
476
|
+
* (`SessionOptions.env`), set on top of whatever the mode gave. On Windows a
|
|
477
|
+
* passed name replaces the inherited variable of the same name in any case,
|
|
478
|
+
* rather than sitting beside it as a second copy.
|
|
479
|
+
*
|
|
480
|
+
* A name reserved for a connected feature's credential (ADR-007) is never
|
|
481
|
+
* carried, whichever mode is in force: `passthrough` copies the daemon's
|
|
482
|
+
* environment and a list mode can name anything, so the filter has to sit
|
|
483
|
+
* here rather than in one caller. A session's own `passed` value is not the
|
|
484
|
+
* daemon's copy and is left alone.
|
|
485
|
+
*/
|
|
486
|
+
export function buildSessionEnv(mode, platform, source = process.env, passed = {}, reserved = RESERVED_FEATURE_CREDENTIALS) {
|
|
487
|
+
const env = {};
|
|
488
|
+
// Windows reads variable names without case, so a reserved name is matched
|
|
489
|
+
// that way there and exactly elsewhere, as every other name is.
|
|
490
|
+
const isReserved = (name) => platform === 'win32'
|
|
491
|
+
? [...reserved].some((entry) => entry.toUpperCase() === name.toUpperCase())
|
|
492
|
+
: reserved.has(name);
|
|
493
|
+
if (mode === 'passthrough') {
|
|
494
|
+
for (const [key, value] of Object.entries(source)) {
|
|
495
|
+
if (value !== undefined && !isReserved(key))
|
|
496
|
+
env[key] = value;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
const baseline = CLEAN_ENV_KEYS[platform === 'win32' ? 'win32' : 'posix'];
|
|
501
|
+
const wanted = new Set((mode === 'clean' ? baseline : [...baseline, ...mode]).map((k) => k.toUpperCase()));
|
|
502
|
+
for (const [key, value] of Object.entries(source)) {
|
|
503
|
+
if (value !== undefined && wanted.has(key.toUpperCase()) && !isReserved(key)) {
|
|
504
|
+
env[key] = value;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
const setOnly = (name, value) => {
|
|
509
|
+
if (platform === 'win32') {
|
|
510
|
+
for (const key of Object.keys(env)) {
|
|
511
|
+
if (key.toUpperCase() === name.toUpperCase())
|
|
512
|
+
delete env[key];
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
env[name] = value;
|
|
516
|
+
};
|
|
517
|
+
for (const [name, value] of Object.entries(passed))
|
|
518
|
+
setOnly(name, value);
|
|
519
|
+
// Always injected (§7): Windows sets no TERM, and TUIs then assume a dumb
|
|
520
|
+
// terminal and disable colour. On Windows any other casing goes first, or
|
|
521
|
+
// the child would see that copy's value instead of these.
|
|
522
|
+
setOnly('TERM', 'xterm-256color');
|
|
523
|
+
setOnly('COLORTERM', 'truecolor');
|
|
524
|
+
return env;
|
|
525
|
+
}
|
|
526
|
+
export class Session {
|
|
527
|
+
id;
|
|
528
|
+
label;
|
|
529
|
+
/** What this session is for, for the human watching it. */
|
|
530
|
+
purpose;
|
|
531
|
+
/** The audit actor that started it: set by the daemon, not by the body. */
|
|
532
|
+
startedBy;
|
|
533
|
+
/** The pre-wrap command as given by the caller. */
|
|
534
|
+
command;
|
|
535
|
+
args;
|
|
536
|
+
/** The agent it was started as, which chooses how its screen is read. */
|
|
537
|
+
agent;
|
|
538
|
+
createdAt;
|
|
539
|
+
pty;
|
|
540
|
+
renderer;
|
|
541
|
+
logger;
|
|
542
|
+
platform;
|
|
543
|
+
endConsoleHost;
|
|
544
|
+
registerConsoleHost;
|
|
545
|
+
spawnPty;
|
|
546
|
+
treeKiller;
|
|
547
|
+
/** How long a kill waits for the deferred program's pid (a test seam). */
|
|
548
|
+
pidWaitMs;
|
|
549
|
+
/** Set once a wait for the program's pid has run out (`programPid`). */
|
|
550
|
+
programWaitExpired = false;
|
|
551
|
+
/** Whether the program has bracketed paste (DEC 2004) enabled. See PASTE_START. */
|
|
552
|
+
bracketedPaste = false;
|
|
553
|
+
/**
|
|
554
|
+
* Whether the most recent `write` took the bracketed-paste branch.
|
|
555
|
+
* Diagnostic only. A program that enabled bracketed paste can still report
|
|
556
|
+
* no markers, and from outside the two causes cannot be told apart: we
|
|
557
|
+
* wrapped and the transport stripped the markers off the input (ConPTY
|
|
558
|
+
* can), or the write raced ahead of the flag. This says which.
|
|
559
|
+
*/
|
|
560
|
+
lastWriteWrapped = null;
|
|
561
|
+
/** Trailing output kept so a mode sequence split across PTY reads is still seen. */
|
|
562
|
+
modeScanTail = '';
|
|
563
|
+
dataListeners = new Set();
|
|
564
|
+
exitListeners = new Set();
|
|
565
|
+
readyListeners = new Set();
|
|
566
|
+
/** Whether the program has hidden the cursor (DECTCEM off), carried to viewers. */
|
|
567
|
+
cursorHidden = false;
|
|
568
|
+
/** Serialises write() so chunked writes cannot interleave. See write(). */
|
|
569
|
+
writeChain = Promise.resolve();
|
|
570
|
+
museSubmissionsQueued = 0;
|
|
571
|
+
musePromptSettler = new MusePromptSettler();
|
|
572
|
+
/** Why the input pipe failed (Windows), once it has: input is refused from then on. */
|
|
573
|
+
inputFailure = null;
|
|
574
|
+
lastChange = Date.now();
|
|
575
|
+
/** Sticky: the rendered screen has shown something at least once. */
|
|
576
|
+
painted = false;
|
|
577
|
+
/**
|
|
578
|
+
* The last input written, for the waiter's echo guard. Memory only, never
|
|
579
|
+
* logged: §4.5 keeps keystroke content out of the audit trail, and this
|
|
580
|
+
* is one string overwritten by the next write.
|
|
581
|
+
*/
|
|
582
|
+
lastInputData = null;
|
|
583
|
+
/** Which prompt the last input answered, and whether it has since gone. */
|
|
584
|
+
stalePrompts = new StalePromptGuard();
|
|
585
|
+
exitedFlag = false;
|
|
586
|
+
exitedAtValue = null;
|
|
587
|
+
exitCodeValue = null;
|
|
588
|
+
conptyStartError = null;
|
|
589
|
+
/** The tree kill under way for a program whose session ended with no exit code. */
|
|
590
|
+
endingProgram = null;
|
|
591
|
+
readyFlag;
|
|
592
|
+
readyReasonValue = 'not-tracked';
|
|
593
|
+
geometryHeldFlag;
|
|
594
|
+
killPromise = null;
|
|
595
|
+
consoleHostSettlement = null;
|
|
596
|
+
/**
|
|
597
|
+
* Times taken immediately before and after the spawn, on Windows. ConPTY
|
|
598
|
+
* creates the console host during that call. Null on any other platform.
|
|
599
|
+
*/
|
|
600
|
+
consoleHostWindow = null;
|
|
601
|
+
/** The end has been queued once. A kill and an exit must not queue it twice. */
|
|
602
|
+
consoleHostQueued = false;
|
|
603
|
+
constructor(id, options, deps = {}) {
|
|
604
|
+
this.id = id;
|
|
605
|
+
this.command = options.command;
|
|
606
|
+
this.args = options.args ?? [];
|
|
607
|
+
this.label = options.label ?? options.command;
|
|
608
|
+
this.purpose = options.purpose ?? '';
|
|
609
|
+
this.startedBy = options.startedBy ?? 'unknown';
|
|
610
|
+
this.agent = options.agent;
|
|
611
|
+
this.createdAt = new Date();
|
|
612
|
+
this.logger = deps.logger ?? NULL_LOGGER;
|
|
613
|
+
this.platform = deps.platform ?? process.platform;
|
|
614
|
+
this.treeKiller = deps.treeKiller ?? taskkillTrees;
|
|
615
|
+
this.endConsoleHost = deps.queueConsoleHostEnd ?? queueConsoleHostEnd;
|
|
616
|
+
this.registerConsoleHost = deps.registerConsoleHostWindow ?? registerConsoleHostWindow;
|
|
617
|
+
this.spawnPty = deps.spawn;
|
|
618
|
+
this.pidWaitMs = deps.pidWaitMs ?? PROGRAM_PID_WAIT_MS;
|
|
619
|
+
// node-pty 1.2.0 is ConPTY-only on Windows: the winpty fallback is gone,
|
|
620
|
+
// so a build below the ConPTY floor cannot start anything. Refused here,
|
|
621
|
+
// with the floor named, rather than deep inside ConPTY as a bare
|
|
622
|
+
// "Cannot launch conpty".
|
|
623
|
+
// The real release is read only on a real Windows host: a test that
|
|
624
|
+
// simulates Windows elsewhere (`platform`) would otherwise read a POSIX
|
|
625
|
+
// kernel version as build 0. A test of the floor passes `osRelease`.
|
|
626
|
+
const release = deps.osRelease ?? (process.platform === 'win32' ? os.release() : undefined);
|
|
627
|
+
if (this.platform === 'win32' && release !== undefined) {
|
|
628
|
+
const build = windowsBuildNumber(release);
|
|
629
|
+
if (build < CONPTY_MINIMUM_BUILD)
|
|
630
|
+
throw new WindowsWithoutConPTYError(build);
|
|
631
|
+
}
|
|
632
|
+
const cols = options.cols ?? DEFAULT_COLS;
|
|
633
|
+
const rows = options.rows ?? DEFAULT_ROWS;
|
|
634
|
+
this.renderer = new ScreenRenderer({ cols, rows, scrollback: DEFAULT_SCROLLBACK });
|
|
635
|
+
// cols/rows say where to START, and nothing more: a size that also froze
|
|
636
|
+
// the grid would leave a viewer with a grid it could not change, and a
|
|
637
|
+
// window of a different shape could only letterbox. Holding is asked
|
|
638
|
+
// for explicitly, because the common case is a human watching in a browser
|
|
639
|
+
// that should simply fill, and the rare case is a run that would be
|
|
640
|
+
// invalidated by a reflow.
|
|
641
|
+
this.geometryHeldFlag = options.hold === true;
|
|
642
|
+
const { file, fileArgs } = this.wrapCommand(options);
|
|
643
|
+
if (!deps.retryAttempt)
|
|
644
|
+
this.logger.info('session spawn', {
|
|
645
|
+
id,
|
|
646
|
+
command: this.command,
|
|
647
|
+
args: this.args,
|
|
648
|
+
wrapped: file !== this.command,
|
|
649
|
+
// Names only: the values are secrets more often than not.
|
|
650
|
+
...(options.env !== undefined ? { envNames: Object.keys(options.env) } : {}),
|
|
651
|
+
});
|
|
652
|
+
// node-pty is loaded on the first start, not with the daemon, so an install
|
|
653
|
+
// that left it unable to open a terminal fails here with what to do
|
|
654
|
+
// (`nativePty.ts`). A test spawn stands in and loads nothing.
|
|
655
|
+
const spawn = this.spawnPty === undefined ? loadNodePty().spawn : undefined;
|
|
656
|
+
// A Windows start that fails part-way must not leave node-pty's
|
|
657
|
+
// half-built terminal behind (`windowsPtyStart.ts`).
|
|
658
|
+
if (spawn !== undefined && process.platform === 'win32')
|
|
659
|
+
releaseFailedStarts();
|
|
660
|
+
if (spawn !== undefined)
|
|
661
|
+
ensureSpawnHelperExecutable();
|
|
662
|
+
// On Windows, ConPTY creates the console host inside this synchronous
|
|
663
|
+
// call, before it returns. The two times are the window a later list
|
|
664
|
+
// uses to recognise that host. Nothing is listed here, and the start
|
|
665
|
+
// does not wait. The platform is the session's, so a test can stand in
|
|
666
|
+
// for Windows without a Windows process.
|
|
667
|
+
const trackConsoleHost = this.platform === 'win32';
|
|
668
|
+
const consoleHostT0 = trackConsoleHost ? Date.now() : 0;
|
|
669
|
+
const spawnOptions = {
|
|
670
|
+
name: 'xterm-256color',
|
|
671
|
+
cols,
|
|
672
|
+
rows,
|
|
673
|
+
cwd: options.cwd ?? process.cwd(),
|
|
674
|
+
// The daemon always passes the mode it resolved and reports; this
|
|
675
|
+
// default serves code that uses SessionManager or Session directly.
|
|
676
|
+
env: buildSessionEnv(deps.sessionEnv ?? DEFAULT_SESSION_ENV, this.platform, process.env, options.env),
|
|
677
|
+
};
|
|
678
|
+
try {
|
|
679
|
+
if (this.spawnPty !== undefined) {
|
|
680
|
+
this.pty = this.spawnPty(file, fileArgs, spawnOptions);
|
|
681
|
+
}
|
|
682
|
+
else if (spawn !== undefined) {
|
|
683
|
+
this.pty = spawn(file, fileArgs, spawnOptions);
|
|
684
|
+
}
|
|
685
|
+
else {
|
|
686
|
+
throw new Error('session spawn is not available');
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
catch (error) {
|
|
690
|
+
// On Windows node-pty loads its native module here, as the terminal is
|
|
691
|
+
// built, so a missing binary surfaces now rather than at the load above.
|
|
692
|
+
throw explainSpawnFailure(error);
|
|
693
|
+
}
|
|
694
|
+
if (trackConsoleHost) {
|
|
695
|
+
this.consoleHostWindow = { t0: consoleHostT0, t1: Date.now() };
|
|
696
|
+
this.registerConsoleHost(this.id, this.consoleHostWindow, this.platform);
|
|
697
|
+
}
|
|
698
|
+
if (this.platform === 'win32') {
|
|
699
|
+
observeConptyStartError(this.pty, (error) => { this.conptyStartError = error; });
|
|
700
|
+
}
|
|
701
|
+
// An error on a Windows terminal's pipes must not take the daemon down
|
|
702
|
+
// (`windowsPtyStart.ts`). Logged once a stream: for the known cause, the
|
|
703
|
+
// console host has gone and the session's exit follows. Input after the
|
|
704
|
+
// input pipe has failed would be lost, so `write` refuses it.
|
|
705
|
+
if (process.platform === 'win32') {
|
|
706
|
+
const reported = new Set();
|
|
707
|
+
listenForTerminalErrors(this.pty, (error, stream) => {
|
|
708
|
+
if (stream === 'input')
|
|
709
|
+
this.inputFailure ??= error;
|
|
710
|
+
if (reported.has(stream))
|
|
711
|
+
return;
|
|
712
|
+
reported.add(stream);
|
|
713
|
+
this.logger.warn(`session ${stream} failed`, { id, error: String(error) });
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
this.pty.onData((data) => {
|
|
717
|
+
// Track bracketed-paste mode from the app's own output (see PASTE_START).
|
|
718
|
+
//
|
|
719
|
+
// Scanned with a carry-over tail because PTY read boundaries are
|
|
720
|
+
// arbitrary: an 8-byte `ESC[?2004h` can straddle two onData callbacks,
|
|
721
|
+
// and a missed transition leaves us writing down the WRONG path for the
|
|
722
|
+
// rest of the session. Keeping the last few characters and
|
|
723
|
+
// prefixing them costs nothing and closes the split.
|
|
724
|
+
//
|
|
725
|
+
// lastIndexOf, not includes: one burst can turn the mode on and off
|
|
726
|
+
// again (TUIs re-assert their modes on redraw), and only the LAST
|
|
727
|
+
// transition reflects the state the app ended up in.
|
|
728
|
+
const scan = this.modeScanTail + data;
|
|
729
|
+
this.bracketedPaste = bracketedPasteAfter(scan, this.bracketedPaste);
|
|
730
|
+
this.cursorHidden = cursorHiddenAfter(scan, this.cursorHidden);
|
|
731
|
+
this.modeScanTail = scan.slice(-MODE_SCAN_TAIL_CHARS);
|
|
732
|
+
const rendered = this.renderer.write(data);
|
|
733
|
+
// First paint is decided by the RENDERER, not by bytes arriving: ConPTY
|
|
734
|
+
// emits mode-set sequences ~140 ms after spawn that draw nothing, and a
|
|
735
|
+
// quiet/readyQuiet that counted them as output would report a CLI ready
|
|
736
|
+
// before its first byte. Checked per chunk only until it
|
|
737
|
+
// holds, so the snapshot cost stops at the first visible character.
|
|
738
|
+
if (!this.painted) {
|
|
739
|
+
void rendered.then(() => {
|
|
740
|
+
if (!this.painted && this.renderer.snapshot().screen !== '')
|
|
741
|
+
this.painted = true;
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
this.lastChange = Date.now();
|
|
745
|
+
for (const listener of this.dataListeners)
|
|
746
|
+
listener(data);
|
|
747
|
+
});
|
|
748
|
+
this.pty.onExit(({ exitCode: reported }) => {
|
|
749
|
+
// node-pty closes a Windows terminal whose output socket failed and
|
|
750
|
+
// reports an exit with no code, while the program runs on: the session
|
|
751
|
+
// can no longer be read or typed into, so it has ended, and its program
|
|
752
|
+
// is ended at once rather than left running where nobody can see or
|
|
753
|
+
// reach it (`endProgram`).
|
|
754
|
+
const exitCode = typeof reported === 'number' ? reported : null;
|
|
755
|
+
this.exitedFlag = true;
|
|
756
|
+
this.exitedAtValue = Date.now();
|
|
757
|
+
this.exitCodeValue = exitCode;
|
|
758
|
+
this.lastChange = Date.now();
|
|
759
|
+
this.logger.info('session exit', { id, exitCode });
|
|
760
|
+
if (!this.programEnded)
|
|
761
|
+
this.endingProgram = this.endProgram();
|
|
762
|
+
for (const listener of this.exitListeners)
|
|
763
|
+
listener(exitCode);
|
|
764
|
+
// The console host is a child of the daemon, so the program ending
|
|
765
|
+
// leaves it running. A later list ends the one host created in this
|
|
766
|
+
// spawn's window. Nothing here waits for that list.
|
|
767
|
+
this.queueConsoleHost();
|
|
768
|
+
});
|
|
769
|
+
// Readiness (§3.1): first paint ≠ ready. With no condition given the
|
|
770
|
+
// session counts as ready at spawn; otherwise readiness flips when the
|
|
771
|
+
// condition holds. A session whose condition never holds stays not-ready,
|
|
772
|
+
// which is the truth and is visible in list/snapshot output.
|
|
773
|
+
if (options.readyText !== undefined || options.readyQuiet !== undefined) {
|
|
774
|
+
this.readyFlag = false;
|
|
775
|
+
this.readyReasonValue = 'pending';
|
|
776
|
+
const condition = options.readyText !== undefined
|
|
777
|
+
? { text: options.readyText }
|
|
778
|
+
: { quiet: options.readyQuiet };
|
|
779
|
+
void waitFor(this, condition, { timeout: MAX_WAIT_TIMEOUT_MS }).then((result) => {
|
|
780
|
+
if (result.matched) {
|
|
781
|
+
this.readyFlag = true;
|
|
782
|
+
this.readyReasonValue = 'condition-met';
|
|
783
|
+
this.logger.info('session ready', { id, reason: result.reason });
|
|
784
|
+
}
|
|
785
|
+
else {
|
|
786
|
+
this.readyReasonValue = 'never-held';
|
|
787
|
+
this.logger.warn('session readiness condition never held', {
|
|
788
|
+
id,
|
|
789
|
+
reason: result.reason,
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
for (const listener of this.readyListeners)
|
|
793
|
+
listener();
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
else {
|
|
797
|
+
// No condition was asked for, so nothing is being checked. `ready` is
|
|
798
|
+
// true, meaning only that the process started, and `readyReason` says
|
|
799
|
+
// plainly that it is not evidence. Some agent CLIs emit nothing for tens
|
|
800
|
+
// of seconds and silently discard input typed during that window, so a bare
|
|
801
|
+
// `true` here is the most dangerous value in the API.
|
|
802
|
+
this.readyFlag = true;
|
|
803
|
+
this.readyReasonValue = 'not-tracked';
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Windows default: wrap in `cmd.exe` (§7: direct ConPTY spawns of
|
|
808
|
+
* single-file binaries hang). POSIX default: direct spawn; `shell: true`
|
|
809
|
+
* wraps in `/bin/sh -c`.
|
|
810
|
+
*
|
|
811
|
+
* The Windows form is `cmd.exe /d /s /c "<line>"` passed as a VERBATIM
|
|
812
|
+
* string (node-pty applies no quoting to string args). `/s` pins cmd's
|
|
813
|
+
* strip-first-and-last-quote behaviour so the outer quotes vanish cleanly
|
|
814
|
+
* and every quote inside `<line>` survives. Without it, a command path
|
|
815
|
+
* containing spaces (e.g. `C:\Program Files\nodejs\node.exe`) is split at
|
|
816
|
+
* the first space. This is the same invocation libuv uses for shell spawns.
|
|
817
|
+
*/
|
|
818
|
+
wrapCommand(options) {
|
|
819
|
+
const wantShell = options.shell ?? this.platform === 'win32';
|
|
820
|
+
if (!wantShell) {
|
|
821
|
+
return {
|
|
822
|
+
// The same absolute path is checked and started. See `shell` on SessionOptions.
|
|
823
|
+
file: resolveExecutable(options.command, this.platform, path.resolve(options.cwd ?? process.cwd())),
|
|
824
|
+
// node-pty's array serialiser skips outer quoting for an argument
|
|
825
|
+
// which itself begins and ends with quotes. A quoted value containing
|
|
826
|
+
// a space then splits in the child. Its string form is passed through
|
|
827
|
+
// verbatim, so serialise literal argv ourselves on Windows.
|
|
828
|
+
fileArgs: this.platform === 'win32'
|
|
829
|
+
? (options.args ?? []).map(windowsArgument).join(' ')
|
|
830
|
+
: options.args ?? [],
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
// Quote the command token if it has whitespace and the caller has not
|
|
834
|
+
// already quoted it; args are shell text and pass through untouched.
|
|
835
|
+
const commandToken = /\s/.test(options.command) && !options.command.startsWith('"')
|
|
836
|
+
? `"${options.command}"`
|
|
837
|
+
: options.command;
|
|
838
|
+
const line = commandLine(commandToken, options.args ?? []);
|
|
839
|
+
if (this.platform === 'win32') {
|
|
840
|
+
const comspec = process.env['ComSpec'] ?? 'cmd.exe';
|
|
841
|
+
return { file: comspec, fileArgs: `/d /s /c "${line}"` };
|
|
842
|
+
}
|
|
843
|
+
return { file: '/bin/sh', fileArgs: ['-c', line] };
|
|
844
|
+
}
|
|
845
|
+
get pid() {
|
|
846
|
+
return this.pty.pid;
|
|
847
|
+
}
|
|
848
|
+
get cols() {
|
|
849
|
+
return this.renderer.cols;
|
|
850
|
+
}
|
|
851
|
+
get rows() {
|
|
852
|
+
return this.renderer.rows;
|
|
853
|
+
}
|
|
854
|
+
get ready() {
|
|
855
|
+
return this.readyFlag;
|
|
856
|
+
}
|
|
857
|
+
/** Why `ready` holds its value. See {@link SessionSummary.readyReason}. */
|
|
858
|
+
get readyReason() {
|
|
859
|
+
return this.readyReasonValue;
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* True only when the grid is HELD: `hold` at start, or a resize that asked
|
|
863
|
+
* for it. A held grid keeps its size while viewports connect and reshape
|
|
864
|
+
* themselves around it; an unheld grid belongs to the controlling viewport,
|
|
865
|
+
* which fits it to the human's window (design §5).
|
|
866
|
+
*/
|
|
867
|
+
get geometryHeld() {
|
|
868
|
+
return this.geometryHeldFlag;
|
|
869
|
+
}
|
|
870
|
+
get exited() {
|
|
871
|
+
return this.exitedFlag;
|
|
872
|
+
}
|
|
873
|
+
/** Epoch ms of process exit: the manager's reap grace counts from here. */
|
|
874
|
+
get exitedAt() {
|
|
875
|
+
return this.exitedAtValue;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* The program's exit code once the session has ended. Null while it runs,
|
|
879
|
+
* and for a session that ended with no code because its output failed: the
|
|
880
|
+
* code node-pty records for its program afterwards is not reported
|
|
881
|
+
* (`howSessionEnded`).
|
|
882
|
+
*/
|
|
883
|
+
get exitCode() {
|
|
884
|
+
return this.exitCodeValue;
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* Whether the session's program is known to have ended: node-pty has
|
|
888
|
+
* recorded its exit code, or its exit came with a code. Until then its
|
|
889
|
+
* tree is walked. The recorded code is enough on its own, before this
|
|
890
|
+
* session's exit event: node-pty closes the process handle first, so the
|
|
891
|
+
* pid is already free. Where node-pty records none (`canReadExitCode`),
|
|
892
|
+
* an exit with no code counts as the end: a pid nothing vouches for is
|
|
893
|
+
* never walked.
|
|
894
|
+
*/
|
|
895
|
+
get programEnded() {
|
|
896
|
+
// node-pty records the code only after it has closed the process handle,
|
|
897
|
+
// which frees the pid, and about a second before this session's exit.
|
|
898
|
+
// The pid is already not the program's, so it is not walked.
|
|
899
|
+
if (recordedExitCode(this.pty) !== undefined)
|
|
900
|
+
return true;
|
|
901
|
+
return this.exitedFlag && (this.exitCodeValue !== null || !canReadExitCode(this.pty));
|
|
902
|
+
}
|
|
903
|
+
/** Whether the input pipe has failed (Windows): input is refused from then on. */
|
|
904
|
+
get inputFailed() {
|
|
905
|
+
return this.inputFailure !== null;
|
|
906
|
+
}
|
|
907
|
+
get watchers() {
|
|
908
|
+
return this.dataListeners.size;
|
|
909
|
+
}
|
|
910
|
+
// ------------------------------------------------------------- WaitTarget
|
|
911
|
+
getScreen() {
|
|
912
|
+
return this.renderer.snapshot().screen;
|
|
913
|
+
}
|
|
914
|
+
lastChangeAt() {
|
|
915
|
+
return this.lastChange;
|
|
916
|
+
}
|
|
917
|
+
isExited() {
|
|
918
|
+
return this.exitedFlag;
|
|
919
|
+
}
|
|
920
|
+
hasPainted() {
|
|
921
|
+
return this.painted;
|
|
922
|
+
}
|
|
923
|
+
lastInput() {
|
|
924
|
+
return this.lastInputData;
|
|
925
|
+
}
|
|
926
|
+
observePrompt(signature) {
|
|
927
|
+
this.stalePrompts.observe(signature);
|
|
928
|
+
}
|
|
929
|
+
isStalePrompt(signature) {
|
|
930
|
+
return this.stalePrompts.isStale(signature);
|
|
931
|
+
}
|
|
932
|
+
// ------------------------------------------------------------------ input
|
|
933
|
+
/**
|
|
934
|
+
* Write to the PTY the way the program on the other end asked to be written
|
|
935
|
+
* to: as a bracketed paste when it enabled that mode, otherwise chunked.
|
|
936
|
+
*
|
|
937
|
+
* Anything under WRITE_CHUNK_CHARS goes straight through either way, so keys
|
|
938
|
+
* and human typing are unaffected. Above it the two paths diverge, and the
|
|
939
|
+
* divergence is the point. See PASTE_START for the evidence that chunking a
|
|
940
|
+
* TUI's input is what loses the front of a long prompt.
|
|
941
|
+
*
|
|
942
|
+
* **Writes are serialised.** The chunked path yields between pieces, and this
|
|
943
|
+
* tool's whole premise is that a human and an agent share one session. So
|
|
944
|
+
* without a queue a keystroke (or a multi-character paste, which is what xterm
|
|
945
|
+
* hands us for a clipboard drop) could land *between* an earlier write's
|
|
946
|
+
* chunks and interleave two inputs into gibberish. Making that ordering the
|
|
947
|
+
* caller's problem would be a trap; the queue keeps writes in call order,
|
|
948
|
+
* as a synchronous write would.
|
|
949
|
+
*
|
|
950
|
+
* Resolves with the screen as it was rendered just before this input went
|
|
951
|
+
* in, taken in the queue, so an earlier write still going in cannot be
|
|
952
|
+
* mistaken for this one's effect (`terminal_type`'s verify compares with it).
|
|
953
|
+
*
|
|
954
|
+
* Rejects with `SessionInputFailedError` once the input pipe has failed,
|
|
955
|
+
* including for the rest of a chunked write it fails part-way through.
|
|
956
|
+
*/
|
|
957
|
+
write(data) {
|
|
958
|
+
const museSubmit = this.agent === 'muse' && museSubmittingText(data);
|
|
959
|
+
if (museSubmit)
|
|
960
|
+
this.museSubmissionsQueued++;
|
|
961
|
+
const queued = this.writeChain.then(() => this.writeInput(data));
|
|
962
|
+
// The chain must survive a failed write, or one rejection would wedge every
|
|
963
|
+
// subsequent write on this session.
|
|
964
|
+
this.writeChain = queued.then(() => { if (museSubmit)
|
|
965
|
+
this.museSubmissionsQueued--; }, () => { if (museSubmit)
|
|
966
|
+
this.museSubmissionsQueued--; });
|
|
967
|
+
return queued;
|
|
968
|
+
}
|
|
969
|
+
async writeInput(data) {
|
|
970
|
+
this.refuseIfInputFailed();
|
|
971
|
+
// Recorded BEFORE the bytes go in, when the screen still shows what this
|
|
972
|
+
// input is answering: the waiter's stale-prompt guard needs that prompt,
|
|
973
|
+
// and its echo guard needs the input itself.
|
|
974
|
+
this.lastInputData = data;
|
|
975
|
+
const { screen } = this.renderer.snapshot();
|
|
976
|
+
this.stalePrompts.noteInput(screen);
|
|
977
|
+
if (this.agent === 'muse' && museSubmittingText(data)) {
|
|
978
|
+
const body = data.slice(0, -1);
|
|
979
|
+
await this.writeData(body);
|
|
980
|
+
await new Promise((resolve) => setTimeout(resolve, MUSE_SUBMIT_DELAY_MS));
|
|
981
|
+
this.refuseIfInputFailed();
|
|
982
|
+
this.refuseIfEnded();
|
|
983
|
+
this.pty.write('\r');
|
|
984
|
+
return screen;
|
|
985
|
+
}
|
|
986
|
+
await this.writeData(data);
|
|
987
|
+
return screen;
|
|
988
|
+
}
|
|
989
|
+
async writeData(data) {
|
|
990
|
+
if (data.length <= WRITE_CHUNK_CHARS) {
|
|
991
|
+
this.pty.write(data);
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
// Bracketed paste: ONE write, no chunking, exactly as a terminal delivers a
|
|
995
|
+
// clipboard drop. The submitting newline (if the caller appended one) is
|
|
996
|
+
// deliberately left OUTSIDE the markers. Inside, a TUI treats it as
|
|
997
|
+
// literal text in the pasted block and the prompt is composed but never
|
|
998
|
+
// sent, which looks identical to input being ignored.
|
|
999
|
+
if (this.bracketedPaste) {
|
|
1000
|
+
const newlineAt = data.search(/[\r\n]+$/);
|
|
1001
|
+
const body = newlineAt === -1 ? data : data.slice(0, newlineAt);
|
|
1002
|
+
const trailer = newlineAt === -1 ? '' : data.slice(newlineAt);
|
|
1003
|
+
this.lastWriteWrapped = true;
|
|
1004
|
+
this.pty.write(`${PASTE_START}${body}${PASTE_END}${trailer}`);
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
this.lastWriteWrapped = false;
|
|
1008
|
+
let offset = 0;
|
|
1009
|
+
while (offset < data.length) {
|
|
1010
|
+
// The pipe can fail while a chunk is in flight.
|
|
1011
|
+
this.refuseIfInputFailed();
|
|
1012
|
+
let end = Math.min(offset + WRITE_CHUNK_CHARS, data.length);
|
|
1013
|
+
// Never split a surrogate pair: half of an astral character is not a
|
|
1014
|
+
// character, and the two halves arriving in separate writes decode to
|
|
1015
|
+
// replacement characters rather than the emoji the caller sent.
|
|
1016
|
+
if (end < data.length) {
|
|
1017
|
+
const code = data.charCodeAt(end - 1);
|
|
1018
|
+
if (code >= 0xd800 && code <= 0xdbff)
|
|
1019
|
+
end -= 1;
|
|
1020
|
+
}
|
|
1021
|
+
this.pty.write(data.slice(offset, end));
|
|
1022
|
+
offset = end;
|
|
1023
|
+
if (offset < data.length) {
|
|
1024
|
+
await new Promise((resolve) => setTimeout(resolve, WRITE_CHUNK_DELAY_MS));
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
/** Input written after the input pipe has failed would be lost: refuse it. */
|
|
1029
|
+
refuseIfInputFailed() {
|
|
1030
|
+
if (this.inputFailure !== null)
|
|
1031
|
+
throw new SessionInputFailedError(this.id, this.inputFailure);
|
|
1032
|
+
}
|
|
1033
|
+
refuseIfEnded() {
|
|
1034
|
+
if (this.exitedFlag || this.isKilled)
|
|
1035
|
+
throw new Error(`Session ${this.id} exited while input was being written.`);
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Resize the PTY.
|
|
1039
|
+
*
|
|
1040
|
+
* Every caller arrives here, a viewport whose window changed shape and an
|
|
1041
|
+
* agent asking for a specific grid alike, because the resize itself is the
|
|
1042
|
+
* same act either way. What differs is only whether the caller also means to stop
|
|
1043
|
+
* anyone else changing it, and that is said explicitly with `hold` rather
|
|
1044
|
+
* than inferred from who is calling. Omitting `hold` leaves the current
|
|
1045
|
+
* setting alone, so a viewport following a window cannot quietly release a
|
|
1046
|
+
* hold that a scripted run is relying on.
|
|
1047
|
+
*
|
|
1048
|
+
* Throws `SessionProgramEndedError` once node-pty has seen the program end,
|
|
1049
|
+
* where it records that (`recordedExitCode`): there is no terminal left to
|
|
1050
|
+
* resize, and node-pty itself throws for that on a Windows terminal that has
|
|
1051
|
+
* drawn.
|
|
1052
|
+
* On Windows a resize asked for before the terminal's first output is held
|
|
1053
|
+
* by node-pty and run later; one that finds the program ended by then is
|
|
1054
|
+
* dropped (`windowsPtyStart.ts`).
|
|
1055
|
+
*/
|
|
1056
|
+
resize(cols, rows, options = {}) {
|
|
1057
|
+
if (this.agent === 'muse' && this.museSubmissionsQueued > 0) {
|
|
1058
|
+
const queued = this.writeChain.then(() => this.resizeNow(cols, rows, options));
|
|
1059
|
+
this.writeChain = queued.then(() => undefined, () => undefined);
|
|
1060
|
+
return queued;
|
|
1061
|
+
}
|
|
1062
|
+
this.resizeNow(cols, rows, options);
|
|
1063
|
+
}
|
|
1064
|
+
resizeNow(cols, rows, options) {
|
|
1065
|
+
const ended = recordedExitCode(this.pty);
|
|
1066
|
+
if (ended !== undefined)
|
|
1067
|
+
throw new SessionProgramEndedError(this.id, ended);
|
|
1068
|
+
this.pty.resize(cols, rows);
|
|
1069
|
+
this.renderer.resize(cols, rows);
|
|
1070
|
+
if (options.hold !== undefined)
|
|
1071
|
+
this.geometryHeldFlag = options.hold;
|
|
1072
|
+
}
|
|
1073
|
+
answerablePrompt(screen, now = Date.now()) {
|
|
1074
|
+
if (this.agent !== 'muse')
|
|
1075
|
+
return detectPrompt(screen);
|
|
1076
|
+
const styled = this.renderer.styledLines().lines;
|
|
1077
|
+
return this.musePromptSettler.detect(screen, now, styled);
|
|
1078
|
+
}
|
|
1079
|
+
// ----------------------------------------------------------------- output
|
|
1080
|
+
/** Live raw-stream subscription (viewer mirroring). Returns unsubscribe. */
|
|
1081
|
+
onData(listener) {
|
|
1082
|
+
this.dataListeners.add(listener);
|
|
1083
|
+
return () => this.dataListeners.delete(listener);
|
|
1084
|
+
}
|
|
1085
|
+
onExit(listener) {
|
|
1086
|
+
this.exitListeners.add(listener);
|
|
1087
|
+
return () => this.exitListeners.delete(listener);
|
|
1088
|
+
}
|
|
1089
|
+
/** Notify the daemon when the readiness condition settles. */
|
|
1090
|
+
onReady(listener) {
|
|
1091
|
+
this.readyListeners.add(listener);
|
|
1092
|
+
return () => this.readyListeners.delete(listener);
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* The rendered terminal as bytes that rebuild it in a fresh terminal of the
|
|
1096
|
+
* same size (design §5): what a viewer receives on connect and after every
|
|
1097
|
+
* grid change, in place of any slice of the raw stream. A slice starts
|
|
1098
|
+
* mid-frame, and a program that only repaints what changed never puts the
|
|
1099
|
+
* rest of its frame back. Every agent CLI repaints that way once its chrome
|
|
1100
|
+
* is up, and on Windows every program does as ConPTY relays it. Resolves
|
|
1101
|
+
* once every byte received before the call has been parsed, and includes
|
|
1102
|
+
* nothing received after it.
|
|
1103
|
+
*/
|
|
1104
|
+
async viewerState(options = {}) {
|
|
1105
|
+
// Read before the await: the bytes behind this flag are the bytes in the
|
|
1106
|
+
// snapshot, not whatever arrives while it is being taken.
|
|
1107
|
+
const hidden = this.cursorHidden;
|
|
1108
|
+
const state = await this.renderer.serialize(options);
|
|
1109
|
+
return hidden ? state + CURSOR_HIDE : state;
|
|
1110
|
+
}
|
|
1111
|
+
/** The filter's styled rows and the viewer replay from one rendered frame. */
|
|
1112
|
+
async captureViewerScreen(above, scrollback) {
|
|
1113
|
+
const hidden = this.cursorHidden;
|
|
1114
|
+
const captured = await this.renderer.capture({ above, scrollback });
|
|
1115
|
+
return { ...captured, state: captured.state + (hidden ? CURSOR_HIDE : '') };
|
|
1116
|
+
}
|
|
1117
|
+
async snapshot() {
|
|
1118
|
+
await this.renderer.flush();
|
|
1119
|
+
const rendered = this.renderer.snapshot();
|
|
1120
|
+
// Every look at the screen is evidence for the stale-prompt guard. A
|
|
1121
|
+
// snapshot that finds no prompt, or a different one, is what lets a later
|
|
1122
|
+
// prompt with identical text count as new rather than as the one just
|
|
1123
|
+
// answered, and that includes the ones the daemon's stall scan and verify
|
|
1124
|
+
// take.
|
|
1125
|
+
this.stalePrompts.observe(detectPrompt(rendered.screen)?.signature ?? null);
|
|
1126
|
+
return {
|
|
1127
|
+
id: this.id,
|
|
1128
|
+
label: this.label,
|
|
1129
|
+
cols: rendered.cols,
|
|
1130
|
+
rows: rendered.rows,
|
|
1131
|
+
cursor: rendered.cursor,
|
|
1132
|
+
exited: this.exitedFlag,
|
|
1133
|
+
exitCode: this.exitCode,
|
|
1134
|
+
screen: rendered.screen,
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
/** Last N lines including scrollback (design §3). */
|
|
1138
|
+
async lastLines(count) {
|
|
1139
|
+
await this.renderer.flush();
|
|
1140
|
+
return this.renderer.lastLines(count);
|
|
1141
|
+
}
|
|
1142
|
+
/** Current viewport lines (for `terminal_find`). */
|
|
1143
|
+
async viewportLines() {
|
|
1144
|
+
await this.renderer.flush();
|
|
1145
|
+
return this.renderer.snapshot().lines;
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* The viewport with `above` lines of scrollback over it, as drawn
|
|
1149
|
+
* (`reasoning.ts`). `firstVisible` is where the viewport begins.
|
|
1150
|
+
*/
|
|
1151
|
+
async styledScreen(above = 0) {
|
|
1152
|
+
await this.renderer.flush();
|
|
1153
|
+
return this.renderer.styledLines({ above });
|
|
1154
|
+
}
|
|
1155
|
+
/** Current rendered rows for a waiter evaluation, which already reads synchronously. */
|
|
1156
|
+
styledScreenNow(above = 0) {
|
|
1157
|
+
return this.renderer.styledLines({ above });
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* The last `count` lines, scrollback included, as drawn, with up to
|
|
1161
|
+
* `context` more lines over them; `firstVisible` is where the `count` begin.
|
|
1162
|
+
*/
|
|
1163
|
+
async styledTail(count, context = 0) {
|
|
1164
|
+
await this.renderer.flush();
|
|
1165
|
+
const { lines } = this.renderer.styledLines({ last: count + context });
|
|
1166
|
+
return { lines, firstVisible: Math.max(0, lines.length - count) };
|
|
1167
|
+
}
|
|
1168
|
+
waitFor(condition, options) {
|
|
1169
|
+
return waitFor(this, condition, options);
|
|
1170
|
+
}
|
|
1171
|
+
summary() {
|
|
1172
|
+
return {
|
|
1173
|
+
id: this.id,
|
|
1174
|
+
label: this.label,
|
|
1175
|
+
purpose: this.purpose,
|
|
1176
|
+
startedBy: this.startedBy,
|
|
1177
|
+
agent: this.agent ?? null,
|
|
1178
|
+
command: this.command,
|
|
1179
|
+
args: this.args,
|
|
1180
|
+
cols: this.cols,
|
|
1181
|
+
rows: this.rows,
|
|
1182
|
+
ready: this.readyFlag,
|
|
1183
|
+
readyReason: this.readyReasonValue,
|
|
1184
|
+
geometryHeld: this.geometryHeldFlag,
|
|
1185
|
+
exited: this.exitedFlag,
|
|
1186
|
+
exitCode: this.exitCode,
|
|
1187
|
+
watchers: this.watchers,
|
|
1188
|
+
createdAt: this.createdAt.toISOString(),
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Kill the whole process tree (design §3.1). Commands are shell-wrapped, so
|
|
1193
|
+
* killing only the direct child (`cmd.exe`) strands the real application,
|
|
1194
|
+
* and orphaned agent CLIs keep running and keep spending paid API tokens.
|
|
1195
|
+
*
|
|
1196
|
+
* Windows: `taskkill /T /F` walks and kills the tree, then `pty.kill()` runs.
|
|
1197
|
+
* node-pty's kill ends no process of its own
|
|
1198
|
+
* (`listNothingToKill` in `windowsPtyStart.ts`), and it closes the
|
|
1199
|
+
* pseudoconsole, which sends CTRL_CLOSE_EVENT to the processes on the
|
|
1200
|
+
* console, only while node-pty still holds the terminal: while the program
|
|
1201
|
+
* runs. After a tree kill that ended the program, its kill closes nothing,
|
|
1202
|
+
* so a process on the session's console outside the killed tree gets no
|
|
1203
|
+
* close event. The console host is not in that tree. After this returns, a
|
|
1204
|
+
* later list ends the one host created during this spawn's window. This does
|
|
1205
|
+
* not wait for that list. The daemon's pseudoconsole handle stays open, and
|
|
1206
|
+
* the host is given no CTRL_CLOSE_EVENT. (The design's Job
|
|
1207
|
+
* Object hardening needs a native module and is
|
|
1208
|
+
* deferred. If the daemon itself dies, its pseudoconsole handles close,
|
|
1209
|
+
* which gives console-attached descendants a close signal.)
|
|
1210
|
+
*
|
|
1211
|
+
* POSIX: the PTY child is the session leader of its own process group, so
|
|
1212
|
+
* signalling the negated pid takes the group down.
|
|
1213
|
+
*
|
|
1214
|
+
* The OS tree kill runs only while the root is still alive. A session whose
|
|
1215
|
+
* program exited on its own is reaped fifteen minutes later, and by then the
|
|
1216
|
+
* process group id may have been recycled, so an unconditional `kill(-pid)`
|
|
1217
|
+
* could take down something unrelated; on Windows `taskkill` cannot walk a
|
|
1218
|
+
* tree from a dead root either. So a grandchild that outlived its parent is
|
|
1219
|
+
* left alone rather than guessed at, a residual risk stated in
|
|
1220
|
+
* `docs/reference/security-model.md`. A session whose program has not been
|
|
1221
|
+
* seen to end (`programEnded`) is walked, whether or not the session has
|
|
1222
|
+
* ended. node-pty holds such a program's handle while it runs and closes it
|
|
1223
|
+
* as it sees the program end, a moment before the code is recorded, so a
|
|
1224
|
+
* kill in that moment can reach a pid just freed: the same kind of race
|
|
1225
|
+
* every kill has while `taskkill` enumerates the processes. Once the code
|
|
1226
|
+
* is recorded the pid is not walked.
|
|
1227
|
+
*/
|
|
1228
|
+
kill() {
|
|
1229
|
+
this.killPromise ??= this.killOnce();
|
|
1230
|
+
return this.killPromise;
|
|
1231
|
+
}
|
|
1232
|
+
/** True from the moment a kill begins, including while it waits for a pid. */
|
|
1233
|
+
get isKilled() {
|
|
1234
|
+
return this.killPromise !== null;
|
|
1235
|
+
}
|
|
1236
|
+
async killOnce() {
|
|
1237
|
+
// node-pty creates a Windows terminal's program only once its output
|
|
1238
|
+
// worker has connected, a few tens of milliseconds after the spawn
|
|
1239
|
+
// returns, and reports pid 0 until then; a start whose connection fails
|
|
1240
|
+
// reports an exit instead. The wait keeps the tree kill below from
|
|
1241
|
+
// skipping a program that is about to exist (`programPid`).
|
|
1242
|
+
const pid = await this.programPid();
|
|
1243
|
+
this.logger.info('session kill', { id: this.id, pid });
|
|
1244
|
+
// Taken before the kill. The kill itself makes node-pty record the exit,
|
|
1245
|
+
// and that later record must not hide the result of a tree we did walk.
|
|
1246
|
+
const exitAlreadyRecorded = recordedExitCode(this.pty) !== undefined;
|
|
1247
|
+
if (this.endingProgram !== null) {
|
|
1248
|
+
// The session is already ending its program, after an exit with no code.
|
|
1249
|
+
await this.endingProgram;
|
|
1250
|
+
}
|
|
1251
|
+
else if (!this.programEnded) {
|
|
1252
|
+
await this.killTree(pid);
|
|
1253
|
+
}
|
|
1254
|
+
try {
|
|
1255
|
+
this.pty.kill();
|
|
1256
|
+
}
|
|
1257
|
+
catch {
|
|
1258
|
+
// Already dead: the outcome we wanted.
|
|
1259
|
+
}
|
|
1260
|
+
// Verify rather than assume. An orphaned agent CLI keeps running and keeps
|
|
1261
|
+
// spending paid API tokens, so the fact worth logging is "it died", not
|
|
1262
|
+
// "we sent a kill". Checking only the root pid is deliberate: a full
|
|
1263
|
+
// descendant walk needs recursive process queries that are far slower than
|
|
1264
|
+
// the kill itself (measured in minutes), and the root dying is what the
|
|
1265
|
+
// caller actually contracted for.
|
|
1266
|
+
// When the exit was already recorded, node-pty had already closed the
|
|
1267
|
+
// process handle and Windows may have given the pid out. A live pid is
|
|
1268
|
+
// then not reported as this session's root surviving: it may be someone
|
|
1269
|
+
// else's process. A pid that is gone is still the result worth logging.
|
|
1270
|
+
// A code recorded by this kill is not that case: the tree was still ours.
|
|
1271
|
+
// A pid of 0 means no program was ever created, and on Windows a liveness
|
|
1272
|
+
// probe of it answers as though something were there: nothing is probed
|
|
1273
|
+
// and no survivor is claimed for it.
|
|
1274
|
+
if (pid > 0 && !this.processAlive(pid)) {
|
|
1275
|
+
this.logger.info('session tree killed', { id: this.id, pid });
|
|
1276
|
+
}
|
|
1277
|
+
else if (pid > 0 && !exitAlreadyRecorded) {
|
|
1278
|
+
this.logger.error('session root SURVIVED the kill and may still be running', {
|
|
1279
|
+
id: this.id,
|
|
1280
|
+
pid,
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
this.queueConsoleHost();
|
|
1284
|
+
this.renderer.dispose();
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* Queue an end of this session's console host, once. The list runs later
|
|
1288
|
+
* and is not awaited. With no window there is nothing to end. On any
|
|
1289
|
+
* platform but Windows the queue does nothing.
|
|
1290
|
+
*/
|
|
1291
|
+
queueConsoleHost() {
|
|
1292
|
+
if (this.platform !== 'win32')
|
|
1293
|
+
return;
|
|
1294
|
+
const window = this.consoleHostWindow;
|
|
1295
|
+
if (window === null || this.consoleHostQueued)
|
|
1296
|
+
return;
|
|
1297
|
+
this.consoleHostQueued = true;
|
|
1298
|
+
let settle = () => undefined;
|
|
1299
|
+
this.consoleHostSettlement = new Promise((resolve) => { settle = resolve; });
|
|
1300
|
+
this.endConsoleHost({
|
|
1301
|
+
id: this.id,
|
|
1302
|
+
window,
|
|
1303
|
+
log: (level, message, meta) => {
|
|
1304
|
+
this.logger[level](message, meta);
|
|
1305
|
+
},
|
|
1306
|
+
onSettled: settle,
|
|
1307
|
+
});
|
|
1308
|
+
}
|
|
1309
|
+
/** The failed attempt's own console-host result, after it has been queued. */
|
|
1310
|
+
whenConsoleHostSettled() {
|
|
1311
|
+
return this.consoleHostSettlement ?? Promise.resolve(false);
|
|
1312
|
+
}
|
|
1313
|
+
/**
|
|
1314
|
+
* The program's pid, waiting for node-pty's deferred program creation:
|
|
1315
|
+
* on Windows the pid is 0 from the spawn until the output worker has
|
|
1316
|
+
* connected and the program exists, and a start whose connection fails
|
|
1317
|
+
* reports an exit instead of a pid, which ends the wait. POSIX reports the
|
|
1318
|
+
* pid at the spawn, so nothing is waited for there.
|
|
1319
|
+
*/
|
|
1320
|
+
async programPid() {
|
|
1321
|
+
// One full wait per session: once a wait has run out with no program, a
|
|
1322
|
+
// later caller (a kill after shutdown's pre-wait) must not spend its budget
|
|
1323
|
+
// waiting again. It still reads the pid, so a program created since is
|
|
1324
|
+
// walked; with none, the kill skips the tree and node-pty's own pending
|
|
1325
|
+
// connection is cancelled by the kill.
|
|
1326
|
+
if (this.programWaitExpired)
|
|
1327
|
+
return this.pty.pid;
|
|
1328
|
+
const deadline = Date.now() + this.pidWaitMs;
|
|
1329
|
+
while (this.pty.pid <= 0 && !this.exitedFlag && Date.now() < deadline) {
|
|
1330
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
1331
|
+
}
|
|
1332
|
+
if (this.pty.pid <= 0 && !this.exitedFlag)
|
|
1333
|
+
this.programWaitExpired = true;
|
|
1334
|
+
return this.pty.pid;
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* The program's pid once node-pty has created it, or null when the session
|
|
1338
|
+
* ended before any program existed: a start whose ConPTY output worker
|
|
1339
|
+
* never connected, or one Windows refused the program of. The start
|
|
1340
|
+
* contract waits here: a session is reported as started only once its
|
|
1341
|
+
* program exists, as node-pty 1.1.0's synchronous spawn guaranteed.
|
|
1342
|
+
*/
|
|
1343
|
+
async startedProgramPid() {
|
|
1344
|
+
const pid = await this.programPid();
|
|
1345
|
+
return pid > 0 ? pid : null;
|
|
1346
|
+
}
|
|
1347
|
+
/** Only the pinned node-pty timeout, before a program exists, can be retried. */
|
|
1348
|
+
get conptyConnectionTimedOut() {
|
|
1349
|
+
return this.platform === 'win32' && this.exitedFlag && this.pty.pid <= 0 &&
|
|
1350
|
+
this.conptyStartError?.message === 'Timed out waiting for ConPTY output worker';
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* What went wrong, for a start that ended before any program existed
|
|
1354
|
+
* (`startedProgramPid` returned null): node-pty 1.1.0's own words for a
|
|
1355
|
+
* program Windows would not create, with Windows' code; for the connection
|
|
1356
|
+
* bound, which 1.1.0 did not have, what actually ran out.
|
|
1357
|
+
*/
|
|
1358
|
+
startFailure() {
|
|
1359
|
+
const code = this.exitCodeValue;
|
|
1360
|
+
if (code !== null && code > 0)
|
|
1361
|
+
return `Cannot create process, error code: ${String(code)}`;
|
|
1362
|
+
if (this.conptyStartError !== null && !this.conptyConnectionTimedOut)
|
|
1363
|
+
return this.conptyStartError.message;
|
|
1364
|
+
return 'the ConPTY output worker never connected, so node-pty never created the program';
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* End the program of a session that ended with no exit code: node-pty
|
|
1368
|
+
* closed its terminal when its output failed, and the program would run on
|
|
1369
|
+
* where nobody can read or type into it, for an agent CLI still acting and
|
|
1370
|
+
* spending. The same tree kill a kill uses. It runs only after the exit, so
|
|
1371
|
+
* the pid is never waited for here; a pid of 0 (no program was created) is
|
|
1372
|
+
* skipped by the tree kill. Never rejects.
|
|
1373
|
+
*/
|
|
1374
|
+
async endProgram() {
|
|
1375
|
+
const pid = await this.programPid();
|
|
1376
|
+
this.logger.warn('session output failed: ending its program', { id: this.id, pid });
|
|
1377
|
+
await this.killTree(pid);
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* The OS tree kill of `kill()`, for a program that may still be running:
|
|
1381
|
+
* `taskkill /T /F` from a live root on Windows, the process group on POSIX.
|
|
1382
|
+
* Never rejects.
|
|
1383
|
+
*/
|
|
1384
|
+
async killTree(pid) {
|
|
1385
|
+
// A pid of 0 is a program node-pty has not created (its deferred
|
|
1386
|
+
// connection) or never created (a failed start): there is no tree, and on
|
|
1387
|
+
// Windows a liveness probe of pid 0 answers as though something were
|
|
1388
|
+
// there, so the checks below would not say no.
|
|
1389
|
+
if (pid <= 0)
|
|
1390
|
+
return;
|
|
1391
|
+
if (this.platform === 'win32') {
|
|
1392
|
+
// A root that has already died leaves no tree to walk. At daemon
|
|
1393
|
+
// shutdown this is the usual case: `killAll` has just killed every
|
|
1394
|
+
// session's tree in one run.
|
|
1395
|
+
const failure = this.processAlive(pid) ? await this.treeKiller([pid]) : null;
|
|
1396
|
+
if (failure !== null) {
|
|
1397
|
+
// Three very different things land here, so report which
|
|
1398
|
+
// actually happened.
|
|
1399
|
+
//
|
|
1400
|
+
// `timedOut` means OUR timeout fired and taskkill was terminated
|
|
1401
|
+
// mid-walk. The tree may be half-killed, so this is the one
|
|
1402
|
+
// that genuinely warrants attention.
|
|
1403
|
+
//
|
|
1404
|
+
// A non-zero exit is NOT proof of failure. `taskkill /T` walks
|
|
1405
|
+
// a live tree, and descendants routinely die of their own
|
|
1406
|
+
// accord (or as a side effect of a parent dying) between
|
|
1407
|
+
// enumeration and the kill call; taskkill then reports "not
|
|
1408
|
+
// found" for those and exits 128 having successfully killed
|
|
1409
|
+
// everything else. Measured: exit 128 alongside 78 SUCCESS
|
|
1410
|
+
// lines on a Qoder tree.
|
|
1411
|
+
this.logger.warn(failure.timedOut
|
|
1412
|
+
? 'tree kill timed out; the process tree may be partially killed'
|
|
1413
|
+
: 'taskkill exited non-zero (usually descendants that vanished mid-walk)', { id: this.id, pid, ...failure, timeoutMs: TREE_KILL_TIMEOUT_MS });
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
else {
|
|
1417
|
+
// SIGKILL outright, with no SIGTERM grace: design §3.1 chooses the
|
|
1418
|
+
// process-group kill precisely so that children which ignore SIGTERM
|
|
1419
|
+
// cannot survive, and a grace period would hand them the chance back.
|
|
1420
|
+
try {
|
|
1421
|
+
process.kill(-pid, 'SIGKILL');
|
|
1422
|
+
}
|
|
1423
|
+
catch (error) {
|
|
1424
|
+
this.logger.warn('process-group kill failed, falling back to pty.kill', {
|
|
1425
|
+
id: this.id,
|
|
1426
|
+
error: String(error),
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* Cheap liveness probe: signal 0 performs the permission and existence
|
|
1433
|
+
* checks without delivering a signal, on Windows as well as POSIX.
|
|
1434
|
+
*/
|
|
1435
|
+
processAlive(pid) {
|
|
1436
|
+
try {
|
|
1437
|
+
process.kill(pid, 0);
|
|
1438
|
+
return true;
|
|
1439
|
+
}
|
|
1440
|
+
catch (error) {
|
|
1441
|
+
// EPERM means the process EXISTS but we are not allowed to signal it
|
|
1442
|
+
// (POSIX). Reporting that as "gone" would make this whole verification
|
|
1443
|
+
// dishonest in the one direction that matters: claiming a clean kill
|
|
1444
|
+
// over a survivor, which is the failure the probe exists to catch.
|
|
1445
|
+
// Only ESRCH ("no such process") is genuine evidence of death.
|
|
1446
|
+
return error.code === 'EPERM';
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
//# sourceMappingURL=session.js.map
|