shellpuppet 0.0.1 → 0.1.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.
Files changed (112) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +340 -8
  4. package/dist/cli/index.d.ts +13 -0
  5. package/dist/cli/index.js +693 -0
  6. package/dist/cli/index.js.map +1 -0
  7. package/dist/client/http.d.ts +82 -0
  8. package/dist/client/http.js +225 -0
  9. package/dist/client/http.js.map +1 -0
  10. package/dist/core/dialogs.d.ts +88 -0
  11. package/dist/core/dialogs.js +214 -0
  12. package/dist/core/dialogs.js.map +1 -0
  13. package/dist/core/echo.d.ts +71 -0
  14. package/dist/core/echo.js +249 -0
  15. package/dist/core/echo.js.map +1 -0
  16. package/dist/core/find.d.ts +34 -0
  17. package/dist/core/find.js +41 -0
  18. package/dist/core/find.js.map +1 -0
  19. package/dist/core/keys.d.ts +22 -0
  20. package/dist/core/keys.js +80 -0
  21. package/dist/core/keys.js.map +1 -0
  22. package/dist/core/manager.d.ts +66 -0
  23. package/dist/core/manager.js +158 -0
  24. package/dist/core/manager.js.map +1 -0
  25. package/dist/core/nativePty.d.ts +69 -0
  26. package/dist/core/nativePty.js +156 -0
  27. package/dist/core/nativePty.js.map +1 -0
  28. package/dist/core/policy.d.ts +61 -0
  29. package/dist/core/policy.js +143 -0
  30. package/dist/core/policy.js.map +1 -0
  31. package/dist/core/promptDetector.d.ts +75 -0
  32. package/dist/core/promptDetector.js +606 -0
  33. package/dist/core/promptDetector.js.map +1 -0
  34. package/dist/core/reasoning.d.ts +252 -0
  35. package/dist/core/reasoning.js +740 -0
  36. package/dist/core/reasoning.js.map +1 -0
  37. package/dist/core/regexBudget.d.ts +44 -0
  38. package/dist/core/regexBudget.js +79 -0
  39. package/dist/core/regexBudget.js.map +1 -0
  40. package/dist/core/renderer.d.ts +112 -0
  41. package/dist/core/renderer.js +225 -0
  42. package/dist/core/renderer.js.map +1 -0
  43. package/dist/core/session.d.ts +311 -0
  44. package/dist/core/session.js +966 -0
  45. package/dist/core/session.js.map +1 -0
  46. package/dist/core/types.d.ts +281 -0
  47. package/dist/core/types.js +47 -0
  48. package/dist/core/types.js.map +1 -0
  49. package/dist/core/waiter.d.ts +86 -0
  50. package/dist/core/waiter.js +317 -0
  51. package/dist/core/waiter.js.map +1 -0
  52. package/dist/core/windowsPtyStart.d.ts +90 -0
  53. package/dist/core/windowsPtyStart.js +129 -0
  54. package/dist/core/windowsPtyStart.js.map +1 -0
  55. package/dist/daemon/audit.d.ts +23 -0
  56. package/dist/daemon/audit.js +51 -0
  57. package/dist/daemon/audit.js.map +1 -0
  58. package/dist/daemon/auth.d.ts +127 -0
  59. package/dist/daemon/auth.js +241 -0
  60. package/dist/daemon/auth.js.map +1 -0
  61. package/dist/daemon/config.d.ts +76 -0
  62. package/dist/daemon/config.js +301 -0
  63. package/dist/daemon/config.js.map +1 -0
  64. package/dist/daemon/index.d.ts +7 -0
  65. package/dist/daemon/index.js +87 -0
  66. package/dist/daemon/index.js.map +1 -0
  67. package/dist/daemon/liveness.d.ts +36 -0
  68. package/dist/daemon/liveness.js +71 -0
  69. package/dist/daemon/liveness.js.map +1 -0
  70. package/dist/daemon/logger.d.ts +7 -0
  71. package/dist/daemon/logger.js +29 -0
  72. package/dist/daemon/logger.js.map +1 -0
  73. package/dist/daemon/meta.d.ts +9 -0
  74. package/dist/daemon/meta.js +24 -0
  75. package/dist/daemon/meta.js.map +1 -0
  76. package/dist/daemon/paths.d.ts +83 -0
  77. package/dist/daemon/paths.js +154 -0
  78. package/dist/daemon/paths.js.map +1 -0
  79. package/dist/daemon/screenshot.d.ts +87 -0
  80. package/dist/daemon/screenshot.js +256 -0
  81. package/dist/daemon/screenshot.js.map +1 -0
  82. package/dist/daemon/server.d.ts +244 -0
  83. package/dist/daemon/server.js +2187 -0
  84. package/dist/daemon/server.js.map +1 -0
  85. package/dist/daemon/terminalReports.d.ts +38 -0
  86. package/dist/daemon/terminalReports.js +84 -0
  87. package/dist/daemon/terminalReports.js.map +1 -0
  88. package/dist/daemon/viewerLauncher.d.ts +135 -0
  89. package/dist/daemon/viewerLauncher.js +280 -0
  90. package/dist/daemon/viewerLauncher.js.map +1 -0
  91. package/dist/daemon/viewerSync.d.ts +38 -0
  92. package/dist/daemon/viewerSync.js +83 -0
  93. package/dist/daemon/viewerSync.js.map +1 -0
  94. package/dist/mcp/config.d.ts +57 -0
  95. package/dist/mcp/config.js +106 -0
  96. package/dist/mcp/config.js.map +1 -0
  97. package/dist/mcp/index.d.ts +10 -0
  98. package/dist/mcp/index.js +69 -0
  99. package/dist/mcp/index.js.map +1 -0
  100. package/dist/mcp/tools.d.ts +59 -0
  101. package/dist/mcp/tools.js +537 -0
  102. package/dist/mcp/tools.js.map +1 -0
  103. package/dist/viewer/icon-16.png +0 -0
  104. package/dist/viewer/icon-180.png +0 -0
  105. package/dist/viewer/icon-32.png +0 -0
  106. package/dist/viewer/icon-512.png +0 -0
  107. package/dist/viewer/icon.svg +66 -0
  108. package/dist/viewer/index.html +56 -0
  109. package/dist/viewer/viewer.css +84 -0
  110. package/dist/viewer/viewer.js +661 -0
  111. package/package.json +66 -7
  112. package/index.js +0 -4
@@ -0,0 +1,966 @@
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 path from 'node:path';
19
+ import { ensureSpawnHelperExecutable, explainSpawnFailure, loadNodePty } from './nativePty.js';
20
+ import { ScreenRenderer } from './renderer.js';
21
+ import { commandLine } from './policy.js';
22
+ import { detectPrompt, StalePromptGuard } from './promptDetector.js';
23
+ import { waitFor } from './waiter.js';
24
+ import { listenForTerminalErrors, releaseFailedStarts } from './windowsPtyStart.js';
25
+ import { DEFAULT_COLS, DEFAULT_ROWS, DEFAULT_SCROLLBACK, MAX_WAIT_TIMEOUT_MS, NULL_LOGGER, } from './types.js';
26
+ /**
27
+ * Hard cap on `taskkill`. Without it a wedged kill never calls back, so
28
+ * `kill()` never resolves, `killAll()` never resolves and daemon shutdown
29
+ * never completes. The daemon then becomes an immortal, undiscoverable
30
+ * process the user can only end via Task Manager.
31
+ *
32
+ * **Why 30 s.** On a real Qoder CLI tree (78 descendants, because it spawns
33
+ * an MCP-server fleet) `taskkill /T /F` took **5,433 ms**. A cap tighter than
34
+ * a normal kill cuts the walk short and leaves the tree to the `pty.kill()`
35
+ * fallback below, the path that cannot reach console-detached descendants.
36
+ * The cap exists to bound the wedged case, not to be tighter than the normal
37
+ * case.
38
+ */
39
+ export const TREE_KILL_TIMEOUT_MS = 30_000;
40
+ /**
41
+ * One `taskkill` run for any number of trees. Every run enumerates every
42
+ * process on the machine before it kills anything, and that is most of its
43
+ * cost. Measured on a Windows machine running about 2,700 processes: 9 to
44
+ * 13 s for one lone process; thirty concurrent runs, one per session, each
45
+ * overran the 30 s cap; one run given all thirty pids took 10 s. So daemon
46
+ * shutdown kills every tree in one run (`SessionManager.killAll`).
47
+ */
48
+ export const taskkillTrees = (pids) => new Promise((resolve) => {
49
+ const startedAt = Date.now();
50
+ execFile('taskkill', ['/T', '/F', ...pids.flatMap((pid) => ['/PID', String(pid)])],
51
+ // A line of output per process killed, descendants included.
52
+ { windowsHide: true, timeout: TREE_KILL_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 }, (error) => {
53
+ resolve(error
54
+ ? {
55
+ // Node also kills a child whose output overruns maxBuffer. Only
56
+ // our timeout counts here, so that case is excluded explicitly:
57
+ // Node 22 leaves `killed` off it, but that is its detail, not a
58
+ // promise.
59
+ timedOut: error.killed === true && error.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER',
60
+ exitCode: error.code ?? null,
61
+ elapsedMs: Date.now() - startedAt,
62
+ }
63
+ : null);
64
+ });
65
+ });
66
+ /**
67
+ * Very large input is written to the PTY in chunks of this size, with
68
+ * WRITE_CHUNK_DELAY_MS between them (see Session.write), but ONLY when the app
69
+ * has not enabled bracketed paste (see PASTE_START below).
70
+ *
71
+ * The threshold is deliberately well above a normal prompt. Chunking exists for
72
+ * the OS limit underneath: a terminal's input buffer is finite (4 KB in
73
+ * canonical mode on Linux), so one multi-kilobyte write to a line-buffered
74
+ * program genuinely can be truncated. Below the threshold nothing changes, so
75
+ * ordinary typing and single keys are untouched.
76
+ */
77
+ const WRITE_CHUNK_CHARS = 1024;
78
+ const WRITE_CHUNK_DELAY_MS = 8;
79
+ /**
80
+ * Bracketed paste (DEC private mode 2004). A TUI that enables it is telling us
81
+ * it wants multi-character input delivered as ONE paste event rather than as a
82
+ * stream of keystrokes, and every real terminal obliges.
83
+ *
84
+ * This matters because chunking and TUIs are actively incompatible. Sent in
85
+ * chunks, a 1,079-character prompt reached Qoder's input box with only its
86
+ * TAIL, while a raw-mode PTY sink received all 1,315 bytes of a
87
+ * marker-bracketed probe across two chunks, front marker and tail marker both
88
+ * present. So the bytes always arrive, and it is the receiving widget that
89
+ * discards everything before the last burst. Chunking a TUI's input is
90
+ * how the loss happens.
91
+ *
92
+ * So: track what the app asks for (it emits `ESC[?2004h` / `ESC[?2004l` on its
93
+ * output stream) and match it. Bracketed paste on → wrap and write once, no
94
+ * chunking, no delay. Off → the OS-limit chunking above still applies, because
95
+ * a line-buffered program has no paste concept and a 4 KB write really can be
96
+ * cut.
97
+ */
98
+ const PASTE_START = '\x1b[200~';
99
+ const PASTE_END = '\x1b[201~';
100
+ const PASTE_MODE_ON = '\x1b[?2004h';
101
+ const PASTE_MODE_OFF = '\x1b[?2004l';
102
+ /** DECTCEM: tracked because xterm's serialisation omits it. See viewerState(). */
103
+ const CURSOR_HIDE = '\x1b[?25l';
104
+ const CURSOR_SHOW = '\x1b[?25h';
105
+ /** A full terminal reset (RIS) and a soft one (DECSTR): both show the cursor. */
106
+ const TERMINAL_RESET = '\x1bc';
107
+ const SOFT_RESET = '\x1b[!p';
108
+ /**
109
+ * Whether the cursor is hidden after this chunk of program output, given
110
+ * whether it was before. The LAST transition in the chunk wins (a TUI
111
+ * re-asserts its modes on every redraw). A reset counts as showing, because
112
+ * both kinds show the cursor (see TERMINAL_RESET).
113
+ */
114
+ export function cursorHiddenAfter(scan, current) {
115
+ const hide = scan.lastIndexOf(CURSOR_HIDE);
116
+ const show = Math.max(scan.lastIndexOf(CURSOR_SHOW), scan.lastIndexOf(TERMINAL_RESET), scan.lastIndexOf(SOFT_RESET));
117
+ if (hide === -1 && show === -1)
118
+ return current;
119
+ return hide > show;
120
+ }
121
+ /**
122
+ * Whether bracketed paste (DEC 2004) is on after this chunk of program
123
+ * output, given whether it was before. The twin of `cursorHiddenAfter`, and
124
+ * for the same reason: the emulator the daemon mirrors turns the mode OFF on
125
+ * a reset, so this scan does too. In @xterm/headless both RIS (`ESC c`) and
126
+ * DECSTR (`ESC [ ! p`) reach `CoreService.reset()`, which puts the DEC
127
+ * private modes back to their defaults, where bracketed paste is false.
128
+ *
129
+ * After a reset the program does not expect paste markers, and would read
130
+ * `ESC[200~` and `ESC[201~` around a long write as literal input. The last
131
+ * transition in the chunk wins, as above: a TUI re-asserts its modes on
132
+ * every redraw.
133
+ */
134
+ export function bracketedPasteAfter(scan, current) {
135
+ const on = scan.lastIndexOf(PASTE_MODE_ON);
136
+ const off = Math.max(scan.lastIndexOf(PASTE_MODE_OFF), scan.lastIndexOf(TERMINAL_RESET), scan.lastIndexOf(SOFT_RESET));
137
+ if (on === -1 && off === -1)
138
+ return current;
139
+ return on > off;
140
+ }
141
+ /** One short of the longest mode sequence: enough to rejoin any split of one. */
142
+ const MODE_SCAN_TAIL_CHARS = PASTE_MODE_ON.length - 1;
143
+ /** A bare command name that is not on PATH: a caller error, mapped to 400. */
144
+ export class CommandNotFoundError extends Error {
145
+ constructor(message) {
146
+ super(message);
147
+ this.name = 'CommandNotFoundError';
148
+ }
149
+ }
150
+ /**
151
+ * Resolve a command to a concrete executable path before spawning directly
152
+ * (`shell: false`). Necessary on **every** platform, for different reasons:
153
+ *
154
+ * - **Windows:** node-pty does not search PATH at all, and fails with a bare
155
+ * `File not found:` naming nothing.
156
+ * - **POSIX:** this is worse, because `pty.spawn` of a nonexistent command
157
+ * *succeeds*. execvp fails inside the forked child, the parent never learns
158
+ * and the caller gets a healthy-looking session that is silently dead. An
159
+ * agent would then wait out its full timeout for output that can never
160
+ * arrive.
161
+ *
162
+ * Resolving up front turns both into an immediate, actionable error.
163
+ */
164
+ function resolveExecutable(command, platform) {
165
+ const isWindows = platform === 'win32';
166
+ const usable = (candidate) => {
167
+ try {
168
+ if (!fs.statSync(candidate).isFile())
169
+ return false;
170
+ if (!isWindows)
171
+ fs.accessSync(candidate, fs.constants.X_OK);
172
+ return true;
173
+ }
174
+ catch {
175
+ return false;
176
+ }
177
+ };
178
+ // On Windows a bare name usually needs a PATHEXT suffix; try suffixed forms
179
+ // first unless the caller already supplied one.
180
+ const extensions = isWindows
181
+ ? (process.env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD').split(';').filter((e) => e !== '')
182
+ : [];
183
+ const candidatesFor = (base) => {
184
+ if (!isWindows)
185
+ return [base];
186
+ const alreadyExtended = extensions.some((e) => base.toLowerCase().endsWith(e.toLowerCase()));
187
+ return alreadyExtended
188
+ ? [base, ...extensions.map((e) => base + e)]
189
+ : [...extensions.map((e) => base + e), base];
190
+ };
191
+ const explicitPath = /[\\/]/.test(command) || (isWindows && /^[a-z]:/i.test(command));
192
+ const searchBases = explicitPath
193
+ ? [command]
194
+ : (process.env['PATH'] ?? '')
195
+ .split(path.delimiter)
196
+ .filter((d) => d !== '')
197
+ .map((dir) => path.join(dir, command));
198
+ for (const base of searchBases) {
199
+ for (const candidate of candidatesFor(base)) {
200
+ if (usable(candidate))
201
+ return candidate;
202
+ }
203
+ }
204
+ throw new CommandNotFoundError(explicitPath
205
+ ? `Not an executable file: ${command}.`
206
+ : `Command not found on PATH: ${command}. Give an absolute path, or drop ` +
207
+ `shell:false (--no-shell) and let the shell wrapper resolve it.`);
208
+ }
209
+ /**
210
+ * A session gets the clean baseline unless the configuration says otherwise
211
+ * (ADR-008): the daemon's environment is whatever the client that auto-started
212
+ * it had, so passing it on would hand that client's secrets to every session.
213
+ */
214
+ export const DEFAULT_SESSION_ENV = 'clean';
215
+ /**
216
+ * The minimal functional variable set for `sessionEnv: "clean"`: enough for
217
+ * shells and ordinary programs to work, without the daemon's secrets. Windows
218
+ * needs rather more scaffolding than POSIX to be usable at all: the standard
219
+ * variables below carry no secrets, and toolchains such as MSBuild, the .NET
220
+ * SDK, PowerShell modules and Git for Windows look for them. POSIX keeps the
221
+ * locale, without which terminal programs lose UTF-8.
222
+ */
223
+ const CLEAN_ENV_KEYS = {
224
+ win32: [
225
+ 'PATH',
226
+ 'PATHEXT',
227
+ 'SYSTEMROOT',
228
+ 'SYSTEMDRIVE',
229
+ 'COMSPEC',
230
+ 'WINDIR',
231
+ 'TEMP',
232
+ 'TMP',
233
+ 'USERPROFILE',
234
+ 'USERNAME',
235
+ 'HOMEDRIVE',
236
+ 'HOMEPATH',
237
+ 'APPDATA',
238
+ 'LOCALAPPDATA',
239
+ 'PROGRAMFILES',
240
+ 'PROGRAMDATA',
241
+ 'NUMBER_OF_PROCESSORS',
242
+ 'PROCESSOR_ARCHITECTURE',
243
+ 'PROCESSOR_IDENTIFIER',
244
+ 'PROCESSOR_LEVEL',
245
+ 'PROCESSOR_REVISION',
246
+ 'OS',
247
+ 'ProgramFiles(x86)',
248
+ 'ProgramW6432',
249
+ 'CommonProgramFiles',
250
+ 'CommonProgramFiles(x86)',
251
+ 'CommonProgramW6432',
252
+ 'ALLUSERSPROFILE',
253
+ 'PUBLIC',
254
+ 'COMPUTERNAME',
255
+ 'USERDOMAIN',
256
+ 'USERDOMAIN_ROAMINGPROFILE',
257
+ 'LOGONSERVER',
258
+ 'PSModulePath',
259
+ 'NoDefaultCurrentDirectoryInExePath',
260
+ ],
261
+ posix: ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TMPDIR'],
262
+ };
263
+ // Words that mark a variable name as holding a credential. A name is split into
264
+ // words at underscores, at lower-to-upper case changes and before the last
265
+ // capital of a run of capitals, so `PAYMENT_API_KEY`, `GithubToken`, `GHToken`,
266
+ // `S3Key` and `SSH_AUTH_SOCK` match while `MAX_TOKENS`, `PWD` and
267
+ // `GIT_AUTHOR_NAME` do not. A word ending in one of CREDENTIAL_SUFFIXES matches
268
+ // too, for names written as one word (`GITHUBTOKEN`, `PGPASSWORD`). The list is
269
+ // advisory: a name need say nothing of what it holds (`DATABASE_URL`), which is
270
+ // why sessions start clean rather than relying on it.
271
+ const CREDENTIAL_WORDS = new Set([
272
+ 'KEY',
273
+ 'KEYS',
274
+ 'APIKEY',
275
+ 'TOKEN',
276
+ 'SECRET',
277
+ 'SECRETS',
278
+ 'PASSWORD',
279
+ 'PASSWORDS',
280
+ 'PASSWD',
281
+ 'PASS',
282
+ 'PW',
283
+ 'PASSPHRASE',
284
+ 'CREDENTIAL',
285
+ 'CREDENTIALS',
286
+ 'CREDS',
287
+ 'COOKIE',
288
+ 'AUTH',
289
+ 'AUTHORIZATION',
290
+ 'BEARER',
291
+ 'JWT',
292
+ 'PAT',
293
+ 'SAS',
294
+ 'DSN',
295
+ 'WEBHOOK',
296
+ ]);
297
+ const CREDENTIAL_SUFFIXES = [
298
+ 'TOKEN',
299
+ 'SECRET',
300
+ 'PASSWORD',
301
+ 'PASSWD',
302
+ 'PASSPHRASE',
303
+ 'APIKEY',
304
+ 'ACCESSKEY',
305
+ 'SECRETKEY',
306
+ 'PRIVATEKEY',
307
+ ];
308
+ function looksLikeCredential(name) {
309
+ return name
310
+ // A lookahead, not `([A-Z]+)([A-Z][a-z])`: that backtracks quadratically on
311
+ // a long run of capitals, and a name can be as long as the environment.
312
+ .replace(/([A-Z])(?=[A-Z][a-z])/g, '$1_')
313
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
314
+ .toUpperCase()
315
+ .split(/_+/)
316
+ .some((word) => CREDENTIAL_WORDS.has(word) || CREDENTIAL_SUFFIXES.some((suffix) => word.endsWith(suffix)));
317
+ }
318
+ /**
319
+ * The names (never the values) of variables in `source` whose names look like
320
+ * credentials, sorted: part of what `passthrough` would hand every session.
321
+ */
322
+ export function credentialShapedNames(source = process.env) {
323
+ return Object.keys(source)
324
+ .filter((name) => source[name] !== undefined && source[name] !== '')
325
+ .filter(looksLikeCredential)
326
+ .sort((a, b) => a.localeCompare(b));
327
+ }
328
+ /**
329
+ * Build the PTY environment for a session. Variable-name matching is
330
+ * case-insensitive on every platform: Windows environment names are, and a
331
+ * list in the configuration means the same wherever the daemon runs.
332
+ *
333
+ * An explicit allowlist is the CLEAN baseline plus the listed names: a bare
334
+ * list would strip system scaffolding that processes need to start at all
335
+ * (verified: node.exe aborts in CSPRNG initialisation without `SystemRoot` on
336
+ * Windows), and "functional minimum plus exactly what you name" is the intent
337
+ * of the mode: naming secrets in, not naming plumbing.
338
+ *
339
+ * `passed` is the session's own variables from the client that started it
340
+ * (`SessionOptions.env`), set on top of whatever the mode gave. On Windows a
341
+ * passed name replaces the inherited variable of the same name in any case,
342
+ * rather than sitting beside it as a second copy.
343
+ */
344
+ export function buildSessionEnv(mode, platform, source = process.env, passed = {}) {
345
+ const env = {};
346
+ if (mode === 'passthrough') {
347
+ for (const [key, value] of Object.entries(source)) {
348
+ if (value !== undefined)
349
+ env[key] = value;
350
+ }
351
+ }
352
+ else {
353
+ const baseline = CLEAN_ENV_KEYS[platform === 'win32' ? 'win32' : 'posix'];
354
+ const wanted = new Set((mode === 'clean' ? baseline : [...baseline, ...mode]).map((k) => k.toUpperCase()));
355
+ for (const [key, value] of Object.entries(source)) {
356
+ if (value !== undefined && wanted.has(key.toUpperCase()))
357
+ env[key] = value;
358
+ }
359
+ }
360
+ const setOnly = (name, value) => {
361
+ if (platform === 'win32') {
362
+ for (const key of Object.keys(env)) {
363
+ if (key.toUpperCase() === name.toUpperCase())
364
+ delete env[key];
365
+ }
366
+ }
367
+ env[name] = value;
368
+ };
369
+ for (const [name, value] of Object.entries(passed))
370
+ setOnly(name, value);
371
+ // Always injected (§7): Windows sets no TERM, and TUIs then assume a dumb
372
+ // terminal and disable colour. On Windows any other casing goes first, or
373
+ // the child would see that copy's value instead of these.
374
+ setOnly('TERM', 'xterm-256color');
375
+ setOnly('COLORTERM', 'truecolor');
376
+ return env;
377
+ }
378
+ export class Session {
379
+ id;
380
+ label;
381
+ /** What this session is for, for the human watching it. */
382
+ purpose;
383
+ /** The audit actor that started it: set by the daemon, not by the body. */
384
+ startedBy;
385
+ /** The pre-wrap command as given by the caller. */
386
+ command;
387
+ args;
388
+ /** The agent it was started as, which chooses how its screen is read. */
389
+ agent;
390
+ createdAt;
391
+ pty;
392
+ renderer;
393
+ logger;
394
+ platform;
395
+ treeKiller;
396
+ /** Whether the program has bracketed paste (DEC 2004) enabled. See PASTE_START. */
397
+ bracketedPaste = false;
398
+ /**
399
+ * Whether the most recent `write` took the bracketed-paste branch.
400
+ * Diagnostic only. A program that enabled bracketed paste can still report
401
+ * no markers, and from outside the two causes cannot be told apart: we
402
+ * wrapped and the transport stripped the markers off the input (ConPTY
403
+ * can), or the write raced ahead of the flag. This says which.
404
+ */
405
+ lastWriteWrapped = null;
406
+ /** Trailing output kept so a mode sequence split across PTY reads is still seen. */
407
+ modeScanTail = '';
408
+ dataListeners = new Set();
409
+ exitListeners = new Set();
410
+ /** Whether the program has hidden the cursor (DECTCEM off), carried to viewers. */
411
+ cursorHidden = false;
412
+ /** Serialises write() so chunked writes cannot interleave. See write(). */
413
+ writeChain = Promise.resolve();
414
+ lastChange = Date.now();
415
+ /** Sticky: the rendered screen has shown something at least once. */
416
+ painted = false;
417
+ /**
418
+ * The last input written, for the waiter's echo guard. Memory only, never
419
+ * logged: §4.5 keeps keystroke content out of the audit trail, and this
420
+ * is one string overwritten by the next write.
421
+ */
422
+ lastInputData = null;
423
+ /** Which prompt the last input answered, and whether it has since gone. */
424
+ stalePrompts = new StalePromptGuard();
425
+ exitedFlag = false;
426
+ exitedAtValue = null;
427
+ exitCodeValue = null;
428
+ readyFlag;
429
+ readyReasonValue = 'not-tracked';
430
+ geometryHeldFlag;
431
+ killed = false;
432
+ constructor(id, options, deps = {}) {
433
+ this.id = id;
434
+ this.command = options.command;
435
+ this.args = options.args ?? [];
436
+ this.label = options.label ?? options.command;
437
+ this.purpose = options.purpose ?? '';
438
+ this.startedBy = options.startedBy ?? 'unknown';
439
+ this.agent = options.agent;
440
+ this.createdAt = new Date();
441
+ this.logger = deps.logger ?? NULL_LOGGER;
442
+ this.platform = deps.platform ?? process.platform;
443
+ this.treeKiller = deps.treeKiller ?? taskkillTrees;
444
+ const cols = options.cols ?? DEFAULT_COLS;
445
+ const rows = options.rows ?? DEFAULT_ROWS;
446
+ this.renderer = new ScreenRenderer({ cols, rows, scrollback: DEFAULT_SCROLLBACK });
447
+ // cols/rows say where to START, and nothing more: a size that also froze
448
+ // the grid would leave a viewer with a grid it could not change, and a
449
+ // window of a different shape could only letterbox. Holding is asked
450
+ // for explicitly, because the common case is a human watching in a browser
451
+ // that should simply fill, and the rare case is a run that would be
452
+ // invalidated by a reflow.
453
+ this.geometryHeldFlag = options.hold === true;
454
+ const { file, fileArgs } = this.wrapCommand(options);
455
+ this.logger.info('session spawn', {
456
+ id,
457
+ command: this.command,
458
+ args: this.args,
459
+ wrapped: file !== this.command,
460
+ // Names only: the values are secrets more often than not.
461
+ ...(options.env !== undefined ? { envNames: Object.keys(options.env) } : {}),
462
+ });
463
+ // node-pty is loaded on the first start, not with the daemon, so an install
464
+ // that left it unable to open a terminal fails here with what to do
465
+ // (`nativePty.ts`).
466
+ const { spawn } = loadNodePty();
467
+ // A Windows start that fails part-way must not leave node-pty's
468
+ // half-built terminal behind (`windowsPtyStart.ts`).
469
+ if (process.platform === 'win32')
470
+ releaseFailedStarts();
471
+ ensureSpawnHelperExecutable();
472
+ try {
473
+ this.pty = spawn(file, fileArgs, {
474
+ name: 'xterm-256color',
475
+ cols,
476
+ rows,
477
+ cwd: options.cwd ?? process.cwd(),
478
+ // The daemon always passes the mode it resolved and reports; this
479
+ // default serves code that uses SessionManager or Session directly.
480
+ env: buildSessionEnv(deps.sessionEnv ?? DEFAULT_SESSION_ENV, this.platform, process.env, options.env),
481
+ });
482
+ }
483
+ catch (error) {
484
+ // On Windows node-pty loads its native module here, as the terminal is
485
+ // built, so a missing binary surfaces now rather than at the load above.
486
+ throw explainSpawnFailure(error);
487
+ }
488
+ // A failed write on a Windows terminal's pipes must not take the daemon
489
+ // down (`windowsPtyStart.ts`). Logged once a stream: for the known cause,
490
+ // the console host has gone and the session's exit follows.
491
+ if (process.platform === 'win32') {
492
+ const reported = new Set();
493
+ listenForTerminalErrors(this.pty, (error, stream) => {
494
+ if (reported.has(stream))
495
+ return;
496
+ reported.add(stream);
497
+ this.logger.warn(`session ${stream} failed`, { id, error: String(error) });
498
+ });
499
+ }
500
+ this.pty.onData((data) => {
501
+ // Track bracketed-paste mode from the app's own output (see PASTE_START).
502
+ //
503
+ // Scanned with a carry-over tail because PTY read boundaries are
504
+ // arbitrary: an 8-byte `ESC[?2004h` can straddle two onData callbacks,
505
+ // and a missed transition leaves us writing down the WRONG path for the
506
+ // rest of the session. Keeping the last few characters and
507
+ // prefixing them costs nothing and closes the split.
508
+ //
509
+ // lastIndexOf, not includes: one burst can turn the mode on and off
510
+ // again (TUIs re-assert their modes on redraw), and only the LAST
511
+ // transition reflects the state the app ended up in.
512
+ const scan = this.modeScanTail + data;
513
+ this.bracketedPaste = bracketedPasteAfter(scan, this.bracketedPaste);
514
+ this.cursorHidden = cursorHiddenAfter(scan, this.cursorHidden);
515
+ this.modeScanTail = scan.slice(-MODE_SCAN_TAIL_CHARS);
516
+ const rendered = this.renderer.write(data);
517
+ // First paint is decided by the RENDERER, not by bytes arriving: ConPTY
518
+ // emits mode-set sequences ~140 ms after spawn that draw nothing, and a
519
+ // quiet/readyQuiet that counted them as output would report a CLI ready
520
+ // before its first byte. Checked per chunk only until it
521
+ // holds, so the snapshot cost stops at the first visible character.
522
+ if (!this.painted) {
523
+ void rendered.then(() => {
524
+ if (!this.painted && this.renderer.snapshot().screen !== '')
525
+ this.painted = true;
526
+ });
527
+ }
528
+ this.lastChange = Date.now();
529
+ for (const listener of this.dataListeners)
530
+ listener(data);
531
+ });
532
+ this.pty.onExit(({ exitCode }) => {
533
+ this.exitedFlag = true;
534
+ this.exitedAtValue = Date.now();
535
+ this.exitCodeValue = exitCode;
536
+ this.lastChange = Date.now();
537
+ this.logger.info('session exit', { id, exitCode });
538
+ for (const listener of this.exitListeners)
539
+ listener(exitCode);
540
+ });
541
+ // Readiness (§3.1): first paint ≠ ready. With no condition given the
542
+ // session counts as ready at spawn; otherwise readiness flips when the
543
+ // condition holds. A session whose condition never holds stays not-ready,
544
+ // which is the truth and is visible in list/snapshot output.
545
+ if (options.readyText !== undefined || options.readyQuiet !== undefined) {
546
+ this.readyFlag = false;
547
+ this.readyReasonValue = 'pending';
548
+ const condition = options.readyText !== undefined
549
+ ? { text: options.readyText }
550
+ : { quiet: options.readyQuiet };
551
+ void waitFor(this, condition, { timeout: MAX_WAIT_TIMEOUT_MS }).then((result) => {
552
+ if (result.matched) {
553
+ this.readyFlag = true;
554
+ this.readyReasonValue = 'condition-met';
555
+ this.logger.info('session ready', { id, reason: result.reason });
556
+ }
557
+ else {
558
+ this.readyReasonValue = 'never-held';
559
+ this.logger.warn('session readiness condition never held', {
560
+ id,
561
+ reason: result.reason,
562
+ });
563
+ }
564
+ });
565
+ }
566
+ else {
567
+ // No condition was asked for, so nothing is being checked. `ready` is
568
+ // true, meaning only that the process started, and `readyReason` says
569
+ // plainly that it is not evidence. Some agent CLIs emit nothing for tens
570
+ // of seconds and silently discard input typed during that window, so a bare
571
+ // `true` here is the most dangerous value in the API.
572
+ this.readyFlag = true;
573
+ this.readyReasonValue = 'not-tracked';
574
+ }
575
+ }
576
+ /**
577
+ * Windows default: wrap in `cmd.exe` (§7: direct ConPTY spawns of
578
+ * single-file binaries hang). POSIX default: direct spawn; `shell: true`
579
+ * wraps in `/bin/sh -c`.
580
+ *
581
+ * The Windows form is `cmd.exe /d /s /c "<line>"` passed as a VERBATIM
582
+ * string (node-pty applies no quoting to string args). `/s` pins cmd's
583
+ * strip-first-and-last-quote behaviour so the outer quotes vanish cleanly
584
+ * and every quote inside `<line>` survives. Without it, a command path
585
+ * containing spaces (e.g. `C:\Program Files\nodejs\node.exe`) is split at
586
+ * the first space. This is the same invocation libuv uses for shell spawns.
587
+ */
588
+ wrapCommand(options) {
589
+ const wantShell = options.shell ?? this.platform === 'win32';
590
+ if (!wantShell) {
591
+ return {
592
+ file: resolveExecutable(options.command, this.platform),
593
+ fileArgs: options.args ?? [],
594
+ };
595
+ }
596
+ // Quote the command token if it has whitespace and the caller has not
597
+ // already quoted it; args are shell text and pass through untouched.
598
+ const commandToken = /\s/.test(options.command) && !options.command.startsWith('"')
599
+ ? `"${options.command}"`
600
+ : options.command;
601
+ const line = commandLine(commandToken, options.args ?? []);
602
+ if (this.platform === 'win32') {
603
+ const comspec = process.env['ComSpec'] ?? 'cmd.exe';
604
+ return { file: comspec, fileArgs: `/d /s /c "${line}"` };
605
+ }
606
+ return { file: '/bin/sh', fileArgs: ['-c', line] };
607
+ }
608
+ get pid() {
609
+ return this.pty.pid;
610
+ }
611
+ get cols() {
612
+ return this.renderer.cols;
613
+ }
614
+ get rows() {
615
+ return this.renderer.rows;
616
+ }
617
+ get ready() {
618
+ return this.readyFlag;
619
+ }
620
+ /** Why `ready` holds its value. See {@link SessionSummary.readyReason}. */
621
+ get readyReason() {
622
+ return this.readyReasonValue;
623
+ }
624
+ /**
625
+ * True only when the grid is HELD: `hold` at start, or a resize that asked
626
+ * for it. A held grid keeps its size while viewports connect and reshape
627
+ * themselves around it; an unheld grid belongs to the controlling viewport,
628
+ * which fits it to the human's window (design §5).
629
+ */
630
+ get geometryHeld() {
631
+ return this.geometryHeldFlag;
632
+ }
633
+ get exited() {
634
+ return this.exitedFlag;
635
+ }
636
+ /** Epoch ms of process exit: the manager's reap grace counts from here. */
637
+ get exitedAt() {
638
+ return this.exitedAtValue;
639
+ }
640
+ get exitCode() {
641
+ return this.exitCodeValue;
642
+ }
643
+ get watchers() {
644
+ return this.dataListeners.size;
645
+ }
646
+ // ------------------------------------------------------------- WaitTarget
647
+ getScreen() {
648
+ return this.renderer.snapshot().screen;
649
+ }
650
+ lastChangeAt() {
651
+ return this.lastChange;
652
+ }
653
+ isExited() {
654
+ return this.exitedFlag;
655
+ }
656
+ hasPainted() {
657
+ return this.painted;
658
+ }
659
+ lastInput() {
660
+ return this.lastInputData;
661
+ }
662
+ observePrompt(signature) {
663
+ this.stalePrompts.observe(signature);
664
+ }
665
+ isStalePrompt(signature) {
666
+ return this.stalePrompts.isStale(signature);
667
+ }
668
+ // ------------------------------------------------------------------ input
669
+ /**
670
+ * Write to the PTY the way the program on the other end asked to be written
671
+ * to: as a bracketed paste when it enabled that mode, otherwise chunked.
672
+ *
673
+ * Anything under WRITE_CHUNK_CHARS goes straight through either way, so keys
674
+ * and human typing are unaffected. Above it the two paths diverge, and the
675
+ * divergence is the point. See PASTE_START for the evidence that chunking a
676
+ * TUI's input is what loses the front of a long prompt.
677
+ *
678
+ * **Writes are serialised.** The chunked path yields between pieces, and this
679
+ * tool's whole premise is that a human and an agent share one session. So
680
+ * without a queue a keystroke (or a multi-character paste, which is what xterm
681
+ * hands us for a clipboard drop) could land *between* an earlier write's
682
+ * chunks and interleave two inputs into gibberish. Making that ordering the
683
+ * caller's problem would be a trap; the queue keeps writes in call order,
684
+ * as a synchronous write would.
685
+ *
686
+ * Resolves with the screen as it was rendered just before this input went
687
+ * in, taken in the queue, so an earlier write still going in cannot be
688
+ * mistaken for this one's effect (`terminal_type`'s verify compares with it).
689
+ */
690
+ write(data) {
691
+ const queued = this.writeChain.then(() => this.writeInput(data));
692
+ // The chain must survive a failed write, or one rejection would wedge every
693
+ // subsequent write on this session.
694
+ this.writeChain = queued.then(() => undefined, () => undefined);
695
+ return queued;
696
+ }
697
+ async writeInput(data) {
698
+ // Recorded BEFORE the bytes go in, when the screen still shows what this
699
+ // input is answering: the waiter's stale-prompt guard needs that prompt,
700
+ // and its echo guard needs the input itself.
701
+ this.lastInputData = data;
702
+ const { screen } = this.renderer.snapshot();
703
+ this.stalePrompts.noteInput(screen);
704
+ if (data.length <= WRITE_CHUNK_CHARS) {
705
+ this.pty.write(data);
706
+ return screen;
707
+ }
708
+ // Bracketed paste: ONE write, no chunking, exactly as a terminal delivers a
709
+ // clipboard drop. The submitting newline (if the caller appended one) is
710
+ // deliberately left OUTSIDE the markers. Inside, a TUI treats it as
711
+ // literal text in the pasted block and the prompt is composed but never
712
+ // sent, which looks identical to input being ignored.
713
+ if (this.bracketedPaste) {
714
+ const newlineAt = data.search(/[\r\n]+$/);
715
+ const body = newlineAt === -1 ? data : data.slice(0, newlineAt);
716
+ const trailer = newlineAt === -1 ? '' : data.slice(newlineAt);
717
+ this.lastWriteWrapped = true;
718
+ this.pty.write(`${PASTE_START}${body}${PASTE_END}${trailer}`);
719
+ return screen;
720
+ }
721
+ this.lastWriteWrapped = false;
722
+ let offset = 0;
723
+ while (offset < data.length) {
724
+ let end = Math.min(offset + WRITE_CHUNK_CHARS, data.length);
725
+ // Never split a surrogate pair: half of an astral character is not a
726
+ // character, and the two halves arriving in separate writes decode to
727
+ // replacement characters rather than the emoji the caller sent.
728
+ if (end < data.length) {
729
+ const code = data.charCodeAt(end - 1);
730
+ if (code >= 0xd800 && code <= 0xdbff)
731
+ end -= 1;
732
+ }
733
+ this.pty.write(data.slice(offset, end));
734
+ offset = end;
735
+ if (offset < data.length) {
736
+ await new Promise((resolve) => setTimeout(resolve, WRITE_CHUNK_DELAY_MS));
737
+ }
738
+ }
739
+ return screen;
740
+ }
741
+ /**
742
+ * Resize the PTY.
743
+ *
744
+ * Every caller arrives here, a viewport whose window changed shape and an
745
+ * agent asking for a specific grid alike, because the resize itself is the
746
+ * same act either way. What differs is only whether the caller also means to stop
747
+ * anyone else changing it, and that is said explicitly with `hold` rather
748
+ * than inferred from who is calling. Omitting `hold` leaves the current
749
+ * setting alone, so a viewport following a window cannot quietly release a
750
+ * hold that a scripted run is relying on.
751
+ */
752
+ resize(cols, rows, options = {}) {
753
+ this.pty.resize(cols, rows);
754
+ this.renderer.resize(cols, rows);
755
+ if (options.hold !== undefined)
756
+ this.geometryHeldFlag = options.hold;
757
+ }
758
+ // ----------------------------------------------------------------- output
759
+ /** Live raw-stream subscription (viewer mirroring). Returns unsubscribe. */
760
+ onData(listener) {
761
+ this.dataListeners.add(listener);
762
+ return () => this.dataListeners.delete(listener);
763
+ }
764
+ onExit(listener) {
765
+ this.exitListeners.add(listener);
766
+ return () => this.exitListeners.delete(listener);
767
+ }
768
+ /**
769
+ * The rendered terminal as bytes that rebuild it in a fresh terminal of the
770
+ * same size (design §5): what a viewer receives on connect and after every
771
+ * grid change, in place of any slice of the raw stream. A slice starts
772
+ * mid-frame, and a program that only repaints what changed never puts the
773
+ * rest of its frame back. Every agent CLI repaints that way once its chrome
774
+ * is up, and on Windows every program does as ConPTY relays it. Resolves
775
+ * once every byte received before the call has been parsed, and includes
776
+ * nothing received after it.
777
+ */
778
+ async viewerState(options = {}) {
779
+ // Read before the await: the bytes behind this flag are the bytes in the
780
+ // snapshot, not whatever arrives while it is being taken.
781
+ const hidden = this.cursorHidden;
782
+ const state = await this.renderer.serialize(options);
783
+ return hidden ? state + CURSOR_HIDE : state;
784
+ }
785
+ async snapshot() {
786
+ await this.renderer.flush();
787
+ const rendered = this.renderer.snapshot();
788
+ // Every look at the screen is evidence for the stale-prompt guard. A
789
+ // snapshot that finds no prompt, or a different one, is what lets a later
790
+ // prompt with identical text count as new rather than as the one just
791
+ // answered, and that includes the ones the daemon's stall scan and verify
792
+ // take.
793
+ this.stalePrompts.observe(detectPrompt(rendered.screen)?.signature ?? null);
794
+ return {
795
+ id: this.id,
796
+ label: this.label,
797
+ cols: rendered.cols,
798
+ rows: rendered.rows,
799
+ cursor: rendered.cursor,
800
+ exited: this.exitedFlag,
801
+ exitCode: this.exitCodeValue,
802
+ screen: rendered.screen,
803
+ };
804
+ }
805
+ /** Last N lines including scrollback (design §3). */
806
+ async lastLines(count) {
807
+ await this.renderer.flush();
808
+ return this.renderer.lastLines(count);
809
+ }
810
+ /** Current viewport lines (for `terminal_find`). */
811
+ async viewportLines() {
812
+ await this.renderer.flush();
813
+ return this.renderer.snapshot().lines;
814
+ }
815
+ /**
816
+ * The viewport with `above` lines of scrollback over it, as drawn
817
+ * (`reasoning.ts`). `firstVisible` is where the viewport begins.
818
+ */
819
+ async styledScreen(above = 0) {
820
+ await this.renderer.flush();
821
+ return this.renderer.styledLines({ above });
822
+ }
823
+ /**
824
+ * The last `count` lines, scrollback included, as drawn, with up to
825
+ * `context` more lines over them; `firstVisible` is where the `count` begin.
826
+ */
827
+ async styledTail(count, context = 0) {
828
+ await this.renderer.flush();
829
+ const { lines } = this.renderer.styledLines({ last: count + context });
830
+ return { lines, firstVisible: Math.max(0, lines.length - count) };
831
+ }
832
+ waitFor(condition, options) {
833
+ return waitFor(this, condition, options);
834
+ }
835
+ summary() {
836
+ return {
837
+ id: this.id,
838
+ label: this.label,
839
+ purpose: this.purpose,
840
+ startedBy: this.startedBy,
841
+ agent: this.agent ?? null,
842
+ command: this.command,
843
+ args: this.args,
844
+ cols: this.cols,
845
+ rows: this.rows,
846
+ ready: this.readyFlag,
847
+ readyReason: this.readyReasonValue,
848
+ geometryHeld: this.geometryHeldFlag,
849
+ exited: this.exitedFlag,
850
+ exitCode: this.exitCodeValue,
851
+ watchers: this.watchers,
852
+ createdAt: this.createdAt.toISOString(),
853
+ };
854
+ }
855
+ /**
856
+ * Kill the whole process tree (design §3.1). Commands are shell-wrapped, so
857
+ * killing only the direct child (`cmd.exe`) strands the real application,
858
+ * and orphaned agent CLIs keep running and keep spending paid API tokens.
859
+ *
860
+ * Windows: `taskkill /T /F` walks and kills the tree; closing the ConPTY via
861
+ * `pty.kill()` also sends CTRL_CLOSE_EVENT to console-attached
862
+ * survivors. (The design's Job Object hardening needs a native module and is
863
+ * deferred. If the daemon itself dies, its ConPTY handles close, which gives
864
+ * console-attached descendants the same close signal.)
865
+ *
866
+ * POSIX: the PTY child is the session leader of its own process group, so
867
+ * signalling the negated pid takes the group down.
868
+ *
869
+ * The OS tree kill runs only while the root is still alive. A session whose
870
+ * program exited on its own is reaped fifteen minutes later, and by then the
871
+ * process group id may have been recycled, so an unconditional `kill(-pid)`
872
+ * could take down something unrelated; on Windows `taskkill` cannot walk a
873
+ * tree from a dead root either. So a grandchild that outlived its parent is
874
+ * left alone rather than guessed at, a residual risk stated in
875
+ * `docs/reference/security-model.md`.
876
+ */
877
+ async kill() {
878
+ if (this.killed)
879
+ return;
880
+ this.killed = true;
881
+ const pid = this.pty.pid;
882
+ this.logger.info('session kill', { id: this.id, pid });
883
+ if (!this.exitedFlag) {
884
+ if (this.platform === 'win32') {
885
+ // A root that has already died leaves no tree to walk. At daemon
886
+ // shutdown this is the usual case: `killAll` has just killed every
887
+ // session's tree in one run.
888
+ const failure = this.processAlive(pid) ? await this.treeKiller([pid]) : null;
889
+ if (failure !== null) {
890
+ // Three very different things land here, so report which
891
+ // actually happened.
892
+ //
893
+ // `timedOut` means OUR timeout fired and taskkill was terminated
894
+ // mid-walk. The tree may be half-killed, so this is the one
895
+ // that genuinely warrants attention.
896
+ //
897
+ // A non-zero exit is NOT proof of failure. `taskkill /T` walks
898
+ // a live tree, and descendants routinely die of their own
899
+ // accord (or as a side effect of a parent dying) between
900
+ // enumeration and the kill call; taskkill then reports "not
901
+ // found" for those and exits 128 having successfully killed
902
+ // everything else. Measured: exit 128 alongside 78 SUCCESS
903
+ // lines on a Qoder tree.
904
+ this.logger.warn(failure.timedOut
905
+ ? 'tree kill timed out; the process tree may be partially killed'
906
+ : 'taskkill exited non-zero (usually descendants that vanished mid-walk)', { id: this.id, pid, ...failure, timeoutMs: TREE_KILL_TIMEOUT_MS });
907
+ }
908
+ }
909
+ else {
910
+ // SIGKILL outright, with no SIGTERM grace: design §3.1 chooses the
911
+ // process-group kill precisely so that children which ignore SIGTERM
912
+ // cannot survive, and a grace period would hand them the chance back.
913
+ try {
914
+ process.kill(-pid, 'SIGKILL');
915
+ }
916
+ catch (error) {
917
+ this.logger.warn('process-group kill failed, falling back to pty.kill', {
918
+ id: this.id,
919
+ error: String(error),
920
+ });
921
+ }
922
+ }
923
+ }
924
+ try {
925
+ this.pty.kill();
926
+ }
927
+ catch {
928
+ // Already dead: the outcome we wanted.
929
+ }
930
+ // Verify rather than assume. An orphaned agent CLI keeps running and keeps
931
+ // spending paid API tokens, so the fact worth logging is "it died", not
932
+ // "we sent a kill". Checking only the root pid is deliberate: a full
933
+ // descendant walk needs recursive process queries that are far slower than
934
+ // the kill itself (measured in minutes), and the root dying is what the
935
+ // caller actually contracted for.
936
+ if (!this.processAlive(pid)) {
937
+ this.logger.info('session tree killed', { id: this.id, pid });
938
+ }
939
+ else {
940
+ this.logger.error('session root SURVIVED the kill and may still be running', {
941
+ id: this.id,
942
+ pid,
943
+ });
944
+ }
945
+ this.renderer.dispose();
946
+ }
947
+ /**
948
+ * Cheap liveness probe: signal 0 performs the permission and existence
949
+ * checks without delivering a signal, on Windows as well as POSIX.
950
+ */
951
+ processAlive(pid) {
952
+ try {
953
+ process.kill(pid, 0);
954
+ return true;
955
+ }
956
+ catch (error) {
957
+ // EPERM means the process EXISTS but we are not allowed to signal it
958
+ // (POSIX). Reporting that as "gone" would make this whole verification
959
+ // dishonest in the one direction that matters: claiming a clean kill
960
+ // over a survivor, which is the failure the probe exists to catch.
961
+ // Only ESRCH ("no such process") is genuine evidence of death.
962
+ return error.code === 'EPERM';
963
+ }
964
+ }
965
+ }
966
+ //# sourceMappingURL=session.js.map