truthspine 0.0.0-stage → 0.2.2

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,963 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // Thin connector transport, compatible with the MCPB's Node >=16 runtime.
5
+ // No TruthSpine engine import. Registration selects a launch destination; it
6
+ // never supplies Store ownership. The installed core verifies native access.
7
+ // (The one exception runs the installed package's own server in this process: inPlaceHandover below.)
8
+ const fs = require("node:fs");
9
+ const path = require("node:path");
10
+ const crypto = require("node:crypto");
11
+ const { spawn } = require("node:child_process");
12
+ const net = require("node:net");
13
+
14
+ const ERROR = "TruthSpine could not start. Open the TruthSpine app and try again. Your purchase is not affected.";
15
+ const fail = () => { throw new Error(ERROR); };
16
+ // Typed launcher results. Every failure still throws the same generic sentence (ERROR) and
17
+ // nothing below changes which conditions fail; a failure that can be told apart safely also
18
+ // carries a stable code so the entry point and host wrappers can show a short, honest message.
19
+ // The catalogue mirrors src/agent-contract/launcher-results.js and is kept inline because
20
+ // generated wrappers (MCPB, VS Code, Codex) must stay single-file with no engine import.
21
+ // license_required and incompatible_version are decided by the installed core after the
22
+ // connection opens, never by this transport.
23
+ const LAUNCHER_RESULTS = Object.freeze({
24
+ app_not_installed: "TruthSpine isn't installed on this computer.",
25
+ app_not_running: "TruthSpine is installed but not running. Open it and try again.",
26
+ app_not_answering: "TruthSpine is installed but did not answer. Open the TruthSpine app and try again.",
27
+ app_not_opened: "TruthSpine is installed but has not been opened yet. Open TruthSpine once, then try again.",
28
+ unavailable: ERROR
29
+ });
30
+ const LAUNCHER_STORE_LINKS = Object.freeze({ win32: "https://apps.microsoft.com/detail/9pbn25k75vdj", darwin: "https://apps.apple.com/us/app/truthspine/id6794478470?mt=12" });
31
+ const LAUNCHER_CODE_PREFIX = "truthspine.launcher.";
32
+ const typedFail = code => { const error = new Error(ERROR); error.code = LAUNCHER_CODE_PREFIX + code; throw error; };
33
+ const typedCode = error => {
34
+ const code = error && typeof error.code === "string" && error.code.indexOf(LAUNCHER_CODE_PREFIX) === 0 ? error.code.slice(LAUNCHER_CODE_PREFIX.length) : null;
35
+ if (code && Object.prototype.hasOwnProperty.call(LAUNCHER_RESULTS, code)) return code;
36
+ return error && error.message === "store_package_recovery_unavailable" ? "app_not_installed" : null;
37
+ };
38
+ // The one line a person should read when the launcher cannot connect.
39
+ function describeLauncherFailure(error, platform) {
40
+ const code = typedCode(error) || "unavailable";
41
+ const where = platform || process.platform;
42
+ const link = code === "app_not_installed" ? LAUNCHER_STORE_LINKS[where] : undefined;
43
+ // (truthspine.app on every platform, and Linux its own page: B8)
44
+ const get = code === "app_not_installed" ? " Get it here: " + (link ? link + " or " + DOWNLOAD_PAGE : LAUNCHER_GET_LINKS[where] || DOWNLOAD_PAGE) : "";
45
+ return { code, message: LAUNCHER_RESULTS[code] + get, storeLink: link };
46
+ }
47
+ const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
48
+ // "continue" stays accepted so an entry an earlier version wrote keeps starting; TruthSpine no longer offers or writes it
49
+ // (Continue retired by the owner, 2026-10-09).
50
+ const HOST_IDS = new Set(["claude-desktop", "claude-code", "codex-cli", "cursor", "vscode", "github-copilot-vscode", "continue", "cline", "cline-cli", "windsurf-devin", "opencode", "opencode-ide", "lm-studio", "kiro", "antigravity", "jetbrains", "zed", "hermes-agent", "openclaw", "copilot-cli", "droid", "pi", "computer-agent", "gemini-cli"]);
51
+ // The smaller tool set each app gets; every app not named here gets the full catalog. Nothing falls into a smaller set by
52
+ // default: Claude Code did, from the copilot fallback (2026-09-08) and its joining the host list (2026-09-24), and a
53
+ // shipped package refused its session_update (Brain 2026-10-29).
54
+ const HOST_TOOL_PROFILES = Object.freeze({
55
+ "claude-desktop": "claude-desktop",
56
+ "lm-studio": "lm-studio",
57
+ opencode: "local-agent", "hermes-agent": "local-agent", openclaw: "local-agent", droid: "local-agent", pi: "local-agent",
58
+ vscode: "copilot", // VS Code's own sync command carries its session updates, not this connection
59
+ "github-copilot-vscode": "copilot", // the same VS Code extension and sync command
60
+ "copilot-cli": "copilot" // named so since July (surface-connector-runtime.js)
61
+ });
62
+ function absolute(value, paths) {
63
+ if (typeof value !== "string" || !value.trim() || value !== value.trim()
64
+ || /[\u0000-\u001f\u007f]/.test(value) || !paths.isAbsolute(value)) fail();
65
+ return paths.resolve(value);
66
+ }
67
+ function equal(a, b, platform) { return platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b; }
68
+ // Program Files, where the Store installs (WindowsApps). Codex starts its servers with a short environment that leaves
69
+ // ProgramFiles out (Main Build, Windows VM 2026-10-10: TruthSpine stopped before Codex saw its tools); Windows keeps
70
+ // it on the system drive, as systemOrProgramFolder below already assumes. The executable must still sit exactly there.
71
+ function windowsProgramFiles(env, paths) {
72
+ const named = env.ProgramFiles || env.PROGRAMFILES || env.ProgramW6432;
73
+ if (named) return absolute(named, paths);
74
+ const system = env.SystemRoot || env.SYSTEMROOT || env.windir || env.WINDIR;
75
+ const drive = typeof system === "string" && paths.isAbsolute(system) ? paths.parse(paths.resolve(system)).root
76
+ : typeof env.SystemDrive === "string" && /^[A-Za-z]:$/.test(env.SystemDrive) ? `${env.SystemDrive}\\` : null;
77
+ if (!drive) fail();
78
+ return paths.join(drive, "Program Files");
79
+ }
80
+ // An app started outside any project works in a system or program folder: JetBrains AI Assistant starts its servers in
81
+ // C:\Windows\system32 (Main Build, 2026-10-09), an app may start in its own install folder. Such a folder is never a
82
+ // project; the connection finds its project instead (launcherProjectRoot returns null).
83
+ function systemOrProgramFolder(root, platform, env) {
84
+ const paths = platform === "win32" ? path.win32 : path.posix;
85
+ const inside = base => {
86
+ if (typeof base !== "string" || !base || !paths.isAbsolute(base)) return false;
87
+ const resolved = paths.resolve(base);
88
+ return equal(root, resolved, platform) || (platform === "win32" ? root.toLowerCase().indexOf(resolved.toLowerCase().replace(/\\$/, "") + "\\") === 0
89
+ : root.indexOf(resolved.replace(/\/$/, "") + "/") === 0);
90
+ };
91
+ if (platform === "win32") {
92
+ const drive = paths.parse(root).root;
93
+ const local = env.LOCALAPPDATA;
94
+ return [env.SystemRoot || env.SYSTEMROOT || env.windir || drive + "Windows", env.ProgramFiles || drive + "Program Files",
95
+ env["ProgramFiles(x86)"] || drive + "Program Files (x86)", env.ProgramW6432, env.ProgramData || drive + "ProgramData",
96
+ local && paths.join(local, "Programs"), local && paths.join(local, "Microsoft", "WindowsApps")].some(inside);
97
+ }
98
+ // /private/var is left out: a Mac's temporary folders live under it.
99
+ return ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/etc", "/opt", "/snap", "/proc", "/sys", "/dev", "/boot", "/var/lib",
100
+ "/System", "/Library", "/Applications", "/private/etc"].some(inside) || /^\/tmp\/\.mount_[^/]+(\/|$)/.test(root);
101
+ }
102
+ // An AI app's own folder is never the person's project either: OpenClaw runs every agent turn in its own workspace
103
+ // (~/.openclaw/workspace, or agents.defaults.workspace in openclaw.json), whatever folder it was started from, and a chat
104
+ // there named that folder (Main Build, Linux 2026-10-10). The apps' settings and data folders in the home folder, and a
105
+ // configured OpenClaw workspace wherever it is, are refused; the connection then finds the person's project.
106
+ const APP_HOME_FOLDERS = [".openclaw", ".hermes", ".codex", ".claude", ".cursor", ".gemini", ".copilot", ".factory", ".pi", ".kiro",
107
+ ".junie", ".ai", ".agents", ".truthspine", ".config", ".local", ".cache", ".vscode", ".vscode-insiders", ".vscode-oss", ".windsurf",
108
+ ".codeium", ".continue", ".cline", ".lmstudio", ".ollama", ".opencode", ".zed", ".devin", ".npm", ".nvm", ".cargo", ".rustup",
109
+ ".docker", ".ssh", ".gnupg"];
110
+ function insideFolder(root, base, platform) {
111
+ const paths = platform === "win32" ? path.win32 : path.posix;
112
+ if (typeof base !== "string" || !base || !paths.isAbsolute(base)) return false;
113
+ const resolved = paths.resolve(base);
114
+ return equal(root, resolved, platform) || (platform === "win32" ? root.toLowerCase().indexOf(resolved.toLowerCase().replace(/\\$/, "") + "\\") === 0
115
+ : root.indexOf(resolved.replace(/\/$/, "") + "/") === 0);
116
+ }
117
+ function openClawWorkspace(homeDir, platform) {
118
+ const paths = platform === "win32" ? path.win32 : path.posix;
119
+ try {
120
+ const file = paths.join(homeDir, ".openclaw", "openclaw.json");
121
+ if (fs.statSync(file).size > 1024 * 1024) return null;
122
+ const workspace = JSON.parse(fs.readFileSync(file, "utf8"))?.agents?.defaults?.workspace;
123
+ if (typeof workspace !== "string" || !workspace.trim()) return null;
124
+ const expanded = workspace.trim().replace(/^~(?=$|[\\/])/, homeDir);
125
+ return paths.isAbsolute(expanded) ? expanded : null;
126
+ } catch { return null; }
127
+ }
128
+ function appOwnFolder(root, homeDir, platform) {
129
+ const paths = platform === "win32" ? path.win32 : path.posix;
130
+ const home = paths.resolve(homeDir);
131
+ const bases = APP_HOME_FOLDERS.map(name => paths.join(home, name));
132
+ if (platform === "win32") bases.push(paths.join(home, "AppData", "Roaming"));
133
+ if (platform === "darwin") bases.push(paths.join(home, "Library"));
134
+ // The person's own program folder, where AppImages and unpacked apps live (Main Build, Linux 0.1.8: a chat started in
135
+ // ~/Applications/VSCode-linux-x64 became a project and was learned at a third of a core), by its own path and by the
136
+ // folder it links to (LinuxImac's ~/Applications points at /data/moved-from-home/Applications).
137
+ if (platform !== "win32") {
138
+ const programs = paths.join(home, "Applications");
139
+ bases.push(programs);
140
+ if (platform === process.platform) { try { bases.push(fs.realpathSync(programs)); } catch { /* none */ } }
141
+ }
142
+ bases.push(openClawWorkspace(home, platform));
143
+ return bases.some(base => insideFolder(root, base, platform));
144
+ }
145
+ // Codex's dated scratch folders, one per day: Documents\Codex\<yyyy-mm-dd>\<name> (also under a OneDrive Documents).
146
+ // Not a new project: a chat working there never registers it (Brainstorming, 2026-10-21: the owner's
147
+ // Documents\Codex\2026-10-16\lo, copies of two public repositories a chat looked at, became "AI Dungeon Master"). Unlike
148
+ // the folders above, one registered earlier stays listed with its records, and asks for its real folder.
149
+ const CODEX_DAY_FOLDER = /^(?:onedrive[^\\/]*[\\/])?documents[\\/]codex(?:[\\/]\d{4}-\d{2}-\d{2}(?:[\\/].*)?)?$/i;
150
+ function scratchFolder(folder, { homeDir, platform = process.platform } = {}) {
151
+ const paths = platform === "win32" ? path.win32 : path.posix;
152
+ if (typeof folder !== "string" || !paths.isAbsolute(folder) || typeof homeDir !== "string" || !paths.isAbsolute(homeDir)) return false;
153
+ const root = longWindowsName(paths.resolve(folder), platform), home = paths.resolve(homeDir);
154
+ if (!insideFolder(root, home, platform) || equal(root, home, platform)) return false;
155
+ return CODEX_DAY_FOLDER.test(paths.relative(home, root));
156
+ }
157
+ // The account's own home folder, from the user database. In the Mac App Store sandbox HOME and os.homedir() are the
158
+ // app's container (~/Library/Containers/<app>/Data), so the person's real home and its Library would otherwise pass
159
+ // as projects; found on TestFlight build 45, 2026-10-10: every chat attached to TruthSpine's own container.
160
+ function accountHomeFolder() {
161
+ try { const home = require("node:os").userInfo().homedir; return typeof home === "string" && home ? home : null; } catch { return null; }
162
+ }
163
+ // The system's temporary folder itself (not a folder inside it): a chat started there has no folder of its own (owner
164
+ // 2026-10-16, "yes to the tmp folder rule"; Main Build, Linux: a chat started in /tmp became a project named "tmp").
165
+ function systemTempFolder(root, platform, env) {
166
+ const paths = platform === "win32" ? path.win32 : path.posix;
167
+ const named = platform === "win32"
168
+ ? [env.TEMP, env.TMP, env.LOCALAPPDATA && paths.join(env.LOCALAPPDATA, "Temp"), (env.SystemRoot || env.SYSTEMROOT || env.windir) && paths.join(env.SystemRoot || env.SYSTEMROOT || env.windir, "Temp")]
169
+ : ["/tmp", "/var/tmp", "/private/tmp", "/private/var/tmp", env.TMPDIR];
170
+ if (platform === process.platform) { try { named.push(require("node:os").tmpdir()); } catch { /* no temporary folder known */ } }
171
+ return named.some(base => typeof base === "string" && paths.isAbsolute(base) && equal(root, paths.resolve(base), platform));
172
+ }
173
+ // TruthSpine's own throwaway folders (Brain 2026-10-28): a folder named truthspine-* in a temporary folder, and every
174
+ // folder inside one, is made by TruthSpine's tests and checks, never by the person; one test run on the owner PC
175
+ // (2026-09-27) left twenty such projects' data in the person's own TruthSpine home. A TruthSpine home that itself lives
176
+ // in a temporary folder (a test's or a check's own) keeps them as projects.
177
+ function temporaryFolders(platform, env) {
178
+ const paths = platform === "win32" ? path.win32 : path.posix;
179
+ const folders = platform === "win32" ? [env.TEMP, env.TMP, env.LOCALAPPDATA && paths.join(env.LOCALAPPDATA, "Temp")]
180
+ : [env.TMPDIR, "/tmp", "/var/tmp", "/private/tmp", "/private/var/tmp", ...(platform === "darwin" ? ["/var/folders", "/private/var/folders"] : [])];
181
+ if (platform === process.platform) {
182
+ try { folders.push(require("node:os").tmpdir()); } catch { /* no temporary folder known */ }
183
+ const account = platform === "win32" ? accountHomeFolder() : null;
184
+ if (account) folders.push(paths.join(account, "AppData", "Local", "Temp"));
185
+ }
186
+ return folders.filter(folder => typeof folder === "string" && paths.isAbsolute(folder)).map(folder => paths.resolve(folder));
187
+ }
188
+ function throwawayFolder(root, homeDir, platform, env) {
189
+ const paths = platform === "win32" ? path.win32 : path.posix;
190
+ const temps = temporaryFolders(platform, env);
191
+ let made = false;
192
+ for (let folder = root; !made && paths.dirname(folder) !== folder; folder = paths.dirname(folder)) {
193
+ made = /^truthspine-/i.test(paths.basename(folder)) && temps.some(temp => equal(paths.dirname(folder), temp, platform));
194
+ }
195
+ const truthHome = env.TRUTHSPINE_HOME || (typeof homeDir === "string" && paths.isAbsolute(homeDir) ? paths.join(homeDir, ".truthspine") : null);
196
+ if (!made || typeof truthHome !== "string" || !paths.isAbsolute(truthHome)) return false;
197
+ return !temps.some(temp => insideFolder(paths.resolve(truthHome), temp, platform));
198
+ }
199
+ // Judged by the path alone (a sandboxed relay may not look inside the folder): the disk root, a home folder (the one
200
+ // given and the account's own), a system or program folder, the temporary folder itself, TruthSpine's own throwaway
201
+ // folders, or an AI app's own folder is never a project.
202
+ function neverAProjectFolder(folder, { homeDir, platform = process.platform, env = process.env } = {}) {
203
+ const paths = platform === "win32" ? path.win32 : path.posix;
204
+ if (typeof folder !== "string" || !paths.isAbsolute(folder)) return true;
205
+ // (also for a saved project: the start-of-app tidy then removes a "MICROS~1" project an earlier version made)
206
+ const root = longWindowsName(paths.resolve(folder), platform);
207
+ if (equal(root, paths.parse(root).root, platform) || systemOrProgramFolder(root, platform, env || {})
208
+ || systemTempFolder(root, platform, env || {}) || throwawayFolder(root, homeDir, platform, env || {})) return true;
209
+ const homes = [homeDir, platform === process.platform ? accountHomeFolder() : null].filter(home => typeof home === "string" && paths.isAbsolute(home));
210
+ return homes.some(home => equal(root, paths.resolve(home), platform) || appOwnFolder(root, home, platform));
211
+ }
212
+ // A Windows short name ("C:\PROGRA~1\MICROS~1") is the same folder as its long one ("C:\Program Files\Microsoft VS
213
+ // Code"), but it matches none of the folders above by name. Cline starts its servers in VS Code's install folder under
214
+ // its short name (Windows VM, 2026-10-20): it became a project named "MICROS~1". The name is read in full first.
215
+ function longWindowsName(root, platform) {
216
+ if (platform !== "win32" || platform !== process.platform || !/~/.test(root)) return root;
217
+ try { return fs.realpathSync.native(root); } catch { return root; }
218
+ }
219
+ function resolveBoundedHostWorkspace({ cwd, homeDir, platform = process.platform, env = process.env } = {}) {
220
+ const paths = platform === "win32" ? path.win32 : path.posix;
221
+ if (typeof cwd !== "string" || !paths.isAbsolute(cwd)
222
+ || typeof homeDir !== "string" || !paths.isAbsolute(homeDir)) throw new Error("TruthSpine needs an absolute host workspace directory.");
223
+ const root = longWindowsName(paths.resolve(cwd), platform);
224
+ if (neverAProjectFolder(root, { homeDir, platform, env })) {
225
+ throw new Error("TruthSpine could not identify a bounded host workspace. Open the intended project or folder; the last app-selected project will not be used for this task.");
226
+ }
227
+ if (!fs.statSync(root).isDirectory()) throw new Error("TruthSpine's host workspace must be an existing directory.");
228
+ const realRoot = fs.realpathSync(root), realHome = fs.realpathSync(homeDir);
229
+ const account = platform === process.platform ? accountHomeFolder() : null;
230
+ let realAccount = null;
231
+ try { realAccount = account ? fs.realpathSync(account) : null; } catch { /* the account home may not be readable in a sandbox */ }
232
+ if (equal(realRoot, realHome, platform) || neverAProjectFolder(realRoot, { homeDir: realHome, platform, env })
233
+ || (realAccount && (equal(realRoot, realAccount, platform) || appOwnFolder(realRoot, realAccount, platform)))) {
234
+ throw new Error("TruthSpine refused a workspace alias to an unbounded home or filesystem root.");
235
+ }
236
+ // Preserve lexical nested-folder/worktree selection; it is not the Git root
237
+ // or the app's last selected project. Native access remains a core decision. VS Code starts servers in "c:\..."
238
+ // (2026-10-09 probe): the drive letter is written one way so one folder is one project.
239
+ return { projectRoot: platform === "win32" ? root.replace(/^[a-z]:/, drive => drive.toUpperCase()) : root };
240
+ }
241
+ function restrictiveTelemetryEnv(...sources) {
242
+ return sources.some(env => {
243
+ const mode = typeof env?.TRUTHSPINE_TELEMETRY_MODE === "string" ? env.TRUTHSPINE_TELEMETRY_MODE.trim().toLowerCase() : "";
244
+ return mode && mode !== "production";
245
+ }) ? { TRUTHSPINE_TELEMETRY_MODE: "disabled" } : {};
246
+ }
247
+
248
+ // Whether TruthSpine's own files are where its installer puts them (Brain 2026-11-01, B8): a copy installed but never opened
249
+ // has written no install record yet, and is told to open TruthSpine once rather than to get it. Names only, nothing run:
250
+ // the Store's command in WindowsApps, the app in Applications, the snap's or the system package's command.
251
+ function installedAppPresent({ platform = process.platform, env = process.env, homeDir = env.HOME || env.USERPROFILE || "",
252
+ exists = file => fs.existsSync(file), names = folder => fs.readdirSync(folder) } = {}) {
253
+ try {
254
+ if (platform === "win32") {
255
+ // (the execution alias is listed, never read: reading it may fail while starting it works)
256
+ const folder = typeof env.LOCALAPPDATA === "string" && path.win32.isAbsolute(env.LOCALAPPDATA) ? path.win32.join(env.LOCALAPPDATA, "Microsoft", "WindowsApps") : null;
257
+ return Boolean(folder) && names(folder).some(name => name.toLowerCase() === "truthspine-runtime.exe");
258
+ }
259
+ if (platform === "darwin") return ["/Applications/TruthSpine.app", homeDir ? path.posix.join(homeDir, "Applications", "TruthSpine.app") : null].some(file => file && exists(file));
260
+ if (platform === "linux") return Object.values(LINUX_PACKAGE_COMMANDS).some(file => exists(file));
261
+ } catch { /* not found */ }
262
+ return false;
263
+ }
264
+
265
+ function readRegistration(filename) {
266
+ let fd;
267
+ try {
268
+ // (no record at all: TruthSpine has never been installed and opened on this computer, B8; or installed, never opened)
269
+ let before;
270
+ try { before = fs.lstatSync(filename); }
271
+ catch (error) { if (error && error.code === "ENOENT") typedFail(installedAppPresent() ? "app_not_opened" : "app_not_installed"); fail(); }
272
+ if (!before.isFile() || before.isSymbolicLink() || before.size > 65536) fail();
273
+ fd = fs.openSync(filename, "r");
274
+ const opened = fs.fstatSync(fd);
275
+ if (!opened.isFile() || opened.size > 65536 || opened.ino !== before.ino || opened.dev !== before.dev) fail();
276
+ const buffer = Buffer.alloc(65537); let used = 0;
277
+ while (used < buffer.length) { const count = fs.readSync(fd, buffer, used, buffer.length - used, null); if (!count) break; used += count; }
278
+ const after = fs.fstatSync(fd);
279
+ if (used > 65536 || used !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs) fail();
280
+ const parsed = JSON.parse(buffer.subarray(0, used).toString("utf8"));
281
+ if (!object(parsed) || parsed.schema !== "truthspine.installed-runtime.v1") fail();
282
+ return parsed;
283
+ } catch (error) { if (["app_not_installed", "app_not_opened"].includes(typedCode(error))) throw error; fail(); }
284
+ finally { if (fd !== undefined) fs.closeSync(fd); }
285
+ }
286
+
287
+ const WINDOWS_OS_NAMES = new Set(["systemroot", "windir", "comspec", "temp", "tmp", "userprofile", "localappdata", "appdata",
288
+ "programfiles", "programfiles(x86)", "programdata", "allusersprofile", "public", "processor_architecture",
289
+ "number_of_processors", "computername", "os", "pathext", "path", "tz"]);
290
+ // Linux: what the AppImage runtime and the server need to find the user's folders, and nothing else.
291
+ // (TZ on both: a chat server reads the day in the zone the app reads it in, Brain 2026-10-30)
292
+ const LINUX_OS_NAMES = new Set(["home", "path", "user", "logname", "lang", "lc_all", "lc_ctype", "lc_messages", "tmpdir",
293
+ "xdg_data_home", "xdg_config_home", "xdg_cache_home", "xdg_runtime_dir", "appimage_extract_and_run", "tz"]);
294
+ const LINUX_APP_ROOT = "@app";
295
+ // The fixed launchers of the Linux packages that have one (src/packaged-platform.cjs keeps the same table; this file ships
296
+ // alone in the VS Code extension, so it keeps its own copy, and a test keeps the two the same). The snap's follows store
297
+ // updates; a versioned /snap/truthspine/<revision>/ path is never accepted.
298
+ const LINUX_PACKAGE_COMMANDS = Object.freeze({ "linux-snap": "/snap/bin/truthspine", "linux-system": "/usr/bin/truthspine" });
299
+ const linuxPackageCommand = name => (typeof name === "string" && Object.prototype.hasOwnProperty.call(LINUX_PACKAGE_COMMANDS, name) ? LINUX_PACKAGE_COMMANDS[name] : null);
300
+ function installedChildEnv({ env, platform, profile, root, hostId, developmentBuild = false }) {
301
+ const childEnv = {};
302
+ const osNames = platform === "linux" ? LINUX_OS_NAMES : WINDOWS_OS_NAMES;
303
+ for (const name of Object.keys(env)) if (osNames.has(name.toLowerCase())) {
304
+ const value = env[name]; if (typeof value !== "string" || /[\u0000-\u001f\u007f]/.test(value)) fail();
305
+ childEnv[name] = value;
306
+ }
307
+ // A development copy's connections follow the app (owner 2026-10-06): no customer mode, so its data stays where
308
+ // the development app keeps it. A customer package still enforces the boundary from its own release marker.
309
+ Object.assign(childEnv, { ELECTRON_RUN_AS_NODE: "1", TRUTHSPINE_PACKAGED_RUNTIME: "1",
310
+ ...(developmentBuild ? {} : { TRUTHSPINE_CUSTOMER_MODE: "1" }),
311
+ TRUTHSPINE_HOME: profile, ...(root ? { TRUTHSPINE_PROJECT_ROOT: root, TRUTHSPINE_LOCK_PROJECT_ROOT: "1" } : { TRUTHSPINE_FIND_PROJECT: "1" }),
312
+ // (the folder the app started this connection in: a chat's attach may name its own folder; mcp-server.js)
313
+ ...(root && env.TRUTHSPINE_PROJECT_FROM_CWD === "1" ? { TRUTHSPINE_FOLLOWED_FOLDER: "1" } : {}),
314
+ TRUTHSPINE_HOST_ID: hostId,
315
+ TRUTHSPINE_MCP_OUTPUT_FRAMING: "jsonl" });
316
+ // Host identity is a policy selector, not authentication or permission to broaden another host's advertised tool
317
+ // profile. An app HOST_TOOL_PROFILES does not name keeps the full catalog, including session_update.
318
+ if (Object.hasOwn(HOST_TOOL_PROFILES, hostId)) childEnv.TRUTHSPINE_MCP_TOOL_PROFILE = HOST_TOOL_PROFILES[hostId];
319
+ // Preserve an existing restrictive opt-out, never an ambient opt-in or
320
+ // telemetry identity. Dropping an opt-out could enable collection when the
321
+ // registered profile has consent. This grants no product access.
322
+ Object.assign(childEnv, restrictiveTelemetryEnv(env));
323
+ // In particular: no NODE_OPTIONS, NODE_PATH, ambient credentials, authority
324
+ // overrides, or mutable runtime-registration path enters the child.
325
+ return childEnv;
326
+ }
327
+
328
+ function buildInstalledMcpLaunchPlan({ registration, registrationPath, projectRoot,
329
+ platform = process.platform, env = process.env, hostId = "claude-desktop" } = {}) {
330
+ if (!["win32", "darwin", "linux"].includes(platform) || !object(registration)
331
+ || registration.schema !== "truthspine.installed-runtime.v1" || !HOST_IDS.has(hostId)) fail();
332
+ const paths = platform === "win32" ? path.win32 : path.posix;
333
+ // No project (null): an app that starts outside any folder; the connection finds its project (launcherProjectRoot).
334
+ const root = projectRoot === null ? null : absolute(projectRoot, paths), profile = absolute(registration.truthHome, paths);
335
+ const registrationFile = absolute(registrationPath, paths);
336
+ if (root && equal(root, paths.parse(root).root, platform)) fail();
337
+ if (env.TRUTHSPINE_HOME !== undefined && !equal(absolute(env.TRUTHSPINE_HOME, paths), profile, platform)) fail();
338
+ // Root comes from this generated connector, never cwd/last app selection.
339
+ if (platform === "darwin") {
340
+ const userData = paths.dirname(registrationFile);
341
+ const marker = "/Library/Containers/com.timeprooflabs.truthspine/Data/";
342
+ const index = userData.indexOf(marker);
343
+ if (index < 1 || !equal(profile, paths.join(userData, "truthspine"), platform)) fail();
344
+ const dataRoot = userData.slice(0, index + marker.length - 1);
345
+ const hash = crypto.createHash("sha256").update(userData).digest("hex").slice(0, 8);
346
+ // No project (null): the bridge finds it for this connection (local-app-mcp-bridge.js find).
347
+ return Object.freeze({ mode: "app-owned-socket", platform, hostId, projectRoot: root, truthHome: profile,
348
+ socketPath: paths.join(dataRoot, ".ts", `mcp-${hash}.sock`) });
349
+ }
350
+ if (platform === "linux") {
351
+ // Linux packaged lane (P12). The AppImage file, or the package's fixed launcher (the snap's /snap/bin/truthspine), is
352
+ // the one stable path: the app inside an AppImage is mounted under /tmp at a new path on every launch, and a snap's
353
+ // folder changes with each update, so no path inside the package is trusted. The package's own entry point (AppRun,
354
+ // the snap's truthspine-launch) turns a leading "@app/" argument into a path inside it.
355
+ const provenance = registration.runtimeProvenance;
356
+ const command = absolute(registration.command, paths);
357
+ const fixed = object(provenance) ? linuxPackageCommand(provenance.packagedPlatform) : null;
358
+ if (!object(provenance) || provenance.packaged !== true
359
+ || !(provenance.packagedPlatform === "linux-appimage" ? /[.]AppImage$/.test(paths.basename(command)) : fixed !== null && command === fixed)
360
+ || !equal(absolute(provenance.appExecutable, paths), command, platform)) fail();
361
+ return Object.freeze({ mode: "installed-stdio", platform, hostId, packageRoot: LINUX_APP_ROOT, command,
362
+ args: Object.freeze([`${LINUX_APP_ROOT}/src/mcp-server.js`]), cwd: root ?? profile, projectRoot: root, truthHome: profile,
363
+ env: Object.freeze(installedChildEnv({ env, platform, profile, root, hostId,
364
+ developmentBuild: registration.developmentBuild === true })) });
365
+ }
366
+ const packageRoot = absolute(registration.packageRoot, paths);
367
+ const executable = absolute(registration.runtimeProvenance && registration.runtimeProvenance.appExecutable, paths);
368
+ const programFiles = windowsProgramFiles(env, paths);
369
+ const localAppData = absolute(env.LOCALAPPDATA || env.LocalAppData || (env.USERPROFILE && paths.join(env.USERPROFILE, "AppData", "Local")), paths);
370
+ const command = paths.join(localAppData, "Microsoft", "WindowsApps", "truthspine-runtime.exe");
371
+ const install = paths.dirname(executable), packageName = paths.basename(install);
372
+ // Current Store lane only. Other volumes/architectures need OS discovery
373
+ // qualification before widening this routing policy, not a Node fallback.
374
+ if (registration.runtimeProvenance.packaged !== true
375
+ || !/^TimeProofLabsLLC\.TruthSpine_\d+\.\d+\.\d+\.\d+_x64__xzspk04648dda$/.test(packageName)
376
+ || !equal(executable, paths.join(programFiles, "WindowsApps", packageName, "TruthSpine.exe"), platform)
377
+ || !equal(packageRoot, paths.join(install, "resources", "app"), platform)
378
+ || !equal(absolute(registration.command, paths), command, platform)) fail();
379
+ const childEnv = installedChildEnv({ env, platform, profile, root, hostId });
380
+ return Object.freeze({ mode: "installed-stdio", platform, hostId, packageRoot, command, args: Object.freeze([paths.join(packageRoot, "src", "mcp-server.js")]),
381
+ cwd: root ?? profile, projectRoot: root, truthHome: profile, env: Object.freeze(childEnv) });
382
+ }
383
+
384
+ function buildInstalledCliLaunchPlan(options = {}) {
385
+ const args = options.args;
386
+ const commands = new Set(["guard", "nudge", "ask-truthspine", "gap-ledger", "context", "sync", "truth-index",
387
+ "coverage", "review", "app", "license", "onboard", "native-agent-edit", "connector-callback"]);
388
+ if (!Array.isArray(args) || args.length < 1 || args.length > 128
389
+ || !commands.has(args[0])
390
+ || args.some(value => typeof value !== "string" || value.includes("\0") || value.length > 65536
391
+ || /^--project-root(?:=|$)/.test(value))
392
+ || args.reduce((total, value) => total + Buffer.byteLength(value), 0) > 262144) fail();
393
+ const plan = buildInstalledMcpLaunchPlan(options);
394
+ // The Mac CLI is an RPC in the app-owned bridge, never a standalone process; a command always names its project.
395
+ if (plan.mode !== "installed-stdio" || !plan.projectRoot) fail();
396
+ const childEnv = { ...plan.env };
397
+ delete childEnv.TRUTHSPINE_MCP_TOOL_PROFILE;
398
+ delete childEnv.TRUTHSPINE_MCP_OUTPUT_FRAMING;
399
+ return Object.freeze({ ...plan, mode: "installed-cli", env: Object.freeze(childEnv),
400
+ args: Object.freeze([plan.platform === "linux" ? `${LINUX_APP_ROOT}/src/customer-connector-cli.js`
401
+ : path.win32.join(plan.packageRoot, "src", "customer-connector-cli.js"), ...args, "--project-root", plan.projectRoot]) });
402
+ }
403
+
404
+ function validateInstalledLaunchPlan(plan) {
405
+ if (!plan || plan.platform !== process.platform) fail();
406
+ try {
407
+ if (plan.platform === "linux" && ["installed-stdio", "installed-cli"].includes(plan.mode)) {
408
+ // The AppImage must still exist, be a runnable file owned by this user (or root, for a system-wide
409
+ // copy) and not writable by everyone. Group-writable is allowed: Ubuntu's default umask gives it.
410
+ const entry = plan.mode === "installed-cli" ? "customer-connector-cli.js" : "mcp-server.js";
411
+ if (plan.packageRoot !== LINUX_APP_ROOT || plan.args[0] !== `${LINUX_APP_ROOT}/src/${entry}`) fail();
412
+ let image;
413
+ try { image = fs.statSync(plan.command); } catch (error) { if (error && error.code === "ENOENT") typedFail("app_not_installed"); fail(); }
414
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
415
+ if (!image.isFile() || (image.mode & 0o002) !== 0 || (image.mode & 0o100) === 0
416
+ || (uid !== null && image.uid !== uid && image.uid !== 0) || !fs.statSync(plan.cwd).isDirectory()) fail();
417
+ } else if (["installed-stdio", "installed-cli"].includes(plan.mode)) {
418
+ const entry = plan.mode === "installed-cli" ? "customer-connector-cli.js" : "mcp-server.js";
419
+ const script = plan.args[0];
420
+ if (!equal(script, path.join(plan.packageRoot, "src", entry), process.platform)) fail();
421
+ let installed;
422
+ try { installed = fs.statSync(script); } catch (error) { if (error && error.code === "ENOENT") typedFail("app_not_installed"); fail(); }
423
+ if (!installed.isFile() || !equal(fs.realpathSync(script), script, process.platform)
424
+ || !fs.statSync(plan.cwd).isDirectory()) fail();
425
+ // Do not stat the execution alias: activation may work while stat fails.
426
+ } else if (plan.mode === "app-owned-socket") {
427
+ let socket;
428
+ try { socket = fs.lstatSync(plan.socketPath); } catch (error) { if (error && error.code === "ENOENT") typedFail("app_not_running"); fail(); }
429
+ if (!socket.isSocket() || socket.isSymbolicLink()
430
+ || (typeof process.getuid === "function" && socket.uid !== process.getuid())) fail();
431
+ } else fail();
432
+ return plan;
433
+ } catch (error) { if (typedCode(error)) throw error; fail(); }
434
+ }
435
+
436
+ function relayInstalledMcp(plan, { input = process.stdin, output = process.stdout,
437
+ spawnImpl = spawn, connectImpl = net.createConnection, shutdownMs = 1500 } = {}) {
438
+ if (!Number.isInteger(shutdownMs) || shutdownMs < 1 || shutdownMs > 5000) fail();
439
+ let child, channel, remoteInput, remoteOutput, timer, hardTimer, confirmationTimer;
440
+ let settled = false, reported = false, stopping = false, requestedCode = 0, failureCode = null;
441
+ const noteFailure = (error, code) => { if (!failureCode && error && ["ENOENT", "ECONNREFUSED", "EACCES"].indexOf(error.code) !== -1) failureCode = code; };
442
+ let resolveClosed;
443
+ const closed = new Promise(resolve => { resolveClosed = resolve; });
444
+ const reportUnconfirmed = () => {
445
+ if (!settled && !reported) {
446
+ reported = true; resolveClosed({ code: 1, pid: child ? child.pid : null, cleanupConfirmed: false });
447
+ }
448
+ };
449
+ const finish = code => {
450
+ if (settled) return;
451
+ settled = true; clearTimeout(timer); clearTimeout(hardTimer); clearTimeout(confirmationTimer);
452
+ input.unpipe(remoteInput); if (remoteOutput) remoteOutput.unpipe(output); input.pause();
453
+ input.removeListener("end", stop); input.removeListener("close", closedInput);
454
+ input.removeListener("error", failed); output.removeListener("error", failed); output.removeListener("close", failed);
455
+ if (!reported) { reported = true; resolveClosed({ code: requestedCode || code, pid: child ? child.pid : null, cleanupConfirmed: true }); }
456
+ };
457
+ function failed() { stop(1); }
458
+ function closedInput() { if (!input.readableEnded) stop(1); }
459
+ function stop(code = 0) {
460
+ if (settled) return;
461
+ requestedCode = requestedCode || code;
462
+ if (stopping) return;
463
+ stopping = true;
464
+ input.unpipe(remoteInput); input.pause();
465
+ if (code && remoteOutput) remoteOutput.unpipe(output);
466
+ if (plan.mode === "app-owned-socket") {
467
+ channel.destroy(); confirmationTimer = setTimeout(reportUnconfirmed, shutdownMs); return;
468
+ }
469
+ if (remoteInput && !remoteInput.destroyed) remoteInput.end();
470
+ timer = setTimeout(() => {
471
+ if (!settled) { try { child.kill(); } catch {} }
472
+ hardTimer = setTimeout(() => {
473
+ if (!settled) { try { child.kill("SIGKILL"); } catch {} }
474
+ confirmationTimer = setTimeout(() => {
475
+ if (!settled && !reported) {
476
+ // A kill request is not terminal evidence. Retain the child's
477
+ // close/error observers and handle; do not claim cleanup or retry.
478
+ reportUnconfirmed();
479
+ }
480
+ }, shutdownMs);
481
+ }, shutdownMs);
482
+ }, shutdownMs);
483
+ }
484
+ try {
485
+ if (plan.mode === "installed-stdio") {
486
+ child = spawnImpl(plan.command, plan.args, { cwd: plan.cwd, env: plan.env, shell: false, windowsHide: true,
487
+ stdio: ["pipe", "pipe", "pipe"] });
488
+ remoteInput = child.stdin; remoteOutput = child.stdout;
489
+ // Never forward raw child diagnostics that may contain credentials.
490
+ child.stderr.on("error", failed); child.stderr.resume();
491
+ child.on("error", error => { noteFailure(error, "app_not_installed"); if (Number.isInteger(child.pid)) failed(); else finish(1); });
492
+ child.on("close", code => finish(code === 0 ? 0 : 1));
493
+ remoteInput.on("error", failed); remoteOutput.on("error", failed);
494
+ remoteOutput.pipe(output, { end: false }); input.pipe(remoteInput);
495
+ } else if (plan.mode === "app-owned-socket") {
496
+ channel = connectImpl(plan.socketPath); remoteInput = channel; remoteOutput = channel;
497
+ channel.on("error", error => { noteFailure(error, "app_not_running"); failed(); });
498
+ channel.on("close", () => finish(stopping ? 0 : 1));
499
+ channel.once("connect", () => {
500
+ if (settled || stopping) return;
501
+ const body = Buffer.from(JSON.stringify({ jsonrpc: "2.0", method: "truthspine/bridge/identify",
502
+ params: { hostId: plan.hostId || "claude-desktop", projectRoot: plan.projectRoot || "", ...(plan.projectRoot ? {} : { find: true }) } }));
503
+ channel.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`), body]));
504
+ channel.pipe(output, { end: false }); input.pipe(channel);
505
+ });
506
+ } else fail();
507
+ input.once("end", stop); input.on("close", closedInput); input.on("error", failed);
508
+ output.on("error", failed); output.on("close", failed);
509
+ if (input.readableEnded) stop();
510
+ } catch { if (child) stop(1); else { if (channel) channel.destroy(); finish(1); } }
511
+ return { closed, stop, pid: child ? child.pid : null, failure: () => failureCode };
512
+ }
513
+
514
+ // Owner's rules 2026-10-08/09: one TruthSpine entry per app, in the app's own user settings, working in whatever
515
+ // folder the person is in, and a chat never inherits the project the TruthSpine app shows. TRUTHSPINE_PROJECT_FROM_CWD=1:
516
+ // the project is the folder the app started this connection in (bounded: never the home folder or a disk root). An app
517
+ // that starts outside any folder (Kiro starts in the home folder) gets null: the connection then finds its project
518
+ // from the folders the app has open or the folder the chat names (mcp-server.js TRUTHSPINE_FIND_PROJECT).
519
+ // TRUTHSPINE_FIND_PROJECT=1: an app whose working folder is never a project (Claude Desktop, LM Studio, window apps)
520
+ // always finds it that way.
521
+ function launcherProjectRoot({ env = process.env, cwd, homeDir } = {}) {
522
+ if (env.TRUTHSPINE_FIND_PROJECT === "1") return null;
523
+ if (env.TRUTHSPINE_PROJECT_FROM_CWD !== "1") return env.TRUTHSPINE_PROJECT_ROOT;
524
+ try { return resolveBoundedHostWorkspace({ cwd: cwd ?? process.cwd(), homeDir: homeDir ?? require("node:os").homedir() }).projectRoot; }
525
+ catch { return null; }
526
+ }
527
+ function installedLauncherOptions() {
528
+ const registrationPath = absolute(process.env.TRUTHSPINE_RUNTIME_REGISTRATION_PATH, path);
529
+ return { registration: readRegistration(registrationPath), registrationPath,
530
+ projectRoot: launcherProjectRoot(),
531
+ hostId: process.env.TRUTHSPINE_LAUNCHER_HOST_ID || "claude-desktop" };
532
+ }
533
+ function startInstalledMcpLauncher() {
534
+ const plan = buildInstalledMcpLaunchPlan(installedLauncherOptions());
535
+ validateInstalledLaunchPlan(plan);
536
+ return relayInstalledMcp(plan);
537
+ }
538
+
539
+ // The relay (owner 2026-10-16: "fix the claude extension gap too"). A Store update ends every process that runs from the
540
+ // TruthSpine package. This launcher runs from outside it when an app starts it with its own Node (Claude Desktop's
541
+ // extension), so it survives, but the TruthSpine it started does not, and the connection ended with it. Where the
542
+ // TruthSpine app has checked the relay on this computer, such a launcher hands the connection to the relay, which starts
543
+ // TruthSpine (through the shared launcher copy, under the Store runtime) and starts the new one after an update.
544
+ // Null when that does not apply: not Windows, already a package process, or no checked relay or shared launcher here.
545
+ function relayDelegationPlan({ platform = process.platform, execPath = process.execPath, env = process.env,
546
+ exists = file => fs.existsSync(file), readText = file => fs.readFileSync(file, "utf8") } = {}) {
547
+ if (platform !== "win32" || /[\\/]WindowsApps[\\/]/i.test(String(execPath || ""))) return null;
548
+ const registration = env.TRUTHSPINE_RUNTIME_REGISTRATION_PATH;
549
+ if (typeof registration !== "string" || !path.win32.isAbsolute(registration) || /[\x00-\x1f\x7f]/.test(registration)) return null;
550
+ const runtimeFolder = path.win32.join(path.win32.dirname(registration), "connector-runtime");
551
+ let relay = null;
552
+ try {
553
+ const ready = JSON.parse(readText(path.win32.join(runtimeFolder, "relay", "relay-ready.json")));
554
+ relay = ready && ready.ok === true && typeof ready.path === "string" && /[\\/]TruthSpine\.Relay\.exe$/i.test(ready.path) ? ready.path : null;
555
+ } catch { relay = null; }
556
+ const launcher = path.win32.join(runtimeFolder, "installed-mcp-launcher.cjs");
557
+ const localAppData = env.LOCALAPPDATA;
558
+ if (!relay || !exists(relay) || !exists(launcher) || typeof localAppData !== "string" || !path.win32.isAbsolute(localAppData)) return null;
559
+ const runtime = path.win32.join(localAppData, "Microsoft", "WindowsApps", "truthspine-runtime.exe");
560
+ return { mode: "installed-stdio", command: relay, args: ["--", runtime, launcher], cwd: process.cwd(),
561
+ env: { ...env, ELECTRON_RUN_AS_NODE: "1", TRUTHSPINE_PACKAGED_RUNTIME: "1" } };
562
+ }
563
+
564
+ // One process per chat (design approved 2026-10-21; owner: "Keep one runtime, measured budget"). When this launcher
565
+ // already runs in the very package its validated plan would start (the same AppImage on Linux, the same Store package
566
+ // on Windows), it becomes the chat server itself: the plan's environment exactly, plus the few keys the runtime needs,
567
+ // then the package's own mcp-server.js in this process. A second Electron-as-node is no longer started for each chat.
568
+ // It still starts one when this launcher runs on another runtime (an app's own Node, the relay), when it was started
569
+ // with NODE_OPTIONS, NODE_PATH or Node flags (they would reach the server, which the clean environment keeps out), or
570
+ // for the Mac's app-owned socket, which starts no server.
571
+ const IN_PLACE_RUNTIME_KEYS = Object.freeze({
572
+ linux: Object.freeze(["APPIMAGE", "APPDIR", "ARGV0", "OWD", "TRUTHSPINE_PACKAGED_PLATFORM"]),
573
+ win32: Object.freeze([])
574
+ });
575
+ function inPlaceHandover(plan, { platform = process.platform, execPath = process.execPath, env = process.env,
576
+ execArgv = process.execArgv, exists = file => { try { return fs.statSync(file).isFile(); } catch { return false; } } } = {}) {
577
+ if (!plan || plan.mode !== "installed-stdio" || plan.platform !== platform || !IN_PLACE_RUNTIME_KEYS[platform]) return null;
578
+ if (env.ELECTRON_RUN_AS_NODE !== "1" || (env.NODE_OPTIONS ?? "") !== "" || (env.NODE_PATH ?? "") !== "" || execArgv.length) return null;
579
+ const paths = platform === "win32" ? path.win32 : path.posix;
580
+ let serverPath;
581
+ if (platform === "linux") {
582
+ const sameAppImage = typeof env.APPIMAGE === "string" && paths.isAbsolute(env.APPIMAGE) && equal(paths.resolve(env.APPIMAGE), plan.command, platform);
583
+ if (!sameAppImage && linuxPackageCommand(env.TRUTHSPINE_PACKAGED_PLATFORM) !== plan.command) return null;
584
+ if (plan.args[0] !== `${LINUX_APP_ROOT}/src/mcp-server.js`) return null;
585
+ serverPath = paths.join(paths.dirname(execPath), "resources", "app", "src", "mcp-server.js");
586
+ } else {
587
+ if (!equal(paths.join(paths.dirname(execPath), "resources", "app"), plan.packageRoot, platform)) return null;
588
+ serverPath = paths.join(plan.packageRoot, "src", "mcp-server.js");
589
+ if (!equal(plan.args[0], serverPath, platform)) return null;
590
+ }
591
+ if (!exists(serverPath)) return null;
592
+ const next = { ...plan.env };
593
+ for (const key of IN_PLACE_RUNTIME_KEYS[platform]) if (typeof env[key] === "string") next[key] = env[key];
594
+ return Object.freeze({ serverPath, cwd: plan.cwd, env: Object.freeze(next) });
595
+ }
596
+ // The handover itself: nothing of this launcher's own start environment is left, and the server runs as its own entry.
597
+ async function handOverInPlace(handover, { importer = file => import(require("node:url").pathToFileURL(file).href) } = {}) {
598
+ for (const key of Object.keys(process.env)) if (!Object.prototype.hasOwnProperty.call(handover.env, key)) delete process.env[key];
599
+ Object.assign(process.env, handover.env);
600
+ process.chdir(handover.cwd);
601
+ process.argv[1] = handover.serverPath;
602
+ await importer(handover.serverPath);
603
+ return { inPlace: true };
604
+ }
605
+
606
+ // The installed copy's plan, validated; Windows tries the Store package again when the recorded one is gone.
607
+ async function installedPlan(signal) {
608
+ const options = installedLauncherOptions();
609
+ let plan = buildInstalledMcpLaunchPlan(options);
610
+ try { validateInstalledLaunchPlan(plan); }
611
+ catch (error) {
612
+ if (plan.platform !== 'win32') throw error;
613
+ plan = (await prepareRecoveredMcpPlan(options, { signal })).plan;
614
+ }
615
+ return plan;
616
+ }
617
+
618
+ // With no TruthSpine to reach (B8, Brain 2026-11-01): the connection stays up and answers by itself, so the chat can say
619
+ // "TruthSpine isn't installed yet. Get it here: <link>" instead of the app showing a server that failed. The page opens
620
+ // only when the chat calls open_download_page after the person says yes, and once TruthSpine is there the next tool call
621
+ // connects this same chat to it (the person's first message is passed on, and the app is told the tools changed).
622
+ // A copy that starts but does not answer within NO_ANSWER_MS is given up the same way.
623
+ const NO_ANSWER_MS = 10000;
624
+ const LAUNCHER_GET_LINKS = Object.freeze({ ...LAUNCHER_STORE_LINKS, linux: "https://truthspine.app/download/linux" });
625
+ const DOWNLOAD_PAGE = "https://truthspine.app/download";
626
+ function noAppLines(code, platform) {
627
+ const link = LAUNCHER_GET_LINKS[platform] || DOWNLOAD_PAGE;
628
+ if (code === "app_not_installed") return { link, say: `TruthSpine isn't installed yet. Get it here: ${link}`,
629
+ next: "Ask the person whether to open this page now, and call open_download_page only if they say yes. Once TruthSpine is installed and open, call attach again: this chat then connects by itself." };
630
+ const say = code === "app_not_opened" ? "Open TruthSpine once. It is installed on this computer but has not been opened yet, so chats can't reach it."
631
+ : code === "app_not_running" ? "TruthSpine is installed but not running. Open the TruthSpine app, then ask again."
632
+ : "TruthSpine is installed but did not answer. Open the TruthSpine app, then ask again.";
633
+ return { link: null, say, next: "Once it is open, call attach again: this chat then connects by itself." };
634
+ }
635
+ function openPage(url, platform, spawnImpl = spawn) {
636
+ const [command, args] = platform === "win32" ? ["explorer.exe", [url]] : platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
637
+ const child = spawnImpl(command, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
638
+ child.on("error", () => {}); child.unref();
639
+ }
640
+ // Newline-framed JSON-RPC lines from a stream (MCP over standard input and output).
641
+ function readLines(stream, onLine) {
642
+ let pending = "";
643
+ const onData = chunk => {
644
+ pending += chunk.toString("utf8");
645
+ let end;
646
+ while ((end = pending.indexOf("\n")) !== -1) { const line = pending.slice(0, end).replace(/\r$/, ""); pending = pending.slice(end + 1); if (line.trim()) onLine(line); }
647
+ };
648
+ stream.on("data", onData);
649
+ return () => stream.removeListener("data", onData);
650
+ }
651
+ const parse = line => { try { const message = JSON.parse(line); return object(message) ? message : null; } catch { return null; } };
652
+
653
+ // Relays to the installed copy, and gives it up when it does not answer the app's first request in time (onSilent gets the
654
+ // lines it was sent). Lines come in through send(); the copy's answers go to output, the swallowed id's answer excepted.
655
+ function answeredRelay(plan, { output, waitMs = NO_ANSWER_MS, onSilent, onAnswered = () => {}, swallowId = null, relay = relayInstalledMcp }) {
656
+ const { PassThrough } = require("node:stream");
657
+ const toCopy = new PassThrough(), fromCopy = new PassThrough();
658
+ const sent = [];
659
+ let waitingFor = undefined, answered = false, gaveUp = false, timer = null;
660
+ const connection = relay(plan, { input: toCopy, output: fromCopy });
661
+ function giveUp() {
662
+ if (gaveUp) return;
663
+ gaveUp = true; clearTimeout(timer); stopReading(); connection.stop(1);
664
+ onSilent(sent.slice());
665
+ }
666
+ const stopReading = readLines(fromCopy, line => {
667
+ if (gaveUp) return;
668
+ const message = parse(line);
669
+ if (message && !answered && waitingFor !== undefined && message.id === waitingFor) { answered = true; clearTimeout(timer); onAnswered(); }
670
+ if (message && swallowId !== null && message.id === swallowId) return;
671
+ output.write(line + "\n");
672
+ });
673
+ // (a copy that ends before it answered is given up too)
674
+ connection.closed.then(result => { if (!answered && !gaveUp && result.code !== 0) giveUp(); });
675
+ return {
676
+ connection,
677
+ send(line) {
678
+ if (gaveUp) return false;
679
+ // (the wait starts with the app's first request: an app may start the connection long before it asks anything)
680
+ if (waitingFor === undefined) {
681
+ const message = parse(line);
682
+ if (message && message.id !== undefined && message.id !== null) { waitingFor = message.id; timer = setTimeout(() => { if (!answered) giveUp(); }, waitMs); }
683
+ }
684
+ if (!answered) sent.push(line);
685
+ toCopy.write(line + "\n");
686
+ return true;
687
+ },
688
+ end() { if (!gaveUp) { clearTimeout(timer); toCopy.end(); } },
689
+ gaveUp: () => gaveUp
690
+ };
691
+ }
692
+
693
+ function serveWithoutApp(code, { input = process.stdin, output = process.stdout, platform = process.platform, attempt,
694
+ waitMs = NO_ANSWER_MS, spawnImpl = spawn, retryEveryMs = 10000, now = () => Date.now(), relay = relayInstalledMcp, earlier = [] } = {}) {
695
+ let resolveClosed, live = null, init = null, lastTry = -Infinity, trying = null, done = false;
696
+ const closed = new Promise(resolve => { resolveClosed = resolve; });
697
+ const write = message => output.write(JSON.stringify(message) + "\n");
698
+ const lines = () => noAppLines(code, platform);
699
+ const finish = codeOut => { if (done) return; done = true; stopReading(); input.removeListener("end", ended); resolveClosed({ code: codeOut, pid: null, cleanupConfirmed: true }); };
700
+ const ended = () => { if (live) { live.end(); live.connection.closed.then(result => finish(result.code)); } else finish(0); };
701
+ const tools = () => [{ name: "attach", description: `Connect TruthSpine. ${lines().say}`, inputSchema: { type: "object", properties: {}, additionalProperties: true } }]
702
+ .concat(code === "app_not_installed" ? [{ name: "open_download_page", description: "Open the TruthSpine download page in the browser. Call it only after the person says yes.",
703
+ inputSchema: { type: "object", properties: {}, additionalProperties: false } }] : []);
704
+ const answer = message => {
705
+ const { method, id } = message;
706
+ const reply = result => { if (id !== undefined && id !== null) write({ jsonrpc: "2.0", id, result }); };
707
+ if (method === "initialize") {
708
+ init = message;
709
+ return reply({ protocolVersion: (message.params && message.params.protocolVersion) || "2025-06-18", capabilities: { tools: { listChanged: true } },
710
+ serverInfo: { name: "truthspine", version: "not-connected" }, instructions: `${lines().say} ${lines().next}` });
711
+ }
712
+ if (method === "tools/list") return reply({ tools: tools() });
713
+ if (method === "resources/list") return reply({ resources: [] });
714
+ if (method === "prompts/list") return reply({ prompts: [] });
715
+ if (method === "ping") return reply({});
716
+ if (method === "tools/call") {
717
+ const name = message.params && message.params.name;
718
+ if (name === "open_download_page" && code === "app_not_installed") {
719
+ try { openPage(lines().link, platform, spawnImpl); return reply({ content: [{ type: "text", text: `Opened ${lines().link}. ${lines().next}` }] }); }
720
+ catch { return reply({ content: [{ type: "text", text: `Could not open the page. The link is ${lines().link}.` }] }); }
721
+ }
722
+ return reply({ content: [{ type: "text", text: `${lines().say} ${lines().next}` }] });
723
+ }
724
+ if (typeof method === "string" && method.indexOf("notifications/") === 0) return undefined;
725
+ if (id !== undefined && id !== null) write({ jsonrpc: "2.0", id, error: { code: -32601, message: lines().say } });
726
+ return undefined;
727
+ };
728
+ // Once TruthSpine is there: the copy gets the app's first request under its own id (its answer is not passed on, the app
729
+ // has one already), the initialized notice, then the waiting call; the app hears that the tools changed.
730
+ async function connect(callLine) {
731
+ let plan;
732
+ try { plan = await attempt(); } catch (error) { const next = typedCode(error); if (next && next !== code && next !== "unavailable") code = next; return false; }
733
+ if (done) return false;
734
+ const handoverId = `truthspine-handover-${crypto.randomUUID()}`;
735
+ let copy = null;
736
+ const outcome = new Promise(resolve => {
737
+ copy = answeredRelay(plan, { output, waitMs, relay, swallowId: handoverId, onAnswered: () => resolve("answered"),
738
+ onSilent: () => { code = "app_not_answering"; resolve("silent"); } });
739
+ });
740
+ const first = init ? { ...init, id: handoverId } : { jsonrpc: "2.0", id: handoverId, method: "initialize",
741
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "truthspine-launcher", version: "1" } } };
742
+ copy.send(JSON.stringify(first));
743
+ if (await outcome !== "answered" || done) { if (!copy.gaveUp()) copy.connection.stop(1); return false; }
744
+ copy.send(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
745
+ live = copy;
746
+ copy.connection.closed.then(result => finish(result.code));
747
+ write({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
748
+ live.send(callLine);
749
+ return true;
750
+ }
751
+ const onLine = line => {
752
+ if (live) { live.send(line); return; }
753
+ const message = parse(line);
754
+ if (!message) return;
755
+ if (message.method === "tools/call" && !trying && now() - lastTry >= retryEveryMs && !(message.params && message.params.name === "open_download_page")) {
756
+ lastTry = now();
757
+ trying = connect(line).then(connected => { trying = null; if (!connected) answer(message); }, () => { trying = null; answer(message); });
758
+ return;
759
+ }
760
+ if (trying) { trying.then(() => onLine(line)); return; }
761
+ answer(message);
762
+ };
763
+ for (const line of earlier) onLine(line);
764
+ const stopReading = readLines(input, onLine);
765
+ input.once("end", ended);
766
+ if (input.readableEnded) ended();
767
+ return { closed, stop: codeOut => finish(codeOut || 0), pid: null, failure: () => code, withoutApp: true };
768
+ }
769
+
770
+ async function startInstalledMcpLauncherWithRecovery({ signal, inPlace = handOverInPlace, input = process.stdin, output = process.stdout,
771
+ waitMs = NO_ANSWER_MS, relay = relayInstalledMcp } = {}) {
772
+ if (signal?.aborted) fail();
773
+ const delegated = relayDelegationPlan();
774
+ if (delegated) return relayInstalledMcp(delegated);
775
+ let plan;
776
+ try { plan = await installedPlan(signal); }
777
+ catch (error) {
778
+ const code = typedCode(error);
779
+ if (!["app_not_installed", "app_not_opened", "app_not_running"].includes(code)) throw error;
780
+ return serveWithoutApp(code, { input, output, waitMs, relay, attempt: () => installedPlan(signal) });
781
+ }
782
+ if (signal?.aborted) fail();
783
+ // (only a plan that passed validation is ever handed over)
784
+ const handover = inPlaceHandover(plan);
785
+ if (handover) return inPlace(handover);
786
+ if (plan.mode !== "installed-stdio") return relayInstalledMcp(plan);
787
+ // A copy that does not answer the app's first request in time is given up, and this connection answers by itself.
788
+ let resolveClosed, without = null;
789
+ const closed = new Promise(resolve => { resolveClosed = resolve; });
790
+ let watched;
791
+ const stopReading = readLines(input, line => { if (without) return; watched.send(line); });
792
+ const ended = () => { if (!without) watched.end(); };
793
+ watched = answeredRelay(plan, { output, waitMs, relay, onSilent: sent => {
794
+ stopReading(); input.removeListener("end", ended);
795
+ without = serveWithoutApp("app_not_answering", { input, output, waitMs, relay, attempt: () => installedPlan(signal), earlier: sent });
796
+ without.closed.then(resolveClosed);
797
+ } });
798
+ input.once("end", ended);
799
+ watched.connection.closed.then(result => { if (!watched.gaveUp()) { stopReading(); resolveClosed(result); } });
800
+ return { closed, stop: code => (without ? without.stop(code) : watched.connection.stop(code)), pid: watched.connection.pid,
801
+ failure: () => (without ? without.failure() : watched.connection.failure()) };
802
+ }
803
+
804
+ // Store package discovery stays in this single-file thin transport so generated
805
+ // VS Code and MCPB launchers cannot omit a recovery dependency. Routing only.
806
+ const NAME = 'TimeProofLabsLLC.TruthSpine';
807
+ const FAMILY = NAME + '_xzspk04648dda';
808
+ const PUBLISHER = 'CN=C757D670-5A7C-4F9F-A475-D820CD5AC334';
809
+ const recoveryFail = () => { const error = new Error('store_package_recovery_unavailable'); error.code = LAUNCHER_CODE_PREFIX + 'app_not_installed'; throw error; };
810
+ function storeVersion(value) {
811
+ if (typeof value !== 'string' || !/^(0|[1-9]\d{0,4})(\.(0|[1-9]\d{0,4})){3}$/.test(value)) recoveryFail();
812
+ const parts = value.split('.').map(Number);
813
+ if (parts.some(n => n > 65535)) recoveryFail();
814
+ return parts;
815
+ }
816
+ function storeAbsolute(value) {
817
+ if (typeof value !== 'string' || !/^[A-Za-z]:\\/.test(value) || /[\x00-\x1f\x7f]/.test(value)
818
+ || value !== value.trim() || value.includes('/') || value !== path.win32.normalize(value)) recoveryFail();
819
+ return value;
820
+ }
821
+ function qualifyCurrentStorePackage({ packages, programFiles, minimumVersion }) {
822
+ if (!Array.isArray(packages) || packages.length !== 1) recoveryFail();
823
+ const row = packages[0], floor = storeVersion(minimumVersion);
824
+ if (!row || typeof row !== 'object' || Array.isArray(row)) recoveryFail();
825
+ const current = storeVersion(row.version);
826
+ const delta = current.map((n, i) => n - floor[i]).find(n => n !== 0) || 0;
827
+ if (delta < 0 || row.name !== NAME || row.family !== FAMILY || row.publisher !== PUBLISHER
828
+ || row.architecture !== 'X64' || row.signatureKind !== 'Store' || row.status !== 'Ok'
829
+ || row.developmentMode !== false || row.partiallyStaged !== false) recoveryFail();
830
+ const fullName = `${NAME}_${row.version}_x64__xzspk04648dda`;
831
+ const expected = path.win32.join(storeAbsolute(programFiles), 'WindowsApps', fullName);
832
+ if (row.fullName !== fullName || storeAbsolute(row.installLocation).toLowerCase() !== expected.toLowerCase()) recoveryFail();
833
+ return Object.freeze({ packageFullName: fullName, version: row.version,
834
+ executable: path.win32.join(expected, 'TruthSpine.exe'), packageRoot: path.win32.join(expected, 'resources', 'app') });
835
+ }
836
+ // Fixed, read-only command: no registration strings or user arguments enter
837
+ // PowerShell source. Current user only; never -AllUsers or elevation.
838
+ const DISCOVERY = "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); $items=@(Get-AppxPackage -Name TimeProofLabsLLC.TruthSpine | ForEach-Object { @{name=$_.Name;family=$_.PackageFamilyName;publisher=$_.Publisher;version=[string]$_.Version;fullName=$_.PackageFullName;architecture=[string]$_.Architecture;signatureKind=[string]$_.SignatureKind;status=[string]$_.Status;developmentMode=[bool]$_.IsDevelopmentMode;partiallyStaged=[bool]$_.IsPartiallyStaged;installLocation=$_.InstallLocation} }); ConvertTo-Json -InputObject $items -Depth 3 -Compress";
839
+ async function discoverCurrentStorePackage({ minimumVersion, signal } = {}) {
840
+ storeVersion(minimumVersion);
841
+ if (process.platform !== 'win32' || signal?.aborted) recoveryFail();
842
+ const systemRoot = storeAbsolute(process.env.SystemRoot || process.env.SYSTEMROOT);
843
+ const programFiles = storeAbsolute(process.env.ProgramFiles || process.env.PROGRAMFILES || process.env.ProgramW6432
844
+ || path.win32.join(path.win32.parse(systemRoot).root, 'Program Files'));
845
+ const executable = path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
846
+ if (fs.realpathSync(executable).toLowerCase() !== executable.toLowerCase()) recoveryFail();
847
+ const env = {};
848
+ for (const key of Object.keys(process.env)) {
849
+ if (/^(systemroot|windir|temp|tmp|userprofile|localappdata|appdata|programfiles|programfiles\(x86\)|programdata|psmodulepath)$/i.test(key)
850
+ && !/^psmodulepath$/i.test(key)) env[key] = process.env[key];
851
+ }
852
+ // Prevent ambient modules/profile/startup injection. Only built-in Windows
853
+ // PowerShell modules are discoverable; module output is bounded and parsed.
854
+ env.PSModulePath = path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'Modules');
855
+ const wire = await new Promise((resolve, reject) => {
856
+ let child, output = '', bytes = 0, failed = false, settled = false, deadline, cleanup;
857
+ const finish = (error, value) => {
858
+ if (settled) return; settled = true;
859
+ clearTimeout(deadline); clearTimeout(cleanup); signal?.removeEventListener('abort', cancel);
860
+ error ? reject(new Error('store_package_recovery_unavailable')) : resolve(value);
861
+ };
862
+ const cancel = () => {
863
+ if (settled || failed) return; failed = true;
864
+ try { child?.kill(); } catch {}
865
+ // Never report successful cleanup or retry when closure is unknown.
866
+ cleanup = setTimeout(() => finish(true), 2000);
867
+ };
868
+ try {
869
+ child = spawn(executable, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', DISCOVERY],
870
+ { cwd: path.win32.join(systemRoot, 'System32'), env, shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
871
+ deadline = setTimeout(cancel, 10000);
872
+ signal?.addEventListener('abort', cancel, { once: true });
873
+ if (signal?.aborted) cancel();
874
+ child.stdout.setEncoding('utf8');
875
+ child.stdout.on('data', chunk => { bytes += Buffer.byteLength(chunk); if (bytes > 16384) cancel(); else if (!failed) output += chunk; });
876
+ child.stderr.on('data', chunk => { bytes += chunk.length; if (bytes > 16384) cancel(); });
877
+ child.stdout.on('error', cancel); child.stderr.on('error', cancel);
878
+ child.on('error', cancel);
879
+ child.on('close', (code, endedBySignal) => finish(failed || code !== 0 || !!endedBySignal, output));
880
+ } catch { cancel(); }
881
+ });
882
+ let packages;
883
+ try { packages = JSON.parse(wire.replace(/^\uFEFF/, '')); } catch { recoveryFail(); }
884
+ return qualifyCurrentStorePackage({ packages, programFiles, minimumVersion });
885
+ }
886
+ async function prepareRecoveredMcpPlan(options, { signal } = {}) {
887
+ // Validate and snapshot all caller routing before any asynchronous work.
888
+ return prepareRecoveredInstalledPlan(buildInstalledMcpLaunchPlan(options), signal);
889
+ }
890
+ async function prepareRecoveredCliPlan(options, { signal } = {}) {
891
+ // Snapshot command arguments before discovery, just like workspace/profile.
892
+ return prepareRecoveredInstalledPlan(buildInstalledCliLaunchPlan(options), signal);
893
+ }
894
+ async function prepareRecoveredInstalledPlan(initial, signal) {
895
+ if (initial.platform !== 'win32' || !['installed-stdio', 'installed-cli'].includes(initial.mode)) recoveryFail();
896
+ // Pin directory identity before awaiting OS discovery. Preserving lexical
897
+ // strings alone would allow a replaced junction/profile to select new data.
898
+ // This is a routing-race check, not ongoing folder authorization or a grant.
899
+ const directories = [initial.projectRoot, initial.truthHome].filter(Boolean);
900
+ const directoryIdentity = directory => {
901
+ try {
902
+ const real = fs.realpathSync(directory);
903
+ const stat = fs.statSync(real, { bigint: true });
904
+ if (!stat.isDirectory() || typeof stat.dev !== 'bigint' || typeof stat.ino !== 'bigint'
905
+ || fs.realpathSync(directory) !== real) recoveryFail();
906
+ return { real, dev: String(stat.dev), ino: String(stat.ino) };
907
+ } catch { recoveryFail(); }
908
+ };
909
+ const originalDirectories = JSON.stringify(directories.map(directoryIdentity));
910
+ const assertDirectories = () => {
911
+ if (JSON.stringify(directories.map(directoryIdentity)) !== originalDirectories) recoveryFail();
912
+ };
913
+ // packageRoot ends resources/app; use its enclosing installation instead.
914
+ const packageName = path.win32.basename(path.win32.dirname(path.win32.dirname(initial.packageRoot)));
915
+ const registered = /^TimeProofLabsLLC\.TruthSpine_(\d+\.\d+\.\d+\.\d+)_x64__xzspk04648dda$/.exec(packageName);
916
+ if (!registered || signal?.aborted) recoveryFail();
917
+ const selected = await discoverCurrentStorePackage({ minimumVersion: registered[1], signal });
918
+ if (signal?.aborted) recoveryFail();
919
+ assertDirectories();
920
+ const entry = initial.mode === 'installed-cli' ? 'customer-connector-cli.js' : 'mcp-server.js';
921
+ const recovered = Object.freeze({ ...initial, packageRoot: selected.packageRoot,
922
+ args: Object.freeze([path.win32.join(selected.packageRoot, 'src', entry), ...initial.args.slice(1)]) });
923
+ validateInstalledLaunchPlan(recovered);
924
+ // Discovery is routing, not a lasting grant. Refuse a package switch while
925
+ // preparing the connection. Native core identity still gates actual work.
926
+ const after = await discoverCurrentStorePackage({ minimumVersion: registered[1], signal });
927
+ if (signal?.aborted || JSON.stringify(after) !== JSON.stringify(selected)) recoveryFail();
928
+ assertDirectories();
929
+ validateInstalledLaunchPlan(recovered);
930
+ return Object.freeze({ plan: recovered, previousVersion: registered[1], package: selected,
931
+ recovered: selected.version !== registered[1] });
932
+ }
933
+
934
+ module.exports = { HOST_IDS, HOST_TOOL_PROFILES, LINUX_PACKAGE_COMMANDS, readRegistration, resolveBoundedHostWorkspace, neverAProjectFolder, scratchFolder, launcherProjectRoot, buildInstalledMcpLaunchPlan, buildInstalledCliLaunchPlan,
935
+ validateInstalledLaunchPlan, restrictiveTelemetryEnv, relayInstalledMcp, relayDelegationPlan, startInstalledMcpLauncher,
936
+ startInstalledMcpLauncherWithRecovery, qualifyCurrentStorePackage, discoverCurrentStorePackage, prepareRecoveredMcpPlan, prepareRecoveredCliPlan,
937
+ LAUNCHER_RESULTS, LAUNCHER_STORE_LINKS, LAUNCHER_GET_LINKS, installedAppPresent, NO_ANSWER_MS, describeLauncherFailure, serveWithoutApp, answeredRelay, inPlaceHandover, handOverInPlace, IN_PLACE_RUNTIME_KEYS };
938
+ if (require.main === module) {
939
+ const controller = new AbortController();
940
+ let connection;
941
+ const stop = () => { controller.abort(); connection?.stop(1); };
942
+ process.once("SIGINT", stop); process.once("SIGTERM", stop);
943
+ (async () => {
944
+ connection = await startInstalledMcpLauncherWithRecovery({ signal: controller.signal, inPlace: handover => {
945
+ // (from here this process is the chat server, which handles its own stop: mcp-server.js)
946
+ process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop);
947
+ return handOverInPlace(handover);
948
+ } });
949
+ if (connection.inPlace) return;
950
+ connection.closed.then(result => {
951
+ process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop);
952
+ if (result.code !== 0) {
953
+ const code = typeof connection.failure === "function" ? connection.failure() : null;
954
+ process.stderr.write(describeLauncherFailure(code ? { code: LAUNCHER_CODE_PREFIX + code } : null).message + "\n");
955
+ }
956
+ process.exitCode = result.code;
957
+ });
958
+ })().catch(error => {
959
+ process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop);
960
+ // Only the catalogue sentence is printed; the caught error's own text never reaches stderr.
961
+ process.stderr.write(describeLauncherFailure(error).message + "\n"); process.exitCode = 1;
962
+ });
963
+ }