shellpuppet 0.1.0 → 0.2.1

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 (101) hide show
  1. package/README.md +210 -33
  2. package/dist/cli/desktopShortcut.d.ts +22 -0
  3. package/dist/cli/desktopShortcut.js +157 -0
  4. package/dist/cli/desktopShortcut.js.map +1 -0
  5. package/dist/cli/index.js +268 -59
  6. package/dist/cli/index.js.map +1 -1
  7. package/dist/client/http.d.ts +74 -3
  8. package/dist/client/http.js +560 -37
  9. package/dist/client/http.js.map +1 -1
  10. package/dist/core/dialogs.d.ts +20 -12
  11. package/dist/core/dialogs.js +31 -19
  12. package/dist/core/dialogs.js.map +1 -1
  13. package/dist/core/manager.d.ts +35 -5
  14. package/dist/core/manager.js +121 -8
  15. package/dist/core/manager.js.map +1 -1
  16. package/dist/core/nativePty.d.ts +9 -5
  17. package/dist/core/nativePty.js +11 -6
  18. package/dist/core/nativePty.js.map +1 -1
  19. package/dist/core/promptDetector.d.ts +37 -3
  20. package/dist/core/promptDetector.js +303 -12
  21. package/dist/core/promptDetector.js.map +1 -1
  22. package/dist/core/reasoning.d.ts +19 -6
  23. package/dist/core/reasoning.js +223 -30
  24. package/dist/core/reasoning.js.map +1 -1
  25. package/dist/core/regexBudget.d.ts +20 -0
  26. package/dist/core/regexBudget.js +25 -1
  27. package/dist/core/regexBudget.js.map +1 -1
  28. package/dist/core/renderer.d.ts +16 -1
  29. package/dist/core/renderer.js +97 -6
  30. package/dist/core/renderer.js.map +1 -1
  31. package/dist/core/selection.d.ts +6 -0
  32. package/dist/core/selection.js +48 -0
  33. package/dist/core/selection.js.map +1 -0
  34. package/dist/core/session.d.ts +267 -13
  35. package/dist/core/session.js +585 -101
  36. package/dist/core/session.js.map +1 -1
  37. package/dist/core/types.d.ts +53 -18
  38. package/dist/core/types.js +30 -6
  39. package/dist/core/types.js.map +1 -1
  40. package/dist/core/waiter.d.ts +12 -4
  41. package/dist/core/waiter.js +63 -70
  42. package/dist/core/waiter.js.map +1 -1
  43. package/dist/core/windowsConsoleHost.d.ts +147 -0
  44. package/dist/core/windowsConsoleHost.js +588 -0
  45. package/dist/core/windowsConsoleHost.js.map +1 -0
  46. package/dist/core/windowsPtyStart.d.ts +100 -29
  47. package/dist/core/windowsPtyStart.js +143 -36
  48. package/dist/core/windowsPtyStart.js.map +1 -1
  49. package/dist/daemon/auth.d.ts +72 -2
  50. package/dist/daemon/auth.js +128 -3
  51. package/dist/daemon/auth.js.map +1 -1
  52. package/dist/daemon/config.d.ts +44 -1
  53. package/dist/daemon/config.js +276 -9
  54. package/dist/daemon/config.js.map +1 -1
  55. package/dist/daemon/folderPicker.d.ts +27 -0
  56. package/dist/daemon/folderPicker.js +115 -0
  57. package/dist/daemon/folderPicker.js.map +1 -0
  58. package/dist/daemon/index.js +20 -19
  59. package/dist/daemon/index.js.map +1 -1
  60. package/dist/daemon/launchProfiles.d.ts +155 -0
  61. package/dist/daemon/launchProfiles.js +554 -0
  62. package/dist/daemon/launchProfiles.js.map +1 -0
  63. package/dist/daemon/liveness.d.ts +1 -1
  64. package/dist/daemon/liveness.js +2 -2
  65. package/dist/daemon/liveness.js.map +1 -1
  66. package/dist/daemon/paths.d.ts +4 -0
  67. package/dist/daemon/paths.js.map +1 -1
  68. package/dist/daemon/restartHold.d.ts +16 -0
  69. package/dist/daemon/restartHold.js +126 -0
  70. package/dist/daemon/restartHold.js.map +1 -0
  71. package/dist/daemon/screenshot.d.ts +58 -1
  72. package/dist/daemon/screenshot.js +172 -26
  73. package/dist/daemon/screenshot.js.map +1 -1
  74. package/dist/daemon/server.d.ts +220 -10
  75. package/dist/daemon/server.js +1975 -205
  76. package/dist/daemon/server.js.map +1 -1
  77. package/dist/daemon/sessionFeed.d.ts +48 -0
  78. package/dist/daemon/sessionFeed.js +101 -0
  79. package/dist/daemon/sessionFeed.js.map +1 -0
  80. package/dist/daemon/viewerLauncher.d.ts +100 -9
  81. package/dist/daemon/viewerLauncher.js +349 -67
  82. package/dist/daemon/viewerLauncher.js.map +1 -1
  83. package/dist/mcp/config.d.ts +7 -14
  84. package/dist/mcp/config.js +10 -21
  85. package/dist/mcp/config.js.map +1 -1
  86. package/dist/mcp/index.js +20 -11
  87. package/dist/mcp/index.js.map +1 -1
  88. package/dist/mcp/tools.d.ts +14 -7
  89. package/dist/mcp/tools.js +161 -60
  90. package/dist/mcp/tools.js.map +1 -1
  91. package/dist/viewer/dashboard-folders.js +20 -0
  92. package/dist/viewer/dashboard-layout.js +52 -0
  93. package/dist/viewer/dashboard.css +67 -0
  94. package/dist/viewer/dashboard.html +44 -0
  95. package/dist/viewer/dashboard.js +1523 -0
  96. package/dist/viewer/icon.ico +0 -0
  97. package/dist/viewer/index.html +12 -7
  98. package/dist/viewer/pane.js +736 -0
  99. package/dist/viewer/viewer.css +18 -7
  100. package/dist/viewer/viewer.js +47 -624
  101. package/package.json +13 -13
@@ -15,14 +15,16 @@
15
15
  */
16
16
  import { execFile } from 'node:child_process';
17
17
  import * as fs from 'node:fs';
18
+ import * as os from 'node:os';
18
19
  import * as path from 'node:path';
19
20
  import { ensureSpawnHelperExecutable, explainSpawnFailure, loadNodePty } from './nativePty.js';
20
21
  import { ScreenRenderer } from './renderer.js';
21
22
  import { commandLine } from './policy.js';
22
- import { detectPrompt, StalePromptGuard } from './promptDetector.js';
23
+ import { detectPrompt, MusePromptSettler, StalePromptGuard } from './promptDetector.js';
23
24
  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';
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';
26
28
  /**
27
29
  * Hard cap on `taskkill`. Without it a wedged kill never calls back, so
28
30
  * `kill()` never resolves, `killAll()` never resolves and daemon shutdown
@@ -37,6 +39,33 @@ import { DEFAULT_COLS, DEFAULT_ROWS, DEFAULT_SCROLLBACK, MAX_WAIT_TIMEOUT_MS, NU
37
39
  * case.
38
40
  */
39
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;
40
69
  /**
41
70
  * One `taskkill` run for any number of trees. Every run enumerates every
42
71
  * process on the machine before it kills anything, and that is most of its
@@ -45,11 +74,11 @@ export const TREE_KILL_TIMEOUT_MS = 30_000;
45
74
  * overran the 30 s cap; one run given all thirty pids took 10 s. So daemon
46
75
  * shutdown kills every tree in one run (`SessionManager.killAll`).
47
76
  */
48
- export const taskkillTrees = (pids) => new Promise((resolve) => {
77
+ export const taskkillTrees = (pids, timeoutMs = TREE_KILL_TIMEOUT_MS) => new Promise((resolve) => {
49
78
  const startedAt = Date.now();
50
79
  execFile('taskkill', ['/T', '/F', ...pids.flatMap((pid) => ['/PID', String(pid)])],
51
80
  // A line of output per process killed, descendants included.
52
- { windowsHide: true, timeout: TREE_KILL_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 }, (error) => {
81
+ { windowsHide: true, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (error) => {
53
82
  resolve(error
54
83
  ? {
55
84
  // Node also kills a child whose output overruns maxBuffer. Only
@@ -76,6 +105,15 @@ export const taskkillTrees = (pids) => new Promise((resolve) => {
76
105
  */
77
106
  const WRITE_CHUNK_CHARS = 1024;
78
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
+ }
79
117
  /**
80
118
  * Bracketed paste (DEC private mode 2004). A TUI that enables it is telling us
81
119
  * it wants multi-character input delivered as ONE paste event rather than as a
@@ -140,13 +178,70 @@ export function bracketedPasteAfter(scan, current) {
140
178
  }
141
179
  /** One short of the longest mode sequence: enough to rejoin any split of one. */
142
180
  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. */
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
+ */
144
186
  export class CommandNotFoundError extends Error {
145
187
  constructor(message) {
146
188
  super(message);
147
189
  this.name = 'CommandNotFoundError';
148
190
  }
149
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
+ }
150
245
  /**
151
246
  * Resolve a command to a concrete executable path before spawning directly
152
247
  * (`shell: false`). Necessary on **every** platform, for different reasons:
@@ -160,8 +255,27 @@ export class CommandNotFoundError extends Error {
160
255
  * arrive.
161
256
  *
162
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.
163
274
  */
164
- function resolveExecutable(command, platform) {
275
+ export function windowsCandidateNamesStream(candidate) {
276
+ return path.win32.basename(candidate).includes(':');
277
+ }
278
+ function resolveExecutable(command, platform, cwd) {
165
279
  const isWindows = platform === 'win32';
166
280
  const usable = (candidate) => {
167
281
  try {
@@ -189,20 +303,42 @@ function resolveExecutable(command, platform) {
189
303
  : [...extensions.map((e) => base + e), base];
190
304
  };
191
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;
192
313
  const searchBases = explicitPath
193
- ? [command]
314
+ ? [rooted]
194
315
  : (process.env['PATH'] ?? '')
195
316
  .split(path.delimiter)
196
317
  .filter((d) => d !== '')
197
318
  .map((dir) => path.join(dir, command));
319
+ const described = (candidate) => candidate === command ? command : `${command} (${candidate})`;
198
320
  for (const base of searchBases) {
199
321
  for (const candidate of candidatesFor(base)) {
200
- if (usable(candidate))
201
- return candidate;
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;
202
337
  }
203
338
  }
339
+ const shown = rooted === command ? command : `${command} (${rooted})`;
204
340
  throw new CommandNotFoundError(explicitPath
205
- ? `Not an executable file: ${command}.`
341
+ ? `Not an executable file: ${shown}.`
206
342
  : `Command not found on PATH: ${command}. Give an absolute path, or drop ` +
207
343
  `shell:false (--no-shell) and let the shell wrapper resolve it.`);
208
344
  }
@@ -340,12 +476,23 @@ export function credentialShapedNames(source = process.env) {
340
476
  * (`SessionOptions.env`), set on top of whatever the mode gave. On Windows a
341
477
  * passed name replaces the inherited variable of the same name in any case,
342
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.
343
485
  */
344
- export function buildSessionEnv(mode, platform, source = process.env, passed = {}) {
486
+ export function buildSessionEnv(mode, platform, source = process.env, passed = {}, reserved = RESERVED_FEATURE_CREDENTIALS) {
345
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);
346
493
  if (mode === 'passthrough') {
347
494
  for (const [key, value] of Object.entries(source)) {
348
- if (value !== undefined)
495
+ if (value !== undefined && !isReserved(key))
349
496
  env[key] = value;
350
497
  }
351
498
  }
@@ -353,8 +500,9 @@ export function buildSessionEnv(mode, platform, source = process.env, passed = {
353
500
  const baseline = CLEAN_ENV_KEYS[platform === 'win32' ? 'win32' : 'posix'];
354
501
  const wanted = new Set((mode === 'clean' ? baseline : [...baseline, ...mode]).map((k) => k.toUpperCase()));
355
502
  for (const [key, value] of Object.entries(source)) {
356
- if (value !== undefined && wanted.has(key.toUpperCase()))
503
+ if (value !== undefined && wanted.has(key.toUpperCase()) && !isReserved(key)) {
357
504
  env[key] = value;
505
+ }
358
506
  }
359
507
  }
360
508
  const setOnly = (name, value) => {
@@ -392,7 +540,14 @@ export class Session {
392
540
  renderer;
393
541
  logger;
394
542
  platform;
543
+ endConsoleHost;
544
+ registerConsoleHost;
545
+ spawnPty;
395
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;
396
551
  /** Whether the program has bracketed paste (DEC 2004) enabled. See PASTE_START. */
397
552
  bracketedPaste = false;
398
553
  /**
@@ -407,10 +562,15 @@ export class Session {
407
562
  modeScanTail = '';
408
563
  dataListeners = new Set();
409
564
  exitListeners = new Set();
565
+ readyListeners = new Set();
410
566
  /** Whether the program has hidden the cursor (DECTCEM off), carried to viewers. */
411
567
  cursorHidden = false;
412
568
  /** Serialises write() so chunked writes cannot interleave. See write(). */
413
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;
414
574
  lastChange = Date.now();
415
575
  /** Sticky: the rendered screen has shown something at least once. */
416
576
  painted = false;
@@ -425,10 +585,21 @@ export class Session {
425
585
  exitedFlag = false;
426
586
  exitedAtValue = null;
427
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;
428
591
  readyFlag;
429
592
  readyReasonValue = 'not-tracked';
430
593
  geometryHeldFlag;
431
- killed = false;
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;
432
603
  constructor(id, options, deps = {}) {
433
604
  this.id = id;
434
605
  this.command = options.command;
@@ -441,6 +612,23 @@ export class Session {
441
612
  this.logger = deps.logger ?? NULL_LOGGER;
442
613
  this.platform = deps.platform ?? process.platform;
443
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
+ }
444
632
  const cols = options.cols ?? DEFAULT_COLS;
445
633
  const rows = options.rows ?? DEFAULT_ROWS;
446
634
  this.renderer = new ScreenRenderer({ cols, rows, scrollback: DEFAULT_SCROLLBACK });
@@ -452,45 +640,73 @@ export class Session {
452
640
  // invalidated by a reflow.
453
641
  this.geometryHeldFlag = options.hold === true;
454
642
  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
- });
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
+ });
463
652
  // node-pty is loaded on the first start, not with the daemon, so an install
464
653
  // that left it unable to open a terminal fails here with what to do
465
- // (`nativePty.ts`).
466
- const { spawn } = loadNodePty();
654
+ // (`nativePty.ts`). A test spawn stands in and loads nothing.
655
+ const spawn = this.spawnPty === undefined ? loadNodePty().spawn : undefined;
467
656
  // A Windows start that fails part-way must not leave node-pty's
468
657
  // half-built terminal behind (`windowsPtyStart.ts`).
469
- if (process.platform === 'win32')
658
+ if (spawn !== undefined && process.platform === 'win32')
470
659
  releaseFailedStarts();
471
- ensureSpawnHelperExecutable();
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
+ };
472
678
  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
- });
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
+ }
482
688
  }
483
689
  catch (error) {
484
690
  // On Windows node-pty loads its native module here, as the terminal is
485
691
  // built, so a missing binary surfaces now rather than at the load above.
486
692
  throw explainSpawnFailure(error);
487
693
  }
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.
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.
491
705
  if (process.platform === 'win32') {
492
706
  const reported = new Set();
493
707
  listenForTerminalErrors(this.pty, (error, stream) => {
708
+ if (stream === 'input')
709
+ this.inputFailure ??= error;
494
710
  if (reported.has(stream))
495
711
  return;
496
712
  reported.add(stream);
@@ -529,14 +745,26 @@ export class Session {
529
745
  for (const listener of this.dataListeners)
530
746
  listener(data);
531
747
  });
532
- this.pty.onExit(({ exitCode }) => {
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;
533
755
  this.exitedFlag = true;
534
756
  this.exitedAtValue = Date.now();
535
757
  this.exitCodeValue = exitCode;
536
758
  this.lastChange = Date.now();
537
759
  this.logger.info('session exit', { id, exitCode });
760
+ if (!this.programEnded)
761
+ this.endingProgram = this.endProgram();
538
762
  for (const listener of this.exitListeners)
539
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();
540
768
  });
541
769
  // Readiness (§3.1): first paint ≠ ready. With no condition given the
542
770
  // session counts as ready at spawn; otherwise readiness flips when the
@@ -561,6 +789,8 @@ export class Session {
561
789
  reason: result.reason,
562
790
  });
563
791
  }
792
+ for (const listener of this.readyListeners)
793
+ listener();
564
794
  });
565
795
  }
566
796
  else {
@@ -589,8 +819,15 @@ export class Session {
589
819
  const wantShell = options.shell ?? this.platform === 'win32';
590
820
  if (!wantShell) {
591
821
  return {
592
- file: resolveExecutable(options.command, this.platform),
593
- fileArgs: options.args ?? [],
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 ?? [],
594
831
  };
595
832
  }
596
833
  // Quote the command token if it has whitespace and the caller has not
@@ -637,9 +874,36 @@ export class Session {
637
874
  get exitedAt() {
638
875
  return this.exitedAtValue;
639
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
+ */
640
883
  get exitCode() {
641
884
  return this.exitCodeValue;
642
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
+ }
643
907
  get watchers() {
644
908
  return this.dataListeners.size;
645
909
  }
@@ -686,24 +950,46 @@ export class Session {
686
950
  * Resolves with the screen as it was rendered just before this input went
687
951
  * in, taken in the queue, so an earlier write still going in cannot be
688
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.
689
956
  */
690
957
  write(data) {
958
+ const museSubmit = this.agent === 'muse' && museSubmittingText(data);
959
+ if (museSubmit)
960
+ this.museSubmissionsQueued++;
691
961
  const queued = this.writeChain.then(() => this.writeInput(data));
692
962
  // The chain must survive a failed write, or one rejection would wedge every
693
963
  // subsequent write on this session.
694
- this.writeChain = queued.then(() => undefined, () => undefined);
964
+ this.writeChain = queued.then(() => { if (museSubmit)
965
+ this.museSubmissionsQueued--; }, () => { if (museSubmit)
966
+ this.museSubmissionsQueued--; });
695
967
  return queued;
696
968
  }
697
969
  async writeInput(data) {
970
+ this.refuseIfInputFailed();
698
971
  // Recorded BEFORE the bytes go in, when the screen still shows what this
699
972
  // input is answering: the waiter's stale-prompt guard needs that prompt,
700
973
  // and its echo guard needs the input itself.
701
974
  this.lastInputData = data;
702
975
  const { screen } = this.renderer.snapshot();
703
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) {
704
990
  if (data.length <= WRITE_CHUNK_CHARS) {
705
991
  this.pty.write(data);
706
- return screen;
992
+ return;
707
993
  }
708
994
  // Bracketed paste: ONE write, no chunking, exactly as a terminal delivers a
709
995
  // clipboard drop. The submitting newline (if the caller appended one) is
@@ -716,11 +1002,13 @@ export class Session {
716
1002
  const trailer = newlineAt === -1 ? '' : data.slice(newlineAt);
717
1003
  this.lastWriteWrapped = true;
718
1004
  this.pty.write(`${PASTE_START}${body}${PASTE_END}${trailer}`);
719
- return screen;
1005
+ return;
720
1006
  }
721
1007
  this.lastWriteWrapped = false;
722
1008
  let offset = 0;
723
1009
  while (offset < data.length) {
1010
+ // The pipe can fail while a chunk is in flight.
1011
+ this.refuseIfInputFailed();
724
1012
  let end = Math.min(offset + WRITE_CHUNK_CHARS, data.length);
725
1013
  // Never split a surrogate pair: half of an astral character is not a
726
1014
  // character, and the two halves arriving in separate writes decode to
@@ -736,7 +1024,15 @@ export class Session {
736
1024
  await new Promise((resolve) => setTimeout(resolve, WRITE_CHUNK_DELAY_MS));
737
1025
  }
738
1026
  }
739
- return screen;
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.`);
740
1036
  }
741
1037
  /**
742
1038
  * Resize the PTY.
@@ -748,13 +1044,38 @@ export class Session {
748
1044
  * than inferred from who is calling. Omitting `hold` leaves the current
749
1045
  * setting alone, so a viewport following a window cannot quietly release a
750
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`).
751
1055
  */
752
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);
753
1068
  this.pty.resize(cols, rows);
754
1069
  this.renderer.resize(cols, rows);
755
1070
  if (options.hold !== undefined)
756
1071
  this.geometryHeldFlag = options.hold;
757
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
+ }
758
1079
  // ----------------------------------------------------------------- output
759
1080
  /** Live raw-stream subscription (viewer mirroring). Returns unsubscribe. */
760
1081
  onData(listener) {
@@ -765,6 +1086,11 @@ export class Session {
765
1086
  this.exitListeners.add(listener);
766
1087
  return () => this.exitListeners.delete(listener);
767
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
+ }
768
1094
  /**
769
1095
  * The rendered terminal as bytes that rebuild it in a fresh terminal of the
770
1096
  * same size (design §5): what a viewer receives on connect and after every
@@ -782,6 +1108,12 @@ export class Session {
782
1108
  const state = await this.renderer.serialize(options);
783
1109
  return hidden ? state + CURSOR_HIDE : state;
784
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
+ }
785
1117
  async snapshot() {
786
1118
  await this.renderer.flush();
787
1119
  const rendered = this.renderer.snapshot();
@@ -798,7 +1130,7 @@ export class Session {
798
1130
  rows: rendered.rows,
799
1131
  cursor: rendered.cursor,
800
1132
  exited: this.exitedFlag,
801
- exitCode: this.exitCodeValue,
1133
+ exitCode: this.exitCode,
802
1134
  screen: rendered.screen,
803
1135
  };
804
1136
  }
@@ -820,6 +1152,10 @@ export class Session {
820
1152
  await this.renderer.flush();
821
1153
  return this.renderer.styledLines({ above });
822
1154
  }
1155
+ /** Current rendered rows for a waiter evaluation, which already reads synchronously. */
1156
+ styledScreenNow(above = 0) {
1157
+ return this.renderer.styledLines({ above });
1158
+ }
823
1159
  /**
824
1160
  * The last `count` lines, scrollback included, as drawn, with up to
825
1161
  * `context` more lines over them; `firstVisible` is where the `count` begin.
@@ -847,7 +1183,7 @@ export class Session {
847
1183
  readyReason: this.readyReasonValue,
848
1184
  geometryHeld: this.geometryHeldFlag,
849
1185
  exited: this.exitedFlag,
850
- exitCode: this.exitCodeValue,
1186
+ exitCode: this.exitCode,
851
1187
  watchers: this.watchers,
852
1188
  createdAt: this.createdAt.toISOString(),
853
1189
  };
@@ -857,11 +1193,20 @@ export class Session {
857
1193
  * killing only the direct child (`cmd.exe`) strands the real application,
858
1194
  * and orphaned agent CLIs keep running and keep spending paid API tokens.
859
1195
  *
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.)
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.)
865
1210
  *
866
1211
  * POSIX: the PTY child is the session leader of its own process group, so
867
1212
  * signalling the negated pid takes the group down.
@@ -872,54 +1217,39 @@ export class Session {
872
1217
  * could take down something unrelated; on Windows `taskkill` cannot walk a
873
1218
  * tree from a dead root either. So a grandchild that outlived its parent is
874
1219
  * left alone rather than guessed at, a residual risk stated in
875
- * `docs/reference/security-model.md`.
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.
876
1227
  */
877
- async kill() {
878
- if (this.killed)
879
- return;
880
- this.killed = true;
881
- const pid = this.pty.pid;
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();
882
1243
  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
- }
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);
923
1253
  }
924
1254
  try {
925
1255
  this.pty.kill();
@@ -933,17 +1263,171 @@ export class Session {
933
1263
  // descendant walk needs recursive process queries that are far slower than
934
1264
  // the kill itself (measured in minutes), and the root dying is what the
935
1265
  // caller actually contracted for.
936
- if (!this.processAlive(pid)) {
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)) {
937
1275
  this.logger.info('session tree killed', { id: this.id, pid });
938
1276
  }
939
- else {
1277
+ else if (pid > 0 && !exitAlreadyRecorded) {
940
1278
  this.logger.error('session root SURVIVED the kill and may still be running', {
941
1279
  id: this.id,
942
1280
  pid,
943
1281
  });
944
1282
  }
1283
+ this.queueConsoleHost();
945
1284
  this.renderer.dispose();
946
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
+ }
947
1431
  /**
948
1432
  * Cheap liveness probe: signal 0 performs the permission and existence
949
1433
  * checks without delivering a signal, on Windows as well as POSIX.