@particle-academy/fancy-term-host 0.1.1 → 0.2.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.
@@ -0,0 +1,508 @@
1
+ 'use strict';
2
+
3
+ var path3 = require('path');
4
+ var url = require('url');
5
+ var os2 = require('os');
6
+ var fs = require('fs');
7
+ require('crypto');
8
+ var child_process = require('child_process');
9
+ var fs3 = require('fs/promises');
10
+
11
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var path3__default = /*#__PURE__*/_interopDefault(path3);
15
+ var os2__default = /*#__PURE__*/_interopDefault(os2);
16
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
17
+ var fs3__default = /*#__PURE__*/_interopDefault(fs3);
18
+
19
+ // src/host-script.ts
20
+
21
+ // src/host-protocol.ts
22
+ var PROTOCOL_VERSION = 2;
23
+
24
+ // src/host-locate.ts
25
+ function resolveHostScript(dirname) {
26
+ const candidates = [
27
+ // Packaged: node-pty must be unpacked, so run the host from the unpacked
28
+ // tree too (its require('node-pty') resolves to the unpacked .node).
29
+ dirname.includes(`app.asar${path3__default.default.sep}`) || dirname.includes("app.asar/") ? dirname.replace(
30
+ /app\.asar([\\/])/,
31
+ `app.asar.unpacked$1`
32
+ ) + path3__default.default.sep + "pty-host.js" : "",
33
+ // Same dir as the compiled main bundle (dev: app/pty-host.js).
34
+ path3__default.default.join(dirname, "pty-host.js"),
35
+ // Defensive: a sibling unpacked dir computed from the asar path.
36
+ path3__default.default.join(dirname.replace("app.asar", "app.asar.unpacked"), "pty-host.js")
37
+ ].filter(Boolean);
38
+ for (const c of candidates) {
39
+ try {
40
+ if (fs__default.default.existsSync(c)) return c;
41
+ } catch {
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+
47
+ // src/host-script.ts
48
+ function ptyHostScriptPath() {
49
+ const here = typeof __dirname !== "undefined" ? __dirname : path3__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('service.cjs', document.baseURI).href))));
50
+ return resolveHostScript(here) ?? path3__default.default.join(here, "pty-host.js");
51
+ }
52
+ var SERVICE_REVISION = `svc1+proto${PROTOCOL_VERSION}`;
53
+ var REVISION_MARKER = "fancy-term-service-revision";
54
+ function servicePlatformFor(platform = process.platform) {
55
+ switch (platform) {
56
+ case "darwin":
57
+ return "launchd";
58
+ case "linux":
59
+ return "systemd";
60
+ case "win32":
61
+ return "windows-task";
62
+ default:
63
+ return null;
64
+ }
65
+ }
66
+ function buildServiceDescriptor(config, ctx = {}) {
67
+ const platform = ctx.platform ?? servicePlatformFor() ?? unsupported(config);
68
+ const home = ctx.home ?? os2__default.default.homedir();
69
+ switch (platform) {
70
+ case "launchd":
71
+ return launchd(config, home, ctx.uid ?? safeUid());
72
+ case "systemd":
73
+ return systemd(config, home);
74
+ case "windows-task":
75
+ return windowsTask(config);
76
+ }
77
+ }
78
+ function unsupported(config) {
79
+ throw new Error(
80
+ `fancy-term-host service: unsupported platform for "${config.label}"`
81
+ );
82
+ }
83
+ function safeUid() {
84
+ const getuid = process.getuid;
85
+ return typeof getuid === "function" ? getuid() : 0;
86
+ }
87
+ function serviceEnv(config) {
88
+ const env = {
89
+ ...config.env,
90
+ // GENIE_USERDATA is the var the existing detached-spawn path already uses
91
+ // (see host-lifecycle.spawnDetached); keep it so the host finds its data.
92
+ GENIE_USERDATA: config.userDataDir,
93
+ FANCY_TERM_SERVICE_REVISION: config.revision
94
+ };
95
+ if (config.runtime.nodePtyDir) {
96
+ env.NODE_PATH = config.runtime.nodePtyDir;
97
+ }
98
+ return env;
99
+ }
100
+ function launchd(config, home, uid) {
101
+ const label = config.label;
102
+ const plistPath = path3__default.default.posix.join(home, "Library", "LaunchAgents", `${label}.plist`);
103
+ const env = serviceEnv(config);
104
+ const outLog = path3__default.default.posix.join(config.logDir, "ptyhost.out.log");
105
+ const errLog = path3__default.default.posix.join(config.logDir, "ptyhost.err.log");
106
+ const envXml = Object.entries(env).map(
107
+ ([k, v]) => ` <key>${xml(k)}</key>
108
+ <string>${xml(v)}</string>`
109
+ ).join("\n");
110
+ const contents = `<?xml version="1.0" encoding="UTF-8"?>
111
+ <!-- ${REVISION_MARKER}: ${config.revision} -->
112
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
113
+ <plist version="1.0">
114
+ <dict>
115
+ <key>Label</key>
116
+ <string>${xml(label)}</string>
117
+ <key>ProgramArguments</key>
118
+ <array>
119
+ <string>${xml(config.runtime.nodePath)}</string>
120
+ <string>${xml(config.hostScript)}</string>
121
+ </array>
122
+ <key>EnvironmentVariables</key>
123
+ <dict>
124
+ ${envXml}
125
+ </dict>
126
+ <key>RunAtLoad</key>
127
+ <true/>
128
+ <key>KeepAlive</key>
129
+ <false/>
130
+ <key>ProcessType</key>
131
+ <string>Background</string>
132
+ <key>StandardOutPath</key>
133
+ <string>${xml(outLog)}</string>
134
+ <key>StandardErrorPath</key>
135
+ <string>${xml(errLog)}</string>
136
+ </dict>
137
+ </plist>
138
+ `;
139
+ const domain = `gui/${uid}`;
140
+ const target = `${domain}/${label}`;
141
+ return {
142
+ platform: "launchd",
143
+ label,
144
+ revision: config.revision,
145
+ unitPath: plistPath,
146
+ unitContents: contents,
147
+ unitMode: 384,
148
+ // bootstrap loads + (RunAtLoad) starts it.
149
+ installArgv: [["launchctl", "bootstrap", domain, plistPath]],
150
+ uninstallArgv: [["launchctl", "bootout", target]],
151
+ startArgv: [["launchctl", "kickstart", "-k", target]],
152
+ stopArgv: [["launchctl", "kill", "SIGTERM", target]],
153
+ statusArgv: ["launchctl", "print", target],
154
+ removePaths: [plistPath]
155
+ };
156
+ }
157
+ function systemd(config, home) {
158
+ const unit = `${config.label}.service`;
159
+ const unitPath = path3__default.default.posix.join(home, ".config", "systemd", "user", unit);
160
+ const env = serviceEnv(config);
161
+ const envLines = Object.entries(env).map(([k, v]) => `Environment=${k}=${systemdEnvValue(v)}`).join("\n");
162
+ const contents = `# ${REVISION_MARKER}: ${config.revision}
163
+ [Unit]
164
+ Description=fancy-term pty-host (${config.label})
165
+ After=default.target
166
+
167
+ [Service]
168
+ Type=simple
169
+ ExecStart=${quoteForExec(config.runtime.nodePath)} ${quoteForExec(config.hostScript)}
170
+ ${envLines}
171
+ Restart=no
172
+
173
+ [Install]
174
+ WantedBy=default.target
175
+ `;
176
+ return {
177
+ platform: "systemd",
178
+ label: config.label,
179
+ revision: config.revision,
180
+ unitPath,
181
+ unitContents: contents,
182
+ unitMode: 420,
183
+ installArgv: [
184
+ ["systemctl", "--user", "daemon-reload"],
185
+ ["systemctl", "--user", "enable", "--now", unit]
186
+ ],
187
+ uninstallArgv: [["systemctl", "--user", "disable", "--now", unit]],
188
+ startArgv: [["systemctl", "--user", "start", unit]],
189
+ stopArgv: [["systemctl", "--user", "stop", unit]],
190
+ statusArgv: ["systemctl", "--user", "is-active", unit],
191
+ removePaths: [unitPath]
192
+ };
193
+ }
194
+ function windowsTask(config) {
195
+ const env = serviceEnv(config);
196
+ const cmdPath = path3__default.default.win32.join(config.userDataDir, `${sanitizeFileName(config.label)}.cmd`);
197
+ const setLines = Object.entries(env).map(([k, v]) => `set "${k}=${v}"`).join("\r\n");
198
+ const contents = [
199
+ "@echo off",
200
+ `rem ${REVISION_MARKER}: ${config.revision}`,
201
+ setLines,
202
+ `"${config.runtime.nodePath}" "${config.hostScript}"`,
203
+ ""
204
+ ].join("\r\n");
205
+ const taskName = config.label;
206
+ const tr = `cmd /c "${cmdPath}"`;
207
+ return {
208
+ platform: "windows-task",
209
+ label: config.label,
210
+ revision: config.revision,
211
+ unitPath: cmdPath,
212
+ unitContents: contents,
213
+ unitMode: 448,
214
+ installArgv: [
215
+ ["schtasks", "/Create", "/TN", taskName, "/TR", tr, "/SC", "ONLOGON", "/RL", "LIMITED", "/F"]
216
+ ],
217
+ uninstallArgv: [["schtasks", "/Delete", "/TN", taskName, "/F"]],
218
+ startArgv: [["schtasks", "/Run", "/TN", taskName]],
219
+ stopArgv: [["schtasks", "/End", "/TN", taskName]],
220
+ statusArgv: ["schtasks", "/Query", "/TN", taskName, "/FO", "LIST"],
221
+ removePaths: [cmdPath]
222
+ };
223
+ }
224
+ function xml(s) {
225
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
226
+ }
227
+ function systemdEnvValue(v) {
228
+ return /\s/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v;
229
+ }
230
+ function quoteForExec(p) {
231
+ return /\s/.test(p) ? `"${p}"` : p;
232
+ }
233
+ function sanitizeFileName(label) {
234
+ return label.replace(/[^A-Za-z0-9._-]+/g, "_");
235
+ }
236
+ function parseInstalledRevision(unitContents) {
237
+ const m = unitContents.match(
238
+ new RegExp(`${REVISION_MARKER}:\\s*(\\S+)`)
239
+ );
240
+ return m ? m[1] : null;
241
+ }
242
+ function resolveServiceRuntime(opts = {}) {
243
+ const env = opts.env ?? process.env;
244
+ const execPath = opts.execPath ?? process.execPath;
245
+ const isElectron = opts.isElectron ?? Boolean(process.versions?.electron);
246
+ const nodePtyDir = opts.nodePtyDir ?? env.FANCY_TERM_NODE_PTY ?? void 0;
247
+ const probe = opts.pathProbe ?? defaultPathProbe;
248
+ const finish = (nodePath, source) => ({
249
+ nodePath,
250
+ ...nodePtyDir ? { nodePtyDir } : {},
251
+ source
252
+ });
253
+ if (opts.nodePath) return finish(opts.nodePath, "explicit");
254
+ if (env.FANCY_TERM_NODE) return finish(env.FANCY_TERM_NODE, "env:FANCY_TERM_NODE");
255
+ if (!isElectron && looksLikeNode(execPath)) {
256
+ return finish(execPath, "process.execPath");
257
+ }
258
+ const onPath = probe(nodeBinNames(), env);
259
+ if (onPath) return finish(onPath, "PATH");
260
+ return null;
261
+ }
262
+ function nodeBinNames() {
263
+ return process.platform === "win32" ? ["node.exe", "node"] : ["node"];
264
+ }
265
+ function looksLikeNode(execPath) {
266
+ const base = path3__default.default.basename(execPath).toLowerCase();
267
+ return base === "node" || base === "node.exe";
268
+ }
269
+ function defaultPathProbe(binNames, env) {
270
+ const PATH = env.PATH ?? env.Path ?? "";
271
+ const dirs = PATH.split(path3__default.default.delimiter).filter(Boolean);
272
+ for (const dir of dirs) {
273
+ for (const bin of binNames) {
274
+ const candidate = path3__default.default.join(dir, bin);
275
+ try {
276
+ if (fs__default.default.existsSync(candidate)) return candidate;
277
+ } catch {
278
+ }
279
+ }
280
+ }
281
+ return null;
282
+ }
283
+ function nodeServiceIo() {
284
+ return {
285
+ run(argv) {
286
+ const [cmd, ...args] = argv;
287
+ return new Promise((resolve) => {
288
+ let stdout = "";
289
+ let stderr = "";
290
+ const child = child_process.spawn(cmd, args, {
291
+ // schtasks/launchctl/systemctl resolve via the shell on win32.
292
+ shell: process.platform === "win32",
293
+ windowsHide: true
294
+ });
295
+ child.stdout?.on("data", (d) => stdout += d.toString());
296
+ child.stderr?.on("data", (d) => stderr += d.toString());
297
+ child.on(
298
+ "error",
299
+ (err) => resolve({ code: -1, stdout, stderr: stderr + String(err) })
300
+ );
301
+ child.on(
302
+ "close",
303
+ (code) => resolve({ code: code ?? -1, stdout, stderr })
304
+ );
305
+ });
306
+ },
307
+ async writeFile(p, contents, opts) {
308
+ await fs3__default.default.mkdir(path3__default.default.dirname(p), { recursive: true });
309
+ await fs3__default.default.writeFile(p, contents, { mode: opts?.mode ?? 384 });
310
+ },
311
+ async readFile(p) {
312
+ try {
313
+ return await fs3__default.default.readFile(p, "utf8");
314
+ } catch {
315
+ return null;
316
+ }
317
+ },
318
+ async mkdirp(dir) {
319
+ await fs3__default.default.mkdir(dir, { recursive: true });
320
+ },
321
+ async rm(p) {
322
+ await fs3__default.default.rm(p, { force: true }).catch(() => {
323
+ });
324
+ },
325
+ async exists(p) {
326
+ try {
327
+ await fs3__default.default.access(p);
328
+ return true;
329
+ } catch {
330
+ return false;
331
+ }
332
+ }
333
+ };
334
+ }
335
+
336
+ // src/service/index.ts
337
+ function isServiceSupported() {
338
+ return servicePlatformFor() !== null;
339
+ }
340
+ function resolveServiceConfig(config) {
341
+ const runtime = config.runtime ?? resolveServiceRuntime();
342
+ if (!runtime) {
343
+ throw new Error(
344
+ "fancy-term-host service: no standalone Node runtime found (set config.runtime or $FANCY_TERM_NODE). Refusing to pin the consumer binary by running on Electron."
345
+ );
346
+ }
347
+ return {
348
+ label: config.label,
349
+ userDataDir: config.userDataDir,
350
+ hostScript: config.hostScript ?? ptyHostScriptPath(),
351
+ runtime,
352
+ env: config.env ?? {},
353
+ revision: config.revision ?? SERVICE_REVISION,
354
+ logDir: config.logDir ?? config.userDataDir
355
+ };
356
+ }
357
+ function descriptorFor(config) {
358
+ return buildServiceDescriptor(resolveServiceConfig(config));
359
+ }
360
+ async function runAll(io, argvList) {
361
+ for (const argv of argvList) {
362
+ const { code, stderr } = await io.run(argv);
363
+ if (code !== 0) {
364
+ throw new Error(
365
+ `command failed (${code}): ${argv.join(" ")}${stderr ? ` \u2014 ${stderr.trim()}` : ""}`
366
+ );
367
+ }
368
+ }
369
+ }
370
+ async function installHostService(config, io = nodeServiceIo()) {
371
+ const desc = descriptorFor(config);
372
+ await io.mkdirp(config.userDataDir);
373
+ await io.writeFile(desc.unitPath, desc.unitContents, { mode: desc.unitMode });
374
+ await runAll(io, desc.installArgv);
375
+ return serviceStatusFor(desc, io);
376
+ }
377
+ async function uninstallHostService(config, io = nodeServiceIo()) {
378
+ const desc = descriptorFor(config);
379
+ for (const argv of desc.uninstallArgv) {
380
+ await io.run(argv);
381
+ }
382
+ for (const p of desc.removePaths) {
383
+ await io.rm(p);
384
+ }
385
+ }
386
+ async function startHostService(config, io = nodeServiceIo()) {
387
+ await runAll(io, descriptorFor(config).startArgv);
388
+ }
389
+ async function stopHostService(config, io = nodeServiceIo()) {
390
+ await runAll(io, descriptorFor(config).stopArgv);
391
+ }
392
+ async function isServiceInstalled(config, io = nodeServiceIo()) {
393
+ return io.exists(descriptorFor(config).unitPath);
394
+ }
395
+ async function serviceStatus(config, io = nodeServiceIo()) {
396
+ return serviceStatusFor(descriptorFor(config), io);
397
+ }
398
+ async function serviceStatusFor(desc, io) {
399
+ const unit = await io.readFile(desc.unitPath);
400
+ const installed = unit !== null;
401
+ const installedRevision = unit ? parseInstalledRevision(unit) ?? void 0 : void 0;
402
+ let running = false;
403
+ let detail;
404
+ if (installed) {
405
+ const { code, stdout, stderr } = await io.run(desc.statusArgv);
406
+ detail = (stdout || stderr).trim() || void 0;
407
+ running = isRunningOutput(desc, code, stdout);
408
+ }
409
+ return {
410
+ platform: desc.platform,
411
+ state: !installed ? "not-installed" : running ? "running" : "installed",
412
+ installed,
413
+ running,
414
+ label: desc.label,
415
+ unitPath: desc.unitPath,
416
+ installedRevision,
417
+ detail
418
+ };
419
+ }
420
+ function isRunningOutput(desc, code, stdout) {
421
+ const out = stdout.toLowerCase();
422
+ switch (desc.platform) {
423
+ case "systemd":
424
+ return code === 0 && out.includes("active") && !out.includes("inactive");
425
+ case "launchd":
426
+ return code === 0 && (out.includes("state = running") || out.includes("pid ="));
427
+ case "windows-task":
428
+ return code === 0 && out.includes("running");
429
+ }
430
+ }
431
+ async function ensureHostService(config, io = nodeServiceIo()) {
432
+ if (!isServiceSupported()) {
433
+ return {
434
+ ok: false,
435
+ installed: false,
436
+ running: false,
437
+ action: "unsupported",
438
+ error: `unsupported platform: ${process.platform}`
439
+ };
440
+ }
441
+ let resolved;
442
+ try {
443
+ resolved = resolveServiceConfig(config);
444
+ } catch (err) {
445
+ return {
446
+ ok: false,
447
+ installed: false,
448
+ running: false,
449
+ action: "failed",
450
+ error: err.message
451
+ };
452
+ }
453
+ const desc = buildServiceDescriptor(resolved);
454
+ const runtime = resolved.runtime;
455
+ try {
456
+ const status = await serviceStatusFor(desc, io);
457
+ if (status.installed && status.installedRevision === resolved.revision) {
458
+ if (status.running) {
459
+ return { ok: true, installed: true, running: true, action: "already-running", runtime };
460
+ }
461
+ await runAll(io, desc.startArgv);
462
+ return { ok: true, installed: true, running: true, action: "started", runtime };
463
+ }
464
+ if (status.installed) {
465
+ for (const argv of desc.uninstallArgv) await io.run(argv);
466
+ for (const p of desc.removePaths) await io.rm(p);
467
+ }
468
+ await io.mkdirp(resolved.userDataDir);
469
+ await io.writeFile(desc.unitPath, desc.unitContents, { mode: desc.unitMode });
470
+ await runAll(io, desc.installArgv);
471
+ await runAll(io, desc.startArgv).catch(() => {
472
+ });
473
+ return {
474
+ ok: true,
475
+ installed: true,
476
+ running: true,
477
+ action: status.installed ? "reinstalled" : "installed-and-started",
478
+ runtime
479
+ };
480
+ } catch (err) {
481
+ return {
482
+ ok: false,
483
+ installed: false,
484
+ running: false,
485
+ action: "failed",
486
+ error: err.message,
487
+ runtime
488
+ };
489
+ }
490
+ }
491
+
492
+ exports.SERVICE_REVISION = SERVICE_REVISION;
493
+ exports.buildServiceDescriptor = buildServiceDescriptor;
494
+ exports.ensureHostService = ensureHostService;
495
+ exports.installHostService = installHostService;
496
+ exports.isServiceInstalled = isServiceInstalled;
497
+ exports.isServiceSupported = isServiceSupported;
498
+ exports.nodeServiceIo = nodeServiceIo;
499
+ exports.parseInstalledRevision = parseInstalledRevision;
500
+ exports.resolveServiceConfig = resolveServiceConfig;
501
+ exports.resolveServiceRuntime = resolveServiceRuntime;
502
+ exports.servicePlatformFor = servicePlatformFor;
503
+ exports.serviceStatus = serviceStatus;
504
+ exports.startHostService = startHostService;
505
+ exports.stopHostService = stopHostService;
506
+ exports.uninstallHostService = uninstallHostService;
507
+ //# sourceMappingURL=service.cjs.map
508
+ //# sourceMappingURL=service.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host-protocol.ts","../src/host-locate.ts","../src/host-script.ts","../src/service/descriptor.ts","../src/service/runtime.ts","../src/service/io.ts","../src/service/index.ts"],"names":["path","fs","f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AAM,IAAA,CAAK,QAAA,EAAU,CAAA;AAC5E,IAAA,MAAM,MAAA,CAAO,EAAA,EAAI,IAAA,CAAK,WAAW,CAAA;AAEjC,IAAA,MAAM,OAAO,EAAA,EAAI,IAAA,CAAK,SAAS,CAAA,CAAE,MAAM,MAAM;AAAA,IAAC,CAAC,CAAA;AAE/C,IAAA,OAAO;AAAA,MACH,EAAA,EAAI,IAAA;AAAA,MACJ,SAAA,EAAW,IAAA;AAAA,MACX,OAAA,EAAS,IAAA;AAAA,MACT,MAAA,EAAQ,MAAA,CAAO,SAAA,GAAY,aAAA,GAAgB,uBAAA;AAAA,MAC3C;AAAA,KACJ;AAAA,EACJ,SAAS,GAAA,EAAK;AACV,IAAA,OAAO;AAAA,MACH,EAAA,EAAI,KAAA;AAAA,MACJ,SAAA,EAAW,KAAA;AAAA,MACX,OAAA,EAAS,KAAA;AAAA,MACT,MAAA,EAAQ,QAAA;AAAA,MACR,OAAQ,GAAA,CAAc,OAAA;AAAA,MACtB;AAAA,KACJ;AAAA,EACJ;AACJ","file":"service.cjs","sourcesContent":["/**\n * Pty-host wire protocol (Tier 3).\n *\n * The detached pty-host (main/terminal/pty-host.ts) and the in-app HostClient\n * (main/terminal/host-client.ts) talk over a local IPC transport — a named pipe\n * on Windows, a unix domain socket on POSIX — using a tiny length-prefixed JSON\n * framing so there's no heavy dependency. This module is PURE (no electron, no\n * node-pty, no net): just the message shapes + the encode/decode for the framing,\n * so it can be imported by both ends AND unit-tested in isolation.\n *\n * Framing: each message is `[4-byte big-endian uint32 length][utf8 JSON body]`.\n * The length prefix is the byte length of the JSON body. A FrameDecoder buffers\n * partial reads and yields whole messages as they complete — TCP/pipe streams\n * don't preserve message boundaries, so we can't assume one `data` event == one\n * message.\n */\n\n/**\n * Protocol version. Bumped whenever the message shapes change in a way that\n * makes an old host incompatible with a new client (or vice-versa). The client\n * refuses to attach to a host whose pidfile reports a different version and\n * spawns a fresh host instead — see host-client.ts connect-or-spawn.\n */\nexport const PROTOCOL_VERSION = 2;\n\n/** Requests the client sends to the host. `seq` correlates a reply. */\nexport type ClientMessage =\n | { kind: 'hello'; seq: number; protocolVersion: number }\n | {\n kind: 'create';\n seq: number;\n opts: {\n id: string;\n cwd: string;\n shell?: string;\n args?: string[];\n cols?: number;\n rows?: number;\n env?: Record<string, string>;\n };\n }\n | { kind: 'write'; id: string; data: string }\n | { kind: 'resize'; id: string; cols: number; rows: number }\n | { kind: 'kill'; id: string }\n | { kind: 'list'; seq: number }\n | { kind: 'set-retained'; id: string; retained: boolean }\n | { kind: 'get-scrollback'; seq: number; id: string }\n | { kind: 'ping'; seq: number }\n | { kind: 'shutdown'; seq: number };\n\n/** Pushes + replies the host sends to the client. */\nexport type HostMessage =\n | { kind: 'hello-ok'; seq: number; protocolVersion: number; pid: number }\n | {\n kind: 'created';\n seq: number;\n result: {\n id: string;\n pid: number;\n shell: string;\n existing: boolean;\n scrollback: string;\n };\n }\n | {\n kind: 'list-result';\n seq: number;\n terminals: Array<{ id: string; pid: number; shell: string }>;\n }\n | { kind: 'scrollback-result'; seq: number; scrollback: string | null }\n | { kind: 'pong'; seq: number }\n | { kind: 'shutdown-ok'; seq: number }\n | { kind: 'data'; id: string; data: string }\n | { kind: 'exit'; id: string; exitCode: number; signal?: number };\n\nexport type Frame = ClientMessage | HostMessage;\n\nconst LENGTH_BYTES = 4;\n\n/** Encode a message as a length-prefixed JSON frame ready for the socket. */\nexport function encodeFrame(msg: Frame): Buffer {\n const body = Buffer.from(JSON.stringify(msg), 'utf8');\n const header = Buffer.allocUnsafe(LENGTH_BYTES);\n header.writeUInt32BE(body.length, 0);\n return Buffer.concat([header, body]);\n}\n\n/**\n * Streaming frame decoder. Feed it raw socket chunks via `push`; it returns the\n * complete messages that became available (zero or more), buffering any partial\n * tail until the rest arrives. One decoder per socket.\n *\n * Resilient by design: a malformed JSON body is skipped (the frame is consumed\n * but yields nothing) rather than throwing — a corrupt frame must not wedge the\n * whole stream. An absurd length prefix (> MAX_FRAME) is treated as a desync and\n * the buffer is reset; the caller can decide whether to drop the connection.\n */\nexport class FrameDecoder {\n private buffer: Buffer = Buffer.alloc(0);\n\n /** Hard cap on a single frame (16 MB). Guards against a runaway/garbage\n * length prefix allocating unbounded memory. node-pty data chunks are tiny;\n * a serialized scrollback is bounded well under this. */\n static readonly MAX_FRAME = 16 * 1024 * 1024;\n\n /** True when the last push hit an oversized/desynced frame. The caller\n * should drop the connection — the stream can't be trusted to realign. */\n desynced = false;\n\n push(chunk: Buffer): Frame[] {\n this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;\n const out: Frame[] = [];\n for (;;) {\n if (this.buffer.length < LENGTH_BYTES) break;\n const len = this.buffer.readUInt32BE(0);\n if (len > FrameDecoder.MAX_FRAME) {\n // Desync / garbage. Reset and flag — realigning a length-prefixed\n // stream after a bad prefix isn't possible without a sentinel.\n this.desynced = true;\n this.buffer = Buffer.alloc(0);\n break;\n }\n if (this.buffer.length < LENGTH_BYTES + len) break; // wait for more\n const body = this.buffer.subarray(LENGTH_BYTES, LENGTH_BYTES + len);\n this.buffer = this.buffer.subarray(LENGTH_BYTES + len);\n try {\n out.push(JSON.parse(body.toString('utf8')) as Frame);\n } catch {\n /* skip a corrupt frame; the framing itself is still aligned */\n }\n }\n return out;\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'node:fs';\nimport crypto from 'node:crypto';\nimport { PROTOCOL_VERSION } from './host-protocol';\n\n/**\n * Path + pidfile resolution for the detached pty-host (Tier 3).\n *\n * Kept ELECTRON-FREE on the resolution side that the host itself uses (the host\n * is a plain node process — no `app`), so the userData path is passed IN. The\n * in-app side (host-client lifecycle) imports `app` separately and feeds it here.\n */\n\nexport interface Pidfile {\n pid: number;\n socketPath: string;\n protocolVersion: number;\n startedAt: number;\n}\n\n/** Short, stable per-user hash so two OS users don't collide on the Windows\n * pipe name (the pipe namespace is machine-global). */\nexport function userHash(): string {\n const seed = `${os.userInfo().username}|${os.hostname()}`;\n return crypto.createHash('sha1').update(seed).digest('hex').slice(0, 12);\n}\n\n/**\n * The local IPC transport address.\n * • Windows: a named pipe `\\\\.\\pipe\\genie-ptyhost-<userhash>`. The default\n * Windows pipe ACL is per-logon-session, so another user on the same machine\n * can't open it — that's our ACL. (Documented; we don't tighten further.)\n * • POSIX: a unix domain socket under userData (preferred — survives /tmp\n * cleaners and is per-user by directory perms) named `ptyhost.sock`.\n */\nexport function socketPathFor(userDataDir: string): string {\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\genie-ptyhost-${userHash()}`;\n }\n // Keep the path short — unix socket paths have a ~104-char limit. userData is\n // typically well under that; fall back to os.tmpdir() if it's pathologically\n // long.\n const candidate = path.join(userDataDir, 'ptyhost.sock');\n if (candidate.length < 100) return candidate;\n return path.join(os.tmpdir(), `genie-ptyhost-${userHash()}.sock`);\n}\n\nexport function pidfilePath(userDataDir: string): string {\n return path.join(userDataDir, 'ptyhost.json');\n}\n\nexport function writePidfile(userDataDir: string, pf: Pidfile): void {\n const target = pidfilePath(userDataDir);\n const tmp = `${target}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(pf));\n fs.renameSync(tmp, target);\n}\n\nexport function readPidfile(userDataDir: string): Pidfile | null {\n try {\n const raw = fs.readFileSync(pidfilePath(userDataDir), 'utf8');\n const pf = JSON.parse(raw) as Pidfile;\n if (\n typeof pf.pid !== 'number' ||\n typeof pf.socketPath !== 'string' ||\n typeof pf.protocolVersion !== 'number'\n ) {\n return null;\n }\n return pf;\n } catch {\n return null;\n }\n}\n\nexport function deletePidfile(userDataDir: string): void {\n try {\n fs.rmSync(pidfilePath(userDataDir), { force: true });\n } catch {\n /* ignore */\n }\n}\n\n/** True when a process with `pid` is alive (signal 0 probes without killing). */\nexport function isPidAlive(pid: number): boolean {\n if (!pid || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM = exists but not ours (still \"alive\"); ESRCH = gone.\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/**\n * Decide whether an existing pidfile points at a usable host.\n * Usable = pid alive AND protocol versions match. A stale/dead/mismatched\n * pidfile means we must spawn a fresh host.\n */\nexport function pidfileUsable(pf: Pidfile | null): boolean {\n if (!pf) return false;\n if (pf.protocolVersion !== PROTOCOL_VERSION) return false;\n if (!isPidAlive(pf.pid)) return false;\n return true;\n}\n\n/**\n * Resolve the compiled pty-host script on disk, trying multiple candidate paths\n * so it works in BOTH `npm run dev` (script at app/pty-host.js next to\n * background.js) AND a packaged asar build. node-pty's native binding can't load\n * from inside an asar, so the host (which requires node-pty) must run UNPACKED —\n * `app.asar.unpacked/...`. We try the unpacked path first, then the in-asar path,\n * then a dev-relative path. Returns the first that exists, or null.\n *\n * `dirname` is main/background's __dirname (the directory the compiled main\n * bundle lives in). The host script is emitted alongside it as `pty-host.js`.\n */\nexport function resolveHostScript(dirname: string): string | null {\n const candidates = [\n // Packaged: node-pty must be unpacked, so run the host from the unpacked\n // tree too (its require('node-pty') resolves to the unpacked .node).\n dirname.includes(`app.asar${path.sep}`) || dirname.includes('app.asar/')\n ? dirname.replace(\n /app\\.asar([\\\\/])/,\n `app.asar.unpacked$1`,\n ) + path.sep + 'pty-host.js'\n : '',\n // Same dir as the compiled main bundle (dev: app/pty-host.js).\n path.join(dirname, 'pty-host.js'),\n // Defensive: a sibling unpacked dir computed from the asar path.\n path.join(dirname.replace('app.asar', 'app.asar.unpacked'), 'pty-host.js'),\n ].filter(Boolean);\n\n for (const c of candidates) {\n try {\n if (fs.existsSync(c)) return c;\n } catch {\n /* keep trying */\n }\n }\n return null;\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { resolveHostScript } from './host-locate';\n\n/**\n * Absolute path to the bundled detached pty-host script (Tier 3), so a\n * `HostSpawner` can launch it as a detached child without knowing this\n * package's dist layout:\n *\n * ```ts\n * import { spawn } from 'node:child_process';\n * import { ptyHostScriptPath } from '@particle-academy/fancy-term-host';\n *\n * const child = spawn(process.execPath, [ptyHostScriptPath(), userDataDir], {\n * detached: true, stdio: 'ignore',\n * });\n * child.unref();\n * ```\n *\n * The host script is emitted alongside this module in `dist/` as\n * `pty-host.js`. Works in both the ESM and CJS builds (esbuild fills in\n * `import.meta.url` for the CJS output; `__dirname` is used when present).\n */\nexport function ptyHostScriptPath(): string {\n const here =\n typeof __dirname !== 'undefined'\n ? __dirname\n : path.dirname(fileURLToPath(import.meta.url));\n // Reuse host-locate's candidate logic (handles dev/packaged layouts); fall\n // back to the expected emitted location if the existence probe misses.\n return resolveHostScript(here) ?? path.join(here, 'pty-host.js');\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport { PROTOCOL_VERSION } from '../host-protocol';\nimport type { HostServiceConfig, ServicePlatform, ServiceRuntime } from './types';\n\n/**\n * Default service revision. Encodes the host PROTOCOL_VERSION so that a protocol\n * bump (which makes an old host incompatible) forces a reinstall — the installed\n * unit carries this marker and `ensureHostService` reinstalls on a mismatch.\n */\nexport const SERVICE_REVISION = `svc1+proto${PROTOCOL_VERSION}`;\n\n/** The marker line embedded in every generated unit, parsed back on upgrade. */\nexport const REVISION_MARKER = 'fancy-term-service-revision';\n\n/** A fully-resolved, per-OS description of the service to install. */\nexport interface ServiceDescriptor {\n platform: ServicePlatform;\n label: string;\n revision: string;\n /** The file we write + own (plist / unit / launcher .cmd). */\n unitPath: string;\n unitContents: string;\n /** POSIX file mode for the unit (e.g. 0o600 plist, 0o700 launcher). */\n unitMode: number;\n /** Commands (after the file is written) to register + start the service. */\n installArgv: string[][];\n /** Commands to stop + deregister. */\n uninstallArgv: string[][];\n startArgv: string[][];\n stopArgv: string[][];\n /** Single command whose output tells us installed/running. */\n statusArgv: string[];\n /** Files to remove on uninstall (unit + any logs we created). */\n removePaths: string[];\n}\n\nexport interface DescriptorContext {\n /** Override the platform (tests). Defaults to the current OS. */\n platform?: ServicePlatform;\n /** Home dir (tests). Defaults to `os.homedir()`. */\n home?: string;\n /** Numeric uid for launchd domain targets (tests / non-posix). */\n uid?: number;\n}\n\n/** Map `process.platform` to a service mechanism, or null when unsupported. */\nexport function servicePlatformFor(\n platform: NodeJS.Platform = process.platform,\n): ServicePlatform | null {\n switch (platform) {\n case 'darwin':\n return 'launchd';\n case 'linux':\n return 'systemd';\n case 'win32':\n return 'windows-task';\n default:\n return null;\n }\n}\n\n/**\n * Build the per-OS descriptor for a service config. PURE — no fs, no spawning —\n * so the generated units + command argv are fully unit-testable.\n */\nexport function buildServiceDescriptor(\n config: ResolvedServiceConfig,\n ctx: DescriptorContext = {},\n): ServiceDescriptor {\n const platform =\n ctx.platform ?? servicePlatformFor() ?? unsupported(config);\n const home = ctx.home ?? os.homedir();\n switch (platform) {\n case 'launchd':\n return launchd(config, home, ctx.uid ?? safeUid());\n case 'systemd':\n return systemd(config, home);\n case 'windows-task':\n return windowsTask(config);\n }\n}\n\nfunction unsupported(config: ResolvedServiceConfig): never {\n throw new Error(\n `fancy-term-host service: unsupported platform for \"${config.label}\"`,\n );\n}\n\nfunction safeUid(): number {\n const getuid = (process as { getuid?: () => number }).getuid;\n return typeof getuid === 'function' ? getuid() : 0;\n}\n\n/**\n * A config with all defaults filled in — produced by `resolveServiceConfig`\n * (see index.ts) and consumed by the descriptor builder.\n */\nexport interface ResolvedServiceConfig {\n label: string;\n userDataDir: string;\n hostScript: string;\n runtime: ServiceRuntime;\n env: Record<string, string>;\n revision: string;\n logDir: string;\n}\n\n/** The environment every platform injects (user-data dir, NODE_PATH, revision). */\nfunction serviceEnv(config: ResolvedServiceConfig): Record<string, string> {\n const env: Record<string, string> = {\n ...config.env,\n // GENIE_USERDATA is the var the existing detached-spawn path already uses\n // (see host-lifecycle.spawnDetached); keep it so the host finds its data.\n GENIE_USERDATA: config.userDataDir,\n FANCY_TERM_SERVICE_REVISION: config.revision,\n };\n if (config.runtime.nodePtyDir) {\n env.NODE_PATH = config.runtime.nodePtyDir;\n }\n return env;\n}\n\n// ── macOS: launchd LaunchAgent ──────────────────────────────────────────────\n\nfunction launchd(\n config: ResolvedServiceConfig,\n home: string,\n uid: number,\n): ServiceDescriptor {\n const label = config.label;\n // launchd targets macOS — always POSIX paths, even if generated elsewhere.\n const plistPath = path.posix.join(home, 'Library', 'LaunchAgents', `${label}.plist`);\n const env = serviceEnv(config);\n const outLog = path.posix.join(config.logDir, 'ptyhost.out.log');\n const errLog = path.posix.join(config.logDir, 'ptyhost.err.log');\n\n const envXml = Object.entries(env)\n .map(\n ([k, v]) =>\n ` <key>${xml(k)}</key>\\n <string>${xml(v)}</string>`,\n )\n .join('\\n');\n\n const contents = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- ${REVISION_MARKER}: ${config.revision} -->\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n <dict>\n <key>Label</key>\n <string>${xml(label)}</string>\n <key>ProgramArguments</key>\n <array>\n <string>${xml(config.runtime.nodePath)}</string>\n <string>${xml(config.hostScript)}</string>\n </array>\n <key>EnvironmentVariables</key>\n <dict>\n${envXml}\n </dict>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <false/>\n <key>ProcessType</key>\n <string>Background</string>\n <key>StandardOutPath</key>\n <string>${xml(outLog)}</string>\n <key>StandardErrorPath</key>\n <string>${xml(errLog)}</string>\n </dict>\n</plist>\n`;\n\n const domain = `gui/${uid}`;\n const target = `${domain}/${label}`;\n return {\n platform: 'launchd',\n label,\n revision: config.revision,\n unitPath: plistPath,\n unitContents: contents,\n unitMode: 0o600,\n // bootstrap loads + (RunAtLoad) starts it.\n installArgv: [['launchctl', 'bootstrap', domain, plistPath]],\n uninstallArgv: [['launchctl', 'bootout', target]],\n startArgv: [['launchctl', 'kickstart', '-k', target]],\n stopArgv: [['launchctl', 'kill', 'SIGTERM', target]],\n statusArgv: ['launchctl', 'print', target],\n removePaths: [plistPath],\n };\n}\n\n// ── Linux: systemd --user unit ──────────────────────────────────────────────\n\nfunction systemd(config: ResolvedServiceConfig, home: string): ServiceDescriptor {\n const unit = `${config.label}.service`;\n // systemd --user targets Linux — always POSIX paths.\n const unitPath = path.posix.join(home, '.config', 'systemd', 'user', unit);\n const env = serviceEnv(config);\n const envLines = Object.entries(env)\n .map(([k, v]) => `Environment=${k}=${systemdEnvValue(v)}`)\n .join('\\n');\n\n const contents = `# ${REVISION_MARKER}: ${config.revision}\n[Unit]\nDescription=fancy-term pty-host (${config.label})\nAfter=default.target\n\n[Service]\nType=simple\nExecStart=${quoteForExec(config.runtime.nodePath)} ${quoteForExec(config.hostScript)}\n${envLines}\nRestart=no\n\n[Install]\nWantedBy=default.target\n`;\n\n return {\n platform: 'systemd',\n label: config.label,\n revision: config.revision,\n unitPath,\n unitContents: contents,\n unitMode: 0o644,\n installArgv: [\n ['systemctl', '--user', 'daemon-reload'],\n ['systemctl', '--user', 'enable', '--now', unit],\n ],\n uninstallArgv: [['systemctl', '--user', 'disable', '--now', unit]],\n startArgv: [['systemctl', '--user', 'start', unit]],\n stopArgv: [['systemctl', '--user', 'stop', unit]],\n statusArgv: ['systemctl', '--user', 'is-active', unit],\n removePaths: [unitPath],\n };\n}\n\n// ── Windows: per-user scheduled task (ONLOGON, no elevation) ─────────────────\n\nfunction windowsTask(config: ResolvedServiceConfig): ServiceDescriptor {\n const env = serviceEnv(config);\n // A launcher .cmd sets env then runs the host — schtasks can't carry rich\n // env cleanly, and the .cmd also records the revision marker.\n const cmdPath = path.win32.join(config.userDataDir, `${sanitizeFileName(config.label)}.cmd`);\n const setLines = Object.entries(env)\n .map(([k, v]) => `set \"${k}=${v}\"`)\n .join('\\r\\n');\n const contents = [\n '@echo off',\n `rem ${REVISION_MARKER}: ${config.revision}`,\n setLines,\n `\"${config.runtime.nodePath}\" \"${config.hostScript}\"`,\n '',\n ].join('\\r\\n');\n\n const taskName = config.label;\n // /RL LIMITED = run with the user's normal (non-elevated) rights.\n // /SC ONLOGON = start at this user's logon. /F = overwrite if present.\n const tr = `cmd /c \"${cmdPath}\"`;\n return {\n platform: 'windows-task',\n label: config.label,\n revision: config.revision,\n unitPath: cmdPath,\n unitContents: contents,\n unitMode: 0o700,\n installArgv: [\n ['schtasks', '/Create', '/TN', taskName, '/TR', tr, '/SC', 'ONLOGON', '/RL', 'LIMITED', '/F'],\n ],\n uninstallArgv: [['schtasks', '/Delete', '/TN', taskName, '/F']],\n startArgv: [['schtasks', '/Run', '/TN', taskName]],\n stopArgv: [['schtasks', '/End', '/TN', taskName]],\n statusArgv: ['schtasks', '/Query', '/TN', taskName, '/FO', 'LIST'],\n removePaths: [cmdPath],\n };\n}\n\n// ── helpers ─────────────────────────────────────────────────────────────────\n\nfunction xml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/** systemd `Environment=` values: wrap in quotes if they contain whitespace. */\nfunction systemdEnvValue(v: string): string {\n return /\\s/.test(v) ? `\"${v.replace(/\"/g, '\\\\\"')}\"` : v;\n}\n\n/** Quote a path for a systemd ExecStart token. */\nfunction quoteForExec(p: string): string {\n return /\\s/.test(p) ? `\"${p}\"` : p;\n}\n\nfunction sanitizeFileName(label: string): string {\n return label.replace(/[^A-Za-z0-9._-]+/g, '_');\n}\n\n/** Read the revision marker out of an installed unit's contents, or null. */\nexport function parseInstalledRevision(unitContents: string): string | null {\n const m = unitContents.match(\n new RegExp(`${REVISION_MARKER}:\\\\s*(\\\\S+)`),\n );\n return m ? m[1] : null;\n}\n","import path from 'node:path';\nimport fs from 'node:fs';\nimport type { ServiceRuntime } from './types';\n\n/**\n * Locate a STANDALONE Node runtime to run the host service on — explicitly NOT\n * the consumer's Electron binary, whose whole problem is that running the host\n * on it pins the executable across auto-updates.\n *\n * Precedence:\n * 1. An explicit `nodePath` (the consumer ships/locates its own node).\n * 2. `$FANCY_TERM_NODE` (a deploy-time override).\n * 3. `process.execPath` — but ONLY if the current process is plain Node, not\n * Electron (`process.versions.electron`), and the binary is named `node`.\n * 4. A `node` / `node.exe` found on `$PATH`.\n *\n * Returns null when no safe standalone runtime is found — the caller should then\n * fall back to the existing detached-spawn (which works for a normal quit) or\n * in-process. Never throws.\n */\nexport interface ResolveRuntimeOptions {\n /** Explicit standalone node path (wins). */\n nodePath?: string;\n /** Directory with an ABI-matched node-pty for that runtime. */\n nodePtyDir?: string;\n /** Environment to read overrides from. Defaults to `process.env`. */\n env?: NodeJS.ProcessEnv;\n /** Current process binary. Defaults to `process.execPath`. */\n execPath?: string;\n /** Whether the current process is Electron. Defaults to detecting it. */\n isElectron?: boolean;\n /** PATH lookup probe (injectable for tests). Defaults to an fs probe. */\n pathProbe?: (binNames: string[], env: NodeJS.ProcessEnv) => string | null;\n}\n\nexport function resolveServiceRuntime(\n opts: ResolveRuntimeOptions = {},\n): ServiceRuntime | null {\n const env = opts.env ?? process.env;\n const execPath = opts.execPath ?? process.execPath;\n const isElectron =\n opts.isElectron ?? Boolean((process as { versions?: Record<string, string> }).versions?.electron);\n const nodePtyDir = opts.nodePtyDir ?? env.FANCY_TERM_NODE_PTY ?? undefined;\n const probe = opts.pathProbe ?? defaultPathProbe;\n\n const finish = (nodePath: string, source: string): ServiceRuntime => ({\n nodePath,\n ...(nodePtyDir ? { nodePtyDir } : {}),\n source,\n });\n\n // 1) Explicit.\n if (opts.nodePath) return finish(opts.nodePath, 'explicit');\n\n // 2) Env override.\n if (env.FANCY_TERM_NODE) return finish(env.FANCY_TERM_NODE, 'env:FANCY_TERM_NODE');\n\n // 3) The current process — only if it's a real standalone node.\n if (!isElectron && looksLikeNode(execPath)) {\n return finish(execPath, 'process.execPath');\n }\n\n // 4) PATH lookup.\n const onPath = probe(nodeBinNames(), env);\n if (onPath) return finish(onPath, 'PATH');\n\n return null;\n}\n\nfunction nodeBinNames(): string[] {\n return process.platform === 'win32' ? ['node.exe', 'node'] : ['node'];\n}\n\nfunction looksLikeNode(execPath: string): boolean {\n const base = path.basename(execPath).toLowerCase();\n return base === 'node' || base === 'node.exe';\n}\n\n/** Walk `$PATH`, returning the first existing `node`/`node.exe`. */\nfunction defaultPathProbe(\n binNames: string[],\n env: NodeJS.ProcessEnv,\n): string | null {\n const PATH = env.PATH ?? env.Path ?? '';\n const dirs = PATH.split(path.delimiter).filter(Boolean);\n for (const dir of dirs) {\n for (const bin of binNames) {\n const candidate = path.join(dir, bin);\n try {\n if (fs.existsSync(candidate)) return candidate;\n } catch {\n /* keep looking */\n }\n }\n }\n return null;\n}\n","import { spawn } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { ServiceIo } from './types';\n\n/**\n * Production {@link ServiceIo}: real fs + child_process. The orchestration in\n * index.ts takes a ServiceIo so tests can inject a fake and never touch the OS.\n */\nexport function nodeServiceIo(): ServiceIo {\n return {\n run(argv) {\n const [cmd, ...args] = argv;\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n const child = spawn(cmd, args, {\n // schtasks/launchctl/systemctl resolve via the shell on win32.\n shell: process.platform === 'win32',\n windowsHide: true,\n });\n child.stdout?.on('data', (d) => (stdout += d.toString()));\n child.stderr?.on('data', (d) => (stderr += d.toString()));\n child.on('error', (err) =>\n resolve({ code: -1, stdout, stderr: stderr + String(err) }),\n );\n child.on('close', (code) =>\n resolve({ code: code ?? -1, stdout, stderr }),\n );\n });\n },\n async writeFile(p, contents, opts) {\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, contents, { mode: opts?.mode ?? 0o600 });\n },\n async readFile(p) {\n try {\n return await fs.readFile(p, 'utf8');\n } catch {\n return null;\n }\n },\n async mkdirp(dir) {\n await fs.mkdir(dir, { recursive: true });\n },\n async rm(p) {\n await fs.rm(p, { force: true }).catch(() => {});\n },\n async exists(p) {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n },\n };\n}\n","/**\n * Per-user OS-service lifecycle for the pty-host. Install / start / stop /\n * status / uninstall + a single `ensureHostService()` that does the\n * install-if-missing-or-stale → start-if-stopped dance.\n *\n * Pairs with the existing detached-host path: the wire protocol, pidfile, and\n * `HostClient` are unchanged, so the consumer connects exactly as today. The\n * difference is WHO launches the host — a per-user service on a standalone Node\n * runtime, not a child of the consumer's Electron binary.\n *\n * Everything here is graceful: `ensureHostService` never throws (inspect `ok`),\n * so a consumer can try the service and, on failure, fall back to\n * `HostSpawner.spawnDetached` (normal-quit survival) → in-process.\n */\n\nimport { ptyHostScriptPath } from '../host-script';\nimport {\n buildServiceDescriptor,\n parseInstalledRevision,\n SERVICE_REVISION,\n servicePlatformFor,\n type ResolvedServiceConfig,\n type ServiceDescriptor,\n} from './descriptor';\nimport { resolveServiceRuntime } from './runtime';\nimport { nodeServiceIo } from './io';\nimport type {\n EnsureResult,\n HostServiceConfig,\n ServiceIo,\n ServiceRuntime,\n ServiceStatus,\n} from './types';\n\nexport { resolveServiceRuntime } from './runtime';\nexport { nodeServiceIo } from './io';\nexport {\n buildServiceDescriptor,\n servicePlatformFor,\n parseInstalledRevision,\n SERVICE_REVISION,\n} from './descriptor';\nexport type { ServiceDescriptor, ResolvedServiceConfig } from './descriptor';\nexport type {\n HostServiceConfig,\n ServiceRuntime,\n ServiceStatus,\n ServiceState,\n ServicePlatform,\n ServiceIo,\n EnsureResult,\n EnsureAction,\n} from './types';\n\n/** True when the current OS has a supported service mechanism. */\nexport function isServiceSupported(): boolean {\n return servicePlatformFor() !== null;\n}\n\n/**\n * Fill in every default (host script, runtime, revision, log dir) so the\n * descriptor builder has a complete config. Throws only if no standalone Node\n * runtime can be resolved — callers that want graceful behaviour should use\n * `ensureHostService`, which catches this.\n */\nexport function resolveServiceConfig(\n config: HostServiceConfig,\n): ResolvedServiceConfig {\n const runtime: ServiceRuntime | null =\n config.runtime ?? resolveServiceRuntime();\n if (!runtime) {\n throw new Error(\n 'fancy-term-host service: no standalone Node runtime found ' +\n '(set config.runtime or $FANCY_TERM_NODE). Refusing to pin the ' +\n 'consumer binary by running on Electron.',\n );\n }\n return {\n label: config.label,\n userDataDir: config.userDataDir,\n hostScript: config.hostScript ?? ptyHostScriptPath(),\n runtime,\n env: config.env ?? {},\n revision: config.revision ?? SERVICE_REVISION,\n logDir: config.logDir ?? config.userDataDir,\n };\n}\n\nfunction descriptorFor(config: HostServiceConfig): ServiceDescriptor {\n return buildServiceDescriptor(resolveServiceConfig(config));\n}\n\n/** Run a list of commands in order; throw on the first non-zero exit. */\nasync function runAll(io: ServiceIo, argvList: string[][]): Promise<void> {\n for (const argv of argvList) {\n const { code, stderr } = await io.run(argv);\n if (code !== 0) {\n throw new Error(\n `command failed (${code}): ${argv.join(' ')}${\n stderr ? ` — ${stderr.trim()}` : ''\n }`,\n );\n }\n }\n}\n\n/** Write the unit file(s) and register + start the service. */\nexport async function installHostService(\n config: HostServiceConfig,\n io: ServiceIo = nodeServiceIo(),\n): Promise<ServiceStatus> {\n const desc = descriptorFor(config);\n await io.mkdirp(config.userDataDir);\n await io.writeFile(desc.unitPath, desc.unitContents, { mode: desc.unitMode });\n await runAll(io, desc.installArgv);\n return serviceStatusFor(desc, io);\n}\n\n/** Stop + deregister the service and remove its unit file(s). */\nexport async function uninstallHostService(\n config: HostServiceConfig,\n io: ServiceIo = nodeServiceIo(),\n): Promise<void> {\n const desc = descriptorFor(config);\n // Best-effort: a not-installed service shouldn't make uninstall throw.\n for (const argv of desc.uninstallArgv) {\n await io.run(argv);\n }\n for (const p of desc.removePaths) {\n await io.rm(p);\n }\n}\n\nexport async function startHostService(\n config: HostServiceConfig,\n io: ServiceIo = nodeServiceIo(),\n): Promise<void> {\n await runAll(io, descriptorFor(config).startArgv);\n}\n\nexport async function stopHostService(\n config: HostServiceConfig,\n io: ServiceIo = nodeServiceIo(),\n): Promise<void> {\n await runAll(io, descriptorFor(config).stopArgv);\n}\n\nexport async function isServiceInstalled(\n config: HostServiceConfig,\n io: ServiceIo = nodeServiceIo(),\n): Promise<boolean> {\n return io.exists(descriptorFor(config).unitPath);\n}\n\nexport async function serviceStatus(\n config: HostServiceConfig,\n io: ServiceIo = nodeServiceIo(),\n): Promise<ServiceStatus> {\n return serviceStatusFor(descriptorFor(config), io);\n}\n\nasync function serviceStatusFor(\n desc: ServiceDescriptor,\n io: ServiceIo,\n): Promise<ServiceStatus> {\n const unit = await io.readFile(desc.unitPath);\n const installed = unit !== null;\n const installedRevision = unit ? parseInstalledRevision(unit) ?? undefined : undefined;\n\n let running = false;\n let detail: string | undefined;\n if (installed) {\n const { code, stdout, stderr } = await io.run(desc.statusArgv);\n detail = (stdout || stderr).trim() || undefined;\n running = isRunningOutput(desc, code, stdout);\n }\n\n return {\n platform: desc.platform,\n state: !installed ? 'not-installed' : running ? 'running' : 'installed',\n installed,\n running,\n label: desc.label,\n unitPath: desc.unitPath,\n installedRevision,\n detail,\n };\n}\n\n/** Interpret each platform's status command output. */\nfunction isRunningOutput(\n desc: ServiceDescriptor,\n code: number,\n stdout: string,\n): boolean {\n const out = stdout.toLowerCase();\n switch (desc.platform) {\n case 'systemd':\n // `systemctl --user is-active` → \"active\" (exit 0) when running.\n return code === 0 && out.includes('active') && !out.includes('inactive');\n case 'launchd':\n // `launchctl print` exits 0 when loaded; \"state = running\" when up.\n return code === 0 && (out.includes('state = running') || out.includes('pid ='));\n case 'windows-task':\n // `schtasks /Query /FO LIST` → a \"Status:\" line of \"Running\".\n return code === 0 && out.includes('running');\n }\n}\n\n/**\n * Ensure the service is installed at the current revision AND running.\n *\n * - already running at this revision → no-op\n * - installed (this revision), stopped → start\n * - installed at a DIFFERENT revision → uninstall + reinstall + start\n * - not installed → install (+ start)\n *\n * NEVER throws. On any failure (no runtime, unsupported OS, a command error) it\n * returns `{ ok: false, … }` with an `error` so the caller can fall back to the\n * detached-spawn path. Snapshot live sessions before a reinstall if you need\n * history to survive it (a reinstall restarts the host).\n */\nexport async function ensureHostService(\n config: HostServiceConfig,\n io: ServiceIo = nodeServiceIo(),\n): Promise<EnsureResult> {\n if (!isServiceSupported()) {\n return {\n ok: false,\n installed: false,\n running: false,\n action: 'unsupported',\n error: `unsupported platform: ${process.platform}`,\n };\n }\n\n let resolved: ResolvedServiceConfig;\n try {\n resolved = resolveServiceConfig(config);\n } catch (err) {\n return {\n ok: false,\n installed: false,\n running: false,\n action: 'failed',\n error: (err as Error).message,\n };\n }\n\n const desc = buildServiceDescriptor(resolved);\n const runtime = resolved.runtime;\n try {\n const status = await serviceStatusFor(desc, io);\n\n if (status.installed && status.installedRevision === resolved.revision) {\n if (status.running) {\n return { ok: true, installed: true, running: true, action: 'already-running', runtime };\n }\n await runAll(io, desc.startArgv);\n return { ok: true, installed: true, running: true, action: 'started', runtime };\n }\n\n if (status.installed) {\n // Stale revision → tear down then reinstall fresh.\n for (const argv of desc.uninstallArgv) await io.run(argv);\n for (const p of desc.removePaths) await io.rm(p);\n }\n\n await io.mkdirp(resolved.userDataDir);\n await io.writeFile(desc.unitPath, desc.unitContents, { mode: desc.unitMode });\n await runAll(io, desc.installArgv);\n // launchd RunAtLoad / systemd --now start on install; nudge to be sure.\n await runAll(io, desc.startArgv).catch(() => {});\n\n return {\n ok: true,\n installed: true,\n running: true,\n action: status.installed ? 'reinstalled' : 'installed-and-started',\n runtime,\n };\n } catch (err) {\n return {\n ok: false,\n installed: false,\n running: false,\n action: 'failed',\n error: (err as Error).message,\n runtime,\n };\n }\n}\n"]}