@gwro/codeaside 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ // Client side of the session host: connect to its named pipe, start it when it
2
+ // isn't running, and relay a console to a session (the `tmux attach` of this port).
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
5
+ import { connect as netConnect } from "node:net";
6
+ import { homedir, userInfo } from "node:os";
7
+ import { dirname, join, resolve } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const HERE = dirname(fileURLToPath(import.meta.url));
11
+ export const HOST_SCRIPT = join(HERE, "host.mjs");
12
+
13
+ /** The one host per Windows user listens here. */
14
+ export function defaultPipe() {
15
+ const user = (userInfo().username || "user").replace(/[^A-Za-z0-9_-]/g, "_");
16
+ return `\\\\.\\pipe\\codeaside-host-${user}`;
17
+ }
18
+
19
+ /** Keys the hub may press, and the bytes a terminal would send for them. */
20
+ export const KEYS = {
21
+ Enter: "\r",
22
+ // A lone ESC through the ConPTY input pipe waits out conhost's escape-sequence
23
+ // timeout; as a win32-input-mode key record (VK_ESCAPE down, up) it is immediate.
24
+ Escape: "\x1b[27;1;27;1;0;1_\x1b[27;1;27;0;0;1_",
25
+ Tab: "\t",
26
+ BTab: "\x1b[Z",
27
+ Up: "\x1b[A",
28
+ Down: "\x1b[B",
29
+ // Application cursor mode (DECCKM) variants; the host picks by the terminal's mode.
30
+ "Up:app": "\x1bOA",
31
+ "Down:app": "\x1bOB",
32
+ // Claude Code's menus (the trust dialog, model picker) ignore arrow keys that
33
+ // arrive through a ConPTY input pipe, but take vi keys. Only for menus: in the
34
+ // prompt box these type letters.
35
+ MenuUp: "k",
36
+ MenuDown: "j",
37
+ };
38
+ for (const d of "123456789") KEYS[d] = d;
39
+
40
+ /**
41
+ * Where Claude Code is. The npm shim (`claude.cmd`) wraps a native `claude.exe` next
42
+ * to it; the installer puts `claude.exe` in ~/.local/bin. ConPTY wants a real
43
+ * executable, so a `.cmd` that can't be unwrapped runs through cmd.exe.
44
+ * @returns {{cmd: string, args: string[], display: string} | null}
45
+ */
46
+ export function resolveClaude(preferred = "claude") {
47
+ if (/[\\/]/.test(preferred)) return existsSync(preferred) ? asCommand(preferred) : null;
48
+ const candidates = [];
49
+ const r = spawnSync("where.exe", [preferred], { encoding: "utf8" });
50
+ for (const line of (r.stdout || "").split(/\r?\n/)) {
51
+ const p = line.trim();
52
+ if (p) candidates.push(p);
53
+ }
54
+ const local = join(homedir(), ".local", "bin", `${preferred}.exe`);
55
+ if (existsSync(local)) candidates.push(local);
56
+ const own = resolve(HERE, "..");
57
+ const usable = candidates.filter((p) => !resolve(p).toLowerCase().startsWith(own.toLowerCase()));
58
+ const exe = usable.find((p) => /\.exe$/i.test(p));
59
+ if (exe) return asCommand(exe);
60
+ const cmd = usable.find((p) => /\.(cmd|bat)$/i.test(p));
61
+ if (cmd) {
62
+ const unwrapped = join(dirname(cmd), "node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe");
63
+ if (existsSync(unwrapped)) return asCommand(unwrapped);
64
+ return asCommand(cmd);
65
+ }
66
+ return null;
67
+ }
68
+
69
+ function asCommand(path) {
70
+ if (/\.(cmd|bat)$/i.test(path)) return { cmd: process.env.ComSpec || "cmd.exe", args: ["/d", "/c", path], display: path };
71
+ return { cmd: path, args: [], display: path };
72
+ }
73
+
74
+ /**
75
+ * Start the host detached and windowless, if the pipe doesn't answer.
76
+ *
77
+ * On Windows the host is started through wscript.exe, which starts it hidden and
78
+ * exits at once, so the host is nobody's child: killing the hub's or the CLI's
79
+ * process tree (taskkill /T, a stopped service) leaves it, and the Claude Code
80
+ * sessions it holds, running. `launcherDir` is where that one-line script lives.
81
+ */
82
+ export async function ensureHost(pipe = defaultPipe(), { logFile = null, launcherDir = null, timeoutMs = 6000 } = {}) {
83
+ if (await pipeAnswers(pipe)) return false;
84
+ if (logFile) mkdirSync(dirname(logFile), { recursive: true });
85
+ const args = [HOST_SCRIPT, "--pipe", pipe, ...(logFile ? ["--log", logFile] : [])];
86
+ if (process.platform === "win32" && launcherDir) {
87
+ mkdirSync(launcherDir, { recursive: true });
88
+ const launcher = join(launcherDir, "host-launcher.vbs");
89
+ const q = (s) => `""${String(s).replace(/"/g, '""')}""`;
90
+ writeFileSync(launcher, `Set sh = CreateObject("WScript.Shell")\r\nsh.Run "${[process.execPath, ...args].map(q).join(" ")}", 0, False\r\n`);
91
+ const wscript = join(process.env.SystemRoot || "C:\\Windows", "System32", "wscript.exe");
92
+ spawnSync(wscript, [launcher], { stdio: "ignore", windowsHide: true, timeout: 10000 });
93
+ } else {
94
+ const child = spawn(process.execPath, args, { detached: true, stdio: "ignore", windowsHide: true });
95
+ child.unref();
96
+ }
97
+ const until = Date.now() + timeoutMs;
98
+ while (Date.now() < until) {
99
+ await new Promise((r) => setTimeout(r, 100));
100
+ if (await pipeAnswers(pipe)) return true;
101
+ }
102
+ throw new Error(`the session host did not start within ${timeoutMs / 1000}s`);
103
+ }
104
+
105
+ export function pipeAnswers(pipe) {
106
+ return new Promise((done) => {
107
+ const s = netConnect(pipe);
108
+ s.once("connect", () => {
109
+ s.destroy();
110
+ done(true);
111
+ });
112
+ s.once("error", () => done(false));
113
+ });
114
+ }
115
+
116
+ /**
117
+ * A control connection: JSON requests, JSON replies. Reused across calls; a
118
+ * dropped connection is replaced on the next request.
119
+ */
120
+ export class HostClient {
121
+ constructor(pipe = defaultPipe()) {
122
+ this.pipe = pipe;
123
+ this.socket = null;
124
+ this.pending = new Map();
125
+ this.seq = 0;
126
+ this.buf = "";
127
+ }
128
+
129
+ connect() {
130
+ if (this.socket && !this.socket.destroyed) return Promise.resolve(this.socket);
131
+ if (this.connecting) return this.connecting;
132
+ this.connecting = new Promise((resolveConn, reject) => {
133
+ const s = netConnect(this.pipe);
134
+ s.setNoDelay?.(true);
135
+ s.once("connect", () => {
136
+ this.socket = s;
137
+ this.connecting = null;
138
+ resolveConn(s);
139
+ });
140
+ s.once("error", (err) => {
141
+ this.connecting = null;
142
+ if (this.socket === s) this.socket = null;
143
+ for (const [, p] of this.pending) p.reject(err);
144
+ this.pending.clear();
145
+ reject(err);
146
+ });
147
+ s.on("close", () => {
148
+ if (this.socket === s) this.socket = null;
149
+ for (const [, p] of this.pending) p.reject(new Error("host connection closed"));
150
+ this.pending.clear();
151
+ });
152
+ s.on("data", (chunk) => {
153
+ this.buf += chunk.toString("utf8");
154
+ let idx;
155
+ while ((idx = this.buf.indexOf("\n")) >= 0) {
156
+ const line = this.buf.slice(0, idx);
157
+ this.buf = this.buf.slice(idx + 1);
158
+ if (!line.trim()) continue;
159
+ let msg;
160
+ try {
161
+ msg = JSON.parse(line);
162
+ } catch {
163
+ continue;
164
+ }
165
+ const p = this.pending.get(msg.id);
166
+ if (!p) continue;
167
+ this.pending.delete(msg.id);
168
+ if (msg.ok) p.resolve(msg.result ?? {});
169
+ else p.reject(Object.assign(new Error(msg.error || "host error"), { code: msg.code }));
170
+ }
171
+ });
172
+ });
173
+ return this.connecting;
174
+ }
175
+
176
+ async request(op, params = {}, { timeout = 5000 } = {}) {
177
+ const s = await this.connect();
178
+ const id = ++this.seq;
179
+ return new Promise((resolveReq, reject) => {
180
+ const timer = setTimeout(() => {
181
+ this.pending.delete(id);
182
+ reject(new Error(`host did not answer ${op} within ${timeout}ms`));
183
+ }, timeout);
184
+ timer.unref?.();
185
+ this.pending.set(id, {
186
+ resolve: (m) => {
187
+ clearTimeout(timer);
188
+ resolveReq(m);
189
+ },
190
+ reject: (e) => {
191
+ clearTimeout(timer);
192
+ reject(e);
193
+ },
194
+ });
195
+ s.write(JSON.stringify({ id, op, ...params }) + "\n");
196
+ });
197
+ }
198
+
199
+ close() {
200
+ this.socket?.destroy();
201
+ this.socket = null;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * A session's screen with its styling: what the host paints for a client that
207
+ * attaches, as text with SGR codes. The connection is dropped once the screen
208
+ * has arrived. No size is sent, so the host keeps the session's own and nothing
209
+ * is resized. Resolves to "" when the host or the session isn't there.
210
+ */
211
+ export function styledScreen(pipe, session, { timeout = 1500, quiet = 60 } = {}) {
212
+ return new Promise((done) => {
213
+ const s = netConnect(pipe);
214
+ let buf = Buffer.alloc(0);
215
+ let quietTimer = null;
216
+ const finish = () => {
217
+ clearTimeout(quietTimer);
218
+ clearTimeout(limit);
219
+ s.destroy();
220
+ const text = buf.toString("utf8");
221
+ const nl = text.indexOf("\n"); // the JSON reply to the attach comes first, on its own line
222
+ let ok = false;
223
+ try {
224
+ ok = nl >= 0 && JSON.parse(text.slice(0, nl)).ok === true;
225
+ } catch {
226
+ /* not a reply */
227
+ }
228
+ done(ok ? text.slice(nl + 1) : "");
229
+ };
230
+ const limit = setTimeout(finish, timeout);
231
+ limit.unref?.();
232
+ s.once("connect", () => s.write(JSON.stringify({ id: 1, op: "attach", session }) + "\n"));
233
+ s.on("data", (chunk) => {
234
+ buf = Buffer.concat([buf, chunk]);
235
+ // The screen comes in one burst; what follows after a pause is live output.
236
+ clearTimeout(quietTimer);
237
+ quietTimer = setTimeout(finish, quiet);
238
+ });
239
+ s.once("error", finish);
240
+ s.once("close", finish);
241
+ });
242
+ }
243
+
244
+ // ConPTY asks the terminal for win32-input-mode at startup, and the relay passes
245
+ // that on, so Windows Terminal sends keys as `ESC [ Vk ; Sc ; Uc ; Kd ; Cs ; Rc _`
246
+ // records. Claude Code needs that fidelity (arrow keys, for one), so the records
247
+ // are forwarded as they are; only the detach chord is picked out of them.
248
+ const WIN32_KEY = /\x1b\[(\d+);(\d+);(\d+);(\d+);(\d+);(\d+)_/g;
249
+ const CTRL_RBRACKET = 0x1d;
250
+
251
+ /** Is Ctrl+] in this input chunk, in any of the ways a Windows terminal can send it? */
252
+ export function isDetachChord(chunk) {
253
+ if (chunk.length === 1 && chunk[0] === CTRL_RBRACKET) return true;
254
+ const s = chunk.toString("latin1");
255
+ if (/\x1b\[(93|221);5u/.test(s)) return true; // kitty keyboard protocol, Ctrl+]
256
+ for (const m of s.matchAll(WIN32_KEY)) {
257
+ const uc = Number(m[3]);
258
+ const keyDown = Number(m[4]) === 1;
259
+ if (keyDown && uc === CTRL_RBRACKET) return true;
260
+ }
261
+ return false;
262
+ }
263
+
264
+ // What the terminal is told on attach (win32-input-mode on, as ConPTY itself asks
265
+ // at startup) and on detach (every mode the session may have left on, off again).
266
+ const ATTACH_MODES = "\x1b[?9001h";
267
+ const DETACH_RESET = "\x1b[?9001l\x1b[?2004l\x1b[?1004l\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[<u\x1b[?25h\x1b[0m";
268
+
269
+ /**
270
+ * Relay this console to a session until it ends or the user detaches (Ctrl+]).
271
+ * @returns {Promise<{reason: "detached"|"ended"|"lost", exitCode?: number}>}
272
+ */
273
+ export function attach({ pipe = defaultPipe(), id, stdin = process.stdin, stdout = process.stdout }) {
274
+ return new Promise((done, fail) => {
275
+ const s = netConnect(pipe);
276
+ let finished = false;
277
+ let header = "";
278
+ let headerDone = false;
279
+ const finish = (result) => {
280
+ if (finished) return;
281
+ finished = true;
282
+ cleanup();
283
+ done(result);
284
+ };
285
+ const send = (msg) => {
286
+ if (!s.destroyed) s.write(JSON.stringify(msg) + "\n");
287
+ };
288
+ const onResize = () => send({ op: "resize", cols: stdout.columns || 80, rows: stdout.rows || 24 });
289
+ const onInput = (chunk) => {
290
+ if (process.env.CODEASIDE_ATTACH_DEBUG) appendFileSync(process.env.CODEASIDE_ATTACH_DEBUG, `${Date.now()} in ${JSON.stringify(chunk.toString("latin1"))}\n`);
291
+ if (isDetachChord(chunk)) {
292
+ // Ctrl+]: detach, leaving the session running.
293
+ send({ op: "detach" });
294
+ return finish({ reason: "detached" });
295
+ }
296
+ send({ op: "input", data: chunk.toString("base64") });
297
+ };
298
+ const wasRaw = stdin.isRaw;
299
+ const cleanup = () => {
300
+ stdin.off("data", onInput);
301
+ stdout.off("resize", onResize);
302
+ if (headerDone) stdout.write(DETACH_RESET);
303
+ if (stdin.isTTY) stdin.setRawMode(!!wasRaw);
304
+ stdin.pause();
305
+ s.destroy();
306
+ };
307
+ s.once("connect", () => {
308
+ send({ op: "attach", session: id, cols: stdout.columns || 80, rows: stdout.rows || 24 });
309
+ if (stdin.isTTY) stdin.setRawMode(true);
310
+ stdin.resume();
311
+ stdin.on("data", onInput);
312
+ stdout.on("resize", onResize);
313
+ });
314
+ s.on("data", (chunk) => {
315
+ if (!headerDone) {
316
+ // The first line is the host's answer; everything after it is terminal output.
317
+ header += chunk.toString("latin1");
318
+ const nl = header.indexOf("\n");
319
+ if (nl < 0) return;
320
+ headerDone = true;
321
+ let reply;
322
+ try {
323
+ reply = JSON.parse(header.slice(0, nl));
324
+ } catch {
325
+ reply = { ok: false, error: "bad reply from host" };
326
+ }
327
+ if (!reply.ok) {
328
+ cleanup();
329
+ return fail(new Error(reply.error || "attach failed"));
330
+ }
331
+ stdout.write(ATTACH_MODES);
332
+ const rest = Buffer.from(header.slice(nl + 1), "latin1");
333
+ if (rest.length) stdout.write(rest);
334
+ return;
335
+ }
336
+ stdout.write(chunk);
337
+ });
338
+ s.on("close", () => finish({ reason: "lost" }));
339
+ s.on("error", (err) => {
340
+ if (finished) return;
341
+ finished = true;
342
+ cleanup();
343
+ fail(err);
344
+ });
345
+ });
346
+ }
package/host/host.mjs ADDED
@@ -0,0 +1,336 @@
1
+ // The session host: the tmux server of this port. Runs Claude Code in ConPTY
2
+ // pseudo-consoles, keeps a headless terminal screen for each, and lets the hub
3
+ // and the CLI type into them, read them back, and attach a console, over a
4
+ // user-private named pipe. Kept small and separate from the hub so a hub restart
5
+ // never ends a session.
6
+ import { createServer } from "node:net";
7
+ import { appendFileSync, mkdirSync } from "node:fs";
8
+ import { dirname, resolve } from "node:path";
9
+ import { randomBytes } from "node:crypto";
10
+ import { fileURLToPath } from "node:url";
11
+ import pty from "@lydell/node-pty";
12
+ import xterm from "@xterm/headless";
13
+ import serialize from "@xterm/addon-serialize";
14
+ import { KEYS, defaultPipe } from "./client.mjs";
15
+
16
+ const { Terminal } = xterm;
17
+ const { SerializeAddon } = serialize;
18
+
19
+ const SCROLLBACK = 5000;
20
+ const DEFAULT_SIZE = { cols: 200, rows: 50 }; // for sessions nobody is attached to
21
+ const MIN_SIZE = { cols: 20, rows: 5 };
22
+ const IDLE_EXIT_MS = 10_000; // no sessions and no clients for this long: exit, like tmux
23
+ // A host started from inside a Claude Code session (a hub run from Claude's shell)
24
+ // would pass these on, and Claude Code then treats the new session as a nested
25
+ // child: no transcript, different hooks. Each session is its own.
26
+ const NESTED_SESSION_MARKERS = /^(CLAUDECODE|CLAUDE_CODE_(CHILD_SESSION|SESSION_ID|SESSION_ATTENDED|ENTRYPOINT|EXECPATH|MESSAGING_SOCKET|MESSAGING_TOKEN|BRIDGE_SESSION_ID|SSE_PORT))$/;
27
+ const STARTUP_GRACE_MS = 30_000;
28
+
29
+ export function startHost({ pipe = defaultPipe(), log = () => {}, exitWhenIdle = true } = {}) {
30
+ /** @type {Map<string, Session>} */
31
+ const sessions = new Map();
32
+ const connections = new Set();
33
+ let lastActivity = Date.now();
34
+ let everHadSession = false;
35
+
36
+ class Session {
37
+ constructor({ name, cwd, cmd, args, env, cols, rows }) {
38
+ this.id = randomBytes(4).toString("hex");
39
+ this.name = name;
40
+ this.cwd = cwd;
41
+ this.cmd = cmd;
42
+ this.args = args;
43
+ this.title = "";
44
+ this.startedAt = Date.now();
45
+ this.exitCode = null;
46
+ this.cols = cols;
47
+ this.rows = rows;
48
+ /** @type {Set<import("node:net").Socket>} */
49
+ this.attached = new Set();
50
+ this.term = new Terminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true });
51
+ this.serializer = new SerializeAddon();
52
+ this.term.loadAddon(this.serializer);
53
+ this.term.onTitleChange((t) => {
54
+ this.title = t;
55
+ });
56
+ const fullEnv = {};
57
+ for (const [k, v] of Object.entries({ ...process.env, ...env })) if (v !== undefined && v !== null && !NESTED_SESSION_MARKERS.test(k)) fullEnv[k] = String(v);
58
+ fullEnv.CODEASIDE_HOST = pipe;
59
+ fullEnv.CODEASIDE_PANE = this.id;
60
+ this.pty = pty.spawn(cmd, args, { name: "xterm-256color", cols, rows, cwd, env: fullEnv, useConpty: true });
61
+ this.pty.onData((data) => {
62
+ this.term.write(data);
63
+ for (const s of this.attached) if (!s.destroyed) s.write(data);
64
+ });
65
+ this.pty.onExit(({ exitCode }) => {
66
+ this.exitCode = exitCode ?? 0;
67
+ log(`session ${this.name} (${this.id}) exited ${this.exitCode}`);
68
+ if (this.exitCode !== 0) {
69
+ // A failed start is only ever diagnosable from what it printed.
70
+ const tail = this.screen(12).split("\n").filter((l) => l.trim());
71
+ if (tail.length) log(` last lines:\n ${tail.join("\n ")}`);
72
+ }
73
+ for (const s of this.attached) {
74
+ if (s.destroyed) continue;
75
+ s.write(`\r\n\x1b[0m[codeaside] session ended (exit ${this.exitCode})\r\n`);
76
+ s.end();
77
+ }
78
+ this.attached.clear();
79
+ sessions.delete(this.id);
80
+ touch();
81
+ // node-pty leaves the input pipe and its conout worker open after a natural
82
+ // exit; kill() on the finished pty releases them.
83
+ setTimeout(() => {
84
+ try {
85
+ this.pty.kill();
86
+ } catch {
87
+ /* already released */
88
+ }
89
+ }, 50).unref?.();
90
+ });
91
+ }
92
+
93
+ get pid() {
94
+ return this.pty.pid || null;
95
+ }
96
+
97
+ get alive() {
98
+ return this.exitCode === null;
99
+ }
100
+
101
+ /** The last `lines` logical lines of the screen and scrollback, wrapped rows joined. */
102
+ screen(lines = 60) {
103
+ // Scrollback plus the viewport, like `capture-pane -J`, minus the blank
104
+ // rows under the last thing drawn, so a short screen isn't all blanks.
105
+ const b = this.term.buffer.active;
106
+ const out = [];
107
+ for (let i = 0; i < b.length; i++) {
108
+ const line = b.getLine(i);
109
+ if (!line) continue;
110
+ const text = line.translateToString(true).replace(/\s+$/, "");
111
+ if (line.isWrapped && out.length) out[out.length - 1] += text;
112
+ else out.push(text);
113
+ }
114
+ while (out.length && !out[out.length - 1]) out.pop();
115
+ return out.slice(-lines).join("\n");
116
+ }
117
+
118
+ write(data) {
119
+ this.pty.write(data);
120
+ }
121
+
122
+ key(name) {
123
+ let seq = KEYS[name];
124
+ if (seq === undefined) throw hostError(400, `key not allowed: ${name}`);
125
+ if ((name === "Up" || name === "Down") && this.term.modes.applicationCursorKeysMode) seq = KEYS[`${name}:app`];
126
+ this.pty.write(seq);
127
+ }
128
+
129
+ resize(cols, rows) {
130
+ cols = Math.max(MIN_SIZE.cols, Math.floor(cols) || DEFAULT_SIZE.cols);
131
+ rows = Math.max(MIN_SIZE.rows, Math.floor(rows) || DEFAULT_SIZE.rows);
132
+ if (cols === this.cols && rows === this.rows) return;
133
+ this.cols = cols;
134
+ this.rows = rows;
135
+ this.term.resize(cols, rows);
136
+ this.pty.resize(cols, rows);
137
+ }
138
+
139
+ attach(socket, cols, rows) {
140
+ this.attached.add(socket);
141
+ // Paint the current screen, then let ConPTY repaint for the client's size.
142
+ socket.write("\x1b[H\x1b[2J" + this.serializer.serialize({ scrollback: 0 }));
143
+ if (this.title) socket.write(`\x1b]0;${this.title}\x07`);
144
+ this.resize(cols, rows);
145
+ socket.on("close", () => this.attached.delete(socket));
146
+ }
147
+
148
+ kill() {
149
+ try {
150
+ this.pty.kill();
151
+ } catch {
152
+ /* already gone */
153
+ }
154
+ }
155
+
156
+ summary() {
157
+ return { id: this.id, name: this.name, cwd: this.cwd, pid: this.pid, title: this.title, attached: this.attached.size, alive: this.alive, startedAt: this.startedAt, cols: this.cols, rows: this.rows };
158
+ }
159
+ }
160
+
161
+ function hostError(code, message) {
162
+ return Object.assign(new Error(message), { code });
163
+ }
164
+
165
+ function touch() {
166
+ lastActivity = Date.now();
167
+ }
168
+
169
+ function uniqueName(base) {
170
+ const clean = (base || "claude").replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 24) || "claude";
171
+ const taken = new Set([...sessions.values()].map((s) => s.name));
172
+ let name = clean;
173
+ for (let n = 2; taken.has(name); n++) name = `${clean}-${n}`;
174
+ return name;
175
+ }
176
+
177
+ function sessionOr404(id) {
178
+ const s = sessions.get(id) || [...sessions.values()].find((x) => x.name === id);
179
+ if (!s) throw hostError(404, `no session ${id}`);
180
+ return s;
181
+ }
182
+
183
+ const ops = {
184
+ ping: () => ({ pid: process.pid, sessions: sessions.size }),
185
+ list: () => ({ sessions: [...sessions.values()].map((s) => s.summary()) }),
186
+ new({ name, cwd, cmd, args = [], env = {}, cols, rows }) {
187
+ if (!cmd) throw hostError(400, "cmd required");
188
+ if (!cwd) throw hostError(400, "cwd required");
189
+ const s = new Session({ name: uniqueName(name), cwd, cmd, args, env, cols: cols || DEFAULT_SIZE.cols, rows: rows || DEFAULT_SIZE.rows });
190
+ sessions.set(s.id, s);
191
+ everHadSession = true;
192
+ touch();
193
+ log(`new session ${s.name} (${s.id}): ${cmd} ${args.join(" ")} in ${cwd}`);
194
+ return { id: s.id, name: s.name, pid: s.pid };
195
+ },
196
+ alive({ session }) {
197
+ const s = sessions.get(session);
198
+ return { alive: !!s && s.alive, name: s?.name, pid: s?.pid ?? null };
199
+ },
200
+ screen({ session, lines = 60 }) {
201
+ return { text: sessionOr404(session).screen(Math.min(Number(lines) || 60, SCROLLBACK)) };
202
+ },
203
+ write({ session, data }) {
204
+ sessionOr404(session).write(String(data ?? ""));
205
+ return {};
206
+ },
207
+ key({ session, key }) {
208
+ sessionOr404(session).key(String(key));
209
+ return {};
210
+ },
211
+ resize({ session, cols, rows }) {
212
+ sessionOr404(session).resize(Number(cols), Number(rows));
213
+ return {};
214
+ },
215
+ kill({ session }) {
216
+ sessionOr404(session).kill();
217
+ return {};
218
+ },
219
+ };
220
+
221
+ const server = createServer((socket) => {
222
+ connections.add(socket);
223
+ touch();
224
+ let buf = "";
225
+ let attachedTo = null;
226
+ socket.setNoDelay?.(true);
227
+ socket.on("data", (chunk) => {
228
+ buf += chunk.toString("utf8");
229
+ let idx;
230
+ while ((idx = buf.indexOf("\n")) >= 0) {
231
+ const line = buf.slice(0, idx);
232
+ buf = buf.slice(idx + 1);
233
+ if (!line.trim()) continue;
234
+ let msg;
235
+ try {
236
+ msg = JSON.parse(line);
237
+ } catch {
238
+ continue;
239
+ }
240
+ if (attachedTo) {
241
+ if (msg.op === "input" && typeof msg.data === "string") attachedTo.write(Buffer.from(msg.data, "base64").toString("utf8"));
242
+ else if (msg.op === "resize") attachedTo.resize(Number(msg.cols), Number(msg.rows));
243
+ else if (msg.op === "detach") socket.end();
244
+ continue;
245
+ }
246
+ if (msg.op === "attach") {
247
+ try {
248
+ const s = sessionOr404(msg.session);
249
+ socket.write(JSON.stringify({ id: msg.id, ok: true, name: s.name }) + "\n");
250
+ attachedTo = s;
251
+ s.attach(socket, Number(msg.cols) || s.cols, Number(msg.rows) || s.rows);
252
+ } catch (err) {
253
+ socket.end(JSON.stringify({ id: msg.id, ok: false, error: err.message, code: err.code }) + "\n");
254
+ }
255
+ continue;
256
+ }
257
+ const fn = ops[msg.op];
258
+ let reply;
259
+ try {
260
+ if (!fn) throw hostError(400, `unknown op ${msg.op}`);
261
+ reply = { id: msg.id, ok: true, result: fn(msg) };
262
+ } catch (err) {
263
+ reply = { id: msg.id, ok: false, error: err.message, code: err.code || 500 };
264
+ }
265
+ if (!socket.destroyed) socket.write(JSON.stringify(reply) + "\n");
266
+ }
267
+ });
268
+ socket.on("close", () => {
269
+ connections.delete(socket);
270
+ touch();
271
+ });
272
+ socket.on("error", () => {});
273
+ });
274
+
275
+ server.listen(pipe, () => log(`host listening on ${pipe}`));
276
+
277
+ let idleTimer = null;
278
+ if (exitWhenIdle) {
279
+ const started = Date.now();
280
+ idleTimer = setInterval(() => {
281
+ const quietFor = Date.now() - lastActivity;
282
+ const pastGrace = everHadSession || Date.now() - started > STARTUP_GRACE_MS;
283
+ // Control connections don't count: the hub keeps one open for as long as it
284
+ // runs, and a host with nothing to hold should still make way for a newer one.
285
+ if (sessions.size === 0 && quietFor > IDLE_EXIT_MS && pastGrace) {
286
+ log("no sessions and no clients; exiting");
287
+ close();
288
+ process.exit(0);
289
+ }
290
+ }, 2000);
291
+ }
292
+
293
+ function close() {
294
+ clearInterval(idleTimer);
295
+ for (const s of connections) s.destroy();
296
+ server.close();
297
+ }
298
+
299
+ return { server, sessions, pipe, close };
300
+ }
301
+
302
+ // ---------- standalone ----------
303
+ const isMain = process.argv[1] && resolve(process.argv[1]).toLowerCase() === resolve(fileURLToPath(import.meta.url)).toLowerCase();
304
+ if (isMain) {
305
+ const argv = process.argv.slice(2);
306
+ const arg = (flag) => {
307
+ const i = argv.indexOf(flag);
308
+ return i >= 0 ? argv[i + 1] : null;
309
+ };
310
+ const pipe = arg("--pipe") || defaultPipe();
311
+ const logFile = arg("--log");
312
+ const log = (msg) => {
313
+ const line = `[${new Date().toISOString()}] ${msg}\n`;
314
+ if (logFile) {
315
+ try {
316
+ mkdirSync(dirname(logFile), { recursive: true });
317
+ appendFileSync(logFile, line);
318
+ } catch {
319
+ /* no log */
320
+ }
321
+ } else process.stdout.write(line);
322
+ };
323
+ const host = startHost({ pipe, log });
324
+ host.server.on("error", (err) => {
325
+ log(`cannot listen on ${pipe}: ${err.message}`);
326
+ process.exit(1);
327
+ });
328
+ process.on("uncaughtException", (err) => log(`uncaught: ${err.stack || err.message}`));
329
+ const stop = () => {
330
+ for (const s of host.sessions.values()) s.kill();
331
+ host.close();
332
+ process.exit(0);
333
+ };
334
+ process.on("SIGINT", stop);
335
+ process.on("SIGTERM", stop);
336
+ }