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,2187 @@
1
+ /**
2
+ * The ShellPuppet daemon: one per user, owns every PTY, serves clients and
3
+ * viewers (design §2). Binds 127.0.0.1 on an OS-assigned port, publishes its
4
+ * discovery record atomically and defends the loopback surface (§4.2):
5
+ * Host-header validation on every request, Origin validation on WebSocket
6
+ * upgrades, bearer-token auth on the API, no CORS headers at all.
7
+ */
8
+ import * as fs from 'node:fs';
9
+ import * as http from 'node:http';
10
+ import { createRequire } from 'node:module';
11
+ import * as path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { WebSocketServer } from 'ws';
14
+ import { SessionManager, PolicyViolationError } from '../core/manager.js';
15
+ import { CommandNotFoundError, DEFAULT_SESSION_ENV, credentialShapedNames } from '../core/session.js';
16
+ import { NativePtyUnavailableError } from '../core/nativePty.js';
17
+ import { commandLine, compilePolicy } from '../core/policy.js';
18
+ import { keyToBytes, knownKeys } from '../core/keys.js';
19
+ import { findOnScreen } from '../core/find.js';
20
+ import { screenShows } from '../core/echo.js';
21
+ import { RegexBudgetError } from '../core/regexBudget.js';
22
+ import { detectPrompt } from '../core/promptDetector.js';
23
+ import { WaitConditionError } from '../core/waiter.js';
24
+ import { agentNames, hideReasoning, latestResult, programName, signatureFor } from '../core/reasoning.js';
25
+ import { ENV_NAME_PATTERN } from '../core/types.js';
26
+ import { TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, viewerCookie, } from './auth.js';
27
+ import { NULL_AUDITOR } from './audit.js';
28
+ import { findBrowser, launchViewer } from './viewerLauncher.js';
29
+ import { DEFAULT_CAPTURE_TIMEOUT_MS, MAX_CAPTURE_TIMEOUT_MS, MIN_CAPTURE_TIMEOUT_MS, captureViewer, } from './screenshot.js';
30
+ import { claimDaemonState, daemonStatePath, ensureHome, inspectDaemonState, readDaemonState, removeDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
31
+ import { daemonRunning } from './liveness.js';
32
+ import { packageVersion } from './meta.js';
33
+ import { terminalReportKind } from './terminalReports.js';
34
+ import { ViewerSync } from './viewerSync.js';
35
+ const DEFAULT_IDLE_MS = 30 * 60_000;
36
+ const IDLE_CHECK_INTERVAL_MS = 60_000;
37
+ /**
38
+ * How often a running daemon checks that daemon.json still names it, and
39
+ * publishes it again when it is missing or names a daemon that has gone.
40
+ */
41
+ const STATE_PUBLISH_CHECK_MS = 10_000;
42
+ /**
43
+ * How long a naturally-exited session stays readable before it is reaped.
44
+ * Long enough for an agent to come back and read the final screen; short
45
+ * enough that a busy day of short-lived sessions does not ratchet memory.
46
+ */
47
+ const EXITED_SESSION_GRACE_MS = 15 * 60_000;
48
+ const MAX_BODY_BYTES = 1_000_000;
49
+ /**
50
+ * Prompt-stall detection: how often live screens are scanned for a
51
+ * permission prompt, and how long the SAME prompt must persist before an
52
+ * alert is emitted. The stall threshold exists so a prompt the human answers
53
+ * within seconds never alerts at all: the alert is for prompts NOBODY is
54
+ * looking at.
55
+ */
56
+ const PROMPT_SCAN_INTERVAL_MS = 5_000;
57
+ const PROMPT_STALL_MS = 20_000;
58
+ /**
59
+ * How long `verify` looks for typed text: a base, plus time for each
60
+ * character, up to a ceiling. Some TUIs work through every keystroke before
61
+ * they draw any of it: OpenCode draws a 300-character line all at once, about
62
+ * 2.2 s after it arrives (about 7 ms a character). The allowance per
63
+ * character leaves room for a slower machine; it is spent only when the text
64
+ * does not show.
65
+ */
66
+ const VERIFY_BASE_MS = 600;
67
+ const VERIFY_MS_PER_CHAR = 15;
68
+ const VERIFY_MAX_MS = 15_000;
69
+ /**
70
+ * Scrollback lines carried in the snapshot a viewer receives (design §5). The
71
+ * viewport is always complete; this bounds the history behind it. A 5,000-line
72
+ * buffer at 160 columns serialises to ~700 KB in ~200 ms of daemon time, and
73
+ * every grid change sends a fresh snapshot to every watcher, so the history
74
+ * a snapshot carries is bounded at 2,000 lines.
75
+ */
76
+ const VIEWER_SNAPSHOT_SCROLLBACK_LINES = 2_000;
77
+ /** Default size of the browser window a screenshot is taken in, in CSS pixels. */
78
+ const CAPTURE_WIDTH = 1_400;
79
+ const CAPTURE_HEIGHT = 900;
80
+ /**
81
+ * Bounds on a grid derived from a browser window (§5).
82
+ *
83
+ * A viewport drives the grid, so the human's monitor would otherwise set what
84
+ * the agent reads: a maximised 4K window at a small font asks for roughly
85
+ * 380x100, and every snapshot the driving agent takes is then about 38,000
86
+ * characters against about 4,000 at the 120x34 default. The bound travels with
87
+ * every geometry frame; past it the page grows its text until this much grid
88
+ * fills the window, then proposes that grid (§5).
89
+ */
90
+ const MAX_VIEWPORT_COLS = 400;
91
+ const MAX_VIEWPORT_ROWS = 150;
92
+ /**
93
+ * RIS plus erase-saved-lines, ahead of every snapshot: the viewer starts from
94
+ * nothing, THROUGH its write queue, so anything it had queued applies before
95
+ * the wipe and nothing stale can paint after it.
96
+ */
97
+ const VIEWER_WIPE = '\x1bc\x1b[3J';
98
+ /**
99
+ * What a watcher is shown when the program is gone: grey, on its own line
100
+ * and identical whether it was sent live at the moment of exit or replayed
101
+ * to someone who joined during the fifteen-minute grace.
102
+ */
103
+ function exitNotice(exitCode) {
104
+ return `\r\n\x1b[90m[process exited: ${String(exitCode)}]\x1b[0m\r\n`;
105
+ }
106
+ /**
107
+ * Static viewer assets, resolved once and served from a fixed allowlist.
108
+ * There is no path concatenation from request input, so no traversal surface.
109
+ * `../viewer/` is `dist/viewer/` in production (copied by the build) and
110
+ * `src/viewer/` under the test runner; the xterm bundles come straight out of
111
+ * node_modules via module resolution.
112
+ */
113
+ const viewerDir = fileURLToPath(new URL('../viewer/', import.meta.url));
114
+ const nodeRequire = createRequire(import.meta.url);
115
+ const xtermJsPath = nodeRequire.resolve('@xterm/xterm');
116
+ const STATIC_ASSETS = {
117
+ '/viewer/viewer.js': { file: path.join(viewerDir, 'viewer.js'), type: 'text/javascript' },
118
+ '/viewer/viewer.css': { file: path.join(viewerDir, 'viewer.css'), type: 'text/css' },
119
+ // The mark. SVG first (crisp at any size, and what the tab uses); the PNGs
120
+ // are for Windows, which wants a raster for the taskbar button of a Chrome
121
+ // --app window. An SVG-only favicon leaves that button showing the generic
122
+ // globe.
123
+ '/viewer/icon.svg': { file: path.join(viewerDir, 'icon.svg'), type: 'image/svg+xml' },
124
+ '/viewer/icon-16.png': { file: path.join(viewerDir, 'icon-16.png'), type: 'image/png', binary: true },
125
+ '/viewer/icon-32.png': { file: path.join(viewerDir, 'icon-32.png'), type: 'image/png', binary: true },
126
+ '/viewer/icon-180.png': { file: path.join(viewerDir, 'icon-180.png'), type: 'image/png', binary: true },
127
+ '/viewer/icon-512.png': { file: path.join(viewerDir, 'icon-512.png'), type: 'image/png', binary: true },
128
+ '/vendor/xterm.js': { file: xtermJsPath, type: 'text/javascript' },
129
+ '/vendor/xterm.css': {
130
+ file: path.join(path.dirname(xtermJsPath), '..', 'css', 'xterm.css'),
131
+ type: 'text/css',
132
+ },
133
+ '/vendor/addon-fit.js': { file: nodeRequire.resolve('@xterm/addon-fit'), type: 'text/javascript' },
134
+ };
135
+ const viewerHtmlPath = path.join(viewerDir, 'index.html');
136
+ /** Thrown by `start()` when a healthy daemon already owns this home. */
137
+ export class AlreadyRunningError extends Error {
138
+ state;
139
+ constructor(state) {
140
+ super(`A healthy daemon is already running (pid ${String(state.pid)}, ` +
141
+ `port ${String(state.port)}).`);
142
+ this.state = state;
143
+ this.name = 'AlreadyRunningError';
144
+ }
145
+ }
146
+ function isRecord(value) {
147
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
148
+ }
149
+ function json(res, code, body) {
150
+ const payload = JSON.stringify(body, null, 2);
151
+ res.writeHead(code, {
152
+ 'content-type': 'application/json; charset=utf-8',
153
+ 'content-length': Buffer.byteLength(payload),
154
+ });
155
+ res.end(payload);
156
+ }
157
+ function readBody(req) {
158
+ return new Promise((resolve, reject) => {
159
+ let size = 0;
160
+ const chunks = [];
161
+ req.on('data', (chunk) => {
162
+ size += chunk.length;
163
+ if (size > MAX_BODY_BYTES) {
164
+ reject(new Error('Request body too large.'));
165
+ req.destroy();
166
+ return;
167
+ }
168
+ chunks.push(chunk);
169
+ });
170
+ req.on('end', () => {
171
+ if (chunks.length === 0) {
172
+ resolve({});
173
+ return;
174
+ }
175
+ try {
176
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
177
+ resolve(isRecord(parsed) ? parsed : {});
178
+ }
179
+ catch {
180
+ reject(new Error('Request body is not valid JSON.'));
181
+ }
182
+ });
183
+ req.on('error', reject);
184
+ });
185
+ }
186
+ function asString(value) {
187
+ return typeof value === 'string' ? value : undefined;
188
+ }
189
+ function asNumber(value) {
190
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
191
+ }
192
+ function asBoolean(value) {
193
+ return typeof value === 'boolean' ? value : undefined;
194
+ }
195
+ function asStringArray(value) {
196
+ if (!Array.isArray(value))
197
+ return undefined;
198
+ return value.every((v) => typeof v === 'string') ? value : undefined;
199
+ }
200
+ /**
201
+ * The bounds a grid is held to wherever it is asked for, so `start` and
202
+ * `resize` cannot disagree about what a legal grid is. An absent side is the
203
+ * session default and is not checked.
204
+ */
205
+ const MIN_GRID_SIDE = 2;
206
+ const MAX_GRID_COLS = 1_000;
207
+ const MAX_GRID_ROWS = 500;
208
+ const GRID_BOUNDS_ERROR = 'cols must be an integer from 2 to 1000 and rows from 2 to 500.';
209
+ function gridOutOfBounds(cols, rows) {
210
+ if (cols !== undefined &&
211
+ (!Number.isInteger(cols) || cols < MIN_GRID_SIDE || cols > MAX_GRID_COLS)) {
212
+ return true;
213
+ }
214
+ return (rows !== undefined &&
215
+ (!Number.isInteger(rows) || rows < MIN_GRID_SIDE || rows > MAX_GRID_ROWS));
216
+ }
217
+ /**
218
+ * What is wrong with the SHAPE of a start request, in words, or null.
219
+ *
220
+ * A field that is present but of the wrong type is refused rather than
221
+ * replaced by a default: a caller with a bug in its own serialisation
222
+ * (`{cols: "80", rows: "24", args: 4}`) is told so, not handed a session at
223
+ * the default grid with no arguments. An absent field takes its default;
224
+ * only present-and-wrong is refused.
225
+ */
226
+ /**
227
+ * Scrollback read over a screen whose reasoning is being hidden: a reasoning
228
+ * block whose first line has scrolled above what is returned is still
229
+ * recognised where it carries on into it (`reasoning.ts`).
230
+ */
231
+ const REASONING_CONTEXT_LINES = 400;
232
+ /** How far back `terminal_result` looks for the latest turn and its answer. */
233
+ const RESULT_LINES = 3000;
234
+ /** Why a signature could not read a screen just now. */
235
+ function overBudgetMessage(signature) {
236
+ return (`The ${signature.name} signature ran past the regular-expression time budget and is set ` +
237
+ 'aside for a minute, so the screen is not returned filtered. Try again shortly.');
238
+ }
239
+ /**
240
+ * A query flag: absent, `0` or `false` is off, `1` or `true` is on, and
241
+ * anything else is null, a mistake the caller is refused for. A flag that
242
+ * guards what leaves the daemon must never read a misspelt "on" as off.
243
+ */
244
+ function queryFlag(url, name) {
245
+ const value = url.searchParams.get(name);
246
+ if (value === null || value === '0' || value === 'false')
247
+ return false;
248
+ if (value === '1' || value === 'true')
249
+ return true;
250
+ return null;
251
+ }
252
+ const BAD_HIDE_REASONING = 'hideReasoning must be true or false (or 1 or 0).';
253
+ /**
254
+ * The cursor among the lines a filtered screen returns: on its own row when
255
+ * that row is kept, on the marker of the block that hid it otherwise.
256
+ */
257
+ function filteredCursor(cursor, filtered) {
258
+ let y = 0;
259
+ for (let k = 0; k < filtered.rows.length; k++) {
260
+ if (filtered.rows[k] <= cursor.y)
261
+ y = k;
262
+ else
263
+ break;
264
+ }
265
+ const kept = filtered.rows[y] === cursor.y && filtered.markers[y] !== true;
266
+ return { x: kept ? cursor.x : 0, y };
267
+ }
268
+ function startShapeError(body) {
269
+ const checks = [
270
+ ['agent', (value) => typeof value === 'string', 'a string'],
271
+ [
272
+ 'args',
273
+ (value) => Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
274
+ 'an array of strings',
275
+ ],
276
+ ['cwd', (value) => typeof value === 'string', 'a string'],
277
+ ['cols', (value) => typeof value === 'number', 'a number'],
278
+ ['rows', (value) => typeof value === 'number', 'a number'],
279
+ ['hold', (value) => typeof value === 'boolean', 'a boolean'],
280
+ ['openViewer', (value) => typeof value === 'boolean', 'a boolean'],
281
+ ['shell', (value) => typeof value === 'boolean', 'a boolean'],
282
+ ['label', (value) => typeof value === 'string', 'a string'],
283
+ ['purpose', (value) => typeof value === 'string', 'a string'],
284
+ ['readyText', (value) => typeof value === 'string', 'a string'],
285
+ [
286
+ 'readyQuiet',
287
+ (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0,
288
+ 'a non-negative number of milliseconds',
289
+ ],
290
+ ];
291
+ for (const [field, accepts, expected] of checks) {
292
+ if (body[field] !== undefined && !accepts(body[field])) {
293
+ return `${field} must be ${expected}.`;
294
+ }
295
+ }
296
+ // The session's own variables, by name and value (§4.6). A refusal names the
297
+ // variable but never quotes its value: the values are secrets more often
298
+ // than not, and errors travel back to callers and into logs.
299
+ const env = body['env'];
300
+ if (env !== undefined) {
301
+ if (typeof env !== 'object' || env === null || Array.isArray(env)) {
302
+ return 'env must be an object mapping variable names to string values.';
303
+ }
304
+ for (const [name, value] of Object.entries(env)) {
305
+ if (!ENV_NAME_PATTERN.test(name)) {
306
+ return `env name ${JSON.stringify(name)} must be letters, digits and underscores, not starting with a digit.`;
307
+ }
308
+ if (typeof value !== 'string' || value.includes('\0')) {
309
+ return `env value for ${name} must be a string with no NUL characters.`;
310
+ }
311
+ }
312
+ }
313
+ return null;
314
+ }
315
+ export class Daemon {
316
+ options;
317
+ logger;
318
+ tokens = new TokenStore();
319
+ manager;
320
+ server;
321
+ wss = new WebSocketServer({ noServer: true });
322
+ sockets = new Set();
323
+ /** Every watcher of a session, with the gate that orders its stream across snapshots. */
324
+ sessionSockets = new Map();
325
+ /**
326
+ * The viewport currently driving each session's grid (§5).
327
+ *
328
+ * Connecting is passive and acting takes control: the first viewport to
329
+ * arrive with nobody driving picks the grid up, a later one adopts what it
330
+ * finds and any deliberate act by that human, such as resizing the window
331
+ * or changing the text size, hands control over. So there is always a way back
332
+ * from a grid somebody else chose, without a control that would mean nothing
333
+ * while a single viewer is the whole product.
334
+ */
335
+ geometryController = new Map();
336
+ /** Subscribers to the daemon-wide event stream (`/events`). */
337
+ eventSockets = new Set();
338
+ /**
339
+ * Per-session prompt tracking for stall alerts: the signature of the prompt
340
+ * currently on screen, when it was first seen and whether it has alerted.
341
+ */
342
+ promptStates = new Map();
343
+ version = packageVersion();
344
+ portValue = null;
345
+ waitsInFlight = 0;
346
+ lastActivity = Date.now();
347
+ idleTimer = null;
348
+ raceCheckTimer = null;
349
+ statePublishTimer = null;
350
+ statePublishRunning = false;
351
+ /** What this daemon published in daemon.json, once it has claimed it. */
352
+ publishedState = null;
353
+ /** The pid of another running daemon already reported as owning daemon.json. */
354
+ foreignOwnerReported = null;
355
+ promptScanTimer = null;
356
+ promptScanRunning = false;
357
+ stopPromise = null;
358
+ audit;
359
+ /**
360
+ * What sessions get from the daemon's environment (ADR-008), resolved once so
361
+ * that what the daemon reports is what its sessions get.
362
+ */
363
+ sessionEnv;
364
+ constructor(options) {
365
+ this.options = options;
366
+ this.logger = options.logger;
367
+ this.audit = options.audit ?? NULL_AUDITOR;
368
+ this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
369
+ this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
370
+ sessionEnv: this.sessionEnv,
371
+ });
372
+ this.server = http.createServer((req, res) => {
373
+ this.handleRequest(req, res).catch((error) => {
374
+ this.logger.error('unhandled request error', { error: String(error) });
375
+ if (!res.headersSent)
376
+ json(res, 500, { error: 'The daemon hit an unexpected error handling this request. Its daemon.log records the error.' });
377
+ });
378
+ });
379
+ this.server.on('upgrade', (req, socket, head) => {
380
+ this.handleUpgrade(req, socket, head);
381
+ });
382
+ }
383
+ get port() {
384
+ if (this.portValue === null)
385
+ throw new Error('Daemon not started.');
386
+ return this.portValue;
387
+ }
388
+ get token() {
389
+ return this.tokens.token;
390
+ }
391
+ get connectedSockets() {
392
+ return this.sockets.size;
393
+ }
394
+ /**
395
+ * How many waits are polling right now. A counter rather than a log line,
396
+ * because `core/` and `client/` may not write to a stream and a test needs
397
+ * to see that a wait whose caller has gone actually stopped.
398
+ */
399
+ get waitsPolling() {
400
+ return this.waitsInFlight;
401
+ }
402
+ get liveSessions() {
403
+ return this.manager.liveCount();
404
+ }
405
+ // ------------------------------------------------------------------ start
406
+ async start() {
407
+ const { home } = this.options;
408
+ const homeResult = await ensureHome(home);
409
+ if (homeResult.warning !== undefined) {
410
+ this.logger.warn('home hardening warning', { warning: homeResult.warning });
411
+ }
412
+ // Defer to an incumbent that is running, even one too busy to answer its
413
+ // health check; clear a record whose daemon has gone (design §2.3).
414
+ const existing = readDaemonState(home);
415
+ if (existing !== null) {
416
+ if (await this.incumbentRunning(existing))
417
+ throw new AlreadyRunningError(existing);
418
+ this.logger.info('clearing stale daemon state', { stalePid: existing.pid });
419
+ removeDaemonStateIf(home, existing);
420
+ }
421
+ await new Promise((resolve, reject) => {
422
+ this.server.once('error', reject);
423
+ this.server.listen(0, '127.0.0.1', () => {
424
+ this.server.removeListener('error', reject);
425
+ resolve();
426
+ });
427
+ });
428
+ const address = this.server.address();
429
+ if (address === null || typeof address === 'string') {
430
+ throw new Error('Failed to determine bound port.');
431
+ }
432
+ this.portValue = address.port;
433
+ // Browser detection is slow the first time it runs (viewerLauncher.ts), and
434
+ // a session start waits for its viewer launch, so look once now and let the
435
+ // memoised answer serve every start.
436
+ if ((this.options.viewer?.launchMode ?? 'none') === 'isolated-app') {
437
+ void findBrowser(this.options.viewer?.browserPath).catch(() => undefined);
438
+ }
439
+ const state = {
440
+ port: this.portValue,
441
+ token: this.tokens.token,
442
+ pid: process.pid,
443
+ version: this.version,
444
+ startedAt: new Date().toISOString(),
445
+ };
446
+ // Atomic claim; on losing the race, defer to the winner (design §2.2:
447
+ // the race is normal, not exceptional). A file that holds no record at all,
448
+ // such as an emptied one, is cleared like a stale record.
449
+ if (!claimDaemonState(home, state)) {
450
+ const winner = inspectDaemonState(home);
451
+ if (winner.kind === 'record' && (await this.incumbentRunning(winner.state))) {
452
+ await this.closeServerOnly();
453
+ throw new AlreadyRunningError(winner.state);
454
+ }
455
+ if (winner.kind === 'record')
456
+ removeDaemonStateIf(home, winner.state);
457
+ if (winner.kind === 'not-a-record') {
458
+ this.logger.warn('clearing a daemon.json that holds no daemon record', {
459
+ length: winner.raw.length,
460
+ });
461
+ removeDaemonStateIfNotARecord(home, winner.raw);
462
+ }
463
+ if (!claimDaemonState(home, state)) {
464
+ await this.closeServerOnly();
465
+ throw new Error(`Could not claim ${daemonStatePath(home)}: it could not be read, or another ` +
466
+ `daemon claimed it first.`);
467
+ }
468
+ }
469
+ // Belt and braces for the unlink/claim TOCTOU sliver: shortly after
470
+ // start-up, if the published record names someone else and nobody is
471
+ // attached to us, bow out quietly. Clients only ever discover the daemon
472
+ // named in the file, so nobody can be depending on us yet.
473
+ this.raceCheckTimer = setTimeout(() => {
474
+ const current = readDaemonState(home);
475
+ if (current !== null &&
476
+ current.pid !== process.pid &&
477
+ this.manager.size() === 0 &&
478
+ this.sockets.size === 0) {
479
+ this.logger.info('lost start-up race after claim, stopping', {
480
+ winnerPid: current.pid,
481
+ });
482
+ void this.stop({ removeState: false }).then(() => {
483
+ this.options.onSelfStop?.('lost-race');
484
+ });
485
+ }
486
+ }, 1_000);
487
+ this.raceCheckTimer.unref();
488
+ // Said once, at start, because passthrough leaks silently otherwise
489
+ // (ADR-008): the names only, never the values.
490
+ const { exposed } = this.environmentReport();
491
+ if (exposed.length > 0) {
492
+ this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
493
+ 'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
494
+ }
495
+ this.publishedState = state;
496
+ this.statePublishTimer = setInterval(() => {
497
+ void this.keepStatePublished();
498
+ }, this.options.statePublishCheckMs ?? STATE_PUBLISH_CHECK_MS);
499
+ this.statePublishTimer.unref();
500
+ const idleMs = this.options.idleMs ?? DEFAULT_IDLE_MS;
501
+ this.idleTimer = setInterval(() => {
502
+ // Reap sessions whose grace has lapsed before judging idleness. A
503
+ // rejected sweep must be caught here, or it becomes an
504
+ // unhandledRejection and the handler in index.ts stops the daemon.
505
+ this.sweepExited().catch((error) => {
506
+ this.logger.warn('exited-session sweep failed', { error: String(error) });
507
+ });
508
+ // Never exit while any session is live: an unattended agent run with no
509
+ // connected clients is a core use case, not idleness (design §2.3).
510
+ if (this.manager.liveCount() === 0 &&
511
+ this.sockets.size === 0 &&
512
+ Date.now() - this.lastActivity > idleMs) {
513
+ this.logger.info('idle shutdown', { idleMs });
514
+ void this.stop().then(() => {
515
+ this.options.onSelfStop?.('idle');
516
+ });
517
+ }
518
+ }, this.options.idleCheckIntervalMs ?? IDLE_CHECK_INTERVAL_MS);
519
+ this.idleTimer.unref();
520
+ // Prompt-stall scanner: overlap-guarded because snapshots are
521
+ // async: a slow render must skip a beat, never queue a backlog.
522
+ this.promptScanTimer = setInterval(() => {
523
+ if (this.promptScanRunning)
524
+ return;
525
+ this.promptScanRunning = true;
526
+ this.scanForPromptStalls()
527
+ .catch((error) => {
528
+ this.logger.warn('prompt scan failed', { error: String(error) });
529
+ })
530
+ .finally(() => {
531
+ this.promptScanRunning = false;
532
+ });
533
+ }, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
534
+ this.promptScanTimer.unref();
535
+ this.logger.info('daemon started', {
536
+ port: this.portValue,
537
+ pid: process.pid,
538
+ version: this.version,
539
+ });
540
+ return { port: this.portValue, token: this.tokens.token };
541
+ }
542
+ /**
543
+ * Whether the daemon a record names is running, so that this one must
544
+ * defer to it: one that answers its health check, or one whose process is
545
+ * alive and whose port accepts a connection although it is too busy to
546
+ * answer. A record naming this very daemon is not an incumbent, and one
547
+ * naming this process that does not answer is a leftover from an earlier
548
+ * process that had the same pid.
549
+ */
550
+ async incumbentRunning(record) {
551
+ if (record.pid === process.pid && record.port === this.portValue)
552
+ return false;
553
+ if (await this.isHealthy(record.port))
554
+ return true;
555
+ if (record.pid === process.pid)
556
+ return false;
557
+ if (await daemonRunning(record)) {
558
+ this.logger.info('deferring to a running daemon that did not answer its health check', {
559
+ pid: record.pid,
560
+ port: record.port,
561
+ });
562
+ return true;
563
+ }
564
+ return false;
565
+ }
566
+ /**
567
+ * Keep daemon.json naming this daemon while it runs. When the file is
568
+ * missing, holds no daemon record or names a daemon that has gone, publish
569
+ * it again, so new clients can still reach this daemon's sessions. When it
570
+ * names another daemon that is running, leave it, but say so once in
571
+ * daemon.log: new clients reach that daemon, and this one's sessions only
572
+ * through clients already connected. A file that cannot be read is left
573
+ * alone, since a failed read says nothing about what it holds.
574
+ */
575
+ async keepStatePublished() {
576
+ const published = this.publishedState;
577
+ if (published === null || this.stopPromise !== null || this.statePublishRunning)
578
+ return;
579
+ this.statePublishRunning = true;
580
+ try {
581
+ const { home } = this.options;
582
+ const file = inspectDaemonState(home);
583
+ if (file.kind === 'unreadable')
584
+ return;
585
+ if (file.kind === 'record') {
586
+ const current = file.state;
587
+ if (current.pid === published.pid && current.port === published.port) {
588
+ this.foreignOwnerReported = null;
589
+ return;
590
+ }
591
+ if (await daemonRunning(current)) {
592
+ if (this.foreignOwnerReported !== current.pid) {
593
+ this.foreignOwnerReported = current.pid;
594
+ this.logger.warn('daemon.json names another running daemon; new clients reach it, not this one', {
595
+ otherPid: current.pid,
596
+ otherPort: current.port,
597
+ sessions: this.manager.size(),
598
+ });
599
+ }
600
+ return;
601
+ }
602
+ removeDaemonStateIf(home, current);
603
+ }
604
+ else if (file.kind === 'not-a-record') {
605
+ removeDaemonStateIfNotARecord(home, file.raw);
606
+ }
607
+ if (this.stopPromise === null && claimDaemonState(home, published)) {
608
+ this.foreignOwnerReported = null;
609
+ this.logger.warn('daemon.json was missing, held no daemon record or named a daemon that has gone; published it again', { pid: published.pid, port: published.port });
610
+ }
611
+ }
612
+ catch (error) {
613
+ this.logger.warn('checking daemon.json failed', { error: String(error) });
614
+ }
615
+ finally {
616
+ this.statePublishRunning = false;
617
+ }
618
+ }
619
+ async isHealthy(port) {
620
+ try {
621
+ const response = await fetch(`http://127.0.0.1:${String(port)}/health`, {
622
+ signal: AbortSignal.timeout(1_500),
623
+ });
624
+ if (!response.ok)
625
+ return false;
626
+ const body = await response.json();
627
+ return typeof body === 'object' && body !== null && body.ok === true;
628
+ }
629
+ catch {
630
+ return false;
631
+ }
632
+ }
633
+ closeServerOnly() {
634
+ return new Promise((resolve) => {
635
+ this.server.close(() => resolve());
636
+ // close() waits for idle connections; nothing is connected this early.
637
+ });
638
+ }
639
+ // ------------------------------------------------------------------- stop
640
+ /**
641
+ * Kill every session's process tree, close everything, remove the state
642
+ * file (unless we lost the race and it now belongs to the winner).
643
+ * The daemon must never exit and strand running agent CLIs (design §2.3).
644
+ */
645
+ stop(opts = {}) {
646
+ // Idle-stop, signal handlers and explicit stops can overlap, so everyone
647
+ // awaits the one real shutdown.
648
+ this.stopPromise ??= this.doStop(opts);
649
+ return this.stopPromise;
650
+ }
651
+ async doStop(opts) {
652
+ if (this.idleTimer !== null)
653
+ clearInterval(this.idleTimer);
654
+ if (this.raceCheckTimer !== null)
655
+ clearTimeout(this.raceCheckTimer);
656
+ if (this.statePublishTimer !== null)
657
+ clearInterval(this.statePublishTimer);
658
+ if (this.promptScanTimer !== null)
659
+ clearInterval(this.promptScanTimer);
660
+ // Stop LISTENING first, before tearing down session trees. Killing process
661
+ // trees is not fast (`taskkill /T` on a loaded machine can take seconds
662
+ // per session), and a daemon that still answers on its port while shutting
663
+ // down looks alive to every client polling /health. `close()` refuses new
664
+ // connections immediately while letting in-flight responses drain on
665
+ // their existing socket, notably the reply to this very shutdown request.
666
+ const listenerClosed = new Promise((resolve) => {
667
+ this.server.close(() => resolve());
668
+ });
669
+ for (const socket of this.sockets) {
670
+ try {
671
+ socket.close();
672
+ }
673
+ catch {
674
+ // Best effort.
675
+ }
676
+ }
677
+ await this.manager.killAll();
678
+ if (opts.removeState !== false) {
679
+ // Remove this daemon's record, or a file that holds none. A file that
680
+ // cannot be read says nothing about what it holds, so it stays.
681
+ const file = inspectDaemonState(this.options.home);
682
+ if (file.kind === 'record' && file.state.pid === process.pid) {
683
+ removeDaemonState(this.options.home);
684
+ }
685
+ else if (file.kind === 'not-a-record') {
686
+ removeDaemonStateIfNotARecord(this.options.home, file.raw);
687
+ }
688
+ }
689
+ // Only now terminate lingering keep-alive connections, so close() cannot hang.
690
+ this.server.closeAllConnections();
691
+ await listenerClosed;
692
+ this.logger.info('daemon stopped');
693
+ }
694
+ /**
695
+ * What sessions inherit (ADR-008): the mode, and under passthrough the names
696
+ * of the credential-shaped variables in the daemon's environment. Never values.
697
+ */
698
+ environmentReport() {
699
+ const mode = this.sessionEnv;
700
+ if (mode === 'passthrough')
701
+ return { mode, exposed: credentialShapedNames(process.env) };
702
+ return { mode: mode === 'clean' ? 'clean' : 'list', exposed: [] };
703
+ }
704
+ // ------------------------------------------------------- request handling
705
+ hostAllowed(host) {
706
+ if (host === undefined || this.portValue === null)
707
+ return false;
708
+ const normalised = host.toLowerCase();
709
+ return (normalised === `127.0.0.1:${String(this.portValue)}` ||
710
+ normalised === `localhost:${String(this.portValue)}`);
711
+ }
712
+ originAllowed(origin) {
713
+ if (origin === undefined)
714
+ return true; // non-browser clients send none
715
+ if (this.portValue === null)
716
+ return false;
717
+ const normalised = origin.toLowerCase();
718
+ return (normalised === `http://127.0.0.1:${String(this.portValue)}` ||
719
+ normalised === `http://localhost:${String(this.portValue)}`);
720
+ }
721
+ async handleRequest(req, res) {
722
+ // DNS-rebinding defence (design §4.2): a browser on any website can make
723
+ // requests reach a loopback port; the Host header gives the rebind away.
724
+ if (!this.hostAllowed(req.headers.host)) {
725
+ json(res, 403, { error: 'Forbidden: unexpected Host header.' });
726
+ return;
727
+ }
728
+ const url = new URL(req.url ?? '/', `http://127.0.0.1:${String(this.portValue ?? 0)}`);
729
+ const segments = url.pathname.split('/').filter((s) => s !== '');
730
+ // Unauthenticated by design (§4.1): clients must be able to poll before
731
+ // the token file settles, and it reveals nothing sensitive.
732
+ if (req.method === 'GET' && url.pathname === '/health') {
733
+ json(res, 200, { ok: true, version: this.version, pid: process.pid });
734
+ return;
735
+ }
736
+ // The viewer page itself is served without auth, and must stay that way:
737
+ // refusing it would tell an unauthenticated caller which session ids
738
+ // exist. The page holds no secrets either.
739
+ //
740
+ // What DOES happen here is the one-use exchange (§4.1): a `vt` in the
741
+ // query is redeemed, once, for a stream credential delivered as an
742
+ // HttpOnly cookie. After this the URL is inert, the page's own scripts
743
+ // never see a credential and the browser attaches the cookie to the
744
+ // WebSocket upgrade by itself. An absent, stale or already-redeemed grant
745
+ // is NOT an error here: the page loads and then reports that it could not
746
+ // connect, which keeps this route's silence about session ids intact.
747
+ if (req.method === 'GET' && segments[0] === 'view') {
748
+ const headers = {
749
+ 'content-type': 'text/html; charset=utf-8',
750
+ 'cache-control': 'no-store',
751
+ // `style-src 'unsafe-inline'` is required: xterm.js sizes
752
+ // rows, the cursor and its character-measurement element with inline
753
+ // styles, and a real browser reported ten CSP violations per load
754
+ // without it. Scripts stay strict under `default-src 'self'`: inline
755
+ // styles cannot execute code, and terminal output never reaches the
756
+ // DOM as markup (xterm renders it as text).
757
+ 'content-security-policy': "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:",
758
+ };
759
+ const redeemed = this.tokens.redeemViewerGrant(url.searchParams.get('vt'));
760
+ if (redeemed !== null) {
761
+ headers['set-cookie'] = viewerCookie(redeemed.sessionId, redeemed.streamToken);
762
+ this.audit.record('viewer', 'grant-redeem', redeemed.sessionId, {
763
+ readOnly: redeemed.readOnly,
764
+ });
765
+ // The grant says which session this is for; `s=` is only how the page
766
+ // learns it. A link whose `s=` had been edited would otherwise spend
767
+ // its grant on a page that then asks for the wrong stream.
768
+ if (url.searchParams.get('s') !== redeemed.sessionId) {
769
+ headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}`;
770
+ res.writeHead(302, headers);
771
+ res.end();
772
+ return;
773
+ }
774
+ }
775
+ res.writeHead(200, headers);
776
+ res.end(fs.readFileSync(viewerHtmlPath));
777
+ return;
778
+ }
779
+ // Browsers request this unprompted, before any <link rel="icon"> is parsed,
780
+ // and a Chrome --app window asks for it when it builds the taskbar
781
+ // button. Serving the real mark here is what stops that button falling
782
+ // back to the generic globe.
783
+ if (req.method === 'GET' && url.pathname === '/favicon.ico') {
784
+ res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'no-store' });
785
+ res.end(fs.readFileSync(path.join(viewerDir, 'icon-32.png')));
786
+ return;
787
+ }
788
+ if (req.method === 'GET') {
789
+ const asset = STATIC_ASSETS[url.pathname];
790
+ if (asset !== undefined) {
791
+ res.writeHead(200, {
792
+ // charset belongs on text only: `image/png; charset=utf-8` is
793
+ // meaningless, and stating an encoding for binary invites a proxy or
794
+ // a browser to treat the bytes as text.
795
+ 'content-type': asset.binary === true ? asset.type : `${asset.type}; charset=utf-8`,
796
+ 'cache-control': 'no-store',
797
+ });
798
+ res.end(fs.readFileSync(asset.file));
799
+ return;
800
+ }
801
+ }
802
+ const auth = this.tokens.verify(bearerToken(req.headers.authorization));
803
+ if (auth === null || auth.kind !== 'client') {
804
+ // Viewer grants and credentials reach only the viewer page and its
805
+ // socket: the HTTP API is client-token territory (design §4.1: no
806
+ // start, no kill, no list for viewers).
807
+ json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
808
+ return;
809
+ }
810
+ this.lastActivity = Date.now();
811
+ // Audit actor (design §4.5): adapters self-identify via a header, the MCP
812
+ // adapter as `mcp:<clientInfo.name>` and the CLI as `cli`. Untrusted input,
813
+ // so sanitise; it labels log lines and nothing else.
814
+ const actorHeader = req.headers['x-shellpuppet-actor'];
815
+ const actor = (typeof actorHeader === 'string'
816
+ ? // eslint-disable-next-line no-control-regex
817
+ actorHeader.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 64)
818
+ : '') || 'client';
819
+ try {
820
+ if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
821
+ const body = await readBody(req);
822
+ const force = asBoolean(body['force']) ?? false;
823
+ const live = this.manager.liveCount();
824
+ if (live > 0 && !force) {
825
+ json(res, 409, {
826
+ error: `Refusing to stop: ${String(live)} live session(s). ` +
827
+ `Pass force to kill them.`,
828
+ });
829
+ return;
830
+ }
831
+ this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
832
+ json(res, 200, { ok: true, stopping: true });
833
+ void this.stop().then(() => {
834
+ this.options.onSelfStop?.('shutdown-request');
835
+ });
836
+ return;
837
+ }
838
+ // Behind the token, unlike /health: names of credential-shaped
839
+ // variables are not for anyone who can reach the port.
840
+ if (req.method === 'GET' && segments.length === 1 && segments[0] === 'environment') {
841
+ json(res, 200, this.environmentReport());
842
+ return;
843
+ }
844
+ if (segments[0] !== 'sessions') {
845
+ json(res, 404, { error: 'Not found.', path: url.pathname });
846
+ return;
847
+ }
848
+ if (req.method === 'GET' && segments.length === 1) {
849
+ json(res, 200, { sessions: this.listWithPrompts(), version: this.version });
850
+ return;
851
+ }
852
+ if (req.method === 'POST' && segments.length === 1) {
853
+ await this.handleStart(req, res, actor);
854
+ return;
855
+ }
856
+ const id = segments[1] ?? '';
857
+ const session = this.manager.get(id);
858
+ if (session === undefined) {
859
+ json(res, 404, { error: `No such session: ${id}` });
860
+ return;
861
+ }
862
+ if (req.method === 'DELETE' && segments.length === 2) {
863
+ this.audit.record(actor, 'kill', id);
864
+ await this.manager.kill(id);
865
+ this.dropSessionArtifacts(id);
866
+ json(res, 200, { ok: true, killed: id });
867
+ return;
868
+ }
869
+ const action = segments[2];
870
+ // A fresh viewer link (§4.1). Grants are one-use and short-lived, so
871
+ // there has to be a way to get another without restarting the session:
872
+ // the human closed the window, the link expired unopened or a second
873
+ // device wants its own. Client token only: a viewer cannot mint itself
874
+ // a new credential, let alone a wider one.
875
+ if (req.method === 'POST' && action === 'viewer') {
876
+ const body = await readBody(req);
877
+ const readOnly = body['readOnly'] === true;
878
+ const grant = this.tokens.mintViewerGrant(id, { readOnly });
879
+ this.audit.record(actor, 'grant-mint', id, { readOnly });
880
+ json(res, 200, {
881
+ viewerUrl: this.viewerUrlFor(id, grant),
882
+ readOnly,
883
+ expiresInMs: VIEWER_GRANT_TTL_MS,
884
+ });
885
+ return;
886
+ }
887
+ // A picture of the viewer, as a browser draws it (§5). The daemon's
888
+ // text snapshot is what the agent reads; this is what the human sees,
889
+ // and the two can disagree in ways no text-level check can catch.
890
+ // Also the faithful way to illustrate documentation.
891
+ if (req.method === 'POST' && action === 'screenshot') {
892
+ const body = await readBody(req);
893
+ // Absent means the default; present and not a number is a mistake to
894
+ // report, not to paper over with the default.
895
+ const width = body['width'] === undefined ? CAPTURE_WIDTH : asNumber(body['width']);
896
+ const height = body['height'] === undefined ? CAPTURE_HEIGHT : asNumber(body['height']);
897
+ if (width === undefined ||
898
+ height === undefined ||
899
+ !Number.isInteger(width) ||
900
+ !Number.isInteger(height) ||
901
+ width < 200 ||
902
+ width > 4_000 ||
903
+ height < 200 ||
904
+ height > 4_000) {
905
+ json(res, 400, { error: 'width and height must be integers between 200 and 4000.' });
906
+ return;
907
+ }
908
+ // A caller who knows its machine is slow, or wants to fail faster,
909
+ // can say how long a capture may take, within these bounds.
910
+ const timeoutMs = body['timeoutMs'] === undefined
911
+ ? DEFAULT_CAPTURE_TIMEOUT_MS
912
+ : asNumber(body['timeoutMs']);
913
+ if (timeoutMs === undefined ||
914
+ !Number.isInteger(timeoutMs) ||
915
+ timeoutMs < MIN_CAPTURE_TIMEOUT_MS ||
916
+ timeoutMs > MAX_CAPTURE_TIMEOUT_MS) {
917
+ json(res, 400, {
918
+ error: `timeoutMs must be an integer between ${String(MIN_CAPTURE_TIMEOUT_MS)} and ` +
919
+ `${String(MAX_CAPTURE_TIMEOUT_MS)}.`,
920
+ });
921
+ return;
922
+ }
923
+ const browser = await findBrowser(this.options.viewer?.browserPath);
924
+ if (browser === null) {
925
+ // No silent fallback to re-rendering the cells ourselves: that would
926
+ // return a picture of what the daemon thinks, labelled as what the
927
+ // browser drew, which is exactly the disagreement this exists to find.
928
+ json(res, 503, {
929
+ error: 'No Chromium-family browser found, so the viewer cannot be photographed. ' +
930
+ 'Install one, or set viewer.browserPath in config.json.',
931
+ });
932
+ return;
933
+ }
934
+ // Read-only, because a photograph must not be able to type into the
935
+ // thing it is photographing.
936
+ const grant = this.tokens.mintViewerGrant(id, { readOnly: true });
937
+ try {
938
+ const capture = await (this.options.capture ?? captureViewer)({
939
+ browser,
940
+ viewerUrl: this.viewerUrlFor(id, grant),
941
+ width,
942
+ height,
943
+ timeoutMs,
944
+ logger: this.logger,
945
+ });
946
+ this.audit.record(actor, 'screenshot', id, { width, height });
947
+ json(res, 200, {
948
+ png: capture.png.toString('base64'),
949
+ // The picture's own dimensions, read from it rather than the request.
950
+ width: capture.width,
951
+ height: capture.height,
952
+ cols: session.cols,
953
+ rows: session.rows,
954
+ lines: capture.rows,
955
+ });
956
+ }
957
+ catch (error) {
958
+ this.logger.warn('screenshot failed', { id, error: String(error) });
959
+ json(res, 500, {
960
+ error: `Could not photograph the viewer: ${String(error)}`,
961
+ });
962
+ }
963
+ finally {
964
+ // The photographer is gone, so its credential goes with it. A human's
965
+ // viewer keeps theirs until the session ends, because a dropped socket
966
+ // has to reconnect without a fresh link; a headless browser that has
967
+ // already closed has nothing to reconnect. In a `finally` because a
968
+ // capture that failed leaves the same credential behind as one that
969
+ // worked.
970
+ this.tokens.revokeViewerGrant(grant);
971
+ }
972
+ return;
973
+ }
974
+ if (req.method === 'GET' && action === 'snapshot') {
975
+ const lastLinesParam = url.searchParams.get('lastLines');
976
+ let count;
977
+ if (lastLinesParam !== null) {
978
+ count = Number(lastLinesParam);
979
+ if (!Number.isInteger(count) || count < 1 || count > 10_000) {
980
+ json(res, 400, { error: 'lastLines must be an integer between 1 and 10000.' });
981
+ return;
982
+ }
983
+ }
984
+ const hide = queryFlag(url, 'hideReasoning');
985
+ if (hide === null) {
986
+ json(res, 400, { error: BAD_HIDE_REASONING });
987
+ return;
988
+ }
989
+ if (!hide) {
990
+ const snapshot = await session.snapshot();
991
+ json(res, 200, count === undefined ? snapshot : { ...snapshot, lastLines: await session.lastLines(count) });
992
+ return;
993
+ }
994
+ // Fails closed: without a signature to read the screen by, nothing
995
+ // is returned, never the screen unfiltered.
996
+ const signature = this.readerFor(session, res);
997
+ if (signature === null)
998
+ return;
999
+ const snapshot = await session.snapshot();
1000
+ const view = await session.styledScreen(REASONING_CONTEXT_LINES);
1001
+ const screen = hideReasoning(view.lines, signature, view.firstVisible);
1002
+ let tail;
1003
+ if (count !== undefined) {
1004
+ const lines = await session.styledTail(count, REASONING_CONTEXT_LINES);
1005
+ tail = hideReasoning(lines.lines, signature, lines.firstVisible);
1006
+ }
1007
+ if (screen === null || tail === null) {
1008
+ json(res, 400, { error: overBudgetMessage(signature) });
1009
+ return;
1010
+ }
1011
+ json(res, 200, {
1012
+ ...snapshot,
1013
+ screen: screen.lines.join('\n'),
1014
+ cursor: filteredCursor(snapshot.cursor, screen),
1015
+ ...(tail !== undefined ? { lastLines: tail.lines } : {}),
1016
+ reasoning: {
1017
+ agent: signature.name,
1018
+ hiddenLines: screen.hiddenLines,
1019
+ hiddenBlocks: screen.hiddenBlocks,
1020
+ ...(tail !== undefined ? { lastLinesHiddenLines: tail.hiddenLines } : {}),
1021
+ },
1022
+ });
1023
+ return;
1024
+ }
1025
+ if (req.method === 'GET' && action === 'result') {
1026
+ const signature = this.readerFor(session, res);
1027
+ if (signature === null)
1028
+ return;
1029
+ const { lines } = await session.styledTail(RESULT_LINES);
1030
+ json(res, 200, {
1031
+ id: session.id,
1032
+ agent: signature.name,
1033
+ exited: session.exited,
1034
+ exitCode: session.exitCode,
1035
+ ...latestResult(lines, signature),
1036
+ });
1037
+ return;
1038
+ }
1039
+ // resize is guarded alongside input/key: node-pty throws on resizing a
1040
+ // dead PTY, which would surface as a bare 500 instead of this 409.
1041
+ if ((action === 'input' || action === 'key' || action === 'resize') &&
1042
+ session.exited) {
1043
+ json(res, 409, {
1044
+ error: `Session ${id} has exited (code ${String(session.exitCode)}) and no longer accepts input or geometry changes.`,
1045
+ });
1046
+ return;
1047
+ }
1048
+ if (req.method === 'POST' && action === 'input') {
1049
+ const body = await readBody(req);
1050
+ const data = asString(body['data']);
1051
+ if (data === undefined) {
1052
+ json(res, 400, { error: 'data (string) is required.' });
1053
+ return;
1054
+ }
1055
+ // Awaited: long input is chunked (Session.write), so verify below must
1056
+ // not read the screen until every chunk has actually been written.
1057
+ // The write resolves with the screen as it was just before this input
1058
+ // went in, which verify compares with, so what was already on screen
1059
+ // cannot make up the typed text's wrapped pieces.
1060
+ //
1061
+ // The exit guard above is not enough on its own: a chunked write spans
1062
+ // real time, so the session can die between the guard and the last
1063
+ // chunk. That is the same "you are writing to a dead session" condition
1064
+ // the guard reports, so it gets the same 409. A 500 would blame the
1065
+ // caller's request for a race in the session's lifetime.
1066
+ let before;
1067
+ try {
1068
+ before = await session.write(data);
1069
+ }
1070
+ catch (error) {
1071
+ json(res, 409, {
1072
+ error: `Session ${id} exited while the input was being written: ${String(error)}`,
1073
+ });
1074
+ return;
1075
+ }
1076
+ // §4.5: content NEVER logged by default, only the length. Keystrokes
1077
+ // are where the secrets are.
1078
+ this.audit.record(actor, 'input', id, {
1079
+ chars: data.length,
1080
+ ...(this.audit.captureContent ? { data } : {}),
1081
+ });
1082
+ this.broadcastControl(id, { type: 'input-source', source: 'agent' });
1083
+ // §3.1: TUIs silently swallow input while loading or when a panel has
1084
+ // stolen focus. verify re-reads the screen and reports whether the
1085
+ // text landed (best effort: hidden-input prompts and heavy
1086
+ // transforms legitimately fail it; `escape` is the focus reset).
1087
+ if (asBoolean(body['verify']) === true) {
1088
+ json(res, 200, {
1089
+ ok: true,
1090
+ bytes: data.length,
1091
+ verified: await this.verifyTyped(session, data, before),
1092
+ });
1093
+ return;
1094
+ }
1095
+ json(res, 200, { ok: true, bytes: data.length });
1096
+ return;
1097
+ }
1098
+ if (req.method === 'POST' && action === 'key') {
1099
+ const body = await readBody(req);
1100
+ const key = asString(body['key']);
1101
+ const bytes = key === undefined ? null : keyToBytes(key);
1102
+ if (key === undefined || bytes === null) {
1103
+ json(res, 400, {
1104
+ error: `Unknown key: ${key ?? '(missing)'}. Known keys: ${knownKeys().join(', ')}`,
1105
+ });
1106
+ return;
1107
+ }
1108
+ // Same exit race as the input endpoint above: 409, not 500.
1109
+ try {
1110
+ await session.write(bytes);
1111
+ }
1112
+ catch (error) {
1113
+ json(res, 409, {
1114
+ error: `Session ${id} exited while the key was being written: ${String(error)}`,
1115
+ });
1116
+ return;
1117
+ }
1118
+ this.audit.record(actor, 'key', id, { key });
1119
+ this.broadcastControl(id, { type: 'input-source', source: 'agent' });
1120
+ json(res, 200, { ok: true, key });
1121
+ return;
1122
+ }
1123
+ if (req.method === 'GET' && action === 'wait') {
1124
+ // Checked before waiting, so a wait that could only end refused is
1125
+ // refused at once.
1126
+ const hide = queryFlag(url, 'hideReasoning');
1127
+ if (hide === null) {
1128
+ json(res, 400, { error: BAD_HIDE_REASONING });
1129
+ return;
1130
+ }
1131
+ const reader = hide ? this.readerFor(session, res) : null;
1132
+ if (hide && reader === null)
1133
+ return;
1134
+ const condition = {};
1135
+ const text = url.searchParams.get('text');
1136
+ const regex = url.searchParams.get('regex');
1137
+ const quiet = url.searchParams.get('quiet');
1138
+ const prompt = url.searchParams.get('prompt');
1139
+ if (text !== null)
1140
+ condition.text = text;
1141
+ if (regex !== null)
1142
+ condition.regex = regex;
1143
+ if (quiet !== null)
1144
+ condition.quiet = Number(quiet);
1145
+ // Presence alone is not enough: `?prompt=false` must not silently
1146
+ // become a prompt wait, and the waiter's exactly-one check counts
1147
+ // `prompt === true` only.
1148
+ if (prompt !== null)
1149
+ condition.prompt = prompt !== 'false' && prompt !== '0';
1150
+ const timeoutParam = url.searchParams.get('timeout');
1151
+ const debounceParam = url.searchParams.get('debounce');
1152
+ const afterInputParam = url.searchParams.get('matchAfterInput');
1153
+ // A wait ends with its caller. A response that closes before it has
1154
+ // been written means the client gave up or its process died, so the
1155
+ // wait is aborted rather than left to poll to its full timeout for an
1156
+ // answer nobody would read. A response that completed normally has
1157
+ // already cleared this.
1158
+ const abort = new AbortController();
1159
+ const onClose = () => {
1160
+ if (!res.writableEnded)
1161
+ abort.abort();
1162
+ };
1163
+ res.on('close', onClose);
1164
+ this.waitsInFlight += 1;
1165
+ let result;
1166
+ try {
1167
+ result = await session.waitFor(condition, {
1168
+ ...(timeoutParam !== null ? { timeout: Number(timeoutParam) } : {}),
1169
+ ...(debounceParam !== null ? { debounce: Number(debounceParam) } : {}),
1170
+ // Same parse as `prompt` above: `false`/`0` mean false, anything
1171
+ // else present means true.
1172
+ ...(afterInputParam !== null
1173
+ ? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
1174
+ : {}),
1175
+ signal: abort.signal,
1176
+ });
1177
+ }
1178
+ finally {
1179
+ this.waitsInFlight -= 1;
1180
+ res.off('close', onClose);
1181
+ }
1182
+ // Nobody to answer, and writing to a closed response throws.
1183
+ if (abort.signal.aborted)
1184
+ return;
1185
+ if (reader !== null) {
1186
+ // The screen as it stands now, a moment after the wait resolved,
1187
+ // with the reasoning left out.
1188
+ const view = await session.styledScreen(REASONING_CONTEXT_LINES);
1189
+ const filtered = hideReasoning(view.lines, reader, view.firstVisible);
1190
+ if (filtered === null) {
1191
+ json(res, 400, { error: overBudgetMessage(reader) });
1192
+ return;
1193
+ }
1194
+ json(res, 200, {
1195
+ ...result,
1196
+ screen: filtered.lines.join('\n'),
1197
+ reasoning: { agent: reader.name, hiddenLines: filtered.hiddenLines, hiddenBlocks: filtered.hiddenBlocks },
1198
+ id: session.id,
1199
+ exited: session.exited,
1200
+ exitCode: session.exitCode,
1201
+ });
1202
+ return;
1203
+ }
1204
+ json(res, 200, {
1205
+ ...result,
1206
+ id: session.id,
1207
+ exited: session.exited,
1208
+ exitCode: session.exitCode,
1209
+ });
1210
+ return;
1211
+ }
1212
+ if (req.method === 'GET' && action === 'find') {
1213
+ const pattern = url.searchParams.get('pattern');
1214
+ if (pattern === null || pattern === '') {
1215
+ json(res, 400, { error: 'pattern is required.' });
1216
+ return;
1217
+ }
1218
+ try {
1219
+ const hide = queryFlag(url, 'hideReasoning');
1220
+ if (hide === null) {
1221
+ json(res, 400, { error: BAD_HIDE_REASONING });
1222
+ return;
1223
+ }
1224
+ if (!hide) {
1225
+ const result = findOnScreen(await session.viewportLines(), pattern);
1226
+ json(res, 200, { id: session.id, pattern, ...result });
1227
+ return;
1228
+ }
1229
+ const signature = this.readerFor(session, res);
1230
+ if (signature === null)
1231
+ return;
1232
+ const view = await session.styledScreen(REASONING_CONTEXT_LINES);
1233
+ const filtered = hideReasoning(view.lines, signature, view.firstVisible);
1234
+ if (filtered === null) {
1235
+ json(res, 400, { error: overBudgetMessage(signature) });
1236
+ return;
1237
+ }
1238
+ // Only the kept rows are searched, each reported by the screen's
1239
+ // own row number, so a hidden row can neither match nor count
1240
+ // towards the cap on matches.
1241
+ const keptRows = [];
1242
+ const keptText = [];
1243
+ filtered.lines.forEach((text, k) => {
1244
+ if (filtered.markers[k])
1245
+ return;
1246
+ keptRows.push(filtered.rows[k]);
1247
+ keptText.push(text);
1248
+ });
1249
+ const result = findOnScreen(keptText, pattern);
1250
+ json(res, 200, {
1251
+ id: session.id,
1252
+ pattern,
1253
+ matches: result.matches.map((match) => ({ ...match, line: keptRows[match.line - 1] + 1 })),
1254
+ truncated: result.truncated,
1255
+ reasoning: { agent: signature.name, hiddenLines: filtered.hiddenLines },
1256
+ });
1257
+ }
1258
+ catch (error) {
1259
+ // A pattern that will not finish is a different mistake from one
1260
+ // that will not compile, and the caller can only fix the one it is
1261
+ // told about.
1262
+ json(res, 400, {
1263
+ error: error instanceof RegexBudgetError
1264
+ ? error.message
1265
+ : `Invalid pattern: ${pattern}`,
1266
+ });
1267
+ }
1268
+ return;
1269
+ }
1270
+ if (req.method === 'POST' && action === 'resize') {
1271
+ const body = await readBody(req);
1272
+ const cols = asNumber(body['cols']);
1273
+ const rows = asNumber(body['rows']);
1274
+ if (cols === undefined || rows === undefined || gridOutOfBounds(cols, rows)) {
1275
+ json(res, 400, { error: GRID_BOUNDS_ERROR });
1276
+ return;
1277
+ }
1278
+ const hold = body['hold'] === true;
1279
+ session.resize(cols, rows, { hold });
1280
+ this.audit.record(actor, 'resize', id, { cols, rows, hold });
1281
+ // An API resize takes the grid away from whichever viewport had it, so
1282
+ // nobody is left believing they still drive it. It does NOT hold
1283
+ // unless asked: a human whose window is now the wrong shape gets it
1284
+ // back by moving that window, which is the only escape they have while
1285
+ // there is no takeover control to press (§5).
1286
+ this.geometryController.delete(id);
1287
+ this.announceGeometry(id, session);
1288
+ json(res, 200, { ok: true, cols, rows, geometryHeld: session.geometryHeld });
1289
+ return;
1290
+ }
1291
+ json(res, 404, { error: 'Not found.', path: url.pathname });
1292
+ }
1293
+ catch (error) {
1294
+ if (error instanceof WaitConditionError) {
1295
+ json(res, 400, { error: error.message });
1296
+ return;
1297
+ }
1298
+ if (error instanceof Error && error.message.startsWith('Request body')) {
1299
+ json(res, 400, { error: error.message });
1300
+ return;
1301
+ }
1302
+ throw error;
1303
+ }
1304
+ }
1305
+ async handleStart(req, res, actor) {
1306
+ const body = await readBody(req);
1307
+ const command = asString(body['command']);
1308
+ if (command === undefined || command === '') {
1309
+ json(res, 400, { error: 'command (string) is required.' });
1310
+ return;
1311
+ }
1312
+ const shapeError = startShapeError(body);
1313
+ if (shapeError !== null) {
1314
+ json(res, 400, { error: shapeError });
1315
+ return;
1316
+ }
1317
+ if (gridOutOfBounds(asNumber(body['cols']), asNumber(body['rows']))) {
1318
+ json(res, 400, { error: GRID_BOUNDS_ERROR });
1319
+ return;
1320
+ }
1321
+ const agent = asString(body['agent']);
1322
+ if (agent !== undefined && !agentNames().includes(agent)) {
1323
+ json(res, 400, {
1324
+ error: `agent must be one of: ${agentNames().join(', ')}. Config agents.signatures can ` +
1325
+ 'describe another.',
1326
+ });
1327
+ return;
1328
+ }
1329
+ // A working directory that is not one is a caller mistake, reported as
1330
+ // one here rather than left to fail deep inside ConPTY as "Cannot create
1331
+ // process, error code: 267", which gives the caller nothing to act on.
1332
+ const cwd = asString(body['cwd']);
1333
+ if (cwd !== undefined) {
1334
+ let isDirectory;
1335
+ try {
1336
+ isDirectory = fs.statSync(cwd).isDirectory();
1337
+ }
1338
+ catch {
1339
+ json(res, 400, { error: `cwd does not exist: ${cwd}` });
1340
+ return;
1341
+ }
1342
+ if (!isDirectory) {
1343
+ json(res, 400, { error: `cwd is not a directory: ${cwd}` });
1344
+ return;
1345
+ }
1346
+ }
1347
+ const options = {
1348
+ command,
1349
+ ...(asStringArray(body['args']) !== undefined ? { args: asStringArray(body['args']) } : {}),
1350
+ ...(asString(body['cwd']) !== undefined ? { cwd: asString(body['cwd']) } : {}),
1351
+ ...(asNumber(body['cols']) !== undefined ? { cols: asNumber(body['cols']) } : {}),
1352
+ ...(asNumber(body['rows']) !== undefined ? { rows: asNumber(body['rows']) } : {}),
1353
+ ...(body['hold'] === true ? { hold: true } : {}),
1354
+ ...(asString(body['label']) !== undefined ? { label: asString(body['label']) } : {}),
1355
+ ...(asString(body['purpose']) !== undefined ? { purpose: asString(body['purpose']) } : {}),
1356
+ ...(agent !== undefined ? { agent } : {}),
1357
+ // From the request's audit identity rather than the body, so it cannot
1358
+ // diverge from the audit trail. Self-declared, not authenticated: see
1359
+ // SessionOptions.startedBy.
1360
+ startedBy: actor,
1361
+ ...(asString(body['readyText']) !== undefined
1362
+ ? { readyText: asString(body['readyText']) }
1363
+ : {}),
1364
+ ...(asNumber(body['readyQuiet']) !== undefined
1365
+ ? { readyQuiet: asNumber(body['readyQuiet']) }
1366
+ : {}),
1367
+ ...(asBoolean(body['shell']) !== undefined ? { shell: asBoolean(body['shell']) } : {}),
1368
+ // Shape-checked above: names to string values.
1369
+ ...(body['env'] !== undefined ? { env: body['env'] } : {}),
1370
+ };
1371
+ const envNames = Object.keys(options.env ?? {});
1372
+ let session;
1373
+ try {
1374
+ session = this.manager.create(options);
1375
+ }
1376
+ catch (error) {
1377
+ if (error instanceof PolicyViolationError) {
1378
+ json(res, 403, { error: error.message });
1379
+ return;
1380
+ }
1381
+ if (error instanceof CommandNotFoundError) {
1382
+ json(res, 400, { error: error.message });
1383
+ return;
1384
+ }
1385
+ // The install cannot open a terminal at all. The message says what to
1386
+ // do, so it goes out as written.
1387
+ if (error instanceof NativePtyUnavailableError) {
1388
+ json(res, 500, { error: error.message });
1389
+ return;
1390
+ }
1391
+ json(res, 500, { error: `Failed to start session: ${String(error)}` });
1392
+ return;
1393
+ }
1394
+ // Commands are policy-visible by definition, so the command line IS
1395
+ // audited (§4.5), unlike typed content. Passed variables are audited by
1396
+ // name only, whatever `audit.captureContent` says: a value is a secret
1397
+ // the caller handed over, not something anyone typed.
1398
+ this.audit.record(actor, 'start', session.id, {
1399
+ command: options.command,
1400
+ args: options.args ?? [],
1401
+ ...(envNames.length > 0 ? { envNames } : {}),
1402
+ ...(agent !== undefined ? { agent } : {}),
1403
+ label: session.label,
1404
+ });
1405
+ // The human's way in (design §3.1): a viewer window the daemon opens for
1406
+ // them or, when nothing opened, a viewer URL the caller hands them. Either
1407
+ // carries a one-use viewer grant, never the client token (§4.1).
1408
+ // The session id goes in the QUERY, not the path, and that is load-bearing
1409
+ // on Windows. Chrome derives an `--app` window's AppUserModelID from
1410
+ // host + PATH only, and Windows groups taskbar buttons
1411
+ // by AppUserModelID. A per-session path would give every viewer its own
1412
+ // taskbar icon; a constant path puts them all under ONE icon whose hover
1413
+ // list is the open sessions, which is how a human with five agent CLIs
1414
+ // running actually navigates. Measured:
1415
+ // /view/s1 -> Chrome.127.0.0.1_/view/s1.… (separate buttons)
1416
+ // /view?s=s1 -> Chrome.127.0.0.1_/view.… (one button, five windows)
1417
+ // `/view/<id>` serves the same page.
1418
+ // A start that asks for no window (the CLI's `--no-viewer`, for a short
1419
+ // scripted session nobody needs to watch) mints no grant and opens
1420
+ // nothing; the session is listed as any other, and `viewer-url` gives a
1421
+ // link to it whenever someone asks.
1422
+ const wantsViewer = body['openViewer'] !== false;
1423
+ const viewerUrl = wantsViewer
1424
+ ? this.viewerUrlFor(session.id, this.tokens.mintViewerGrant(session.id))
1425
+ : '';
1426
+ // Open the window for the human, and wait to hear whether anything
1427
+ // opened: the launcher only spawns, detached, so the wait costs the start
1428
+ // milliseconds, and the answer decides what the caller is told. A browser
1429
+ // that will not start must never fail a session start, the one path every
1430
+ // delegate depends on, so the launcher is built not to throw, and a
1431
+ // failure here is logged and counts as "nothing opened".
1432
+ const launch = this.options.launcher ?? launchViewer;
1433
+ let opened;
1434
+ if (!wantsViewer) {
1435
+ opened = { launched: false, mode: 'none', reason: 'not requested at start' };
1436
+ }
1437
+ else {
1438
+ try {
1439
+ opened = await launch(viewerUrl, this.options.home, this.options.viewer ?? {}, this.logger);
1440
+ }
1441
+ catch (error) {
1442
+ this.logger.warn('viewer launch failed', { id: session.id, error: String(error) });
1443
+ opened = {
1444
+ launched: false,
1445
+ mode: this.options.viewer?.launchMode ?? 'none',
1446
+ reason: String(error),
1447
+ };
1448
+ }
1449
+ }
1450
+ // One grant per start, and the window has it. A window that opened gives
1451
+ // the caller no link: a link nobody asked for would sit in a transcript as
1452
+ // a live capability until it expired (§4.1). When nothing opened, the
1453
+ // grant never reached a browser, so the same URL goes to the caller as the
1454
+ // human's way in, audited like any other link under the actor that asked
1455
+ // for the session. A window's use of its grant shows in the log as the
1456
+ // `grant-redeem` its page performs.
1457
+ const handOver = wantsViewer && !opened.launched;
1458
+ if (handOver)
1459
+ this.audit.record(actor, 'grant-mint', session.id, { readOnly: false });
1460
+ json(res, 200, {
1461
+ id: session.id,
1462
+ label: session.label,
1463
+ pid: session.pid,
1464
+ cols: session.cols,
1465
+ rows: session.rows,
1466
+ ready: session.ready,
1467
+ // Without the reason, `ready: true` is ambiguous: it may mean nothing
1468
+ // was checked. Callers need to tell those apart before they type.
1469
+ readyReason: session.readyReason,
1470
+ geometryHeld: session.geometryHeld,
1471
+ viewer: {
1472
+ opened: opened.launched,
1473
+ mode: opened.mode,
1474
+ ...(opened.reason !== undefined ? { reason: opened.reason } : {}),
1475
+ },
1476
+ ...(handOver ? { viewerUrl } : {}),
1477
+ });
1478
+ }
1479
+ /**
1480
+ * The signature that reads a session's screen for `hideReasoning` and
1481
+ * `terminal_result`. Without one, a 400 is sent and null returned: those
1482
+ * readers fail closed.
1483
+ */
1484
+ readerFor(session, res) {
1485
+ const signature = signatureFor(session.agent, session.command);
1486
+ if (signature !== null)
1487
+ return signature;
1488
+ const known = agentNames().join(', ');
1489
+ json(res, 400, {
1490
+ error: session.agent !== undefined
1491
+ ? `Session ${session.id} was started as agent "${session.agent}", whose signature is not ` +
1492
+ `available now (removed from config, or set aside for running past its time budget), ` +
1493
+ `so its screen is not read for hideReasoning or a result.`
1494
+ : `Session ${session.id} runs ${programName(session.command)}, which has no agent ` +
1495
+ `signature, so its screen is not returned with hideReasoning or read for a result. ` +
1496
+ `Start it with agent set to one of: ${known}. Read it without hideReasoning only if ` +
1497
+ `no agent's reasoning is on it.`,
1498
+ });
1499
+ return null;
1500
+ }
1501
+ /**
1502
+ * Poll for the typed text to appear on screen, for longer the longer the
1503
+ * text (VERIFY_MS_PER_CHAR). Matches on the last
1504
+ * printable run of the input (up to 40 chars) so a trailing Enter or an
1505
+ * embedded control sequence does not defeat the check. For input long
1506
+ * enough to be lost in pieces, it matches on the FIRST run as well (see the
1507
+ * needle comments below for the loss this exists to catch).
1508
+ *
1509
+ * Both needles must appear, read the way a TUI wraps typed text
1510
+ * (`screenShows`): a long prompt is redrawn across the rows of an input
1511
+ * box, and the line break, the continuation row's indent, the box's border
1512
+ * and any side panel drawn on the same rows land in the middle of the
1513
+ * needle. `before` is the screen as it was before the input: rows still the
1514
+ * same are not read as wrapped pieces of it.
1515
+ */
1516
+ async verifyTyped(session, typed, before) {
1517
+ // eslint-disable-next-line no-control-regex
1518
+ const printableRuns = typed.split(/[\x00-\x1f\x7f]+/).filter((s) => s.length > 0);
1519
+ // Check the HEAD as well as the tail, and only for input long enough to be
1520
+ // lost in pieces. A long prompt can reach a TUI with its front missing and
1521
+ // its tail intact, so a tail-only check could not fail on the one loss
1522
+ // mode it needs to catch. A check that cannot fail is worse than no check:
1523
+ // it converts a silent problem into a confident wrong answer.
1524
+ const needles = [];
1525
+ const last = printableRuns[printableRuns.length - 1];
1526
+ if (last !== undefined)
1527
+ needles.push(last.slice(-40));
1528
+ const first = printableRuns[0];
1529
+ if (first !== undefined && typed.length > 200)
1530
+ needles.push(first.slice(0, 40));
1531
+ // A false report for text that arrived perfectly is not harmless: an agent
1532
+ // trusting it would retype and DUPLICATE its input, which is worse than
1533
+ // not checking at all.
1534
+ const visible = needles.filter((n) => n.trim() !== '');
1535
+ if (visible.length === 0)
1536
+ return true; // control/whitespace only: nothing to see
1537
+ const deadline = Date.now() + Math.min(VERIFY_BASE_MS + typed.length * VERIFY_MS_PER_CHAR, VERIFY_MAX_MS);
1538
+ for (;;) {
1539
+ const { screen } = await session.snapshot();
1540
+ if (visible.every((needle) => screenShows(screen, needle, before)))
1541
+ return true;
1542
+ if (Date.now() >= deadline)
1543
+ return false;
1544
+ await new Promise((resolve) => setTimeout(resolve, 50));
1545
+ }
1546
+ }
1547
+ /**
1548
+ * Reap naturally-exited sessions once their grace lapses, releasing what a
1549
+ * kill releases: the renderer, the session's viewer grants and credentials, and its
1550
+ * watcher sockets, so an abandoned viewer tab cannot hold off idle shutdown.
1551
+ */
1552
+ async sweepExited() {
1553
+ const graceMs = this.options.exitedGraceMs ?? EXITED_SESSION_GRACE_MS;
1554
+ const reaped = await this.manager.reapExited(graceMs);
1555
+ for (const id of reaped) {
1556
+ this.audit.record('daemon', 'reap', id);
1557
+ this.dropSessionArtifacts(id);
1558
+ }
1559
+ }
1560
+ /** Revoke a removed session's viewer grants and credentials and close its watcher sockets. */
1561
+ dropSessionArtifacts(id) {
1562
+ this.tokens.revokeViewerTokens(id);
1563
+ for (const [ws, sync] of this.sessionSockets.get(id) ?? []) {
1564
+ sync.close();
1565
+ try {
1566
+ ws.close();
1567
+ }
1568
+ catch {
1569
+ // Best effort.
1570
+ }
1571
+ }
1572
+ this.sessionSockets.delete(id);
1573
+ this.geometryController.delete(id);
1574
+ }
1575
+ /** Whether a live viewport is currently driving this session's grid. */
1576
+ hasGeometryController(sessionId) {
1577
+ const controller = this.geometryController.get(sessionId);
1578
+ if (controller === undefined)
1579
+ return false;
1580
+ if (controller.readyState === controller.OPEN)
1581
+ return true;
1582
+ this.geometryController.delete(sessionId);
1583
+ return false;
1584
+ }
1585
+ // ---------------------------------------------------- prompt-stall alerts
1586
+ /**
1587
+ * Session list decorated with whatever prompt each session is holding. The
1588
+ * stall alert also goes to `daemon.log` and the `/events` socket, but an
1589
+ * agent reaches the daemon through request-and-answer tool calls or one-shot
1590
+ * CLI runs, so it can never hold that socket: `terminal_list` is how a
1591
+ * manager agent learns that its delegate is blocked, which is the whole
1592
+ * point of detecting it.
1593
+ *
1594
+ * Read from the scanner's own state rather than re-detecting here: one
1595
+ * source of truth means what the list reports and what the log announces
1596
+ * cannot disagree, and a list call stays cheap (no render per session).
1597
+ * The cost is staleness bounded by the scan interval: 5 s, immaterial
1598
+ * against prompts that sit for minutes.
1599
+ */
1600
+ listWithPrompts() {
1601
+ const now = Date.now();
1602
+ return this.manager.list().map((summary) => {
1603
+ const state = this.promptStates.get(summary.id);
1604
+ if (state === undefined)
1605
+ return summary;
1606
+ return {
1607
+ ...summary,
1608
+ waitingOnPrompt: {
1609
+ question: state.prompt.question,
1610
+ options: state.prompt.options,
1611
+ waitingMs: now - state.since,
1612
+ alerted: state.alerted,
1613
+ },
1614
+ };
1615
+ });
1616
+ }
1617
+ /**
1618
+ * Scan every live session's screen for a permission prompt and alert when
1619
+ * the SAME prompt has been waiting longer than the stall threshold, so an
1620
+ * unserviced prompt does not cost the delegate tens of idle minutes until
1621
+ * someone happens to snapshot the session.
1622
+ */
1623
+ async scanForPromptStalls() {
1624
+ const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
1625
+ const seen = new Set();
1626
+ for (const summary of this.manager.list()) {
1627
+ const session = this.manager.get(summary.id);
1628
+ if (session === undefined || session.exited)
1629
+ continue;
1630
+ seen.add(session.id);
1631
+ let detected;
1632
+ try {
1633
+ const snapshot = await session.snapshot();
1634
+ detected = detectPrompt(snapshot.screen);
1635
+ }
1636
+ catch (error) {
1637
+ // One session's render fault must not blind the scan for every
1638
+ // session after it in list order, so skip it and keep scanning; its
1639
+ // own prompt state, if any, waits for a healthier beat.
1640
+ this.logger.warn('prompt scan skipped a session', {
1641
+ id: session.id,
1642
+ error: String(error),
1643
+ });
1644
+ continue;
1645
+ }
1646
+ const previous = this.promptStates.get(session.id);
1647
+ if (detected === null) {
1648
+ // Tolerate ONE missed beat before believing the prompt is gone.
1649
+ // Detection reads a snapshot rendered concurrently with PTY output, so
1650
+ // a beat can legitimately land mid-repaint and see a half-drawn
1651
+ // screen. Clearing on the first miss would let that transient reset the
1652
+ // stall clock, and a prompt whose redraw kept landing on scan beats
1653
+ // could postpone its alert indefinitely: a silent failure of exactly
1654
+ // the case the alert exists for. The cost of waiting is one scan
1655
+ // interval of staleness on the clear; the cost of not waiting is an
1656
+ // unalerted stall.
1657
+ if (previous !== undefined && previous.misses === 0) {
1658
+ previous.misses = 1;
1659
+ continue;
1660
+ }
1661
+ if (previous?.alerted === true) {
1662
+ this.emitEvent({
1663
+ type: 'prompt-clear',
1664
+ session: session.id,
1665
+ label: summary.label ?? null,
1666
+ });
1667
+ // Viewers were told the prompt was waiting; they must be told it is
1668
+ // over, or a badge raised by the stall alert never comes down.
1669
+ this.broadcastControl(session.id, { type: 'prompt-clear' });
1670
+ }
1671
+ this.promptStates.delete(session.id);
1672
+ continue;
1673
+ }
1674
+ // A real sighting cancels a pending miss: the prompt is still there.
1675
+ // Refresh the stored prompt with it, too: the signature deliberately
1676
+ // normalises Grok's radio markers so that MOVING the selection does not
1677
+ // restart the stall clock, which means the same signature can describe a
1678
+ // visibly different set of options. Storing only on signature change
1679
+ // would serve a stale selection to `terminal_list` and to a viewer
1680
+ // joining late.
1681
+ if (previous !== undefined) {
1682
+ previous.misses = 0;
1683
+ previous.prompt = detected;
1684
+ }
1685
+ if (previous === undefined || previous.signature !== detected.signature) {
1686
+ // A new (or changed) prompt starts its stall clock; it has not
1687
+ // alerted yet, so a prompt answered promptly stays silent.
1688
+ if (previous?.alerted === true) {
1689
+ // The previous prompt was announced and has now been replaced
1690
+ // rather than cleared. Retract it, otherwise a viewer badges the
1691
+ // old question while a different one is on screen.
1692
+ //
1693
+ // BOTH channels, symmetrically with the null path above. Retracting
1694
+ // to viewers only would leave `/events` emitting stall(Q1) then
1695
+ // stall(Q2) with no clear between them, which reads as two concurrent
1696
+ // holds or an unresolved first one. Nothing in this repository
1697
+ // subscribes to it, but the socket is a real API and an asymmetric
1698
+ // one is a trap for the first thing that consumes it.
1699
+ this.emitEvent({
1700
+ type: 'prompt-clear',
1701
+ session: session.id,
1702
+ label: summary.label ?? null,
1703
+ });
1704
+ this.broadcastControl(session.id, { type: 'prompt-clear' });
1705
+ }
1706
+ this.promptStates.set(session.id, {
1707
+ signature: detected.signature,
1708
+ since: Date.now(),
1709
+ alerted: false,
1710
+ prompt: detected,
1711
+ misses: 0,
1712
+ });
1713
+ continue;
1714
+ }
1715
+ if (!previous.alerted && Date.now() - previous.since >= stallMs) {
1716
+ previous.alerted = true;
1717
+ const waitingMs = Date.now() - previous.since;
1718
+ this.audit.record('daemon', 'prompt-stall', session.id);
1719
+ this.logger.warn('session waiting on a prompt', {
1720
+ id: session.id,
1721
+ waitingMs,
1722
+ question: detected.question,
1723
+ });
1724
+ this.emitEvent({
1725
+ type: 'prompt-stall',
1726
+ session: session.id,
1727
+ label: summary.label ?? null,
1728
+ waitingMs,
1729
+ question: detected.question,
1730
+ options: detected.options,
1731
+ });
1732
+ // The session's own viewers get the same signal, so an open viewer
1733
+ // tab can badge itself without subscribing to the daemon stream.
1734
+ this.broadcastControl(session.id, {
1735
+ type: 'prompt-stall',
1736
+ waitingMs,
1737
+ question: detected.question,
1738
+ // The options travel to viewers as well as to /events, so the badge
1739
+ // can say what the choices are, not only THAT something is being
1740
+ // asked.
1741
+ options: detected.options,
1742
+ });
1743
+ }
1744
+ }
1745
+ // Sessions that exited or were reaped take their prompt state with them.
1746
+ for (const id of [...this.promptStates.keys()]) {
1747
+ if (!seen.has(id))
1748
+ this.promptStates.delete(id);
1749
+ }
1750
+ }
1751
+ /** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
1752
+ emitEvent(event) {
1753
+ const message = JSON.stringify({ ...event, at: new Date().toISOString() });
1754
+ for (const ws of this.eventSockets) {
1755
+ if (ws.readyState === ws.OPEN)
1756
+ ws.send(message);
1757
+ }
1758
+ }
1759
+ // ------------------------------------------------------------- websockets
1760
+ handleUpgrade(req, socket, head) {
1761
+ const reject = (code, reason) => {
1762
+ socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\nConnection: close\r\n\r\n`);
1763
+ socket.destroy();
1764
+ };
1765
+ if (!this.hostAllowed(req.headers.host)) {
1766
+ reject(403, 'Forbidden');
1767
+ return;
1768
+ }
1769
+ // Browsers always send Origin on WS; a foreign one means a hostile page
1770
+ // is probing the loopback daemon (design §4.2).
1771
+ if (!this.originAllowed(req.headers.origin)) {
1772
+ reject(403, 'Forbidden');
1773
+ return;
1774
+ }
1775
+ // Parsed inside a guard, before anything is authenticated: Node's HTTP
1776
+ // parser accepts an unparsable request target (`GET http://[ HTTP/1.1`)
1777
+ // and hands it over verbatim, and no exception may escape the upgrade
1778
+ // event. Such a request is refused with a 400.
1779
+ let url;
1780
+ try {
1781
+ url = new URL(req.url ?? '/', `http://127.0.0.1:${String(this.portValue ?? 0)}`);
1782
+ }
1783
+ catch {
1784
+ reject(400, 'Bad Request');
1785
+ return;
1786
+ }
1787
+ const segments = url.pathname.split('/').filter((s) => s !== '');
1788
+ // Daemon-wide event stream: prompt-stall alerts and their clears, as TEXT
1789
+ // JSON frames. CLIENT token only: viewer credentials are session-scoped
1790
+ // and must not see other sessions' prompts.
1791
+ if (segments.length === 1 && segments[0] === 'events') {
1792
+ const auth = this.tokens.verify(url.searchParams.get('token'));
1793
+ if (auth === null || auth.kind !== 'client') {
1794
+ reject(401, 'Unauthorized');
1795
+ return;
1796
+ }
1797
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
1798
+ this.attachEventSocket(ws);
1799
+ });
1800
+ return;
1801
+ }
1802
+ if (segments[0] !== 'sessions' || segments[2] !== 'stream') {
1803
+ reject(404, 'Not Found');
1804
+ return;
1805
+ }
1806
+ const sessionId = segments[1] ?? '';
1807
+ // Auth BEFORE existence: session ids are sequential, and answering 404 to
1808
+ // an unauthenticated prober would let it enumerate which ones exist,
1809
+ // the same leak the unauthenticated viewer route deliberately avoids.
1810
+ //
1811
+ // Two ways in, and a viewer grant is neither (§4.1). A client token may
1812
+ // ride the query, because it is the same-user secret from `daemon.json`
1813
+ // and never travels in a URL a human sees. A browser presents the
1814
+ // HttpOnly cookie it was given when its grant was redeemed, which is why
1815
+ // nothing a page script holds can open a socket.
1816
+ // Every cookie of that name is tried, not the first: cookies ignore ports,
1817
+ // so a page served from any other loopback port can plant one beside the
1818
+ // daemon's own, and a value that will not even decode is skipped rather
1819
+ // than thrown on. And only a credential for THIS session counts: one the
1820
+ // daemon issued for another session, planted ahead of the right one, is
1821
+ // passed over rather than taken as the answer.
1822
+ const auth = this.tokens.verify(url.searchParams.get('token')) ??
1823
+ cookieValues(req.headers.cookie, VIEWER_COOKIE)
1824
+ .map((value) => this.tokens.verifyStreamToken(value))
1825
+ .find((found) => found?.kind === 'viewer' && found.sessionId === sessionId) ??
1826
+ null;
1827
+ if (auth === null || (auth.kind === 'viewer' && auth.sessionId !== sessionId)) {
1828
+ reject(401, 'Unauthorized');
1829
+ return;
1830
+ }
1831
+ const readOnly = auth.kind === 'viewer' && auth.readOnly;
1832
+ const session = this.manager.get(sessionId);
1833
+ if (session === undefined) {
1834
+ reject(404, 'Not Found');
1835
+ return;
1836
+ }
1837
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
1838
+ // Which credential opened the socket travels with it, so the audit log
1839
+ // names that credential rather than assuming a browser: `client` for
1840
+ // the client token on the query, `viewer` for a viewer cookie.
1841
+ this.attachSocket(ws, session, { kind: auth.kind, readOnly });
1842
+ });
1843
+ }
1844
+ /** Attach a subscriber to the daemon-wide event stream. */
1845
+ attachEventSocket(ws) {
1846
+ this.sockets.add(ws);
1847
+ this.eventSockets.add(ws);
1848
+ this.lastActivity = Date.now();
1849
+ this.audit.record('client', 'events-connect', '-');
1850
+ ws.send(JSON.stringify({ type: 'hello', version: this.version }));
1851
+ ws.on('close', () => {
1852
+ this.sockets.delete(ws);
1853
+ this.eventSockets.delete(ws);
1854
+ this.lastActivity = Date.now();
1855
+ });
1856
+ ws.on('error', () => {
1857
+ ws.close();
1858
+ });
1859
+ // The stream is outbound-only; inbound frames are ignored by design.
1860
+ }
1861
+ /** Send a JSON control message (TEXT frame) to every watcher of a session. */
1862
+ broadcastControl(sessionId, control) {
1863
+ const watchers = this.sessionSockets.get(sessionId);
1864
+ if (watchers === undefined)
1865
+ return;
1866
+ const message = JSON.stringify(control);
1867
+ for (const ws of watchers.keys()) {
1868
+ if (ws.readyState === ws.OPEN)
1869
+ ws.send(message);
1870
+ }
1871
+ }
1872
+ /**
1873
+ * Tell every watcher the current grid and who drives it, then hand each one
1874
+ * a snapshot at that size. Both halves matter: the frame moves their grid,
1875
+ * and the snapshot repaints it from the daemon's renderer rather than from
1876
+ * xterm's in-place reflow of what they had (§5).
1877
+ */
1878
+ announceGeometry(sessionId, session, options = {}) {
1879
+ for (const [ws, sync] of this.sessionSockets.get(sessionId) ?? []) {
1880
+ if (ws.readyState === ws.OPEN) {
1881
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
1882
+ }
1883
+ if (options.resync !== false)
1884
+ sync.resync();
1885
+ }
1886
+ }
1887
+ /** What one watcher is told about the grid, from its own point of view. */
1888
+ geometryFrame(session, ws) {
1889
+ return {
1890
+ type: 'geometry',
1891
+ cols: session.cols,
1892
+ rows: session.rows,
1893
+ // The most a viewport may ask for (§5), with every frame: a page whose
1894
+ // window wants more can then size its text for the grid it will be
1895
+ // given, rather than proposing one it never will be.
1896
+ max: { cols: MAX_VIEWPORT_COLS, rows: MAX_VIEWPORT_ROWS },
1897
+ control: session.geometryHeld
1898
+ ? 'held'
1899
+ : this.geometryController.get(session.id) === ws
1900
+ ? 'yours'
1901
+ : 'adopt',
1902
+ };
1903
+ }
1904
+ /** The viewer URL for a session, carrying a one-use grant. */
1905
+ viewerUrlFor(sessionId, grant) {
1906
+ return (`http://127.0.0.1:${String(this.port)}/view` +
1907
+ `?s=${encodeURIComponent(sessionId)}&vt=${grant}`);
1908
+ }
1909
+ /** The daemon's rendered state as viewer bytes: a wipe, then the rebuild. */
1910
+ async snapshotForViewer(session) {
1911
+ try {
1912
+ const state = await session.viewerState({
1913
+ scrollback: VIEWER_SNAPSHOT_SCROLLBACK_LINES,
1914
+ });
1915
+ return VIEWER_WIPE + state;
1916
+ }
1917
+ catch (error) {
1918
+ // The gate releases live bytes anyway; the viewer just misses this repaint.
1919
+ this.logger.warn('viewer snapshot failed', { id: session.id, error: String(error) });
1920
+ throw error;
1921
+ }
1922
+ }
1923
+ /**
1924
+ * Wire protocol: BINARY frames carry terminal bytes (snapshots, live mirror,
1925
+ * exit notice); TEXT frames are JSON control messages. Incoming text frames
1926
+ * are either JSON controls (resize) or bytes for the program: a person's
1927
+ * keystrokes, or the viewer's terminal answering the program
1928
+ * (terminalReports.ts).
1929
+ */
1930
+ attachSocket(ws, session, credential) {
1931
+ const { readOnly } = credential;
1932
+ // The audit actor is the credential that opened this socket, not the
1933
+ // route: `viewer` means the socket presented a viewer cookie (what a
1934
+ // viewer link's grant becomes when it is opened), and `client` means the
1935
+ // same-user client token rode the query. The actor names the credential,
1936
+ // not the person or program behind it.
1937
+ const actor = credential.kind;
1938
+ this.sockets.add(ws);
1939
+ let watchers = this.sessionSockets.get(session.id);
1940
+ if (watchers === undefined) {
1941
+ watchers = new Map();
1942
+ this.sessionSockets.set(session.id, watchers);
1943
+ }
1944
+ const sync = new ViewerSync((bytes) => {
1945
+ if (ws.readyState === ws.OPEN)
1946
+ ws.send(Buffer.from(bytes, 'utf8'));
1947
+ }, () => this.snapshotForViewer(session));
1948
+ watchers.set(ws, sync);
1949
+ this.lastActivity = Date.now();
1950
+ this.audit.record(actor, 'ws-connect', session.id);
1951
+ // Who this session belongs to and what it is for. Sent before anything
1952
+ // else so the window is identifiable the instant it paints: with several
1953
+ // viewer windows open, an unlabelled one is indistinguishable from the
1954
+ // rest until you read its terminal content and infer.
1955
+ ws.send(JSON.stringify({
1956
+ type: 'identity',
1957
+ session: session.id,
1958
+ label: session.label,
1959
+ purpose: session.purpose,
1960
+ startedBy: session.startedBy,
1961
+ command: commandLine(session.command, session.args),
1962
+ // The page reflects this rather than deciding it: its own toggle is a
1963
+ // convenience, this is the daemon's answer (§4.1).
1964
+ readOnly,
1965
+ // A session stays reachable for fifteen minutes after its process
1966
+ // exits, and a viewer joining in that window is told so at once,
1967
+ // rather than shown a terminal that looks alive.
1968
+ exited: session.exited,
1969
+ exitCode: session.exitCode,
1970
+ }));
1971
+ // Settle geometry from the SERVER on connect, before the viewer decides
1972
+ // anything for itself. A viewer that fitted on open would resize the PTY
1973
+ // before it could learn whether it was entitled to. The frame below says
1974
+ // which of the three positions this viewer is in, so the choice is made
1975
+ // knowing the answer rather than raced against it.
1976
+ //
1977
+ // This MUST precede the snapshot below: the viewer writes snapshot bytes
1978
+ // into whatever grid it currently has, so sizing it afterwards reflows
1979
+ // content that was already laid out at the wrong width.
1980
+ //
1981
+ // Nobody driving, and free to be driven: this viewport picks it up, and
1982
+ // will propose a grid that fills its window. A read-only credential never
1983
+ // drives, because choosing the grid is a write.
1984
+ if (!session.geometryHeld &&
1985
+ !readOnly &&
1986
+ !this.hasGeometryController(session.id)) {
1987
+ this.geometryController.set(session.id, ws);
1988
+ }
1989
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
1990
+ // What the daemon renders, as the bytes that rebuild it (design §5). Not
1991
+ // a slice of the raw stream: a slice starts mid-frame, and a program that
1992
+ // only repaints what changed never puts the rest of its frame back. Every
1993
+ // agent CLI repaints that way once its chrome is up, and on Windows every
1994
+ // program does as ConPTY relays it. Live bytes queue behind the
1995
+ // snapshot in the gate.
1996
+ sync.resync();
1997
+ // Whoever was watching when the process exited got this notice on the
1998
+ // wire, and someone who arrives inside the fifteen-minute grace is owed
1999
+ // the same thing: without it the screen is just the program's last frame,
2000
+ // which looks exactly like a program that is still there. Delivered
2001
+ // AFTER the resync, so the gate holds it behind the snapshot instead of
2002
+ // letting the snapshot's wipe erase it.
2003
+ if (session.exited) {
2004
+ sync.deliver(exitNotice(session.exitCode));
2005
+ }
2006
+ // A stall is announced once, at the moment it trips. Someone who opens the
2007
+ // viewer BECAUSE they were told a session is stuck arrives after
2008
+ // the only announcement, and is the exact person the badge is for. Replay the
2009
+ // current state to them.
2010
+ const held = this.promptStates.get(session.id);
2011
+ if (held?.alerted === true) {
2012
+ ws.send(JSON.stringify({
2013
+ type: 'prompt-stall',
2014
+ waitingMs: Date.now() - held.since,
2015
+ question: held.prompt.question,
2016
+ options: held.prompt.options,
2017
+ }));
2018
+ }
2019
+ const unsubscribeData = session.onData((data) => sync.deliver(data));
2020
+ const unsubscribeExit = session.onExit((exitCode) => {
2021
+ sync.deliver(exitNotice(exitCode));
2022
+ // The notice is bytes on the terminal; the page needs a frame to change
2023
+ // its own state.
2024
+ if (ws.readyState === ws.OPEN) {
2025
+ ws.send(JSON.stringify({ type: 'exited', exitCode }));
2026
+ }
2027
+ });
2028
+ // A protocol error, such as a malformed frame or a reset mid-handshake,
2029
+ // is logged and closes the socket rather than escaping as an uncaught
2030
+ // exception. The close handler below does the bookkeeping either way.
2031
+ ws.on('error', (error) => {
2032
+ this.logger.warn('viewer socket error', { id: session.id, error: String(error) });
2033
+ ws.close();
2034
+ });
2035
+ ws.on('message', (message) => {
2036
+ this.lastActivity = Date.now();
2037
+ const text = typeof message === 'string' ? message : message.toString('utf8');
2038
+ try {
2039
+ const parsed = JSON.parse(text);
2040
+ if (typeof parsed === 'object' &&
2041
+ parsed !== null &&
2042
+ parsed.type === 'resize') {
2043
+ const { cols, rows } = parsed;
2044
+ if (!readOnly &&
2045
+ typeof cols === 'number' &&
2046
+ typeof rows === 'number' &&
2047
+ Number.isInteger(cols) &&
2048
+ Number.isInteger(rows) &&
2049
+ cols >= 2 &&
2050
+ cols <= 1_000 &&
2051
+ rows >= 2 &&
2052
+ rows <= 500 &&
2053
+ !session.exited) {
2054
+ if (session.geometryHeld) {
2055
+ // Held against viewports. Answer with the real grid so the page
2056
+ // stops proposing one it will never be given.
2057
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
2058
+ return;
2059
+ }
2060
+ const wanted = {
2061
+ cols: Math.min(cols, MAX_VIEWPORT_COLS),
2062
+ rows: Math.min(rows, MAX_VIEWPORT_ROWS),
2063
+ };
2064
+ // Asking is the deliberate act that takes control, whether or not
2065
+ // the grid actually moves: a viewport that already fits is still
2066
+ // the one driving.
2067
+ const handedOver = this.geometryController.get(session.id) !== ws;
2068
+ this.geometryController.set(session.id, ws);
2069
+ const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
2070
+ let applied = false;
2071
+ try {
2072
+ session.resize(wanted.cols, wanted.rows);
2073
+ applied = true;
2074
+ }
2075
+ catch (error) {
2076
+ // A resize can race the session's exit (a viewer fitting its
2077
+ // window while looking at a dying session). node-pty throws on
2078
+ // a dead PTY, and an exception escaping a WS handler would take
2079
+ // the whole daemon down via the uncaughtException path.
2080
+ this.logger.warn('viewer resize failed', {
2081
+ id: session.id,
2082
+ error: String(error),
2083
+ });
2084
+ }
2085
+ // A geometry change is a geometry change whoever made it, and
2086
+ // `resize` is on the list of audited actions the security page
2087
+ // publishes. Only the ones that actually took: a proposal the
2088
+ // grid already satisfied moved nothing, and one that threw
2089
+ // because the session was dying moved nothing either, so neither
2090
+ // is recorded as a success. `hold` is false because a viewport
2091
+ // never holds: holding is asked for explicitly, over the API (§5).
2092
+ if (changed && applied) {
2093
+ this.audit.record(actor, 'resize', session.id, {
2094
+ cols: wanted.cols,
2095
+ rows: wanted.rows,
2096
+ hold: false,
2097
+ });
2098
+ }
2099
+ // Everyone sees the same grid, and each is told whether they are
2100
+ // now driving it. A proposal that changed nothing needs no
2101
+ // snapshot, because the page already shows this grid. But if the
2102
+ // grid changed hands, everyone is told that much, or the old
2103
+ // driver goes on believing it is theirs.
2104
+ if (changed)
2105
+ this.announceGeometry(session.id, session);
2106
+ else if (handedOver)
2107
+ this.announceGeometry(session.id, session, { resync: false });
2108
+ }
2109
+ return;
2110
+ }
2111
+ }
2112
+ catch {
2113
+ // Not JSON: bytes for the program, a person's keystrokes or the
2114
+ // viewer's terminal answering the program. Straight into the PTY
2115
+ // either way: shared typing is the point of the tool.
2116
+ }
2117
+ if (readOnly) {
2118
+ // A watch-only credential. Dropped silently and on the daemon's side:
2119
+ // the page has already been told it is read-only and disables its own
2120
+ // input, so anything arriving here is not a human mistyping.
2121
+ return;
2122
+ }
2123
+ if (session.exited) {
2124
+ // A session stays reachable for fifteen minutes after its process
2125
+ // exits, and input typed into that window is refused out loud, as the
2126
+ // HTTP path refuses it with a 409.
2127
+ // Told to this socket alone: the other watchers did not type it.
2128
+ if (ws.readyState === ws.OPEN) {
2129
+ ws.send(JSON.stringify({
2130
+ type: 'input-refused',
2131
+ reason: 'exited',
2132
+ exitCode: session.exitCode,
2133
+ }));
2134
+ }
2135
+ return;
2136
+ }
2137
+ // write() is async, so a failure arrives as a rejection and never as a
2138
+ // synchronous throw: a try/catch here would be dead code. Not awaited:
2139
+ // this is the viewer's data handler and must stay responsive, and
2140
+ // ordering is guaranteed inside write() by its queue rather than here.
2141
+ // (xterm hands us multi-character strings for pastes and escape
2142
+ // sequences, so this is not always one keystroke.) .catch keeps the exit
2143
+ // race, the session dying mid-write, from escaping as an unhandled
2144
+ // rejection.
2145
+ void session.write(text).catch((error) => {
2146
+ this.logger.warn('viewer input failed', {
2147
+ id: session.id,
2148
+ error: String(error),
2149
+ });
2150
+ });
2151
+ // The viewer's terminal answering the program, such as where the cursor
2152
+ // is or that the window gained focus, is written above like a keystroke
2153
+ // because the program asked for it. Nobody typed it, so it is audited
2154
+ // as a report and leaves the "last input" indicator alone (§4.5, §5).
2155
+ // Content only under captureContent, as for input.
2156
+ const report = terminalReportKind(text);
2157
+ if (report !== null) {
2158
+ this.audit.record(actor, 'report', session.id, {
2159
+ kind: report,
2160
+ chars: text.length,
2161
+ ...(this.audit.captureContent ? { data: text } : {}),
2162
+ });
2163
+ return;
2164
+ }
2165
+ this.audit.record(actor, 'input', session.id, {
2166
+ chars: text.length,
2167
+ ...(this.audit.captureContent ? { data: text } : {}),
2168
+ });
2169
+ this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
2170
+ });
2171
+ ws.on('close', () => {
2172
+ unsubscribeData();
2173
+ unsubscribeExit();
2174
+ sync.close();
2175
+ this.sockets.delete(ws);
2176
+ this.sessionSockets.get(session.id)?.delete(ws);
2177
+ // The grid stays where it is; it simply no longer belongs to anyone, so
2178
+ // the next viewport to arrive or to act picks it up.
2179
+ if (this.geometryController.get(session.id) === ws) {
2180
+ this.geometryController.delete(session.id);
2181
+ }
2182
+ this.lastActivity = Date.now();
2183
+ this.audit.record(actor, 'ws-close', session.id);
2184
+ });
2185
+ }
2186
+ }
2187
+ //# sourceMappingURL=server.js.map