install / plugin_first.js

"use strict";
// plugin_tool.js's plugin-first commands (docs\build\PLUGINFIRST_REPORT.md), plain CommonJS, run by main\install.cmd
// /plugin-first and main\uninstall.cmd with LM Studio's node.exe:
//   stage-first --src <repo>\lmstudio-plugin --out <run_dir>\plugin-stage\msi-chat --repo <repo> --run-dir <run_dir>
//       --python <python.exe> --node <node.exe> --lms <lms.exe> --plugins-root <root> --newt-exe <newt.exe>
//       [--max-per-day <1-10>] -- <install args>
//     the stage of `stage`, plus the plan baked into src\baked.ts (BOOTSTRAP_PLAN: the repository, the run folder,
//     python, the SHA-256 of bootstrap.js and of every installer file, the install args, the install's environment)
//     and the install ticket <run_dir>\state\bootstrap.json ("pending"). It installs nothing: the plugin's main() does.
//     Exit 0, 2 usage (bad install args, no --real outside MSI_CHAT_TEST), 3 Locus already installed here or a
//     plugin-first install running, 4 failed, 5 refused (under MSI_CHAT_TEST: a run folder, stage, plugins root, lms
//     or newt outside MSI_CHAT_TEST_ROOT, or --real; outside it: --real without MSI_CHAT_ALLOW_REAL=1).
//   bootstrap-status --run-dir <run_dir> [--wait <s>] [--json]
//     0 done, 1 no ticket, 3 failed, 6 running, 7 pending (LM Studio has not run the plugin yet).
//   bootstrap-forget --run-dir <run_dir> [--plugin-dir <folder>] --yes-really
//     deletes the ticket, the plan file and a stale lock, and marks the plugin folder (ours) as uninstalled, so the
//     plugin never installs Locus again by itself: 0 forgotten, 1 nothing there, 4 refused (a bootstrap is running).
//   stale-devices --run-dir <run_dir>
//     3 when an uninstall without /purge left devices in devices.json (only the count is read and printed), else 0.
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");

const STATUS = Object.freeze({ DONE: 0, NONE: 1, FAILED: 3, RUNNING: 6, PENDING: 7 });
const MAX_WAIT_S = 3600;

module.exports = function pluginFirstCommands(tool) {
  const { ToolError, EXIT, PLUGIN_ROOT, OWNER, NAME, absPath, guard, testMode, canonical, stageInto, needYes, isOurPluginDir, writeJson } = tool;
  const boot = require(path.join(PLUGIN_ROOT, "bootstrap.js"));
  const UNINSTALLED_MARKER = "locus-uninstalled.json";

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

  // The install's environment: the launch_env names (3.1) from this console's own values, a short system PATH, the
  // paths install.cmd reads, and under MSI_CHAT_TEST only the test switches. Never LMS_*, never MSI_CHAT_ALLOW_REAL.
  function planEnv(paths) {
    const own = process.env;
    const systemRoot = lookupEnv(own, "SystemRoot");
    if (typeof systemRoot !== "string" || systemRoot === "") throw new ToolError(EXIT.FAILED, "SystemRoot is not set in this console");
    const temp = lookupEnv(own, "TEMP");
    const env = {
      SystemRoot: systemRoot, windir: lookupEnv(own, "windir") || systemRoot, SystemDrive: lookupEnv(own, "SystemDrive") || systemRoot.slice(0, 2),
      ComSpec: lookupEnv(own, "ComSpec") || path.win32.join(systemRoot, "system32", "cmd.exe"), PATHEXT: ".COM;.EXE;.BAT;.CMD",
      PATH: [path.win32.join(systemRoot, "system32"), systemRoot, path.win32.join(systemRoot, "System32", "Wbem"),
        path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0")].join(";"),
      TEMP: temp, TMP: lookupEnv(own, "TMP") || temp, USERPROFILE: lookupEnv(own, "USERPROFILE"), HOMEDRIVE: lookupEnv(own, "HOMEDRIVE"),
      HOMEPATH: lookupEnv(own, "HOMEPATH"), APPDATA: lookupEnv(own, "APPDATA"), LOCALAPPDATA: lookupEnv(own, "LOCALAPPDATA"),
      PYTHONDONTWRITEBYTECODE: "1",
      MSI_CHAT_PYTHON: paths.python, MSI_CHAT_NODE: paths.node, MSI_CHAT_LMS: paths.lms, MSI_CHAT_RUN_DIR: paths.runDir,
      MSI_CHAT_PLUGINS_ROOT: paths.pluginsRoot, MSI_CHAT_NEWT_EXE: paths.newtExe,
      MSI_CHAT_PLUGIN_DIR: path.win32.join(paths.pluginsRoot, OWNER, NAME),     // the staged plugin's folder, recorded by install
    };
    for (const name of Object.keys(env)) if (env[name] === undefined || env[name] === "") delete env[name];
    if (testMode()) {
      for (const [name, value] of Object.entries(own)) {
        if (/^MSI_CHAT_TEST(_[A-Z0-9_]+)?$|^MSI_CHAT_NEWT_SHA256$/.test(name) && typeof value === "string" && value !== "") env[name] = value;
      }
    }
    return env;
  }

  function installArgs(rest) {
    const args = Array.isArray(rest) ? rest.slice() : [];
    if (args.includes("--no-provision")) {
      throw new ToolError(EXIT.USAGE, "--no-provision: the plugin-first install makes the address itself (--real); for an install " +
        "without the address use main\\install.cmd --no-provision");
    }
    const real = args.includes("--real");
    if (testMode() && real) throw new ToolError(EXIT.REFUSED, "refused under MSI_CHAT_TEST: --real (the test uses the fakes)");
    if (!testMode() && !real) {
      throw new ToolError(EXIT.USAGE, "say --real: the plugin makes the DNS record and the tunnel site (set MSI_CHAT_ALLOW_REAL=1 first)");
    }
    if (real && process.env.MSI_CHAT_ALLOW_REAL !== "1") {
      throw new ToolError(EXIT.REFUSED, "refused: a real install needs --real AND MSI_CHAT_ALLOW_REAL=1 (set it in this console first)");
    }
    if (!args.includes("--yes")) args.push("--yes");
    const problem = boot.installArgsProblem(args, real);
    if (problem) throw new ToolError(EXIT.USAGE, problem);
    return { args, real };
  }

  function stateDirOf(runDir) {
    return path.win32.join(runDir, "state");
  }

  function readJson(file) {
    return boot.readJson(fs, file);
  }

  function lockView(runDir) {
    const file = path.win32.join(stateDirOf(runDir), boot.LOCK_FILE);
    let text = null;
    let mtime = null;
    try {
      text = fs.readFileSync(file, "utf8");
      mtime = fs.statSync(file).mtimeMs;
    } catch (err) {
      text = null;
    }
    const alive = (pid) => {
      try {
        process.kill(pid, 0);
        return true;
      } catch (err) {
        return err.code === "EPERM";
      }
    };
    return boot.lockState(text, mtime, Date.now(), alive);
  }

  // Locus is installed here when settings.json exists AND names a secrets folder holding install.json (after an
  // uninstall without /purge, settings.json stays but install.json is gone: that may be installed over).
  function installedProblem(runDir) {
    const settings = readJson(path.win32.join(runDir, "settings.json"));
    if (!settings || typeof settings.secrets_dir !== "string") return null;
    const installJson = path.win32.join(settings.secrets_dir, "install.json");
    if (!fs.existsSync(installJson)) return null;
    return "Locus is already installed in " + runDir + " (settings.json and " + installJson + "): the plugin-first install is " +
      "for a PC without Locus. Uninstall first (set MSI_CHAT_ALLOW_REAL=1, then main\\uninstall.cmd --real), or keep this " +
      "install and add the plugin the old way (main\\install.cmd /plugin)";
  }

  // Under MSI_CHAT_TEST the places the install writes or starts must lie under MSI_CHAT_TEST_ROOT; the plugin's source,
  // the repository, python and node are read and run from wherever they are.
  const GUARDED = ["out", "run-dir", "lms", "plugins-root", "newt-exe"];

  async function cmdStageFirst(opts) {
    const p = {};
    for (const [key, name] of [["src", "src"], ["out", "out"], ["repo", "repo"], ["run-dir", "runDir"], ["python", "python"],
      ["node", "node"], ["lms", "lms"], ["plugins-root", "pluginsRoot"], ["newt-exe", "newtExe"]]) {
      p[name] = absPath(opts, key);
      if (GUARDED.includes(key)) guard("--" + key, p[name]);
    }
    if (canonical(p.src) !== canonical(PLUGIN_ROOT) || canonical(p.src) !== canonical(path.win32.join(p.repo, "lmstudio-plugin"))) {
      throw new ToolError(EXIT.USAGE, "--src must be this plugin's folder, <repo>\\lmstudio-plugin");
    }
    if (canonical(p.out) !== canonical(path.win32.join(p.runDir, "plugin-stage", "msi-chat"))) {
      throw new ToolError(EXIT.USAGE, "--out must be <run dir>\\plugin-stage\\msi-chat");
    }
    const max = opts["max-per-day"] === undefined ? 3 : Number(opts["max-per-day"]);
    if (!Number.isInteger(max) || max < 1 || max > 10) throw new ToolError(EXIT.USAGE, "--max-per-day must be 1-10");
    const { args, real } = installArgs(opts["--"]);
    const installed = installedProblem(p.runDir);
    if (installed) throw new ToolError(EXIT.CHECK, installed);
    const lock = lockView(p.runDir);
    if (lock.state === "fresh") {
      throw new ToolError(EXIT.CHECK, "Locus is installing itself right now (bootstrap pid " + lock.pid + "): wait until it ends " +
        "(plugin_tool.js bootstrap-status), then stage again if needed");
    }
    const collected = boot.collectFiles(p.repo);
    if (collected.problems.length > 0) throw new ToolError(EXIT.FAILED, "the repository is not complete: " + collected.problems.join("; "));
    const bootstrapPath = path.win32.join(PLUGIN_ROOT, "bootstrap.js");
    const plan = {
      schema: 1, stage_id: crypto.randomBytes(16).toString("hex"), made: new Date().toISOString(), repo: p.repo, run_dir: p.runDir,
      python: p.python, node: p.node, bootstrap: { path: bootstrapPath, sha256: boot.sha256File(bootstrapPath) },
      files: collected.files, install_args: args, real, env: planEnv(p), max_per_day: max,
    };
    const checked = boot.checkPlan(plan);
    if (!checked.ok) throw new ToolError(EXIT.USAGE, checked.reason);
    const planText = JSON.stringify(plan);
    const settingsPath = path.win32.join(p.runDir, "settings.json");
    const copied = stageInto(p.src, p.out, settingsPath, planText);
    if (tool.stagedPlan(p.out) !== planText) throw new ToolError(EXIT.FAILED, "the stage does not hold the plan that was baked");
    const stateDir = stateDirOf(p.runDir);
    fs.mkdirSync(stateDir, { recursive: true });
    fs.mkdirSync(path.win32.join(p.runDir, "logs"), { recursive: true });
    fs.rmSync(path.win32.join(stateDir, boot.PLAN_FILE), { force: true });
    boot.writeJsonAtomic(fs, path.win32.join(stateDir, boot.TICKET_FILE),
      { schema: 1, stage_id: plan.stage_id, made: plan.made, state: "pending", attempts: [], done: null, max_per_day: max });
    process.stdout.write("staged for plugin-first: " + p.out + " (" + copied.length + " source files; " +
      Object.keys(plan.files).length + " installer files hashed; " + (real ? "real" : "MSI_CHAT_TEST") + "; install args: " +
      args.join(" ") + ")\nthe install ticket: " + path.win32.join(stateDir, boot.TICKET_FILE) + " (pending; stage " +
      plan.stage_id.slice(0, 8) + ")\n");
    return EXIT.OK;
  }

  function describe(runDir) {
    const stateDir = stateDirOf(runDir);
    const ticket = readJson(path.win32.join(stateDir, boot.TICKET_FILE));
    const lock = lockView(runDir);
    const log = path.win32.join(runDir, "logs", boot.LOG_FILE);
    const status = path.win32.join(runDir, "logs", boot.STATUS_FILE);
    const attempts = ticket && Array.isArray(ticket.attempts) ? ticket.attempts : [];
    const last = attempts[attempts.length - 1] || null;
    const view = { state: "none", code: STATUS.NONE, stage: ticket && ticket.stage_id, attempts: attempts.length, log, status,
      note: ticket && ticket.note ? ticket.note : null, lock: lock.state, pid: lock.pid };
    if (!ticket || ticket.schema !== 1) return Object.assign(view, { text: "plugin-first: none (no install ticket in " + stateDir + ")" });
    if (lock.state === "fresh") {
      return Object.assign(view, { state: "running", code: STATUS.RUNNING, text: "plugin-first: running (bootstrap pid " + lock.pid +
        " since " + lock.started + "; log " + log + ")" });
    }
    if (ticket.state === "done") {
      return Object.assign(view, { state: "done", code: STATUS.DONE, text: "plugin-first: done (Locus installed itself at " + ticket.done + ")" +
        (ticket.note ? ": " + ticket.note : "") });
    }
    if (attempts.length === 0) {
      return Object.assign(view, { state: "pending", code: STATUS.PENDING, text: "plugin-first: pending (LM Studio has not run the plugin's " +
        "install yet; it runs main() when the plugin is installed and at every LM Studio start)" });
    }
    const reason = last && last.result === "failed" ? "failed at " + last.step + ": " + last.reason
      : "the last attempt stopped without a result (see " + log + ")";
    return Object.assign(view, { state: "failed", code: STATUS.FAILED, reason, text: "plugin-first: " + reason + " (attempt " + attempts.length +
      "; it tries again at the next LM Studio start, at most " + (Number.isInteger(ticket.max_per_day) ? ticket.max_per_day : 3) +
      " times a day; status page " + status + ")" });
  }

  async function cmdStatus(opts) {
    const runDir = absPath(opts, "run-dir");
    guard("--run-dir", runDir);
    const wait = opts.wait === undefined ? 0 : Number(opts.wait);
    if (!Number.isInteger(wait) || wait < 0 || wait > MAX_WAIT_S) throw new ToolError(EXIT.USAGE, "--wait must be 0-" + MAX_WAIT_S + " seconds");
    const end = Date.now() + wait * 1000;
    let view = describe(runDir);
    let shown = "";
    while ((view.state === "pending" || view.state === "running") && Date.now() < end) {
      if (opts.json === undefined && view.text !== shown) {
        process.stdout.write(view.text + "\n");
        shown = view.text;
      }
      await new Promise((r) => setTimeout(r, 1000));
      view = describe(runDir);
    }
    if (opts.json !== undefined) process.stdout.write(JSON.stringify(view) + "\n");
    else if (view.text !== shown) process.stdout.write(view.text + "\n");
    return view.code;
  }

  // bootstrap-forget --run-dir <dir> [--plugin-dir <folder>] --yes-really: the ticket, the plan file and a stale lock go;
  // with --plugin-dir (uninstall.cmd: the folder that installed Locus) a plugin of ours gets the uninstalled marker,
  // which the Hub plugin reads: without it "no ticket and Locus not installed" would mean "install" at the next start.
  function cmdForget(opts) {
    needYes(opts);
    const runDir = absPath(opts, "run-dir");
    guard("--run-dir", runDir);
    const pluginDir = opts["plugin-dir"] === undefined ? null : absPath(opts, "plugin-dir");
    if (pluginDir !== null) guard("--plugin-dir", pluginDir);
    const lock = lockView(runDir);
    if (lock.state === "fresh") {
      throw new ToolError(EXIT.FAILED, "Locus is installing itself right now (bootstrap pid " + lock.pid + "): wait until it ends, then " +
        "run this again");
    }
    const stateDir = stateDirOf(runDir);
    let removed = 0;
    for (const name of [boot.TICKET_FILE, boot.PLAN_FILE, boot.LOCK_FILE]) {
      const file = path.win32.join(stateDir, name);
      if (fs.existsSync(file)) {
        fs.rmSync(file, { force: true, maxRetries: 3 });
        removed += 1;
      }
    }
    let marked = false;
    if (pluginDir !== null && fs.existsSync(pluginDir) && !fs.lstatSync(pluginDir).isSymbolicLink() && isOurPluginDir(pluginDir)) {
      writeJson(path.win32.join(pluginDir, UNINSTALLED_MARKER), { schema: 1, t: new Date().toISOString(), by: "uninstall.cmd" });
      marked = true;
    }
    process.stdout.write(removed > 0 || marked ? "plugin-first: forgotten (the plugin does not install Locus again by itself" +
      (marked ? "; marked in " + pluginDir : "") + ")\n" : "plugin-first: nothing to forget\n");
    return removed > 0 || marked ? EXIT.OK : EXIT.NONE;
  }

  // An uninstall without /purge keeps the secrets folder, so devices.json still lists the phones of the earlier
  // install. The plugin-first install always makes a NEW address (stage-first refuses a folder that still holds
  // install.json), so those phones cannot reach it, and while they are listed the first new phone would neither get
  // the QR page (pair --first-only: "already paired") nor the right to manage devices. Only the count is read out.
  function cmdStaleDevices(opts) {
    const runDir = absPath(opts, "run-dir");
    guard("--run-dir", runDir);
    const settings = readJson(path.win32.join(runDir, "settings.json"));
    if (!settings || typeof settings.secrets_dir !== "string" || !/^[A-Za-z]:[\\/]/.test(settings.secrets_dir)) return EXIT.OK;
    guard("secrets_dir", settings.secrets_dir);
    if (fs.existsSync(path.win32.join(settings.secrets_dir, "install.json"))) return EXIT.OK;
    const devices = readJson(path.win32.join(settings.secrets_dir, "devices.json"));
    const count = devices && Array.isArray(devices.devices) ? devices.devices.length : 0;
    if (count === 0) return EXIT.OK;
    process.stdout.write(count + (count === 1 ? " device" : " devices") + " of the earlier install " + (count === 1 ? "is" : "are") +
      " still listed in " + path.win32.join(settings.secrets_dir, "devices.json") + ". The new install makes a new address, " +
      "which they cannot reach; while they are listed, the first new phone gets no QR page and may not manage devices.\n" +
      "Sign them out first: locus reset-keys --yes (a new master key; every listed device signed out).\n");
    return EXIT.CHECK;
  }

  return { "stage-first": cmdStageFirst, "bootstrap-status": cmdStatus, "bootstrap-forget": cmdForget,
    "stale-devices": cmdStaleDevices };
};