@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.
package/README.md CHANGED
@@ -86,6 +86,12 @@ Switchable behind one `PtyBackend` interface (see [`docs/persistence.md`](./docs
86
86
  that survives a full quit of the app. The backend proxies calls over a named
87
87
  pipe (Windows) / unix socket (POSIX); reopening reattaches to the still-running
88
88
  shells.
89
+ - **T3+ — per-user OS service.** Run the pty-host as a `launchd` / `systemd
90
+ --user` / Windows-task service on its **own** standalone Node runtime, so an
91
+ Electron auto-update never pins the consumer binary — terminals survive quits
92
+ *and* updates. Subpath `@particle-academy/fancy-term-host/service`;
93
+ `ensureHostService(...)` installs-if-missing → starts, with graceful fallback.
94
+ See [`docs/service.md`](./docs/service.md).
89
95
 
90
96
  ### Spawning the detached host (T3)
91
97
 
@@ -1,30 +1,10 @@
1
- import fs, { existsSync, statSync } from 'fs';
2
- import os2 from 'os';
3
1
  import path from 'path';
2
+ import os from 'os';
3
+ import fs from 'fs';
4
4
  import crypto from 'crypto';
5
5
 
6
- // src/cwd.ts
7
- function toNativeCwd(p) {
8
- if (process.platform !== "win32" || !p) return p;
9
- const m = /^\/([A-Za-z])\/(.*)$/.exec(p);
10
- if (m) return `${m[1].toUpperCase()}:\\${m[2].replace(/\//g, "\\")}`;
11
- const root = /^\/([A-Za-z])\/?$/.exec(p);
12
- if (root) return `${root[1].toUpperCase()}:\\`;
13
- return p;
14
- }
15
- function resolveSpawnCwd(requested) {
16
- if (requested) {
17
- const native = toNativeCwd(requested);
18
- try {
19
- if (existsSync(native) && statSync(native).isDirectory()) return native;
20
- } catch {
21
- }
22
- }
23
- return os2.homedir();
24
- }
25
-
26
6
  // src/host-protocol.ts
27
- var PROTOCOL_VERSION = 1;
7
+ var PROTOCOL_VERSION = 2;
28
8
  var LENGTH_BYTES = 4;
29
9
  function encodeFrame(msg) {
30
10
  const body = Buffer.from(JSON.stringify(msg), "utf8");
@@ -67,7 +47,7 @@ var _FrameDecoder = class _FrameDecoder {
67
47
  _FrameDecoder.MAX_FRAME = 16 * 1024 * 1024;
68
48
  var FrameDecoder = _FrameDecoder;
69
49
  function userHash() {
70
- const seed = `${os2.userInfo().username}|${os2.hostname()}`;
50
+ const seed = `${os.userInfo().username}|${os.hostname()}`;
71
51
  return crypto.createHash("sha1").update(seed).digest("hex").slice(0, 12);
72
52
  }
73
53
  function socketPathFor(userDataDir) {
@@ -76,7 +56,7 @@ function socketPathFor(userDataDir) {
76
56
  }
77
57
  const candidate = path.join(userDataDir, "ptyhost.sock");
78
58
  if (candidate.length < 100) return candidate;
79
- return path.join(os2.tmpdir(), `genie-ptyhost-${userHash()}.sock`);
59
+ return path.join(os.tmpdir(), `genie-ptyhost-${userHash()}.sock`);
80
60
  }
81
61
  function pidfilePath(userDataDir) {
82
62
  return path.join(userDataDir, "ptyhost.json");
@@ -142,6 +122,6 @@ function resolveHostScript(dirname) {
142
122
  return null;
143
123
  }
144
124
 
145
- export { FrameDecoder, PROTOCOL_VERSION, deletePidfile, encodeFrame, isPidAlive, pidfilePath, pidfileUsable, readPidfile, resolveHostScript, resolveSpawnCwd, socketPathFor, toNativeCwd, userHash, writePidfile };
146
- //# sourceMappingURL=chunk-WMP4YLM5.js.map
147
- //# sourceMappingURL=chunk-WMP4YLM5.js.map
125
+ export { FrameDecoder, PROTOCOL_VERSION, deletePidfile, encodeFrame, isPidAlive, pidfilePath, pidfileUsable, readPidfile, resolveHostScript, socketPathFor, userHash, writePidfile };
126
+ //# sourceMappingURL=chunk-7NXYRMNA.js.map
127
+ //# sourceMappingURL=chunk-7NXYRMNA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host-protocol.ts","../src/host-locate.ts"],"names":[],"mappings":";;;;;;AAuBO,IAAM,gBAAA,GAAmB;AAsDhC,IAAM,YAAA,GAAe,CAAA;AAGd,SAAS,YAAY,GAAA,EAAoB;AAC5C,EAAA,MAAM,OAAO,MA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AAA;AAAA,EACnD;AACJ;AAOO,SAAS,cAAc,EAAA,EAA6B;AACvD,EAAA,IAAI,CAAC,IAAI,OAAO,KAAA;AAChB,EAAA,IAAI,EAAA,CAAG,eAAA,KAAoB,gBAAA,EAAkB,OAAO,KAAA;AACpD,EAAA,IAAI,CAAC,UAAA,CAAW,EAAA,CAAG,GAAG,GAAG,OAAO,KAAA;AAChC,EAAA,OAAO,IAAA;AACX;AAaO,SAAS,kBAAkB,OAAA,EAAgC;AAC9D,EAAA,MAAM,UAAA,GAAa;AAAA;AAAA;AAAA,IAGf,OAAA,CAAQ,QAAA,CAAS,CAAA,QAAA,EAAW,IAAA,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,GAAI,IAAA,CAAK,GAAA,GAAM,aAAA,GACf,EAAA;AAAA;AAAA,IAEN,IAAA,CAAK,IAAA,CAAK,OAAA,EAAS,aAAa,CAAA;AAAA;AAAA,IAEhC,KAAK,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,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-7NXYRMNA.js","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"]}
@@ -0,0 +1,12 @@
1
+ import { resolveHostScript } from './chunk-7NXYRMNA.js';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ function ptyHostScriptPath() {
6
+ const here = typeof __dirname !== "undefined" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
7
+ return resolveHostScript(here) ?? path.join(here, "pty-host.js");
8
+ }
9
+
10
+ export { ptyHostScriptPath };
11
+ //# sourceMappingURL=chunk-DB3SIE53.js.map
12
+ //# sourceMappingURL=chunk-DB3SIE53.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host-script.ts"],"names":[],"mappings":";;;;AAuBO,SAAS,iBAAA,GAA4B;AACxC,EAAA,MAAM,IAAA,GACF,OAAO,SAAA,KAAc,WAAA,GACf,SAAA,GACA,KAAK,OAAA,CAAQ,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAC,CAAA;AAGrD,EAAA,OAAO,kBAAkB,IAAI,CAAA,IAAK,IAAA,CAAK,IAAA,CAAK,MAAM,aAAa,CAAA;AACnE","file":"chunk-DB3SIE53.js","sourcesContent":["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"]}
@@ -0,0 +1,26 @@
1
+ import { existsSync, statSync } from 'fs';
2
+ import os from 'os';
3
+
4
+ // src/cwd.ts
5
+ function toNativeCwd(p) {
6
+ if (process.platform !== "win32" || !p) return p;
7
+ const m = /^\/([A-Za-z])\/(.*)$/.exec(p);
8
+ if (m) return `${m[1].toUpperCase()}:\\${m[2].replace(/\//g, "\\")}`;
9
+ const root = /^\/([A-Za-z])\/?$/.exec(p);
10
+ if (root) return `${root[1].toUpperCase()}:\\`;
11
+ return p;
12
+ }
13
+ function resolveSpawnCwd(requested) {
14
+ if (requested) {
15
+ const native = toNativeCwd(requested);
16
+ try {
17
+ if (existsSync(native) && statSync(native).isDirectory()) return native;
18
+ } catch {
19
+ }
20
+ }
21
+ return os.homedir();
22
+ }
23
+
24
+ export { resolveSpawnCwd, toNativeCwd };
25
+ //# sourceMappingURL=chunk-V3MW5UTX.js.map
26
+ //# sourceMappingURL=chunk-V3MW5UTX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cwd.ts"],"names":[],"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,IAAI,SAAA,EAAW;AACX,IAAA,MAAM,MAAA,GAAS,YAAY,SAAS,CAAA;AACpC,IAAA,IAAI;AACA,MAAA,IAAI,UAAA,CAAW,MAAM,CAAA,IAAK,QAAA,CAAS,MAAM,CAAA,CAAE,WAAA,IAAe,OAAO,MAAA;AAAA,IACrE,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACJ;AACA,EAAA,OAAO,GAAG,OAAA,EAAQ;AACtB","file":"chunk-V3MW5UTX.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"]}
package/dist/index.cjs CHANGED
@@ -650,7 +650,7 @@ function createSnapshotStore(config) {
650
650
  }
651
651
 
652
652
  // src/host-protocol.ts
653
- var PROTOCOL_VERSION = 1;
653
+ var PROTOCOL_VERSION = 2;
654
654
  var LENGTH_BYTES = 4;
655
655
  function encodeFrame(msg) {
656
656
  const body = Buffer.from(JSON.stringify(msg), "utf8");
@@ -881,6 +881,42 @@ var HostClient = class _HostClient extends events.EventEmitter {
881
881
  isConnected() {
882
882
  return this.connected;
883
883
  }
884
+ /**
885
+ * Gracefully shut the host DOWN — the deliberate counterpart to
886
+ * `disconnect()` (which leaves the host running). Asks the host to kill its
887
+ * ptys, remove its pidfile/socket, and exit cleanly, then drops the local
888
+ * socket. Use this when a consumer needs the host genuinely gone — e.g.
889
+ * before an Electron auto-update whose installer must overwrite the binary
890
+ * the host runs on — INSTEAD of SIGKILLing by pidfile pid, which skips the
891
+ * host's own cleanup.
892
+ *
893
+ * The client mirror already holds the live scrollback, so snapshot via the
894
+ * SnapshotStore BEFORE calling this if you want T1 history to survive.
895
+ *
896
+ * Resolves once the host acknowledges (`shutdown-ok`) or the connection
897
+ * closes (the host exited), whichever comes first; never rejects — a host
898
+ * that's already gone is a successful shutdown.
899
+ */
900
+ shutdownHost(timeoutMs = 2e3) {
901
+ if (!this.socket || !this.connected) {
902
+ this.disconnect();
903
+ return Promise.resolve();
904
+ }
905
+ this.connected = false;
906
+ return new Promise((resolve) => {
907
+ let done = false;
908
+ const finish = () => {
909
+ if (done) return;
910
+ done = true;
911
+ clearTimeout(timer);
912
+ this.disconnect();
913
+ resolve();
914
+ };
915
+ const timer = setTimeout(finish, timeoutMs);
916
+ this.socket?.once("close", finish);
917
+ this.request({ kind: "shutdown", seq: this.nextSeq() }).then(finish).catch(finish);
918
+ });
919
+ }
884
920
  /** Disconnect WITHOUT killing host ptys (before-quit leave-running). */
885
921
  disconnect() {
886
922
  this.connected = false;
@@ -1160,6 +1196,17 @@ function disconnectHostLeaveRunning() {
1160
1196
  }
1161
1197
  }
1162
1198
  }
1199
+ async function shutdownHost(timeoutMs = 2e3) {
1200
+ const c = client;
1201
+ usingHost = false;
1202
+ client = null;
1203
+ setActiveBackend(inProcessBackend());
1204
+ if (!c) return;
1205
+ try {
1206
+ await c.shutdownHost(timeoutMs);
1207
+ } catch {
1208
+ }
1209
+ }
1163
1210
  function ptyHostScriptPath() {
1164
1211
  const here = typeof __dirname !== "undefined" ? __dirname : path__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
1165
1212
  return resolveHostScript(here) ?? path__default.default.join(here, "pty-host.js");
@@ -1196,6 +1243,7 @@ exports.resolveSpawnCwd = resolveSpawnCwd;
1196
1243
  exports.scanOsc7Cwd = scanOsc7Cwd;
1197
1244
  exports.setActiveBackend = setActiveBackend;
1198
1245
  exports.shellKind = shellKind;
1246
+ exports.shutdownHost = shutdownHost;
1199
1247
  exports.socketPathFor = socketPathFor;
1200
1248
  exports.subscribeBackendEvents = subscribeBackendEvents;
1201
1249
  exports.terminalManager = terminalManager;