install / plugin_tool.js

"use strict";
// MSI chat plugin tool (build contract 8.3), plain CommonJS, run with LM Studio's node.exe by install.cmd /
// uninstall.cmd. Commands (exit codes: 0 ok, 1 not installed / nothing, 2 usage, 3 check failed, 4 failed,
// 5 refused under MSI_CHAT_TEST):
//   stage --src <repo>\lmstudio-plugin --out <run_dir>\plugin-stage\msi-chat --settings <settings path>
//   install --stage <dir> --lms <lms.exe> --yes-really            runs "<lms> dev -i -y" in the stage (lms's code)
//   remove --plugins-root <root> (--owner <owner> --name <name> | --dir <folder>) --yes-really   (a plugin of our owner
//                                                                  whose manifest names its folder: msi-chat, locus)
//   unstage --out <dir> --yes-really                               deletes a stage made by "stage"
//   check-settings --settings <path> [--newt-sha256 <hex>]         the plugin's and the launcher's checks
//   check-sha256 --file <path> --sha256 <hex>
//   check-paths [--run-dir <dir>] [--plugins-root <dir>] [--lms <exe>] [--stage <dir>]
//   plugin-installed (--settings <path> | --dir <folder> | --plugins-root <root>)   0 installed, 1 not
//   plugin-dir --settings <path> --plugins-root <root>             prints the plugin folder that installed Locus
// Plugin-first (install\plugin_first.js, docs\build\PLUGINFIRST_REPORT.md): stage-first, bootstrap-status,
// bootstrap-forget, stale-devices. The Hub copy (install\plugin_publish.js, docs\build\PUBLISH_REPORT.md): publish-stage.
// The test guard: with MSI_CHAT_TEST=1 this tool needs MSI_CHAT_TEST_ROOT (the test's sandbox: one absolute folder, or
// several separated by ";") and refuses (5) every place it would write, delete or start that is not under it: the run
// folder, the stage, the settings file, the plugins root, lms, newt, the publish copy. The plugin's source folder, the
// repository, python and node may be anywhere. This file names no place of any PC.
const crypto = require("node:crypto");
const childProcess = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");
const { pathToFileURL } = require("node:url");

const EXIT = Object.freeze({ OK: 0, NONE: 1, USAGE: 2, CHECK: 3, FAILED: 4, REFUSED: 5 });
const PLUGIN_ROOT = path.resolve(__dirname, "..");
const TEST_ROOT_NAME = "MSI_CHAT_TEST_ROOT";

// This plugin's identity: the Hub owner and the name, from its own manifest.json (never written in the code).
const OURS = readManifest(PLUGIN_ROOT) || {};
const OWNER = typeof OURS.owner === "string" ? OURS.owner : "";
const NAME = typeof OURS.name === "string" ? OURS.name : "";

class ToolError extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
  }
}

function testMode() {
  return process.env.MSI_CHAT_TEST === "1";
}

// The path Windows would really open: resolved, trailing dots and spaces of each part dropped (Windows ignores
// them), and the deepest existing part run through realpath (long names for 8.3 ones, junctions and links followed).
function canonical(p) {
  const parts = path.win32.resolve(p).split("\\").map((part, i) => (i === 0 ? part : part.replace(/[. ]+$/, "")));
  let head = parts.join("\\");
  const tail = [];
  while (!fs.existsSync(head) && path.win32.dirname(head) !== head) {
    tail.unshift(path.win32.basename(head));
    head = path.win32.dirname(head);
  }
  let real = head;
  try {
    real = fs.realpathSync.native(head);
  } catch (err) {
    // keep the resolved form
  }
  return path.win32.join(real, ...tail).replace(/\\+$/, "").toLowerCase();
}

function isUnder(root, p) {
  return p === root || p.startsWith(root + "\\");
}

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)));
}

// The test roots of this process (MSI_CHAT_TEST_ROOT; same rules as src\settings.ts testRootProblem), canonical.
// Under MSI_CHAT_TEST a missing or unusable root refuses every guarded command.
function testRoots() {
  const value = process.env[TEST_ROOT_NAME];
  const roots = typeof value === "string" ? value.split(";").filter((part) => part !== "") : [];
  const refuse = (why) => new ToolError(EXIT.REFUSED, "refused under MSI_CHAT_TEST: " + TEST_ROOT_NAME + " " + why);
  if (roots.length === 0) throw refuse("is missing (set it to the test's sandbox folder)");
  for (const root of roots) {
    if (!isAbsWinPath(root)) throw refuse("holds a path that is not an absolute Windows path");
    if (root.replace(/[\\/]+$/, "").length <= 2) throw refuse("must name a folder, not a whole drive");
    if (/(^|[\\/])[^\\/]*~\d/.test(root)) throw refuse("holds an 8.3 short name");
  }
  return roots.map(canonical);
}

// Under MSI_CHAT_TEST: the path Windows would really open must lie under one of the test roots (an 8.3 part that
// does not exist cannot be resolved and is refused).
function guard(label, p) {
  if (!testMode()) return;
  const roots = testRoots();
  const n = canonical(p);
  if (/(^|\\)[^\\]*~\d/.test(n) || !roots.some((root) => isUnder(root, n))) {
    throw new ToolError(EXIT.REFUSED, "refused under MSI_CHAT_TEST: " + label + " is outside " + TEST_ROOT_NAME);
  }
}

function parseArgs(argv) {
  const opts = {};
  for (let i = 0; i < argv.length; i += 1) {
    const arg = argv[i];
    if (!arg.startsWith("--")) throw new ToolError(EXIT.USAGE, "unexpected argument " + JSON.stringify(arg));
    if (arg === "--") {                     // stage-first: the install args follow, as they are
      opts["--"] = argv.slice(i + 1);
      break;
    }
    const key = arg.slice(2);
    if (key === "yes-really" || key === "json") {
      opts[key] = true;
    } else {
      if (i + 1 >= argv.length) throw new ToolError(EXIT.USAGE, "missing value for " + arg);
      opts[key] = argv[i + 1];
      i += 1;
    }
  }
  return opts;
}

function absPath(opts, key) {
  const value = opts[key];
  if (typeof value !== "string" || !/^[A-Za-z]:[\\/]/.test(value) || /[\u0000-\u001f"<>|?*]/.test(value) ||
      value.indexOf(":", 2) !== -1) {
    throw new ToolError(EXIT.USAGE, "--" + key + " needs an absolute path");
  }
  return path.win32.resolve(value);
}

function needYes(opts) {
  if (opts["yes-really"] !== true) throw new ToolError(EXIT.USAGE, "this command needs --yes-really");
}

function readManifest(dir) {
  try {
    return JSON.parse(fs.readFileSync(path.join(dir, "manifest.json"), "utf8"));
  } catch (err) {
    return null;
  }
}

function isOurs(manifest, owner, name) {
  return manifest !== null && typeof manifest === "object" && manifest.owner === owner && manifest.name === name &&
    manifest.type === "plugin" && manifest.runner === "node";
}

const PLAIN_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i;

// A plugin folder of OUR owner, whatever its name (the Hub plugin is named by its own manifest, "locus"; the staged one
// "msi-chat"): <...>\<OWNER>\<name> whose manifest.json says type plugin, runner node, owner OWNER, name = the folder's name.
function isOurPluginDir(dir) {
  const name = path.win32.basename(dir);
  const owner = path.win32.basename(path.win32.dirname(dir));
  return owner === OWNER && PLAIN_NAME.test(name) && isOurs(readManifest(dir), OWNER, name);
}

// True when `inner` is `outer` or lies inside it.
function isInside(outer, inner) {
  const rel = path.win32.relative(outer, inner);
  return rel === "" || (!rel.startsWith("..") && !path.win32.isAbsolute(rel));
}

function refuseLink(dir) {
  if (fs.lstatSync(dir).isSymbolicLink()) throw new ToolError(EXIT.FAILED, "refusing a link or junction: " + dir);
}

// Never delete or replace the plugin's own source folder (it holds the same manifest).
function refuseSource(dir) {
  if (canonical(dir) === canonical(PLUGIN_ROOT)) throw new ToolError(EXIT.FAILED, "refusing the plugin's source folder: " + dir);
}

// The staged package files carry the runtime dependency only: LM Studio's own npm install then fetches the SDK
// tree and nothing that is only for development (typescript, @types/node).
function runtimePackage(pkg) {
  return { name: pkg.name, version: pkg.version, private: true, description: pkg.description, license: pkg.license,
    dependencies: pkg.dependencies };
}

function runtimeLock(lock, pkg) {
  const packages = {};
  for (const [key, entry] of Object.entries(lock.packages || {})) {
    if (key === "") {
      const root = Object.assign({}, entry, { name: pkg.name, version: pkg.version });
      delete root.devDependencies;
      packages[key] = root;
    } else if (entry.dev !== true) {
      if (entry.hasInstallScript) throw new ToolError(EXIT.FAILED, "the lock pins a package with an install script: " + key);
      packages[key] = entry;
    }
  }
  return Object.assign({}, lock, { name: pkg.name, version: pkg.version, packages });
}

function writeJson(file, value) {
  fs.writeFileSync(file, JSON.stringify(value, null, 2) + "\n", "utf8");
}

function copyTsTree(srcDir, outDir) {
  fs.mkdirSync(outDir, { recursive: true });
  const copied = [];
  for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
    const from = path.join(srcDir, entry.name);
    if (entry.isSymbolicLink()) continue;
    if (entry.isDirectory()) {
      copied.push(...copyTsTree(from, path.join(outDir, entry.name)).map((f) => entry.name + "/" + f));
    } else if (entry.isFile() && entry.name.endsWith(".ts")) {
      fs.copyFileSync(from, path.join(outDir, entry.name));
      copied.push(entry.name);
    }
  }
  return copied;
}

// The staged src\baked.ts: the settings path, for a plugin-first stage the plan (JSON text; "" = none), and for the
// Hub copy (publish-stage) the digests of the installer files (JSON text; "" = not a Hub copy).
function bakedSource(settingsPath, planText = "", hubText = "") {
  return "// Written by install\\plugin_tool.js " + (hubText ? "publish-stage" : "stage") + ": " +
    (hubText ? "no path of any PC, the Hub digests only." : "the absolute path of Locus's settings.json.") + "\n" +
    "export const SETTINGS_PATH: string = " + JSON.stringify(settingsPath) + ";\n" +
    "// The plugin-first plan (stage-first only; empty = main() only starts an installed Locus).\n" +
    "export const BOOTSTRAP_PLAN: string = " + JSON.stringify(planText) + ";\n" +
    "// The Hub copy's digests (publish-stage only; empty = not a Hub copy): main() derives the plan from its own folder.\n" +
    "export const HUB_FILES: string = " + JSON.stringify(hubText) + ";\n";
}

function bakedConst(stage, name) {
  try {
    const text = fs.readFileSync(path.join(stage, "src", "baked.ts"), "utf8");
    const m = text.match(new RegExp(name + ": string = (\"(?:[^\"\\\\]|\\\\.)*\");"));
    return m ? JSON.parse(m[1]) : "";
  } catch (err) {
    return "";
  }
}

function stagedSettingsPath(stage) {
  return bakedConst(stage, "SETTINGS_PATH");
}

function stagedPlan(stage) {
  return bakedConst(stage, "BOOTSTRAP_PLAN");
}

// A stage is only ever <something>\plugin-stage\msi-chat, made by this tool: our manifest, the marker file and a
// baked settings path. The plugin's source folder and LM Studio's installed copy never pass all three.
const STAGE_MARKER = ".msi-chat-stage";

function hasStageShape(dir) {
  return path.win32.basename(dir).toLowerCase() === NAME &&
    path.win32.basename(path.win32.dirname(dir)).toLowerCase() === "plugin-stage";
}

function isStage(dir) {
  return hasStageShape(dir) && isOurs(readManifest(dir), OWNER, NAME) && fs.existsSync(path.join(dir, STAGE_MARKER)) &&
    stagedSettingsPath(dir) !== "";
}

function writeStage(src, dir, settings, planText = "") {
  fs.mkdirSync(dir, { recursive: true });
  fs.copyFileSync(path.join(src, "manifest.json"), path.join(dir, "manifest.json"));
  fs.copyFileSync(path.join(src, "tsconfig.json"), path.join(dir, "tsconfig.json"));
  const pkg = JSON.parse(fs.readFileSync(path.join(src, "package.json"), "utf8"));
  const lock = JSON.parse(fs.readFileSync(path.join(src, "package-lock.json"), "utf8"));
  writeJson(path.join(dir, "package.json"), runtimePackage(pkg));
  writeJson(path.join(dir, "package-lock.json"), runtimeLock(lock, pkg));
  const copied = copyTsTree(path.join(src, "src"), path.join(dir, "src"));
  fs.writeFileSync(path.join(dir, "src", "baked.ts"), bakedSource(settings, planText), "utf8");
  writeJson(path.join(dir, STAGE_MARKER), { schema: 1, made_by: planText ? "plugin_tool.js stage-first" : "plugin_tool.js stage",
    settings, plugin_first: planText ? { stage_id: JSON.parse(planText).stage_id } : null });
  return copied;
}

// Removes a leftover <out>.new / <out>.old of an earlier interrupted stage, only when it is ours.
function clearLeftover(dir) {
  if (!fs.existsSync(dir)) return;
  refuseLink(dir);
  if (!isOurs(readManifest(dir), OWNER, NAME) && fs.readdirSync(dir).length > 0) {
    throw new ToolError(EXIT.FAILED, "refusing to clear " + dir + ": it is not a leftover stage");
  }
  fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 });
}

function renameRetry(from, to) {
  for (let i = 0; ; i += 1) {
    try {
      fs.renameSync(from, to);
      return;
    } catch (err) {
      if (i >= 5 || (err.code !== "EPERM" && err.code !== "EBUSY")) throw err;
      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
    }
  }
}

// Builds the new stage beside the old one and swaps it in, so a failure never leaves a broken stage.
function cmdStage(opts) {
  const src = absPath(opts, "src");
  const out = absPath(opts, "out");
  const settings = absPath(opts, "settings");
  guard("--out", out);
  guard("--settings", settings);
  if (!/\.json$/i.test(settings)) throw new ToolError(EXIT.USAGE, "--settings must name a .json file");
  if (!fs.existsSync(settings)) throw new ToolError(EXIT.FAILED, "the settings file does not exist: " + settings);
  const copied = stageInto(src, out, settings);
  process.stdout.write("staged " + out + " (" + copied.length + " source files, settings " + settings + ")\n");
  return EXIT.OK;
}

// The stage itself (stage, and stage-first with a plan): returns the copied source names.
function stageInto(src, out, settings, planText = "") {
  if (!hasStageShape(out)) throw new ToolError(EXIT.USAGE, "--out must be <run dir>\\plugin-stage\\msi-chat");
  if (!isOurs(readManifest(src), OWNER, NAME)) throw new ToolError(EXIT.FAILED, "--src is not the Locus plugin folder");
  if (isInside(src, out) || isInside(out, src)) throw new ToolError(EXIT.USAGE, "--out and --src must not hold each other");
  refuseSource(out);
  if (fs.existsSync(out)) {
    refuseLink(out);
    if (!isStage(out)) throw new ToolError(EXIT.FAILED, "--out exists and is not a stage made by this tool: " + out);
  }
  const fresh = out + ".new";
  const old = out + ".old";
  clearLeftover(fresh);
  clearLeftover(old);
  let copied;
  try {
    copied = writeStage(src, fresh, settings, planText);
  } catch (err) {
    fs.rmSync(fresh, { recursive: true, force: true, maxRetries: 3 });
    throw err;
  }
  if (fs.existsSync(out)) renameRetry(out, old);
  renameRetry(fresh, out);
  fs.rmSync(old, { recursive: true, force: true, maxRetries: 3 });
  return copied;
}

const LMS_TIMEOUT_MS = 600000;

function cmdInstall(opts) {
  needYes(opts);
  const stage = absPath(opts, "stage");
  const lms = absPath(opts, "lms");
  guard("--lms", lms);
  guard("--stage", stage);
  if (!isStage(stage)) throw new ToolError(EXIT.FAILED, "--stage is not a Locus stage made by this tool (run stage first)");
  if (!fs.existsSync(lms)) throw new ToolError(EXIT.FAILED, "lms not found: " + lms);
  process.stdout.write("running: \"" + lms + "\" dev -i -y   (in " + stage + ")\n");
  const res = childProcess.spawnSync(lms, ["dev", "-i", "-y"], {
    cwd: stage, stdio: "inherit", windowsHide: false, timeout: LMS_TIMEOUT_MS,
  });
  if (res.error) throw new ToolError(EXIT.FAILED, "could not run lms (or it took over 10 minutes): " + (res.error.code || res.error.name));
  return typeof res.status === "number" ? res.status : EXIT.FAILED;
}

// Deletes <dir> when it is not a link, lies (after realpath) inside <root>, is not the plugin's source and holds
// the owner/name manifest. Links and junctions inside it are removed as links, never followed (Node's rmSync).
function deleteOurFolder(root, dir, owner, name) {
  if (!fs.existsSync(dir)) return false;
  refuseLink(dir);
  refuseSource(dir);
  if (!isInside(canonical(root), canonical(dir))) throw new ToolError(EXIT.FAILED, "refusing: " + dir + " leads outside " + root);
  if (!isOurs(readManifest(dir), owner, name)) {
    throw new ToolError(EXIT.FAILED, "refusing: " + dir + " does not hold the " + owner + "/" + name + " manifest");
  }
  fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 });
  return true;
}

// remove --plugins-root <root> (--owner <owner> --name <name> | --dir <root>\<owner>\<name>): a plugin of OUR owner
// whose manifest names its folder; --dir is what uninstall.cmd passes (settings.plugin.installed_dir, through plugin-dir).
function cmdRemove(opts) {
  needYes(opts);
  const root = absPath(opts, "plugins-root");
  guard("--plugins-root", root);
  let owner = opts.owner;
  let name = opts.name;
  if (opts.dir !== undefined) {
    const dir = absPath(opts, "dir");
    owner = path.win32.basename(path.win32.dirname(dir));
    name = path.win32.basename(dir);
    if (canonical(path.win32.dirname(path.win32.dirname(dir))) !== canonical(root)) {
      throw new ToolError(EXIT.FAILED, "refusing: " + dir + " is not <plugins root>\\<owner>\\<name> under " + root);
    }
  }
  if (!PLAIN_NAME.test(owner || "") || !PLAIN_NAME.test(name || "")) throw new ToolError(EXIT.USAGE, "--owner and --name must be plain names");
  if (owner !== OWNER) {
    throw new ToolError(opts.dir !== undefined ? EXIT.FAILED : EXIT.USAGE, "refusing: only plugins of " + OWNER + " are removed by this tool");
  }
  const ownerDir = path.join(root, owner);
  const dir = path.join(ownerDir, name);
  if (fs.existsSync(ownerDir)) refuseLink(ownerDir);
  if (!deleteOurFolder(root, dir, owner, name)) {
    process.stdout.write("not installed: " + dir + "\n");
    return EXIT.NONE;
  }
  if (fs.existsSync(ownerDir) && fs.readdirSync(ownerDir).length === 0) fs.rmdirSync(ownerDir);
  process.stdout.write("removed " + dir + "\n");
  return EXIT.OK;
}

function cmdUnstage(opts) {
  needYes(opts);
  const out = absPath(opts, "out");
  guard("--out", out);
  if (!fs.existsSync(out)) {
    process.stdout.write("no stage: " + out + "\n");
    return EXIT.NONE;
  }
  refuseLink(out);
  refuseSource(out);
  if (!isStage(out)) throw new ToolError(EXIT.FAILED, "refusing: " + out + " is not a stage made by this tool");
  fs.rmSync(out, { recursive: true, force: true, maxRetries: 3 });
  process.stdout.write("removed the stage " + out + "\n");
  return EXIT.OK;
}

function sha256File(file) {
  const hash = crypto.createHash("sha256");
  const fd = fs.openSync(file, "r");
  try {
    const buf = Buffer.alloc(1 << 20);
    let n;
    while ((n = fs.readSync(fd, buf, 0, buf.length, null)) > 0) hash.update(buf.subarray(0, n));
  } finally {
    fs.closeSync(fd);
  }
  return hash.digest("hex");
}

function hexArg(opts, key) {
  const value = String(opts[key] || "").toLowerCase();
  if (!/^[0-9a-f]{64}$/.test(value)) throw new ToolError(EXIT.USAGE, "--" + key + " needs 64 hex characters");
  return value;
}

function cmdCheckSha256(opts) {
  const file = absPath(opts, "file");
  const want = hexArg(opts, "sha256");
  if (!fs.existsSync(file)) throw new ToolError(EXIT.FAILED, "file not found: " + file);
  const got = sha256File(file);
  if (got !== want) {
    process.stderr.write("SHA-256 mismatch: " + file + " is " + got + ", the pinned value is " + want + "\n");
    return EXIT.CHECK;
  }
  process.stdout.write("SHA-256 ok: " + file + "\n");
  return EXIT.OK;
}

async function pluginChecks(raw) {
  const settingsTs = await import(pathToFileURL(path.join(PLUGIN_ROOT, "src", "settings.ts")).href);
  const launcher = require(path.join(PLUGIN_ROOT, "launcher.js"));
  const exists = (p) => fs.existsSync(p);
  const plugin = settingsTs.checkSettingsObject(raw, { exists }, { testMode: testMode(), testRoot: process.env[TEST_ROOT_NAME] });
  if (!plugin.ok) return { code: plugin.refused ? EXIT.REFUSED : EXIT.CHECK, reason: "plugin: " + plugin.reason };
  const launch = launcher.checkSettings(raw, exists);
  if (!launch.ok) return { code: launch.code === launcher.EXIT.REFUSED ? EXIT.REFUSED : EXIT.CHECK, reason: "launcher: " + launch.reason };
  return null;
}

function newtProblem(raw, want) {
  const newt = raw && raw.newt;
  if (!newt || typeof newt.exe !== "string" || !/^[A-Za-z]:[\\/]/.test(newt.exe)) return "newt.exe: not an absolute path";
  if (String(newt.sha256 || "").toLowerCase() !== want) return "newt.sha256 in the settings is not the pinned value";
  if (!fs.existsSync(newt.exe)) return "newt.exe: file not found";
  if (sha256File(newt.exe) !== want) return "the release's newt.exe does not match the pinned SHA-256";
  return null;
}

async function cmdCheckSettings(opts) {
  const file = absPath(opts, "settings");
  guard("--settings", file);
  const want = opts["newt-sha256"] === undefined ? null : hexArg(opts, "newt-sha256");
  let raw;
  try {
    const text = fs.readFileSync(file, "utf8");
    raw = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
  } catch (err) {
    process.stderr.write("settings: missing, unreadable or not JSON: " + file + "\n");
    return EXIT.CHECK;
  }
  const problem = (await pluginChecks(raw)) || (want === null ? null : (() => {
    const reason = newtProblem(raw, want);
    return reason === null ? null : { code: EXIT.CHECK, reason };
  })());
  if (problem !== null) {
    process.stderr.write("settings check failed: " + problem.reason + "\n");
    return problem.code;
  }
  process.stdout.write("settings ok: " + file + "\n");
  return EXIT.OK;
}

function cmdCheckPaths(opts) {
  for (const key of ["run-dir", "plugins-root", "lms", "stage"]) {
    if (opts[key] !== undefined) guard("--" + key, absPath(opts, key));
  }
  return EXIT.OK;
}

// plugin-installed (--settings <path> | --dir <folder> | --plugins-root <root>): 0 when the folder (the settings'
// plugin.installed_dir, the given one, or <root>\<OWNER>\<NAME>) holds a plugin of ours whose manifest names it.
function cmdPluginInstalled(opts) {
  let dir;
  if (opts.settings !== undefined) {
    const raw = JSON.parse(fs.readFileSync(absPath(opts, "settings"), "utf8").replace(/^\uFEFF/, ""));
    const installed = raw && raw.plugin && raw.plugin.installed_dir;
    if (typeof installed !== "string") throw new ToolError(EXIT.CHECK, "settings: plugin.installed_dir is missing");
    dir = absPath({ dir: installed }, "dir");
  } else if (opts.dir !== undefined) {
    dir = absPath(opts, "dir");
  } else {
    dir = path.join(absPath(opts, "plugins-root"), OWNER, NAME);
  }
  const yes = isOurPluginDir(dir);
  process.stdout.write((yes ? "installed: " : "not installed: ") + dir + "\n");
  return yes ? EXIT.OK : EXIT.NONE;
}

// plugin-dir --settings <path> --plugins-root <root>: prints the plugin folder that installed Locus, for uninstall.cmd
// (which must know it BEFORE msi-chat uninstall --purge deletes the run folder): settings.plugin.installed_dir when the
// settings can be read and it is <root>\<OWNER>\<name>, else <root>\<OWNER>\<NAME>. Only the path is printed.
function cmdPluginDir(opts) {
  const root = absPath(opts, "plugins-root");
  const settings = absPath(opts, "settings");
  guard("--plugins-root", root);
  let dir = path.join(root, OWNER, NAME);
  try {
    const raw = JSON.parse(fs.readFileSync(settings, "utf8").replace(/^\uFEFF/, ""));
    const installed = raw && raw.plugin && raw.plugin.installed_dir;
    if (typeof installed === "string" && isAbsWinPath(installed)) {
      const candidate = path.win32.resolve(installed);
      const owner = path.win32.basename(path.win32.dirname(candidate));
      if (owner === OWNER && PLAIN_NAME.test(path.win32.basename(candidate)) &&
          canonical(path.win32.dirname(path.win32.dirname(candidate))) === canonical(root)) {
        dir = candidate;
      }
    }
  } catch (err) {
    // no settings, or unreadable: the default
  }
  process.stdout.write(dir + "\n");
  return EXIT.OK;
}

const COMMANDS = {
  stage: cmdStage,
  install: cmdInstall,
  remove: cmdRemove,
  unstage: cmdUnstage,
  "check-settings": cmdCheckSettings,
  "check-sha256": cmdCheckSha256,
  "check-paths": cmdCheckPaths,
  "plugin-installed": cmdPluginInstalled,
  "plugin-dir": cmdPluginDir,
  ...require("./plugin_first.js")({
    ToolError, EXIT, PLUGIN_ROOT, OWNER, NAME, absPath, guard, testMode, canonical, stageInto, stagedPlan, needYes, isOurPluginDir, writeJson,
  }),
  ...require("./plugin_publish.js")({
    ToolError, EXIT, PLUGIN_ROOT, OWNER, absPath, guard, canonical, readManifest, refuseLink, refuseSource, isInside, renameRetry,
    runtimePackage, runtimeLock, writeJson, sha256File, bakedSource,
  }),
};

async function main(argv) {
  const command = COMMANDS[argv[0]];
  if (!command) {
    process.stderr.write("usage: plugin_tool.js <" + Object.keys(COMMANDS).join("|") + "> [--options]\n");
    return EXIT.USAGE;
  }
  try {
    if (OWNER === "" || NAME === "") throw new ToolError(EXIT.FAILED, "the plugin's own manifest.json is missing or has no owner and name");
    return await command(parseArgs(argv.slice(1)));
  } catch (err) {
    process.stderr.write("plugin_tool " + argv[0] + ": " + (err && err.message ? err.message : String(err)) + "\n");
    return err instanceof ToolError ? err.code : EXIT.FAILED;
  }
}

module.exports = { main, runtimeLock, runtimePackage, bakedSource, EXIT, OWNER, NAME };

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