@particle-academy/fancy-term-host 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,150 @@
1
+ # Per-user OS service (`@particle-academy/fancy-term-host/service`)
2
+
3
+ Run the pty-host as a **per-user OS service on its own standalone Node runtime**,
4
+ so an Electron auto-update never pins the consumer's binary and live terminals
5
+ survive both quits *and* updates.
6
+
7
+ This is a **subpath** — server/web consumers that just use the in-process or
8
+ detached backends never pull it in. Import it only in the desktop/Electron host.
9
+
10
+ ## The problem it solves
11
+
12
+ The detached host (T3) is spawned with `process.execPath` + `ELECTRON_RUN_AS_NODE`
13
+ so `node-pty`'s native binding matches the Electron ABI. But the running host
14
+ then **holds the app's executable open**. On an auto-update (NSIS / Squirrel), the
15
+ installer must overwrite that binary — the surviving host pins it, so the update
16
+ can't proceed, and killing the host to let it through loses the live sessions.
17
+
18
+ A service on its **own** runtime is never the app binary, so it's never pinned.
19
+
20
+ ## API
21
+
22
+ ```ts
23
+ import {
24
+ ensureHostService,
25
+ installHostService,
26
+ uninstallHostService,
27
+ startHostService,
28
+ stopHostService,
29
+ isServiceInstalled,
30
+ serviceStatus,
31
+ resolveServiceRuntime,
32
+ buildServiceDescriptor,
33
+ isServiceSupported,
34
+ SERVICE_REVISION,
35
+ } from "@particle-academy/fancy-term-host/service";
36
+ ```
37
+
38
+ ### `ensureHostService(config): Promise<EnsureResult>`
39
+
40
+ The one call most consumers need. It:
41
+
42
+ 1. Resolves a standalone runtime (or returns `{ ok: false }` — never throws).
43
+ 2. Reads the installed unit's revision.
44
+ 3. **already running, same revision** → no-op · **installed, stopped** → start ·
45
+ **stale revision** → uninstall + reinstall + start · **absent** → install + start.
46
+
47
+ ```ts
48
+ const r = await ensureHostService({
49
+ label: "academy.particle.genie.ptyhost",
50
+ userDataDir: app.getPath("userData"),
51
+ runtime: { nodePath: "/opt/genie/runtime/node", nodePtyDir: "/opt/genie/native" },
52
+ });
53
+ if (!r.ok) {
54
+ // fall back — the service couldn't be set up (perms / unsupported / no runtime)
55
+ // → use HostSpawner.spawnDetached (survives a normal quit) → in-process.
56
+ }
57
+ ```
58
+
59
+ `EnsureResult` = `{ ok, installed, running, action, runtime?, error? }`, where
60
+ `action` is one of `already-running | started | installed-and-started |
61
+ reinstalled | failed | unsupported`.
62
+
63
+ ### Config
64
+
65
+ ```ts
66
+ interface HostServiceConfig {
67
+ label: string; // reverse-DNS-ish, stable per app+user
68
+ userDataDir: string; // host pidfile / socket / snapshots live here
69
+ hostScript?: string; // default: ptyHostScriptPath()
70
+ runtime?: ServiceRuntime; // default: resolveServiceRuntime()
71
+ env?: Record<string,string>;
72
+ revision?: string; // default: SERVICE_REVISION (encodes PROTOCOL_VERSION)
73
+ logDir?: string; // default: userDataDir
74
+ }
75
+ ```
76
+
77
+ ## The runtime / node-pty ABI question (the important part)
78
+
79
+ The service must **not** run on the consumer's Electron binary (that reintroduces
80
+ the pin). So `node-pty` must load against whatever runtime the service uses.
81
+ `resolveServiceRuntime()` picks one, in order:
82
+
83
+ 1. an explicit `nodePath` you pass,
84
+ 2. `$FANCY_TERM_NODE`,
85
+ 3. `process.execPath` — only when the current process is **plain Node** (not
86
+ Electron, binary named `node`),
87
+ 4. a `node` / `node.exe` on `$PATH`.
88
+
89
+ It **refuses** an Electron binary outright, and returns `null` when nothing safe
90
+ is found (so the caller falls back).
91
+
92
+ You still have to make sure that runtime can load `node-pty`:
93
+
94
+ - **Ship a standalone Node** with the app and build/prebuild `node-pty` for its
95
+ ABI (`node-gyp` / `prebuild-install`), then point `runtime.nodePath` at it and
96
+ `runtime.nodePtyDir` at the directory holding the ABI-matched `.node` (it's
97
+ added to the service's `NODE_PATH`), **or**
98
+ - rely on a system Node that already has a compatible `node-pty` resolvable from
99
+ the host script's own `node_modules`.
100
+
101
+ > This is deliberately a consumer/CI decision, not something the package bundles:
102
+ > shipping prebuilt native binaries for every OS×arch belongs in your app's build
103
+ > pipeline. The service layer itself is pure JS.
104
+
105
+ ## What each platform installs
106
+
107
+ | OS | Mechanism | Unit location | No elevation |
108
+ |---|---|---|---|
109
+ | macOS | `launchd` LaunchAgent | `~/Library/LaunchAgents/<label>.plist` | ✅ (per-user agent) |
110
+ | Linux | `systemd --user` unit | `~/.config/systemd/user/<label>.service` | ✅ (`--user`) |
111
+ | Windows | scheduled task (`ONLOGON`) + launcher `.cmd` | task `<label>`, cmd in `userDataDir` | ✅ (`/RL LIMITED`) |
112
+
113
+ `buildServiceDescriptor(config)` returns the exact unit contents + command argv
114
+ for inspection/testing without touching the OS.
115
+
116
+ ## Versioning + handoff
117
+
118
+ The installed unit carries a revision marker; the default `SERVICE_REVISION`
119
+ encodes the host `PROTOCOL_VERSION`. When a consumer update bumps the protocol,
120
+ `ensureHostService` sees the mismatch and reinstalls — so you never keep an
121
+ incompatible host alive. A reinstall restarts the host, so **snapshot live
122
+ sessions (the T1 path) or call `shutdownHost()` first** if you need history to
123
+ survive the handoff.
124
+
125
+ ## Graceful fallback
126
+
127
+ Nothing here is load-bearing for the app to function: `ensureHostService` never
128
+ throws. The recommended chain is **service → detached spawn → in-process**:
129
+
130
+ ```ts
131
+ const svc = await ensureHostService(cfg);
132
+ if (svc.ok) {
133
+ // connect via HostClient as usual
134
+ } else {
135
+ // configureHostLifecycle({ spawner, … }); await initTerminalBackend();
136
+ // (detached spawn survives a normal quit; in-process is the final floor)
137
+ }
138
+ ```
139
+
140
+ ## Testing
141
+
142
+ The lifecycle takes an injected `ServiceIo` (`run` / `writeFile` / `readFile` /
143
+ `mkdirp` / `rm` / `exists`), so you can unit-test install/ensure/status against a
144
+ fake filesystem + command runner without launchctl/systemctl/schtasks. See
145
+ `src/__tests__/service-*.test.ts`.
146
+
147
+ > **Cross-platform validation.** The descriptor generation + lifecycle logic are
148
+ > unit-tested on every platform. The *actual* `launchctl` / `systemctl --user` /
149
+ > `schtasks` install paths should still be smoke-tested on real macOS / Linux /
150
+ > Windows before you depend on them in production.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@particle-academy/fancy-term-host",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "Headless Node terminal backend for @particle-academy/fancy-term — owns the PTYs (node-pty) and the T1/T2/T3 persistence engine (snapshot+replay, retained PTYs, detached pty-host) behind four injected ports. OS-agnostic, zero hard third-party deps.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,6 +27,16 @@
27
27
  "import": "./dist/pty-host.js",
28
28
  "require": "./dist/pty-host.cjs"
29
29
  },
30
+ "./service": {
31
+ "import": {
32
+ "types": "./dist/service.d.ts",
33
+ "default": "./dist/service.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/service.d.cts",
37
+ "default": "./dist/service.cjs"
38
+ }
39
+ },
30
40
  "./package.json": "./package.json"
31
41
  },
32
42
  "files": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cwd.ts","../src/host-protocol.ts","../src/host-locate.ts"],"names":["os"],"mappings":";;;;;;AA8BO,SAAS,YAAY,CAAA,EAAmB;AAC3C,EAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,OAAA,IAAW,CAAC,GAAG,OAAO,CAAA;AAC/C,EAAA,MAAM,CAAA,GAAI,sBAAA,CAAuB,IAAA,CAAK,CAAC,CAAA;AACvC,EAAA,IAAI,CAAA,EAAG,OAAO,CAAA,EAAG,CAAA,CAAE,CAAC,CAAA,CAAE,WAAA,EAAa,CAAA,GAAA,EAAM,EAAE,CAAC,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,IAAI,CAAC,CAAA,CAAA;AAClE,EAAA,MAAM,IAAA,GAAO,mBAAA,CAAoB,IAAA,CAAK,CAAC,CAAA;AACvC,EAAA,IAAI,MAAM,OAAO,CAAA,EAAG,KAAK,CAAC,CAAA,CAAE,aAAa,CAAA,GAAA,CAAA;AACzC,EAAA,OAAO,CAAA;AACX;AAOO,SAAS,gBAAgB,SAAA,EAA8C;AAC1E,EAAA,IA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,KAAK,UAAA,EAAY;AACxB,IAAA,IAAI;AACA,MAAA,IAAI,EAAA,CAAG,UAAA,CAAW,CAAC,CAAA,EAAG,OAAO,CAAA;AAAA,IACjC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACJ;AACA,EAAA,OAAO,IAAA;AACX","file":"chunk-M5TFZDJA.js","sourcesContent":["/**\n * Spawn-cwd normalization (Tier 1.5 companion to osc7.ts).\n *\n * Git Bash / MSYS reports `$PWD` in MSYS form (`/c/Users/me`), not native\n * Windows (`C:\\Users\\me`). The OSC-7 hook emits that raw, and `parseFileUrl`\n * only converts the drive-colon form (`/C:/...`), so an MSYS path flows through\n * unchanged. Handing `/c/Users/me` to node-pty as a working dir makes Windows\n * fail with ERROR_DIRECTORY (error code 267) — terminal creation crashes.\n *\n * Two small, OS-agnostic helpers fix this at the source:\n * - `toNativeCwd` converts an MSYS path to native Windows form (no-op on\n * POSIX, or when already native).\n * - `resolveSpawnCwd` native-converts the requested dir AND validates it,\n * falling back to the home directory so a stale/foreign/deleted cwd can\n * never crash spawn.\n *\n * Used at both spawn sites (manager.ts, pty-host.ts) and at the OSC-7 capture\n * so the persisted `live_cwd` is already a valid native path.\n */\n\nimport { existsSync, statSync } from 'node:fs';\nimport os from 'node:os';\n\n/**\n * Convert an MSYS/Git-Bash cwd to a native Windows path.\n * /c/Users/me -> C:\\Users\\me\n * /d/work -> D:\\work\n * /c -> C:\\ (bare drive root)\n * No-op on non-win32, on an empty string, or on an already-native path.\n */\nexport function toNativeCwd(p: string): string {\n if (process.platform !== 'win32' || !p) return p;\n const m = /^\\/([A-Za-z])\\/(.*)$/.exec(p);\n if (m) return `${m[1].toUpperCase()}:\\\\${m[2].replace(/\\//g, '\\\\')}`;\n const root = /^\\/([A-Za-z])\\/?$/.exec(p);\n if (root) return `${root[1].toUpperCase()}:\\\\`;\n return p;\n}\n\n/**\n * Resolve the directory a pty should actually spawn in. Prefer the requested\n * dir (native-converted); if it isn't an existing directory, fall back to the\n * home directory — so a stale, foreign, or deleted cwd can't crash spawn.\n */\nexport function resolveSpawnCwd(requested: string | undefined | null): string {\n if (requested) {\n const native = toNativeCwd(requested);\n try {\n if (existsSync(native) && statSync(native).isDirectory()) return native;\n } catch {\n /* fall through to home */\n }\n }\n return os.homedir();\n}\n","/**\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"]}