@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 @@
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","fileURLToPath","os","spawn"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuBO,IAAM,gBAAA,GAAmB,CAAA;;;ACgGzB,SAAS,kBAAkB,OAAA,EAAgC;AAC9D,EAAA,MAAM,UAAA,GAAa;AAAA;AAAA;AAAA,IAGf,OAAA,CAAQ,QAAA,CAAS,CAAA,QAAA,EAAWA,sBAAA,CAAK,GAAG,CAAA,CAAE,CAAA,IAAK,OAAA,CAAQ,QAAA,CAAS,WAAW,CAAA,GACjE,OAAA,CAAQ,OAAA;AAAA,MACJ,kBAAA;AAAA,MACA,CAAA,mBAAA;AAAA,KACJ,GAAIA,sBAAA,CAAK,GAAA,GAAM,aAAA,GACf,EAAA;AAAA;AAAA,IAENA,sBAAA,CAAK,IAAA,CAAK,OAAA,EAAS,aAAa,CAAA;AAAA;AAAA,IAEhCA,uBAAK,IAAA,CAAK,OAAA,CAAQ,QAAQ,UAAA,EAAY,mBAAmB,GAAG,aAAa;AAAA,GAC7E,CAAE,OAAO,OAAO,CAAA;AAEhB,EAAA,KAAA,MAAW,KAAK,UAAA,EAAY;AACxB,IAAA,IAAI;AACA,MAAA,IAAIC,mBAAA,CAAG,UAAA,CAAW,CAAC,CAAA,EAAG,OAAO,CAAA;AAAA,IACjC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACJ;AACA,EAAA,OAAO,IAAA;AACX;;;ACxHO,SAAS,iBAAA,GAA4B;AACxC,EAAA,MAAM,IAAA,GACF,OAAO,SAAA,KAAc,WAAA,GACf,SAAA,GACAD,uBAAK,OAAA,CAAQE,iBAAA,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MAAA,KAAA,MAAW,KAAK,IAAA,CAAK,WAAA,EAAa,MAAM,EAAA,CAAG,GAAG,CAAC,CAAA;AAAA,IACnD;AAEA,IAAA,MAAM,EAAA,CAAG,MAAA,CAAO,QAAA,CAAS,WAAW,CAAA;AACpC,IAAA,MAAM,EAAA,CAAG,SAAA,CAAU,IAAA,CAAK,QAAA,EAAU,IAAA,CAAK,cAAc,EAAE,IAAA,EAAM,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"]}
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Per-user OS-service layer (Tier 3+) — run the pty-host as a launchd
3
+ * LaunchAgent / systemd --user unit / Windows per-user scheduled task, on its
4
+ * OWN standalone Node runtime instead of the consumer's Electron binary.
5
+ *
6
+ * Why: the detached host launched via `process.execPath` (Electron-as-node)
7
+ * PINS the consumer's executable, so an Electron auto-update can't overwrite it
8
+ * without killing live sessions. A service on its own runtime is never pinned —
9
+ * terminals survive both quits AND updates.
10
+ *
11
+ * The wire protocol, `HostClient`, pidfile, and socket path are all UNCHANGED;
12
+ * only the host's launch + lifecycle move here. See docs/persistence.md.
13
+ */
14
+ /** The per-OS service mechanism. */
15
+ type ServicePlatform = 'launchd' | 'systemd' | 'windows-task';
16
+ /**
17
+ * The standalone runtime the service runs the host on. MUST NOT be the
18
+ * consumer's Electron binary (that reintroduces the pin) — a plain Node.
19
+ */
20
+ interface ServiceRuntime {
21
+ /** Absolute path to a standalone `node` (never `electron`). */
22
+ nodePath: string;
23
+ /**
24
+ * Directory holding an ABI-matched `node-pty` build for `nodePath` (added to
25
+ * the service's `NODE_PATH`). Omit if node-pty resolves normally from the
26
+ * host script's own `node_modules`.
27
+ */
28
+ nodePtyDir?: string;
29
+ /** How this runtime was resolved (diagnostics only). */
30
+ source: string;
31
+ }
32
+ /** Inputs describing the service to install for this user. */
33
+ interface HostServiceConfig {
34
+ /**
35
+ * Reverse-DNS-ish service label, stable per app + user, e.g.
36
+ * `"academy.particle.genie.ptyhost"`. Used as the launchd Label, the
37
+ * systemd unit name, and the Windows task name.
38
+ */
39
+ label: string;
40
+ /** User-data dir the host uses for its pidfile / socket / snapshots. */
41
+ userDataDir: string;
42
+ /** Path to the pty-host script. Defaults to `ptyHostScriptPath()`. */
43
+ hostScript?: string;
44
+ /** The standalone runtime. Defaults to `resolveServiceRuntime()`. */
45
+ runtime?: ServiceRuntime;
46
+ /** Extra environment variables for the host process. */
47
+ env?: Record<string, string>;
48
+ /**
49
+ * Service revision. Bump (or rely on the default, which encodes the host
50
+ * protocol version) to force a reinstall on upgrade so a stale unit doesn't
51
+ * keep running an incompatible host.
52
+ */
53
+ revision?: string;
54
+ /** Directory for the service's stdout/stderr logs. Defaults to userDataDir. */
55
+ logDir?: string;
56
+ }
57
+ type ServiceState = 'running' | 'installed' | 'not-installed' | 'unsupported' | 'unknown';
58
+ /** A snapshot of the installed service's state. */
59
+ interface ServiceStatus {
60
+ platform: ServicePlatform | 'unsupported';
61
+ state: ServiceState;
62
+ installed: boolean;
63
+ running: boolean;
64
+ label: string;
65
+ /** Path to the written unit/plist/launcher, when applicable. */
66
+ unitPath?: string;
67
+ /** The revision recorded in the installed unit, if any. */
68
+ installedRevision?: string;
69
+ /** Free-text diagnostic (last command output / error). */
70
+ detail?: string;
71
+ }
72
+ /** What `ensureHostService()` did. */
73
+ type EnsureAction = 'already-running' | 'started' | 'installed-and-started' | 'reinstalled' | 'failed' | 'unsupported';
74
+ /** Result of `ensureHostService()` — never throws; inspect `ok`. */
75
+ interface EnsureResult {
76
+ /** True when the service is installed AND running at the matching revision. */
77
+ ok: boolean;
78
+ installed: boolean;
79
+ running: boolean;
80
+ action: EnsureAction;
81
+ runtime?: ServiceRuntime;
82
+ /** Set when `ok` is false — the reason, so the caller can fall back. */
83
+ error?: string;
84
+ }
85
+ /**
86
+ * Injected IO so the orchestration is unit-testable without touching the real
87
+ * OS. `nodeServiceIo()` is the production implementation.
88
+ */
89
+ interface ServiceIo {
90
+ /** Run a command; resolves with the exit code + captured output. */
91
+ run(argv: string[]): Promise<{
92
+ code: number;
93
+ stdout: string;
94
+ stderr: string;
95
+ }>;
96
+ writeFile(path: string, contents: string, opts?: {
97
+ mode?: number;
98
+ }): Promise<void>;
99
+ readFile(path: string): Promise<string | null>;
100
+ mkdirp(dir: string): Promise<void>;
101
+ rm(path: string): Promise<void>;
102
+ exists(path: string): Promise<boolean>;
103
+ }
104
+
105
+ /**
106
+ * Default service revision. Encodes the host PROTOCOL_VERSION so that a protocol
107
+ * bump (which makes an old host incompatible) forces a reinstall — the installed
108
+ * unit carries this marker and `ensureHostService` reinstalls on a mismatch.
109
+ */
110
+ declare const SERVICE_REVISION = "svc1+proto2";
111
+ /** A fully-resolved, per-OS description of the service to install. */
112
+ interface ServiceDescriptor {
113
+ platform: ServicePlatform;
114
+ label: string;
115
+ revision: string;
116
+ /** The file we write + own (plist / unit / launcher .cmd). */
117
+ unitPath: string;
118
+ unitContents: string;
119
+ /** POSIX file mode for the unit (e.g. 0o600 plist, 0o700 launcher). */
120
+ unitMode: number;
121
+ /** Commands (after the file is written) to register + start the service. */
122
+ installArgv: string[][];
123
+ /** Commands to stop + deregister. */
124
+ uninstallArgv: string[][];
125
+ startArgv: string[][];
126
+ stopArgv: string[][];
127
+ /** Single command whose output tells us installed/running. */
128
+ statusArgv: string[];
129
+ /** Files to remove on uninstall (unit + any logs we created). */
130
+ removePaths: string[];
131
+ }
132
+ interface DescriptorContext {
133
+ /** Override the platform (tests). Defaults to the current OS. */
134
+ platform?: ServicePlatform;
135
+ /** Home dir (tests). Defaults to `os.homedir()`. */
136
+ home?: string;
137
+ /** Numeric uid for launchd domain targets (tests / non-posix). */
138
+ uid?: number;
139
+ }
140
+ /** Map `process.platform` to a service mechanism, or null when unsupported. */
141
+ declare function servicePlatformFor(platform?: NodeJS.Platform): ServicePlatform | null;
142
+ /**
143
+ * Build the per-OS descriptor for a service config. PURE — no fs, no spawning —
144
+ * so the generated units + command argv are fully unit-testable.
145
+ */
146
+ declare function buildServiceDescriptor(config: ResolvedServiceConfig, ctx?: DescriptorContext): ServiceDescriptor;
147
+ /**
148
+ * A config with all defaults filled in — produced by `resolveServiceConfig`
149
+ * (see index.ts) and consumed by the descriptor builder.
150
+ */
151
+ interface ResolvedServiceConfig {
152
+ label: string;
153
+ userDataDir: string;
154
+ hostScript: string;
155
+ runtime: ServiceRuntime;
156
+ env: Record<string, string>;
157
+ revision: string;
158
+ logDir: string;
159
+ }
160
+ /** Read the revision marker out of an installed unit's contents, or null. */
161
+ declare function parseInstalledRevision(unitContents: string): string | null;
162
+
163
+ /**
164
+ * Locate a STANDALONE Node runtime to run the host service on — explicitly NOT
165
+ * the consumer's Electron binary, whose whole problem is that running the host
166
+ * on it pins the executable across auto-updates.
167
+ *
168
+ * Precedence:
169
+ * 1. An explicit `nodePath` (the consumer ships/locates its own node).
170
+ * 2. `$FANCY_TERM_NODE` (a deploy-time override).
171
+ * 3. `process.execPath` — but ONLY if the current process is plain Node, not
172
+ * Electron (`process.versions.electron`), and the binary is named `node`.
173
+ * 4. A `node` / `node.exe` found on `$PATH`.
174
+ *
175
+ * Returns null when no safe standalone runtime is found — the caller should then
176
+ * fall back to the existing detached-spawn (which works for a normal quit) or
177
+ * in-process. Never throws.
178
+ */
179
+ interface ResolveRuntimeOptions {
180
+ /** Explicit standalone node path (wins). */
181
+ nodePath?: string;
182
+ /** Directory with an ABI-matched node-pty for that runtime. */
183
+ nodePtyDir?: string;
184
+ /** Environment to read overrides from. Defaults to `process.env`. */
185
+ env?: NodeJS.ProcessEnv;
186
+ /** Current process binary. Defaults to `process.execPath`. */
187
+ execPath?: string;
188
+ /** Whether the current process is Electron. Defaults to detecting it. */
189
+ isElectron?: boolean;
190
+ /** PATH lookup probe (injectable for tests). Defaults to an fs probe. */
191
+ pathProbe?: (binNames: string[], env: NodeJS.ProcessEnv) => string | null;
192
+ }
193
+ declare function resolveServiceRuntime(opts?: ResolveRuntimeOptions): ServiceRuntime | null;
194
+
195
+ /**
196
+ * Production {@link ServiceIo}: real fs + child_process. The orchestration in
197
+ * index.ts takes a ServiceIo so tests can inject a fake and never touch the OS.
198
+ */
199
+ declare function nodeServiceIo(): ServiceIo;
200
+
201
+ /**
202
+ * Per-user OS-service lifecycle for the pty-host. Install / start / stop /
203
+ * status / uninstall + a single `ensureHostService()` that does the
204
+ * install-if-missing-or-stale → start-if-stopped dance.
205
+ *
206
+ * Pairs with the existing detached-host path: the wire protocol, pidfile, and
207
+ * `HostClient` are unchanged, so the consumer connects exactly as today. The
208
+ * difference is WHO launches the host — a per-user service on a standalone Node
209
+ * runtime, not a child of the consumer's Electron binary.
210
+ *
211
+ * Everything here is graceful: `ensureHostService` never throws (inspect `ok`),
212
+ * so a consumer can try the service and, on failure, fall back to
213
+ * `HostSpawner.spawnDetached` (normal-quit survival) → in-process.
214
+ */
215
+
216
+ /** True when the current OS has a supported service mechanism. */
217
+ declare function isServiceSupported(): boolean;
218
+ /**
219
+ * Fill in every default (host script, runtime, revision, log dir) so the
220
+ * descriptor builder has a complete config. Throws only if no standalone Node
221
+ * runtime can be resolved — callers that want graceful behaviour should use
222
+ * `ensureHostService`, which catches this.
223
+ */
224
+ declare function resolveServiceConfig(config: HostServiceConfig): ResolvedServiceConfig;
225
+ /** Write the unit file(s) and register + start the service. */
226
+ declare function installHostService(config: HostServiceConfig, io?: ServiceIo): Promise<ServiceStatus>;
227
+ /** Stop + deregister the service and remove its unit file(s). */
228
+ declare function uninstallHostService(config: HostServiceConfig, io?: ServiceIo): Promise<void>;
229
+ declare function startHostService(config: HostServiceConfig, io?: ServiceIo): Promise<void>;
230
+ declare function stopHostService(config: HostServiceConfig, io?: ServiceIo): Promise<void>;
231
+ declare function isServiceInstalled(config: HostServiceConfig, io?: ServiceIo): Promise<boolean>;
232
+ declare function serviceStatus(config: HostServiceConfig, io?: ServiceIo): Promise<ServiceStatus>;
233
+ /**
234
+ * Ensure the service is installed at the current revision AND running.
235
+ *
236
+ * - already running at this revision → no-op
237
+ * - installed (this revision), stopped → start
238
+ * - installed at a DIFFERENT revision → uninstall + reinstall + start
239
+ * - not installed → install (+ start)
240
+ *
241
+ * NEVER throws. On any failure (no runtime, unsupported OS, a command error) it
242
+ * returns `{ ok: false, … }` with an `error` so the caller can fall back to the
243
+ * detached-spawn path. Snapshot live sessions before a reinstall if you need
244
+ * history to survive it (a reinstall restarts the host).
245
+ */
246
+ declare function ensureHostService(config: HostServiceConfig, io?: ServiceIo): Promise<EnsureResult>;
247
+
248
+ export { type EnsureAction, type EnsureResult, type HostServiceConfig, type ResolvedServiceConfig, SERVICE_REVISION, type ServiceDescriptor, type ServiceIo, type ServicePlatform, type ServiceRuntime, type ServiceState, type ServiceStatus, buildServiceDescriptor, ensureHostService, installHostService, isServiceInstalled, isServiceSupported, nodeServiceIo, parseInstalledRevision, resolveServiceConfig, resolveServiceRuntime, servicePlatformFor, serviceStatus, startHostService, stopHostService, uninstallHostService };
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Per-user OS-service layer (Tier 3+) — run the pty-host as a launchd
3
+ * LaunchAgent / systemd --user unit / Windows per-user scheduled task, on its
4
+ * OWN standalone Node runtime instead of the consumer's Electron binary.
5
+ *
6
+ * Why: the detached host launched via `process.execPath` (Electron-as-node)
7
+ * PINS the consumer's executable, so an Electron auto-update can't overwrite it
8
+ * without killing live sessions. A service on its own runtime is never pinned —
9
+ * terminals survive both quits AND updates.
10
+ *
11
+ * The wire protocol, `HostClient`, pidfile, and socket path are all UNCHANGED;
12
+ * only the host's launch + lifecycle move here. See docs/persistence.md.
13
+ */
14
+ /** The per-OS service mechanism. */
15
+ type ServicePlatform = 'launchd' | 'systemd' | 'windows-task';
16
+ /**
17
+ * The standalone runtime the service runs the host on. MUST NOT be the
18
+ * consumer's Electron binary (that reintroduces the pin) — a plain Node.
19
+ */
20
+ interface ServiceRuntime {
21
+ /** Absolute path to a standalone `node` (never `electron`). */
22
+ nodePath: string;
23
+ /**
24
+ * Directory holding an ABI-matched `node-pty` build for `nodePath` (added to
25
+ * the service's `NODE_PATH`). Omit if node-pty resolves normally from the
26
+ * host script's own `node_modules`.
27
+ */
28
+ nodePtyDir?: string;
29
+ /** How this runtime was resolved (diagnostics only). */
30
+ source: string;
31
+ }
32
+ /** Inputs describing the service to install for this user. */
33
+ interface HostServiceConfig {
34
+ /**
35
+ * Reverse-DNS-ish service label, stable per app + user, e.g.
36
+ * `"academy.particle.genie.ptyhost"`. Used as the launchd Label, the
37
+ * systemd unit name, and the Windows task name.
38
+ */
39
+ label: string;
40
+ /** User-data dir the host uses for its pidfile / socket / snapshots. */
41
+ userDataDir: string;
42
+ /** Path to the pty-host script. Defaults to `ptyHostScriptPath()`. */
43
+ hostScript?: string;
44
+ /** The standalone runtime. Defaults to `resolveServiceRuntime()`. */
45
+ runtime?: ServiceRuntime;
46
+ /** Extra environment variables for the host process. */
47
+ env?: Record<string, string>;
48
+ /**
49
+ * Service revision. Bump (or rely on the default, which encodes the host
50
+ * protocol version) to force a reinstall on upgrade so a stale unit doesn't
51
+ * keep running an incompatible host.
52
+ */
53
+ revision?: string;
54
+ /** Directory for the service's stdout/stderr logs. Defaults to userDataDir. */
55
+ logDir?: string;
56
+ }
57
+ type ServiceState = 'running' | 'installed' | 'not-installed' | 'unsupported' | 'unknown';
58
+ /** A snapshot of the installed service's state. */
59
+ interface ServiceStatus {
60
+ platform: ServicePlatform | 'unsupported';
61
+ state: ServiceState;
62
+ installed: boolean;
63
+ running: boolean;
64
+ label: string;
65
+ /** Path to the written unit/plist/launcher, when applicable. */
66
+ unitPath?: string;
67
+ /** The revision recorded in the installed unit, if any. */
68
+ installedRevision?: string;
69
+ /** Free-text diagnostic (last command output / error). */
70
+ detail?: string;
71
+ }
72
+ /** What `ensureHostService()` did. */
73
+ type EnsureAction = 'already-running' | 'started' | 'installed-and-started' | 'reinstalled' | 'failed' | 'unsupported';
74
+ /** Result of `ensureHostService()` — never throws; inspect `ok`. */
75
+ interface EnsureResult {
76
+ /** True when the service is installed AND running at the matching revision. */
77
+ ok: boolean;
78
+ installed: boolean;
79
+ running: boolean;
80
+ action: EnsureAction;
81
+ runtime?: ServiceRuntime;
82
+ /** Set when `ok` is false — the reason, so the caller can fall back. */
83
+ error?: string;
84
+ }
85
+ /**
86
+ * Injected IO so the orchestration is unit-testable without touching the real
87
+ * OS. `nodeServiceIo()` is the production implementation.
88
+ */
89
+ interface ServiceIo {
90
+ /** Run a command; resolves with the exit code + captured output. */
91
+ run(argv: string[]): Promise<{
92
+ code: number;
93
+ stdout: string;
94
+ stderr: string;
95
+ }>;
96
+ writeFile(path: string, contents: string, opts?: {
97
+ mode?: number;
98
+ }): Promise<void>;
99
+ readFile(path: string): Promise<string | null>;
100
+ mkdirp(dir: string): Promise<void>;
101
+ rm(path: string): Promise<void>;
102
+ exists(path: string): Promise<boolean>;
103
+ }
104
+
105
+ /**
106
+ * Default service revision. Encodes the host PROTOCOL_VERSION so that a protocol
107
+ * bump (which makes an old host incompatible) forces a reinstall — the installed
108
+ * unit carries this marker and `ensureHostService` reinstalls on a mismatch.
109
+ */
110
+ declare const SERVICE_REVISION = "svc1+proto2";
111
+ /** A fully-resolved, per-OS description of the service to install. */
112
+ interface ServiceDescriptor {
113
+ platform: ServicePlatform;
114
+ label: string;
115
+ revision: string;
116
+ /** The file we write + own (plist / unit / launcher .cmd). */
117
+ unitPath: string;
118
+ unitContents: string;
119
+ /** POSIX file mode for the unit (e.g. 0o600 plist, 0o700 launcher). */
120
+ unitMode: number;
121
+ /** Commands (after the file is written) to register + start the service. */
122
+ installArgv: string[][];
123
+ /** Commands to stop + deregister. */
124
+ uninstallArgv: string[][];
125
+ startArgv: string[][];
126
+ stopArgv: string[][];
127
+ /** Single command whose output tells us installed/running. */
128
+ statusArgv: string[];
129
+ /** Files to remove on uninstall (unit + any logs we created). */
130
+ removePaths: string[];
131
+ }
132
+ interface DescriptorContext {
133
+ /** Override the platform (tests). Defaults to the current OS. */
134
+ platform?: ServicePlatform;
135
+ /** Home dir (tests). Defaults to `os.homedir()`. */
136
+ home?: string;
137
+ /** Numeric uid for launchd domain targets (tests / non-posix). */
138
+ uid?: number;
139
+ }
140
+ /** Map `process.platform` to a service mechanism, or null when unsupported. */
141
+ declare function servicePlatformFor(platform?: NodeJS.Platform): ServicePlatform | null;
142
+ /**
143
+ * Build the per-OS descriptor for a service config. PURE — no fs, no spawning —
144
+ * so the generated units + command argv are fully unit-testable.
145
+ */
146
+ declare function buildServiceDescriptor(config: ResolvedServiceConfig, ctx?: DescriptorContext): ServiceDescriptor;
147
+ /**
148
+ * A config with all defaults filled in — produced by `resolveServiceConfig`
149
+ * (see index.ts) and consumed by the descriptor builder.
150
+ */
151
+ interface ResolvedServiceConfig {
152
+ label: string;
153
+ userDataDir: string;
154
+ hostScript: string;
155
+ runtime: ServiceRuntime;
156
+ env: Record<string, string>;
157
+ revision: string;
158
+ logDir: string;
159
+ }
160
+ /** Read the revision marker out of an installed unit's contents, or null. */
161
+ declare function parseInstalledRevision(unitContents: string): string | null;
162
+
163
+ /**
164
+ * Locate a STANDALONE Node runtime to run the host service on — explicitly NOT
165
+ * the consumer's Electron binary, whose whole problem is that running the host
166
+ * on it pins the executable across auto-updates.
167
+ *
168
+ * Precedence:
169
+ * 1. An explicit `nodePath` (the consumer ships/locates its own node).
170
+ * 2. `$FANCY_TERM_NODE` (a deploy-time override).
171
+ * 3. `process.execPath` — but ONLY if the current process is plain Node, not
172
+ * Electron (`process.versions.electron`), and the binary is named `node`.
173
+ * 4. A `node` / `node.exe` found on `$PATH`.
174
+ *
175
+ * Returns null when no safe standalone runtime is found — the caller should then
176
+ * fall back to the existing detached-spawn (which works for a normal quit) or
177
+ * in-process. Never throws.
178
+ */
179
+ interface ResolveRuntimeOptions {
180
+ /** Explicit standalone node path (wins). */
181
+ nodePath?: string;
182
+ /** Directory with an ABI-matched node-pty for that runtime. */
183
+ nodePtyDir?: string;
184
+ /** Environment to read overrides from. Defaults to `process.env`. */
185
+ env?: NodeJS.ProcessEnv;
186
+ /** Current process binary. Defaults to `process.execPath`. */
187
+ execPath?: string;
188
+ /** Whether the current process is Electron. Defaults to detecting it. */
189
+ isElectron?: boolean;
190
+ /** PATH lookup probe (injectable for tests). Defaults to an fs probe. */
191
+ pathProbe?: (binNames: string[], env: NodeJS.ProcessEnv) => string | null;
192
+ }
193
+ declare function resolveServiceRuntime(opts?: ResolveRuntimeOptions): ServiceRuntime | null;
194
+
195
+ /**
196
+ * Production {@link ServiceIo}: real fs + child_process. The orchestration in
197
+ * index.ts takes a ServiceIo so tests can inject a fake and never touch the OS.
198
+ */
199
+ declare function nodeServiceIo(): ServiceIo;
200
+
201
+ /**
202
+ * Per-user OS-service lifecycle for the pty-host. Install / start / stop /
203
+ * status / uninstall + a single `ensureHostService()` that does the
204
+ * install-if-missing-or-stale → start-if-stopped dance.
205
+ *
206
+ * Pairs with the existing detached-host path: the wire protocol, pidfile, and
207
+ * `HostClient` are unchanged, so the consumer connects exactly as today. The
208
+ * difference is WHO launches the host — a per-user service on a standalone Node
209
+ * runtime, not a child of the consumer's Electron binary.
210
+ *
211
+ * Everything here is graceful: `ensureHostService` never throws (inspect `ok`),
212
+ * so a consumer can try the service and, on failure, fall back to
213
+ * `HostSpawner.spawnDetached` (normal-quit survival) → in-process.
214
+ */
215
+
216
+ /** True when the current OS has a supported service mechanism. */
217
+ declare function isServiceSupported(): boolean;
218
+ /**
219
+ * Fill in every default (host script, runtime, revision, log dir) so the
220
+ * descriptor builder has a complete config. Throws only if no standalone Node
221
+ * runtime can be resolved — callers that want graceful behaviour should use
222
+ * `ensureHostService`, which catches this.
223
+ */
224
+ declare function resolveServiceConfig(config: HostServiceConfig): ResolvedServiceConfig;
225
+ /** Write the unit file(s) and register + start the service. */
226
+ declare function installHostService(config: HostServiceConfig, io?: ServiceIo): Promise<ServiceStatus>;
227
+ /** Stop + deregister the service and remove its unit file(s). */
228
+ declare function uninstallHostService(config: HostServiceConfig, io?: ServiceIo): Promise<void>;
229
+ declare function startHostService(config: HostServiceConfig, io?: ServiceIo): Promise<void>;
230
+ declare function stopHostService(config: HostServiceConfig, io?: ServiceIo): Promise<void>;
231
+ declare function isServiceInstalled(config: HostServiceConfig, io?: ServiceIo): Promise<boolean>;
232
+ declare function serviceStatus(config: HostServiceConfig, io?: ServiceIo): Promise<ServiceStatus>;
233
+ /**
234
+ * Ensure the service is installed at the current revision AND running.
235
+ *
236
+ * - already running at this revision → no-op
237
+ * - installed (this revision), stopped → start
238
+ * - installed at a DIFFERENT revision → uninstall + reinstall + start
239
+ * - not installed → install (+ start)
240
+ *
241
+ * NEVER throws. On any failure (no runtime, unsupported OS, a command error) it
242
+ * returns `{ ok: false, … }` with an `error` so the caller can fall back to the
243
+ * detached-spawn path. Snapshot live sessions before a reinstall if you need
244
+ * history to survive it (a reinstall restarts the host).
245
+ */
246
+ declare function ensureHostService(config: HostServiceConfig, io?: ServiceIo): Promise<EnsureResult>;
247
+
248
+ export { type EnsureAction, type EnsureResult, type HostServiceConfig, type ResolvedServiceConfig, SERVICE_REVISION, type ServiceDescriptor, type ServiceIo, type ServicePlatform, type ServiceRuntime, type ServiceState, type ServiceStatus, buildServiceDescriptor, ensureHostService, installHostService, isServiceInstalled, isServiceSupported, nodeServiceIo, parseInstalledRevision, resolveServiceConfig, resolveServiceRuntime, servicePlatformFor, serviceStatus, startHostService, stopHostService, uninstallHostService };