launcher.js

"use strict";
// MSI chat launcher (build contract 8.2). Plain CommonJS, no dependencies. Run for a few milliseconds:
//   <node.exe> launcher.js <settings.json>
// It starts the keepalive DETACHED and hidden, with the settings' launch_env exactly, then exits on the
// child's "spawn" event. Once this launcher has exited, the keepalive's parent PID is dead, so LM Studio's
// "taskkill /pid <plugin> /T /F" no longer reaches it (M0). It never reads or forwards process.env.
// Exit codes: 0 spawned, 2 spawn error, 3 bad settings (or usage), 4 nothing after 8 s, 5 refused under MSI_CHAT_TEST.
// T3 copies this file byte for byte into <release>\plugin\launcher.js.
const childProcess = require("node:child_process");
const fs = require("node:fs");

const SPAWN_TIMEOUT_MS = 8000;
const EXIT = Object.freeze({ OK: 0, SPAWN_ERROR: 2, BAD_SETTINGS: 3, TIMEOUT: 4, REFUSED: 5 });
const MAX_SETTINGS_BYTES = 1000000;

// The test guard (contract rules 4 and 5): with launch_env.MSI_CHAT_TEST = "1" (every T3/T4 test sets it) launch_env
// must also hold MSI_CHAT_TEST_ROOT, the test's sandbox (one absolute folder, or several separated by ";"), and the run
// folder, the keepalive and the settings file must lie under it. The launcher names no place of any PC.
const TEST_ROOT_NAME = "MSI_CHAT_TEST_ROOT";

const SECRET_NAME = /(KEY|TOKEN|SECRET|PASS|CREDENTIAL|AUTH|COOKIE|SESSION)/i;
const SECRET_PREFIX = /^(CF_|CLOUDFLARE|NEWT_|TUNNEL)/i;
const LONG_TOKEN = /[A-Za-z0-9_-]{40,}/;
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_()]*$/;

function isPlainObject(v) {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

// Same rules as src\settings.ts isAbsWinPath: plain parts only (no "..", ".", empty part, trailing dot or space).
function isAbsWinPath(v) {
  if (typeof v !== "string" || v.length < 3 || v.length > 1024) return false;
  if (!/^[A-Za-z]:[\\/]/.test(v)) return false;
  if (/[\u0000-\u001f\u007f"<>|?*]/.test(v)) return false;
  if (v.indexOf(":", 2) !== -1) return false;
  const parts = v.split(/[\\/]/).slice(1);
  return parts.every((part, i) => (part === "" ? i === parts.length - 1 : part !== "." && part !== ".." && !/[. ]$/.test(part)));
}

function norm(p) {
  return p.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase();
}

function hasShortName(p) {
  return /(^|\\)[^\\]*~\d/.test(norm(p));
}

function splitRoots(value) {
  return value.split(";").filter((part) => part !== "");
}

// Same rules as src\settings.ts testRootProblem / isUnderTestRoot (the tests hold both to one table).
function testRootProblem(value) {
  if (typeof value !== "string" || splitRoots(value).length === 0) return TEST_ROOT_NAME + " is missing (set it to the test's sandbox folder)";
  for (const root of splitRoots(value)) {
    if (!isAbsWinPath(root)) return TEST_ROOT_NAME + " holds a path that is not an absolute Windows path";
    if (norm(root).length <= 2) return TEST_ROOT_NAME + " must name a folder, not a whole drive";
    if (hasShortName(root)) return TEST_ROOT_NAME + " holds an 8.3 short name";
  }
  return null;
}

function isUnderTestRoot(p, rootValue) {
  if (testRootProblem(rootValue) !== null || hasShortName(p)) return false;
  const n = norm(p);
  return splitRoots(rootValue).some((root) => n === norm(root) || n.startsWith(norm(root) + "\\"));
}

function testPathProblem(name, p, rootValue) {
  if (typeof p === "string" && hasShortName(p)) return "refused under MSI_CHAT_TEST: " + name + " holds an 8.3 short name";
  if (typeof p !== "string" || !isUnderTestRoot(p, rootValue)) return "refused under MSI_CHAT_TEST: " + name + " is outside " + TEST_ROOT_NAME;
  return null;
}

function envLookup(env, name) {
  const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());
  return key === undefined ? undefined : env[key];
}

// Same rules as src\settings.ts launchEnvProblem (the tests hold both to one table).
function launchEnvProblem(env, exists) {
  if (!isPlainObject(env)) return "launch_env: not an object";
  const names = Object.keys(env);
  if (names.length === 0 || names.length > 64) return "launch_env: wrong number of names";
  const seen = new Set();
  for (const name of names) {
    if (!ENV_NAME.test(name)) return "launch_env: a name is not a plain variable name";
    if (/^LMS_/i.test(name)) return "launch_env: LMS_* names are refused (" + name + ")";
    if (SECRET_NAME.test(name) || SECRET_PREFIX.test(name)) return "launch_env: a secret-like name is refused (" + name + ")";
    if (seen.has(name.toLowerCase())) return "launch_env: a name appears twice (" + name + ")";
    seen.add(name.toLowerCase());
    const value = env[name];
    if (typeof value !== "string") return "launch_env: " + name + " is not a string";
    if (value.length > 8192 || value.includes("\u0000")) return "launch_env: " + name + " is too long or holds NUL";
    if (LONG_TOKEN.test(value)) return "launch_env: " + name + " holds a token-like value";
  }
  for (const name of ["SystemRoot", "PATH", "TEMP", "USERPROFILE"]) {
    const value = envLookup(env, name);
    if (typeof value !== "string" || value.length === 0) return "launch_env: " + name + " is missing";
  }
  const systemRoot = envLookup(env, "SystemRoot");
  if (!isAbsWinPath(systemRoot) || !exists(systemRoot.replace(/[\\/]+$/, "") + "\\System32")) {
    return "launch_env: SystemRoot does not hold System32";
  }
  for (const name of ["TEMP", "USERPROFILE"]) {
    if (!isAbsWinPath(envLookup(env, name))) return "launch_env: " + name + " is not an absolute path";
  }
  return null;
}

function pathProblem(raw, exists) {
  for (const field of ["run_dir", "logs_dir", "python", "keepalive"]) {
    if (!isAbsWinPath(raw[field])) return field + ": not an absolute path";
  }
  if (!/(^|[\\/])python\.exe$/i.test(raw.python) || raw.python.includes(" ")) return "python: must be a python.exe path without spaces";
  if (!/\.py$/i.test(raw.keepalive)) return "keepalive: not a .py file";
  for (const field of ["python", "keepalive"]) {
    if (!exists(raw[field])) return field + ": file not found";
  }
  return null;
}

// Under the test: the root must be usable and every place the launcher writes or starts must lie under it.
function testModeProblem(raw, root, settingsPath) {
  const rootProblem = testRootProblem(root);
  if (rootProblem !== null) return "refused under MSI_CHAT_TEST: " + rootProblem;
  const guarded = { run_dir: raw.run_dir, state_dir: raw.state_dir, logs_dir: raw.logs_dir, keepalive: raw.keepalive,
    "the settings file": settingsPath };
  for (const [field, value] of Object.entries(guarded)) {
    if (typeof value !== "string") continue;
    const problem = testPathProblem(field, value, root);
    if (problem !== null) return problem;
  }
  return null;
}

// Checks the fields the launcher uses. Returns {ok: true, s} or {ok: false, code, reason, logsDir}.
// With launch_env.MSI_CHAT_TEST = "1" every place outside launch_env.MSI_CHAT_TEST_ROOT is refused (exit 5), the
// settings file's own path included when it is given; a logs dir outside the root is never written, not even for
// the line that says why.
function checkSettings(raw, exists, settingsPath) {
  const fail = (code, reason, logsDir) => ({ ok: false, code, reason, logsDir: logsDir || null });
  if (!isPlainObject(raw)) return fail(EXIT.BAD_SETTINGS, "settings: not a JSON object");
  const testMode = isPlainObject(raw.launch_env) && raw.launch_env.MSI_CHAT_TEST === "1";
  const root = testMode ? envLookup(raw.launch_env, TEST_ROOT_NAME) : undefined;
  const logsOk = isAbsWinPath(raw.logs_dir) && (!testMode || (typeof root === "string" && isUnderTestRoot(raw.logs_dir, root)));
  const logsDir = logsOk ? raw.logs_dir : null;
  if (raw.schema !== 1) return fail(EXIT.BAD_SETTINGS, "schema: not 1", logsDir);
  const problem = pathProblem(raw, exists) || launchEnvProblem(raw.launch_env, exists);
  if (problem) return fail(EXIT.BAD_SETTINGS, problem, logsDir);
  if (testMode) {
    const refusal = testModeProblem(raw, root, settingsPath);
    if (refusal !== null) return fail(EXIT.REFUSED, refusal, logsDir);
  }
  return {
    ok: true,
    s: Object.freeze({
      runDir: raw.run_dir,
      logsDir: raw.logs_dir,
      python: raw.python,
      keepalive: raw.keepalive,
      launchEnv: Object.freeze(Object.assign({}, raw.launch_env)),
    }),
  };
}

// The keepalive's command line (contract section 4).
function keepaliveCommand(s, settingsPath) {
  return {
    command: s.python,
    args: ["-I", "-B", "-X", "utf8", s.keepalive, "--settings", settingsPath],
    options: { detached: true, windowsHide: true, env: Object.assign({}, s.launchEnv), cwd: s.runDir },
  };
}

function readSettings(settingsPath, deps) {
  if (typeof settingsPath !== "string" || !isAbsWinPath(settingsPath)) {
    return { ok: false, code: EXIT.BAD_SETTINGS, reason: "usage: launcher.js <absolute settings.json path>", logsDir: null };
  }
  let raw;
  try {
    const text = deps.fs.readFileSync(settingsPath, "utf8");
    if (text.length > MAX_SETTINGS_BYTES) throw new Error("too large");
    raw = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
  } catch (err) {
    return { ok: false, code: EXIT.BAD_SETTINGS, reason: "settings: missing, unreadable or not JSON", logsDir: null };
  }
  return checkSettings(raw, (p) => deps.fs.existsSync(p), settingsPath);
}

function makeRecorder(deps, logsDir) {
  return (event, extra) => {
    if (!logsDir) return;
    const line = Object.assign({ t: deps.now().toISOString(), event, pid: deps.pid }, extra || {});
    try {
      deps.fs.mkdirSync(logsDir, { recursive: true });
      deps.fs.appendFileSync(logsDir + "\\launcher.jsonl", JSON.stringify(line) + "\n");
    } catch (err) {
      // Logging must never stop the start.
    }
  };
}

// Runs the launcher. Resolves to the exit code; deps are injectable for tests.
function run(argv, overrides) {
  const deps = Object.assign(
    { fs, spawn: childProcess.spawn, timeoutMs: SPAWN_TIMEOUT_MS, now: () => new Date(), pid: process.pid },
    overrides || {},
  );
  const settingsPath = argv[0];
  const checked = readSettings(settingsPath, deps);
  const record = makeRecorder(deps, checked.logsDir || (checked.ok ? checked.s.logsDir : null));
  if (!checked.ok) {
    record("bad-settings", { code: checked.code, reason: checked.reason });
    return Promise.resolve(checked.code);
  }
  return new Promise((resolve) => {
    let out = null;
    let done = false;
    const finish = (code, event, extra) => {
      if (done) return;
      done = true;
      clearTimeout(timer);
      record(event, extra);
      if (out !== null) {
        try { deps.fs.closeSync(out); } catch (err) { /* already closed */ }
      }
      resolve(code);
    };
    const timer = setTimeout(() => finish(EXIT.TIMEOUT, "timeout", { ms: deps.timeoutMs }), deps.timeoutMs);
    try {
      deps.fs.mkdirSync(checked.s.logsDir, { recursive: true });
      out = deps.fs.openSync(checked.s.logsDir + "\\keepalive_stdio.log", "a");
      const cmd = keepaliveCommand(checked.s, settingsPath);
      const child = deps.spawn(cmd.command, cmd.args, Object.assign({ stdio: ["ignore", out, out] }, cmd.options));
      child.once("error", (err) => finish(EXIT.SPAWN_ERROR, "spawn-error", { code: String((err && err.code) || "error") }));
      child.once("spawn", () => {
        child.unref();
        finish(EXIT.OK, "spawned", { keepalivePid: child.pid });
      });
    } catch (err) {
      finish(EXIT.SPAWN_ERROR, "spawn-error", { code: String((err && err.code) || (err && err.name) || "error") });
    }
  });
}

module.exports = {
  run, checkSettings, keepaliveCommand, launchEnvProblem, isAbsWinPath, testRootProblem, isUnderTestRoot, TEST_ROOT_NAME,
  SPAWN_TIMEOUT_MS, EXIT,
};

if (require.main === module) {
  run(process.argv.slice(2)).then((code) => process.exit(code));
}