repoburg 1.3.302 → 1.3.304

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 (37) hide show
  1. package/agent-pane/backend/dist/index.js +2656 -434
  2. package/agent-pane/backend/dist/server.js +2751 -434
  3. package/agent-pane/backend/scripts/session-host.mjs +860 -0
  4. package/agent-pane/frontend/dist/assets/{TerminalView-C6AkFuDP.js → TerminalView-BN_4GKd9.js} +1 -1
  5. package/agent-pane/frontend/dist/assets/index-CaUGqLNi.js +836 -0
  6. package/agent-pane/frontend/dist/index.html +1 -1
  7. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.d.ts +30 -2
  8. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js +108 -6
  9. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js.map +1 -1
  10. package/backend/dist/src/agent-runtime/agent-runtime.controller.d.ts +4 -2
  11. package/backend/dist/src/agent-runtime/agent-runtime.controller.js +49 -9
  12. package/backend/dist/src/agent-runtime/agent-runtime.controller.js.map +1 -1
  13. package/backend/dist/src/agent-runtime/agent-runtime.types.d.ts +20 -1
  14. package/backend/dist/src/interactive-chat/chat.service.js +9 -2
  15. package/backend/dist/src/interactive-chat/chat.service.js.map +1 -1
  16. package/backend/dist/src/session-inputs/session-inputs.module.js +2 -0
  17. package/backend/dist/src/session-inputs/session-inputs.module.js.map +1 -1
  18. package/backend/dist/src/session-inputs/session-inputs.service.d.ts +4 -1
  19. package/backend/dist/src/session-inputs/session-inputs.service.js +15 -2
  20. package/backend/dist/src/session-inputs/session-inputs.service.js.map +1 -1
  21. package/backend/dist/tsconfig.build.tsbuildinfo +1 -1
  22. package/daemon/dist/agentPane.js +6 -2
  23. package/daemon/dist/agents.js +74 -0
  24. package/daemon/dist/agents.spec.js +90 -0
  25. package/daemon/dist/api/agents.js +38 -0
  26. package/daemon/dist/api/services.js +25 -0
  27. package/daemon/dist/index.js +7 -3
  28. package/daemon/dist/serviceManager.js +28 -2
  29. package/daemon/dist/serviceRoller.js +133 -0
  30. package/daemon/dist/serviceRoller.spec.js +132 -0
  31. package/package.json +2 -1
  32. package/tabtape/extension/dist/build-info.json +4 -4
  33. package/tabtape/extension/dist/manifest.json +1 -1
  34. package/tabtape/extension/dist/recorder.js +51 -39
  35. package/tabtape/extension/dist/recorder.js.map +1 -1
  36. package/tabtape/ui/dist/build-info.json +4 -4
  37. package/agent-pane/frontend/dist/assets/index-DoReiVY-.js +0 -834
@@ -0,0 +1,860 @@
1
+ #!/usr/bin/env node
2
+ /* global process, setTimeout, clearTimeout, setInterval, clearInterval, Buffer */
3
+ /**
4
+ * Session host: the parent of one runtime process (a Claude CLI or a Codex
5
+ * app-server). It runs detached from the daemon, so a daemon restart, an
6
+ * update or a crash does not end the runtime or its running turn. The next
7
+ * daemon attaches over a unix socket and reads what it missed from the log.
8
+ *
9
+ * daemon ── unix socket ──> session host ── pipes ──> claude / codex app-server
10
+ * └─ out.log, err.log, exit.json
11
+ *
12
+ * Rules (each one backed by a spike, see
13
+ * .repoburg/plans/zero-downtime-daemon-upgrade.md):
14
+ *
15
+ * 1. Bytes and lines only, no frame parsing: Claude and Codex share it.
16
+ * 2. A socket close is not stdin EOF. Only an explicit request (signal, eof)
17
+ * stops the child.
18
+ * 3. Only complete stdin lines reach the child: a daemon that dies mid-line
19
+ * must not hand the child half a JSON line.
20
+ * 4. Never block on a slow daemon: past the backlog limit the socket is
21
+ * dropped and the daemon attaches again, replaying from the log.
22
+ * 5. A log failure (disk full, size limit) never touches the child: the host
23
+ * sets `lossy`, keeps forwarding, and a later attach that needs the log is
24
+ * refused.
25
+ * 6. On child exit: write exit.json, drain for at most 2 s, exit.
26
+ * 7. Offsets are logical byte offsets into the child's stdout since it
27
+ * started; `lineEnd` is always a line boundary.
28
+ * 8. Node built-ins only; it runs on the runtime's own node, unbundled.
29
+ *
30
+ * Protocol v1 (frozen once shipped; a change needs a new `v`). The first line
31
+ * of every connection is one JSON object:
32
+ *
33
+ * {"v":1,"op":"attach","after":N} header line, stdout bytes from N, then
34
+ * live; the rest of the connection is stdin
35
+ * {"v":1,"op":"status"} one reply line
36
+ * {"v":1,"op":"signal","signal":S} signals the child
37
+ * {"v":1,"op":"eof"} closes the child's stdin
38
+ * {"v":1,"op":"ack","upto":N} bytes before N may be dropped
39
+ * {"v":1,"op":"limit","noHostMs":N} sets the no-host limit
40
+ *
41
+ * Anything else gets {"ok":false,...} and leaves the host as it was.
42
+ *
43
+ * Downgrade guard: while no daemon is attached, the host asks
44
+ * GET <daemonUrl>/api/session-hosts/protocol every 2 s. Connection refused:
45
+ * the daemon is down, wait. A JSON list with this protocol: expect an attach
46
+ * within 60 s. Anything else is a daemon that cannot adopt hosts, so the child
47
+ * is stopped before that daemon resumes the turn in a second process.
48
+ *
49
+ * Usage: node session-host.mjs <dir> <config-json> <command> [args...]
50
+ * The child gets this process's environment and working directory.
51
+ */
52
+
53
+ import fs from 'node:fs';
54
+ import net from 'node:net';
55
+ import path from 'node:path';
56
+ import http from 'node:http';
57
+ import { spawn } from 'node:child_process';
58
+
59
+ const PROTOCOL = 1;
60
+ const LOG_HEADER_PREFIX = 'session-host-log v1 oldest=';
61
+ const LOG_HEADER_DIGITS = 20;
62
+ const LOG_HEADER_LEN = LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS + 1;
63
+ const MAX_REQUEST_LINE = 64 * 1024;
64
+ const MAX_PENDING_STDIN = 512 * 1024 * 1024;
65
+ const REPLAY_CHUNK = 1024 * 1024;
66
+ const ROTATE_MIN_ACKED = 64 * 1024;
67
+ const ROTATE_MAX_TAIL = 4 * 1024 * 1024;
68
+ const ERR_LOG_LIMIT = 16 * 1024 * 1024;
69
+ const SIGNALS = new Set(['SIGTERM', 'SIGKILL', 'SIGINT', 'SIGHUP', 'SIGQUIT', 'SIGUSR1', 'SIGUSR2']);
70
+
71
+ const [dir, configJson, command, ...args] = process.argv.slice(2);
72
+ if (!dir || !configJson || !command) {
73
+ process.stderr.write('usage: session-host.mjs <dir> <config-json> <command> [args...]\n');
74
+ process.exit(2);
75
+ }
76
+
77
+ /** @type {Record<string, unknown>} */
78
+ let config = {};
79
+ try {
80
+ config = JSON.parse(configJson);
81
+ } catch {
82
+ process.stderr.write('session-host: config is not JSON\n');
83
+ process.exit(2);
84
+ }
85
+ const num = (v, d) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : d);
86
+ const LOG_SOFT_LIMIT = num(config.logSoftLimit, 256 * 1024 * 1024);
87
+ const LOG_HARD_LIMIT = num(config.logHardLimit, 1024 * 1024 * 1024);
88
+ const BACKLOG_LIMIT = num(config.backlogLimit, 16 * 1024 * 1024);
89
+ const EXIT_DRAIN_MS = num(config.exitDrainMs, 2_000);
90
+ const GUARD_POLL_MS = num(config.guardPollMs, 2_000);
91
+ const GUARD_ATTACH_MS = num(config.guardAttachMs, 60_000);
92
+ const KILL_GRACE_MS = num(config.killGraceMs, 10_000);
93
+ const daemonUrl = typeof config.daemonUrl === 'string' ? config.daemonUrl.replace(/\/+$/, '') : '';
94
+ let noHostMs = Math.max(1_000, num(config.noHostMs, 30 * 60_000));
95
+
96
+ const dirAbs = path.resolve(dir);
97
+ const file = (name) => path.join(dirAbs, name);
98
+
99
+ fs.mkdirSync(dirAbs, { recursive: true, mode: 0o700 });
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // Logs
103
+ // ---------------------------------------------------------------------------
104
+
105
+ /** Logical offset of the first byte after the last stdout byte. */
106
+ let end = 0;
107
+ /** Logical offset after the last complete stdout line. */
108
+ let lineEnd = 0;
109
+ /** Logical offset of the first byte still in out.log. */
110
+ let oldest = 0;
111
+ /** Highest offset the daemon acknowledged. */
112
+ let acked = 0;
113
+ let lossy = false;
114
+ /** @type {string | null} */
115
+ let lossyReason = null;
116
+ let softWarned = false;
117
+
118
+ function logHeader(offset) {
119
+ return LOG_HEADER_PREFIX + String(offset).padStart(LOG_HEADER_DIGITS, '0') + '\n';
120
+ }
121
+
122
+ /** @type {number | null} */
123
+ let logFd = null;
124
+ try {
125
+ logFd = fs.openSync(file('out.log'), 'w+', 0o600);
126
+ writeAll(logFd, Buffer.from(logHeader(0)));
127
+ } catch (err) {
128
+ logFd = null;
129
+ lossy = true;
130
+ lossyReason = `open_failed: ${err && err.code}`;
131
+ }
132
+
133
+ /** @type {number | null} */
134
+ let errFd = null;
135
+ let errBytes = 0;
136
+ try {
137
+ errFd = fs.openSync(file('err.log'), 'a', 0o600);
138
+ } catch {
139
+ errFd = null;
140
+ }
141
+
142
+ function writeAll(fd, buf) {
143
+ let off = 0;
144
+ while (off < buf.length) off += fs.writeSync(fd, buf, off, buf.length - off);
145
+ }
146
+
147
+ /** Append to err.log (child stderr and host notes), up to its limit. */
148
+ function errLog(buf) {
149
+ if (errFd === null || errBytes >= ERR_LOG_LIMIT) return;
150
+ const chunk = errBytes + buf.length > ERR_LOG_LIMIT ? buf.subarray(0, ERR_LOG_LIMIT - errBytes) : buf;
151
+ try {
152
+ writeAll(errFd, chunk);
153
+ errBytes += chunk.length;
154
+ } catch {
155
+ // stderr is a diagnostic; losing it never touches the child
156
+ }
157
+ }
158
+
159
+ function note(text) {
160
+ errLog(Buffer.from(`[session-host ${new Date().toISOString()}] ${text}\n`));
161
+ }
162
+
163
+ function setLossy(reason) {
164
+ if (lossy) return;
165
+ lossy = true;
166
+ lossyReason = reason;
167
+ note(`log lossy: ${reason}`);
168
+ }
169
+
170
+ function writeLog(chunk) {
171
+ if (lossy || logFd === null) return;
172
+ if (end + chunk.length - oldest > LOG_HARD_LIMIT) {
173
+ setLossy('log_limit');
174
+ return;
175
+ }
176
+ try {
177
+ writeAll(logFd, chunk);
178
+ } catch (err) {
179
+ setLossy(`write_failed: ${err && err.code}`);
180
+ return;
181
+ }
182
+ if (!softWarned && end + chunk.length - oldest > LOG_SOFT_LIMIT) {
183
+ softWarned = true;
184
+ note(`log passed ${LOG_SOFT_LIMIT} bytes`);
185
+ }
186
+ }
187
+
188
+ /** Drop acknowledged bytes: the unacknowledged tail moves to a new out.log.
189
+ * Only when the tail is small (turn end) and no replay reads the file. A
190
+ * lossy log whose bytes are all acknowledged starts over clean. */
191
+ function maybeRotate() {
192
+ if (pump) return;
193
+ if (lossy) {
194
+ if (acked >= end) rewriteLog(Buffer.alloc(0), end);
195
+ return;
196
+ }
197
+ if (logFd === null) return;
198
+ if (acked - oldest < ROTATE_MIN_ACKED || end - acked > ROTATE_MAX_TAIL) return;
199
+ const tail = Buffer.alloc(end - acked);
200
+ try {
201
+ if (tail.length > 0) fs.readSync(logFd, tail, 0, tail.length, LOG_HEADER_LEN + (acked - oldest));
202
+ } catch (err) {
203
+ note(`rotation read failed: ${err && err.code}`);
204
+ return;
205
+ }
206
+ rewriteLog(tail, acked);
207
+ }
208
+
209
+ function rewriteLog(tail, newOldest) {
210
+ const next = file('out.log.next');
211
+ try {
212
+ const fd = fs.openSync(next, 'w+', 0o600);
213
+ writeAll(fd, Buffer.from(logHeader(newOldest)));
214
+ if (tail.length > 0) writeAll(fd, tail);
215
+ fs.renameSync(next, file('out.log'));
216
+ if (logFd !== null) fs.closeSync(logFd);
217
+ logFd = fd;
218
+ oldest = newOldest;
219
+ lossy = false;
220
+ lossyReason = null;
221
+ softWarned = false;
222
+ } catch (err) {
223
+ note(`rotation failed: ${err && err.code}`);
224
+ try {
225
+ fs.rmSync(next, { force: true });
226
+ } catch {
227
+ // nothing left to clean
228
+ }
229
+ }
230
+ }
231
+
232
+ /** Remove a file or symlink (a dangling one too); absent is fine. */
233
+ function unlinkQuiet(p) {
234
+ try {
235
+ fs.unlinkSync(p);
236
+ } catch {
237
+ // absent
238
+ }
239
+ }
240
+
241
+ function writeJsonAtomic(name, value) {
242
+ const tmp = file(`${name}.tmp`);
243
+ fs.writeFileSync(tmp, JSON.stringify(value) + '\n', { mode: 0o600 });
244
+ fs.renameSync(tmp, file(name));
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------
248
+ // Child
249
+ // ---------------------------------------------------------------------------
250
+
251
+ const startedAt = new Date().toISOString();
252
+ /** @type {{ code: number | null, signal: string | null, error?: string, at: string } | null} */
253
+ let exited = null;
254
+ let stdinClosed = false;
255
+ let stdoutEnded = false;
256
+ /** @type {ReturnType<typeof setTimeout> | null} */
257
+ let killTimer = null;
258
+
259
+ const child = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
260
+
261
+ try {
262
+ writeJsonAtomic('child.json', { pid: child.pid ?? null, hostPid: process.pid, command, startedAt });
263
+ } catch (err) {
264
+ note(`child.json not written: ${err && err.code}`);
265
+ }
266
+
267
+ child.stdin.on('error', () => {
268
+ // EPIPE once the child is gone; the exit path reports it
269
+ });
270
+
271
+ child.stdout.on('data', (chunk) => {
272
+ writeLog(chunk);
273
+ const nl = chunk.lastIndexOf(10);
274
+ if (nl !== -1) lineEnd = end + nl + 1;
275
+ end += chunk.length;
276
+ if (client && !pump) sendLive(chunk);
277
+ });
278
+ child.stdout.on('end', () => {
279
+ stdoutEnded = true;
280
+ maybeFinish();
281
+ });
282
+ child.stdout.on('error', () => {
283
+ stdoutEnded = true;
284
+ maybeFinish();
285
+ });
286
+ child.stderr.on('data', (chunk) => errLog(chunk));
287
+ child.stderr.on('error', () => {});
288
+
289
+ child.on('error', (err) => {
290
+ // spawn failure (ENOENT, EACCES): there is no child to wait for
291
+ if (exited) return;
292
+ onChildExit(null, null, err && err.message ? String(err.message) : 'spawn failed');
293
+ stdoutEnded = true;
294
+ maybeFinish();
295
+ });
296
+ child.on('exit', (code, signal) => onChildExit(code, signal));
297
+
298
+ function onChildExit(code, signal, error) {
299
+ if (exited) return;
300
+ exited = { code, signal, ...(error ? { error } : {}), at: new Date().toISOString() };
301
+ try {
302
+ writeJsonAtomic('exit.json', exited);
303
+ } catch (err) {
304
+ note(`exit.json not written: ${err && err.code}`);
305
+ }
306
+ if (killTimer) clearTimeout(killTimer);
307
+ stopNoHostTimer();
308
+ stopGuard();
309
+ // A grandchild may hold stdout open: never wait longer than the cap.
310
+ setTimeout(() => finish(), EXIT_DRAIN_MS).unref();
311
+ maybeFinish();
312
+ }
313
+
314
+ /** Stop the child for the host's own reasons (no-host limit, guard). */
315
+ function stopChild(reason) {
316
+ if (exited) return;
317
+ note(`stopping the child: ${reason}`);
318
+ try {
319
+ child.kill('SIGTERM');
320
+ } catch {
321
+ // already gone
322
+ }
323
+ if (!killTimer) {
324
+ killTimer = setTimeout(() => {
325
+ if (exited) return;
326
+ note('child did not exit after SIGTERM, sending SIGKILL');
327
+ try {
328
+ child.kill('SIGKILL');
329
+ } catch {
330
+ // already gone
331
+ }
332
+ }, KILL_GRACE_MS);
333
+ }
334
+ }
335
+
336
+ // ---------------------------------------------------------------------------
337
+ // Socket
338
+ // ---------------------------------------------------------------------------
339
+
340
+ /** @type {net.Socket | null} */
341
+ let client = null;
342
+ /** Replay in progress for the attached client. @type {{ pos: number } | null} */
343
+ let pump = null;
344
+
345
+ const sockPath = socketPath(dirAbs);
346
+ try {
347
+ fs.rmSync(file('sock'), { force: true });
348
+ } catch {
349
+ // nothing to remove
350
+ }
351
+
352
+ const server = net.createServer((sock) => onConnection(sock));
353
+ server.on('error', (err) => {
354
+ note(`socket server failed: ${err && err.message}`);
355
+ // Without a socket nobody can attach: stop the child, keep the log.
356
+ stopChild('socket_failed');
357
+ });
358
+ server.listen(sockPath, () => {
359
+ try {
360
+ fs.chmodSync(file('sock'), 0o600);
361
+ } catch {
362
+ // the 0700 directory still protects it
363
+ }
364
+ startNoHostTimer();
365
+ startGuard();
366
+ });
367
+
368
+ /** Path to bind and connect: <dir>/sock, or a short alias in /tmp when that
369
+ * is longer than a unix socket path may be. Same rule as the daemon's client. */
370
+ function socketPath(hostDir) {
371
+ const direct = path.join(hostDir, 'sock');
372
+ if (Buffer.byteLength(direct) < 100) return direct;
373
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
374
+ const base = path.join('/tmp', `rbsh-${uid}`);
375
+ const alias = path.join(base, path.basename(hostDir));
376
+ try {
377
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
378
+ const st = fs.lstatSync(base);
379
+ if (!st.isDirectory() || (typeof process.getuid === 'function' && st.uid !== process.getuid())) {
380
+ throw new Error(`${base} is not ours`);
381
+ }
382
+ fs.chmodSync(base, 0o700);
383
+ let target = null;
384
+ try {
385
+ target = fs.readlinkSync(alias);
386
+ } catch {
387
+ // no alias yet
388
+ }
389
+ if (target !== hostDir) {
390
+ // unlink, not rm: rm skips a link whose target is gone.
391
+ unlinkQuiet(alias);
392
+ fs.symlinkSync(hostDir, alias);
393
+ }
394
+ } catch (err) {
395
+ note(`socket alias failed: ${err && err.message}`);
396
+ return direct;
397
+ }
398
+ return path.join(alias, 'sock');
399
+ }
400
+
401
+ function reply(sock, obj) {
402
+ try {
403
+ sock.end(JSON.stringify(obj) + '\n');
404
+ } catch {
405
+ // client already gone
406
+ }
407
+ }
408
+
409
+ function onConnection(sock) {
410
+ sock.on('error', () => {
411
+ // close follows
412
+ });
413
+ let head = Buffer.alloc(0);
414
+ const onData = (chunk) => {
415
+ head = head.length ? Buffer.concat([head, chunk]) : chunk;
416
+ const nl = head.indexOf(10);
417
+ if (nl === -1) {
418
+ if (head.length > MAX_REQUEST_LINE) {
419
+ sock.off('data', onData);
420
+ reply(sock, { ok: false, error: 'bad_request' });
421
+ }
422
+ return;
423
+ }
424
+ sock.off('data', onData);
425
+ const line = head.subarray(0, nl).toString('utf8');
426
+ const rest = head.subarray(nl + 1);
427
+ let req = null;
428
+ try {
429
+ req = JSON.parse(line);
430
+ } catch {
431
+ req = null;
432
+ }
433
+ handleRequest(sock, req, rest);
434
+ };
435
+ sock.on('data', onData);
436
+ }
437
+
438
+ function handleRequest(sock, req, rest) {
439
+ if (!req || typeof req !== 'object' || Array.isArray(req)) {
440
+ reply(sock, { ok: false, error: 'bad_request' });
441
+ return;
442
+ }
443
+ if (req.v !== PROTOCOL) {
444
+ reply(sock, { ok: false, error: 'unsupported_version', versions: [PROTOCOL] });
445
+ return;
446
+ }
447
+ switch (req.op) {
448
+ case 'status':
449
+ reply(sock, { ok: true, ...statusBody() });
450
+ return;
451
+ case 'attach':
452
+ attach(sock, req, rest);
453
+ return;
454
+ case 'signal': {
455
+ const signal = typeof req.signal === 'string' ? req.signal : '';
456
+ if (!SIGNALS.has(signal)) {
457
+ reply(sock, { ok: false, error: 'bad_signal' });
458
+ return;
459
+ }
460
+ if (exited) {
461
+ reply(sock, { ok: false, error: 'exited' });
462
+ return;
463
+ }
464
+ note(`signal ${signal} requested`);
465
+ try {
466
+ child.kill(signal);
467
+ } catch {
468
+ // gone meanwhile; the exit path reports it
469
+ }
470
+ reply(sock, { ok: true });
471
+ return;
472
+ }
473
+ case 'eof':
474
+ if (!stdinClosed) {
475
+ stdinClosed = true;
476
+ note('stdin EOF requested');
477
+ try {
478
+ child.stdin.end();
479
+ } catch {
480
+ // already closed
481
+ }
482
+ }
483
+ reply(sock, { ok: true });
484
+ return;
485
+ case 'ack': {
486
+ const upto = req.upto;
487
+ if (!Number.isSafeInteger(upto) || upto < 0) {
488
+ reply(sock, { ok: false, error: 'bad_offset' });
489
+ return;
490
+ }
491
+ if (upto > acked) acked = Math.min(upto, lineEnd);
492
+ maybeRotate();
493
+ reply(sock, { ok: true, acked, oldest });
494
+ return;
495
+ }
496
+ case 'limit': {
497
+ const ms = req.noHostMs;
498
+ if (!Number.isSafeInteger(ms) || ms < 1_000) {
499
+ reply(sock, { ok: false, error: 'bad_limit' });
500
+ return;
501
+ }
502
+ noHostMs = ms;
503
+ if (!client) startNoHostTimer();
504
+ reply(sock, { ok: true, noHostMs });
505
+ return;
506
+ }
507
+ default:
508
+ reply(sock, { ok: false, error: 'unsupported_op' });
509
+ }
510
+ }
511
+
512
+ function statusBody() {
513
+ return {
514
+ v: PROTOCOL,
515
+ end,
516
+ lineEnd,
517
+ oldest,
518
+ acked,
519
+ child: { pid: child.pid ?? null, command },
520
+ exited,
521
+ lossy,
522
+ lossyReason,
523
+ hostAttached: client !== null,
524
+ hostPid: process.pid,
525
+ noHostMs,
526
+ stdinClosed,
527
+ startedAt,
528
+ };
529
+ }
530
+
531
+ function attach(sock, req, rest) {
532
+ const after = req.after;
533
+ if (!Number.isSafeInteger(after) || after < oldest || after > end) {
534
+ reply(sock, { ok: false, error: 'bad_offset', oldest, end });
535
+ return;
536
+ }
537
+ if (after < end && (lossy || logFd === null)) {
538
+ reply(sock, { ok: false, error: 'lossy', end, lossyReason });
539
+ return;
540
+ }
541
+ if (client) dropClient('replaced');
542
+ client = sock;
543
+ stopNoHostTimer();
544
+ stopGuard();
545
+
546
+ const header = {
547
+ ok: true,
548
+ v: PROTOCOL,
549
+ after,
550
+ end,
551
+ lineEnd,
552
+ oldest,
553
+ child: { pid: child.pid ?? null, command },
554
+ exited,
555
+ lossy,
556
+ hostPid: process.pid,
557
+ };
558
+ sock.write(JSON.stringify(header) + '\n');
559
+
560
+ // stdin: only complete lines reach the child
561
+ const parts = [];
562
+ let partsLen = 0;
563
+ const onStdin = (chunk) => {
564
+ if (client !== sock) return;
565
+ const nl = chunk.lastIndexOf(10);
566
+ if (nl === -1) {
567
+ parts.push(chunk);
568
+ partsLen += chunk.length;
569
+ if (partsLen > MAX_PENDING_STDIN) {
570
+ note('stdin line too long, dropping the client');
571
+ dropClient('stdin_line_too_long');
572
+ }
573
+ return;
574
+ }
575
+ parts.push(chunk.subarray(0, nl + 1));
576
+ const out = parts.length === 1 ? parts[0] : Buffer.concat(parts);
577
+ parts.length = 0;
578
+ partsLen = 0;
579
+ if (nl + 1 < chunk.length) {
580
+ const tail = Buffer.from(chunk.subarray(nl + 1));
581
+ parts.push(tail);
582
+ partsLen = tail.length;
583
+ }
584
+ if (stdinClosed || exited) return;
585
+ if (!child.stdin.write(out)) {
586
+ sock.pause();
587
+ child.stdin.once('drain', () => {
588
+ if (client === sock) sock.resume();
589
+ });
590
+ }
591
+ };
592
+ sock.on('data', onStdin);
593
+ sock.on('close', () => {
594
+ // The half line a dying daemon left is dropped (rule 3).
595
+ parts.length = 0;
596
+ partsLen = 0;
597
+ if (client !== sock) return;
598
+ client = null;
599
+ pump = null;
600
+ if (!exited) {
601
+ startNoHostTimer();
602
+ startGuard();
603
+ } else {
604
+ maybeFinish();
605
+ }
606
+ });
607
+ if (rest.length > 0) onStdin(rest);
608
+
609
+ if (after < end) {
610
+ pump = { pos: after };
611
+ void runPump(sock, pump);
612
+ } else if (exited && stdoutEnded) {
613
+ sock.end();
614
+ }
615
+ }
616
+
617
+ /** Send the log from the attach offset, then switch to live forwarding.
618
+ * Single-threaded: the switch happens in the same tick as the last read, so
619
+ * no live chunk slips between the two. */
620
+ async function runPump(sock, p) {
621
+ const buf = Buffer.alloc(REPLAY_CHUNK);
622
+ while (client === sock && pump === p) {
623
+ if (p.pos >= end) {
624
+ pump = null;
625
+ if (exited && stdoutEnded) sock.end();
626
+ maybeRotate();
627
+ return;
628
+ }
629
+ const want = Math.min(REPLAY_CHUNK, end - p.pos);
630
+ let n = 0;
631
+ try {
632
+ n = fs.readSync(logFd, buf, 0, want, LOG_HEADER_LEN + (p.pos - oldest));
633
+ } catch (err) {
634
+ note(`replay read failed: ${err && err.code}`);
635
+ dropClient('replay_failed');
636
+ return;
637
+ }
638
+ if (n <= 0) {
639
+ note('replay read short');
640
+ dropClient('replay_failed');
641
+ return;
642
+ }
643
+ p.pos += n;
644
+ const more = sock.write(Buffer.from(buf.subarray(0, n)));
645
+ if (!more) {
646
+ await new Promise((resolve) => {
647
+ const done = () => {
648
+ sock.off('drain', done);
649
+ sock.off('close', done);
650
+ resolve();
651
+ };
652
+ sock.on('drain', done);
653
+ sock.on('close', done);
654
+ });
655
+ }
656
+ }
657
+ }
658
+
659
+ function sendLive(chunk) {
660
+ const sock = client;
661
+ if (!sock) return;
662
+ sock.write(chunk);
663
+ if (sock.writableLength > BACKLOG_LIMIT) {
664
+ note(`daemon reads too slowly (${sock.writableLength} bytes queued), dropping it`);
665
+ dropClient('backlog');
666
+ }
667
+ }
668
+
669
+ function dropClient(reason) {
670
+ const sock = client;
671
+ if (!sock) return;
672
+ client = null;
673
+ pump = null;
674
+ note(`client dropped: ${reason}`);
675
+ sock.destroy();
676
+ if (!exited) {
677
+ startNoHostTimer();
678
+ startGuard();
679
+ }
680
+ }
681
+
682
+ // ---------------------------------------------------------------------------
683
+ // No-host limit
684
+ // ---------------------------------------------------------------------------
685
+
686
+ /** @type {ReturnType<typeof setTimeout> | null} */
687
+ let noHostTimer = null;
688
+
689
+ function startNoHostTimer() {
690
+ stopNoHostTimer();
691
+ if (exited || client) return;
692
+ noHostTimer = setTimeout(() => {
693
+ noHostTimer = null;
694
+ if (!client) stopChild(`no daemon attached for ${noHostMs} ms`);
695
+ }, noHostMs);
696
+ }
697
+
698
+ function stopNoHostTimer() {
699
+ if (noHostTimer) clearTimeout(noHostTimer);
700
+ noHostTimer = null;
701
+ }
702
+
703
+ // ---------------------------------------------------------------------------
704
+ // Downgrade guard
705
+ // ---------------------------------------------------------------------------
706
+
707
+ /** @type {ReturnType<typeof setInterval> | null} */
708
+ let guardTimer = null;
709
+ /** @type {number | null} */
710
+ let guardDeadline = null;
711
+ /** @type {string | null} */
712
+ let guardBootId = null;
713
+ let guardBusy = false;
714
+
715
+ function startGuard() {
716
+ if (!daemonUrl || guardTimer || exited || client) return;
717
+ guardDeadline = null;
718
+ guardBootId = null;
719
+ guardTimer = setInterval(guardTick, GUARD_POLL_MS);
720
+ }
721
+
722
+ function stopGuard() {
723
+ if (guardTimer) clearInterval(guardTimer);
724
+ guardTimer = null;
725
+ guardDeadline = null;
726
+ }
727
+
728
+ function guardTick() {
729
+ if (guardBusy || client || exited) return;
730
+ guardBusy = true;
731
+ askDaemon((answer) => {
732
+ guardBusy = false;
733
+ if (client || exited || !guardTimer) return;
734
+ if (answer.kind === 'down') {
735
+ // Daemon down or busy: wait for it. A new daemon gets a fresh deadline.
736
+ guardDeadline = null;
737
+ return;
738
+ }
739
+ if (answer.kind === 'supported') {
740
+ if (guardBootId !== answer.bootId) {
741
+ guardBootId = answer.bootId;
742
+ guardDeadline = Date.now() + GUARD_ATTACH_MS;
743
+ return;
744
+ }
745
+ if (guardDeadline === null) guardDeadline = Date.now() + GUARD_ATTACH_MS;
746
+ else if (Date.now() >= guardDeadline) {
747
+ stopGuard();
748
+ stopChild('the daemon did not attach');
749
+ }
750
+ return;
751
+ }
752
+ stopGuard();
753
+ stopChild(`the daemon cannot adopt this host (${answer.detail})`);
754
+ });
755
+ }
756
+
757
+ /** GET the daemon's protocol list. down: no answer (refused, timeout);
758
+ * supported: lists this protocol; other: anything else. */
759
+ function askDaemon(done) {
760
+ let settled = false;
761
+ const settle = (answer) => {
762
+ if (settled) return;
763
+ settled = true;
764
+ done(answer);
765
+ };
766
+ let req;
767
+ try {
768
+ req = http.get(`${daemonUrl}/api/session-hosts/protocol`, { timeout: 1_500 }, (res) => {
769
+ const chunks = [];
770
+ let size = 0;
771
+ res.on('data', (c) => {
772
+ size += c.length;
773
+ if (size <= 64 * 1024) chunks.push(c);
774
+ });
775
+ res.on('end', () => {
776
+ if (res.statusCode !== 200) {
777
+ settle({ kind: 'other', detail: `HTTP ${res.statusCode}` });
778
+ return;
779
+ }
780
+ let body = null;
781
+ try {
782
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
783
+ } catch {
784
+ settle({ kind: 'other', detail: 'not JSON' });
785
+ return;
786
+ }
787
+ if (body && Array.isArray(body.protocols) && body.protocols.includes(PROTOCOL)) {
788
+ settle({ kind: 'supported', bootId: typeof body.bootId === 'string' ? body.bootId : null });
789
+ } else {
790
+ settle({ kind: 'other', detail: 'protocol not listed' });
791
+ }
792
+ });
793
+ res.on('error', () => settle({ kind: 'down' }));
794
+ });
795
+ } catch {
796
+ settle({ kind: 'down' });
797
+ return;
798
+ }
799
+ req.on('timeout', () => {
800
+ req.destroy();
801
+ settle({ kind: 'down' });
802
+ });
803
+ req.on('error', () => settle({ kind: 'down' }));
804
+ }
805
+
806
+ // ---------------------------------------------------------------------------
807
+ // Exit
808
+ // ---------------------------------------------------------------------------
809
+
810
+ let finishing = false;
811
+
812
+ /** Exit once the child is gone, its stdout drained and the attached daemon
813
+ * has everything (or at the cap set in onChildExit). */
814
+ function maybeFinish() {
815
+ if (!exited || !stdoutEnded || finishing) return;
816
+ if (client && pump) return; // the pump ends the socket when it is done
817
+ if (client) {
818
+ const sock = client;
819
+ sock.end();
820
+ sock.once('close', () => finish());
821
+ return;
822
+ }
823
+ finish();
824
+ }
825
+
826
+ function finish() {
827
+ if (finishing) return;
828
+ finishing = true;
829
+ try {
830
+ server.close();
831
+ } catch {
832
+ // not listening
833
+ }
834
+ try {
835
+ fs.rmSync(file('sock'), { force: true });
836
+ } catch {
837
+ // gone already
838
+ }
839
+ if (sockPath !== path.join(dirAbs, 'sock')) unlinkQuiet(path.dirname(sockPath));
840
+ try {
841
+ if (logFd !== null) fs.closeSync(logFd);
842
+ } catch {
843
+ // closing anyway
844
+ }
845
+ process.exit(0);
846
+ }
847
+
848
+ process.on('SIGTERM', () => stopChild('host got SIGTERM'));
849
+ process.on('SIGINT', () => stopChild('host got SIGINT'));
850
+ process.on('SIGHUP', () => {
851
+ // detached; a closing terminal or session is no reason to stop the child
852
+ });
853
+ process.on('SIGPIPE', () => {});
854
+ process.on('uncaughtException', (err) => {
855
+ note(`uncaught: ${err && err.stack ? err.stack : err}`);
856
+ });
857
+ process.on('unhandledRejection', (err) => {
858
+ note(`unhandled rejection: ${err && err.stack ? err.stack : err}`);
859
+ });
860
+