src / mac.ts

// Locus for macOS, the plugin's pure rules (docs/build/MAC_REPORT.md), modeled on the Linux plugin's src/linux.ts (the
// HUB_FILES, install-args, plan, ticket, lock and decision rules are the same). The Hub copy has no path baked in, only
// HUB_FILES (the digests of the installer files, made at publish time). main() derives everything at run time:
// - its own folder, in one of LM Studio's two shapes (manifest.json beside the code, owner and name equal to the two
//   folder names), the LM Studio home lying under HOME (and not HOME itself):
//     classic   <LM Studio home>/extensions/plugins/<owner>/<name>
//     app       <LM Studio home>/apps/<app>/extensions/plugins/<owner>/<name>   (Bionic.app: apps/bionic)
// - from HOME only (no XDG on macOS): the base ~/Library/Application Support/Locus, its run folder run/ (settings,
//   state, logs), the installer source installer/, newt/newt; python is /usr/bin/python3 (Apple's Command Line Tools);
// - the bootstrap is the plugin's own bootstrap.js, checked against the digest baked beside the files.
// The paths hold a space ("Application Support"): they are only ever passed as argv, never into a shell line.
// No I/O here: the probes are injected (src/start.ts does the I/O). Erasable TypeScript only.
import { createHash } from "node:crypto";

export const PLUGIN_LOG = "locus-plugin.log";
export const UNINSTALLED_MARKER = "locus-uninstalled.json";
export const TICKET_FILE = "bootstrap.json";
export const LOCK_FILE = "bootstrap.lock";
export const PLAN_FILE = "bootstrap-plan.json";
export const SYSTEM_PYTHON = "/usr/bin/python3";
export const TEST_ROOT_NAME = "MSI_CHAT_TEST_ROOT";
export const TEST_HUB_ARGS_NAME = "MSI_CHAT_TEST_HUB_ARGS";
export const LOCK_MAX_AGE_MS = 45 * 60 * 1000;
export const LOCK_UNREADABLE_MS = 60 * 1000;
export const BASE_REL = "/Library/Application Support/Locus";
export const PLAN_PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
export const PLAN_LANG = "en_US.UTF-8";
const HUB_SCHEMA = 1;
const MAX_HUB_BYTES = 200_000;
const MAX_LEVELS_UP = 2;
const PLAIN_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
const HEX64 = /^[0-9a-f]{64}$/;
const STAGE = /^[0-9a-f]{32}$/;
const REL_PATH = /^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/;
const BARE_FLAGS: readonly string[] = ["--real", "--yes"];
const VALUE_FLAGS: readonly string[] = ["--newt", "--engine-port", "--admin-port", "--lmstudio-api", "--python"];
const ARG_VALUE = /^[A-Za-z0-9:/._-]{1,260}$/;
const TEST_ENV_NAME = /^MSI_CHAT_TEST(_[A-Z0-9_]+)?$/;

type Json = Record<string, unknown>;
type Env = Readonly<Record<string, string | undefined>>;

function isObject(value: unknown): value is Json {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

// An absolute POSIX path without dot segments or control characters.
export function isAbsPosix(p: unknown): p is string {
  if (typeof p !== "string" || !p.startsWith("/") || p.length > 4096 || /[\u0000-\u001f]/.test(p)) return false;
  return !p.split("/").some((part) => part === "." || part === "..");
}

export function normPosix(p: string): string {
  const n = p.replace(/\/+/g, "/");
  return n.length > 1 ? n.replace(/\/$/, "") : n;
}

export function isUnder(p: string, root: string): boolean {
  const a = normPosix(p);
  const r = normPosix(root);
  return a === r || a.startsWith(r === "/" ? "/" : r + "/");
}

function parentOf(p: string): string | null {
  const n = normPosix(p);
  const i = n.lastIndexOf("/");
  return i <= 0 ? null : n.slice(0, i);
}

function baseOf(p: string): string {
  const n = normPosix(p);
  return n.slice(n.lastIndexOf("/") + 1);
}

function lookup(env: Env, name: string): string | undefined {
  const value = env[name];
  return typeof value === "string" && value !== "" ? value : undefined;
}

export interface PluginFolder {
  readonly dir: string;
  readonly manifest: Json;
}

export function findPluginFolder(candidates: readonly string[], readManifest: (dir: string) => unknown): PluginFolder | null {
  for (const candidate of candidates) {
    if (!isAbsPosix(candidate)) continue;
    let dir: string | null = normPosix(candidate);
    for (let level = 0; level <= MAX_LEVELS_UP && dir !== null; level += 1) {
      const manifest = readManifest(dir);
      if (isObject(manifest) && manifest.type === "plugin" && manifest.runner === "node") return { dir, manifest };
      dir = parentOf(dir);
    }
  }
  return null;
}

export interface PluginPlace {
  readonly pluginDir: string;
  readonly owner: string;
  readonly name: string;
  readonly lmHome: string;
  readonly app: string | null;
}

// <lmhome>/extensions/plugins/<owner>/<name> (classic) or <lmhome>/apps/<app>/extensions/plugins/<owner>/<name> (the app
// shape: the folder above extensions/ is a plain name in a folder named "apps"), the manifest's owner and name being the
// folder names, lmhome under HOME and not HOME itself.
export function hubShape(folder: PluginFolder | null, home: unknown): PluginPlace | null {
  if (folder === null || !isAbsPosix(home)) return null;
  const { dir, manifest } = folder;
  const owner = manifest.owner;
  const name = manifest.name;
  if (typeof owner !== "string" || typeof name !== "string" || !PLAIN_NAME.test(owner) || !PLAIN_NAME.test(name)) return null;
  const ownerDir = parentOf(dir);
  const pluginsDir = ownerDir === null ? null : parentOf(ownerDir);
  const extensionsDir = pluginsDir === null ? null : parentOf(pluginsDir);
  const above = extensionsDir === null ? null : parentOf(extensionsDir);
  if (ownerDir === null || pluginsDir === null || extensionsDir === null || above === null) return null;
  if (baseOf(dir) !== name || baseOf(ownerDir) !== owner) return null;
  if (baseOf(pluginsDir) !== "plugins" || baseOf(extensionsDir) !== "extensions") return null;
  const usable = (p: string | null): p is string => p !== null && isUnder(p, home) && normPosix(p) !== normPosix(home);
  const appsDir = parentOf(above);
  const appHome = appsDir !== null && baseOf(appsDir) === "apps" ? parentOf(appsDir) : null;
  // the app shape when its LM Studio home is usable; else (HOME itself or outside it: ~/apps/<x>) a classic home
  if (appHome !== null && usable(appHome)) {
    const app = baseOf(above);
    return PLAIN_NAME.test(app) ? { pluginDir: dir, owner, name, lmHome: appHome, app } : null;
  }
  return usable(above) ? { pluginDir: dir, owner, name, lmHome: above, app: null } : null;
}

// The folders main() looks at for its own place: the module's folder, the folder of argv[1] (LM Studio runs
// ./.lmstudio/production.js in the plugin's folder), and cwd.
export function pluginFolderCandidates(moduleUrl: string | undefined, argv1: string | undefined, cwd: string): string[] {
  const out: string[] = [];
  const add = (p: string | null): void => {
    if (p !== null && isAbsPosix(p) && !out.includes(normPosix(p))) out.push(normPosix(p));
  };
  if (typeof moduleUrl === "string" && moduleUrl.startsWith("file:///")) {
    try {
      add(parentOf(decodeURIComponent(moduleUrl.slice("file://".length))));
    } catch {
      // not a usable URL
    }
  }
  if (typeof argv1 === "string" && /\.(js|mjs|cjs|ts)$/i.test(argv1)) {
    const script = argv1.startsWith("/") ? argv1 : normPosix(cwd) + "/" + argv1.replace(/^(\.\/)+/, "");
    add(parentOf(script));
  }
  add(isAbsPosix(cwd) ? cwd : null);
  return out;
}

export interface MacPaths extends PluginPlace {
  readonly home: string;
  readonly dataRoot: string;
  readonly runDir: string;
  readonly settings: string;
  readonly stateDir: string;
  readonly logsDir: string;
  readonly installer: string;
  readonly newt: string;
  readonly python: string;
  readonly lms: string;
  readonly node: string;
  readonly bootstrap: string;
}

// Every place of the install from the plugin's place, HOME and the node that runs main(). null when HOME is not
// usable or the plugin is not under it (nothing is ever put outside HOME). XDG names are not read on macOS.
export function macPaths(place: PluginPlace, env: Env, nodePath: string): MacPaths | null {
  const home = lookup(env, "HOME");
  if (!isAbsPosix(home) || normPosix(home) === "/" || !isUnder(place.pluginDir, home)) return null;
  const dataRoot = normPosix(home) + BASE_REL;
  const runDir = dataRoot + "/run";
  return Object.freeze({
    ...place, home: normPosix(home), dataRoot, runDir, settings: runDir + "/settings.json", stateDir: runDir + "/state",
    logsDir: runDir + "/logs", installer: dataRoot + "/installer", newt: dataRoot + "/newt/newt", python: SYSTEM_PYTHON,
    lms: place.lmHome + "/bin/lms", node: nodePath, bootstrap: place.pluginDir + "/bootstrap.js",
  });
}

export function installerMissing(paths: MacPaths, exists: (p: string) => boolean): string | null {
  const gone = (what: string, p: string): string => "Locus: " + what + " is missing (expected " + p + "): nothing done";
  if (!exists(paths.installer + "/main/install.sh") || !exists(paths.installer + "/main/msi_linux.py")) {
    return "Locus: the installer is not on this machine (expected " + paths.installer + "): nothing done";
  }
  if (!exists(paths.lms)) return gone("lms", paths.lms);
  if (!exists(paths.python)) return gone("python3", paths.python);
  if (!exists(paths.bootstrap)) return gone("the plugin's bootstrap.js", paths.bootstrap);
  return null;
}

// --- HUB_FILES --------------------------------------------------------------------------------------------------------

export interface HubFiles {
  readonly revision: number;
  readonly bootstrapSha256: string;
  readonly files: Readonly<Record<string, string>>;
  readonly installArgs: readonly string[];
  readonly maxPerDay: number;
  readonly stageId: string;
}

export function hubStageId(text: string): string {
  return createHash("sha256").update(text, "utf8").digest("hex").slice(0, 32);
}

export function installArgsProblem(args: unknown, real: boolean): string | null {
  if (!Array.isArray(args) || args.length > 40) return "install_args: not a list";
  let sawReal = false;
  for (let i = 0; i < args.length; i += 1) {
    const arg: unknown = args[i];
    if (typeof arg === "string" && BARE_FLAGS.includes(arg)) {
      sawReal = sawReal || arg === "--real";
      continue;
    }
    if (typeof arg === "string" && VALUE_FLAGS.includes(arg)) {
      const value: unknown = args[i + 1];
      if (typeof value !== "string" || !ARG_VALUE.test(value) || value.startsWith("-") || value.includes("..")) {
        return "install_args: " + arg + " needs a plain value";
      }
      i += 1;
      continue;
    }
    return "install_args: " + JSON.stringify(arg) + " is not accepted";
  }
  if (sawReal !== real) return real ? "install_args: a real plan needs --real" : "install_args: --real in a test plan";
  return null;
}

export function parseHubFiles(text: string): { readonly ok: true; readonly hub: HubFiles } | { readonly ok: false; readonly reason: string } {
  const fail = (reason: string) => ({ ok: false as const, reason: "HUB_FILES: " + reason });
  if (text.length === 0 || text.length > MAX_HUB_BYTES) return fail("empty or too large");
  let raw: unknown;
  try {
    raw = JSON.parse(text);
  } catch {
    return fail("not valid JSON");
  }
  if (!isObject(raw)) return fail("not a JSON object");
  if (raw.schema !== HUB_SCHEMA) return fail("schema is not " + HUB_SCHEMA);
  if (typeof raw.revision !== "number" || !Number.isInteger(raw.revision) || raw.revision < 1) return fail("revision is not a whole number");
  if (typeof raw.bootstrap_sha256 !== "string" || !HEX64.test(raw.bootstrap_sha256)) return fail("bootstrap_sha256 is not 64 hex characters");
  const files = raw.files;
  if (!isObject(files) || Object.keys(files).length === 0 || Object.keys(files).length > 2000) return fail("files is not a list of digests");
  for (const [rel, digest] of Object.entries(files)) {
    if (!REL_PATH.test(rel) || rel.split("/").some((p) => p === "." || p === "..")) return fail("a bad path in files " + JSON.stringify(rel));
    if (typeof digest !== "string" || !HEX64.test(digest)) return fail("a bad digest for " + rel);
  }
  const argsProblem = installArgsProblem(raw.install_args, true);
  if (argsProblem !== null) return fail(argsProblem);
  const max = raw.max_per_day;
  if (typeof max !== "number" || !Number.isInteger(max) || max < 1 || max > 10) return fail("max_per_day is not 1-10");
  return { ok: true, hub: Object.freeze({ revision: raw.revision, bootstrapSha256: raw.bootstrap_sha256,
    files: Object.freeze({ ...(files as Record<string, string>) }), installArgs: Object.freeze([...(raw.install_args as string[])]),
    maxPerDay: max, stageId: hubStageId(text) }) };
}

export function parseTestHubArgs(value: unknown): { readonly ok: true; readonly args: readonly string[] } | { readonly ok: false; readonly reason: string } {
  if (value === undefined || value === "") return { ok: true, args: [] };
  let raw: unknown;
  try {
    raw = typeof value === "string" ? JSON.parse(value) : null;
  } catch {
    raw = null;
  }
  if (!Array.isArray(raw) || !raw.every((a) => typeof a === "string")) return { ok: false, reason: TEST_HUB_ARGS_NAME + ": not a JSON list of strings" };
  const problem = installArgsProblem([...raw, "--yes"], false);
  return problem === null ? { ok: true, args: raw as string[] } : { ok: false, reason: TEST_HUB_ARGS_NAME + ": " + problem };
}

// --- the plan ---------------------------------------------------------------------------------------------------------

export function testRootProblem(value: unknown): string | null {
  if (typeof value !== "string" || value === "") return TEST_ROOT_NAME + " is missing (set it to the test's sandbox folder)";
  if (!isAbsPosix(value)) return TEST_ROOT_NAME + " is not an absolute path";
  if (normPosix(value) === "/") return TEST_ROOT_NAME + " must name a folder, not /";
  return null;
}

// The install's environment: HOME, macOS's system PATH, LANG, the Locus names; under MSI_CHAT_TEST its switches. Never
// LMS_*, no XDG name.
export function planEnv(env: Env, paths: MacPaths, testMode: boolean): { readonly ok: true; readonly env: Readonly<Record<string, string>> } | { readonly ok: false; readonly reason: string } {
  const out: Record<string, string> = { HOME: paths.home, PATH: PLAN_PATH, LANG: PLAN_LANG,
    PYTHONDONTWRITEBYTECODE: "1", MSI_CHAT_PLUGIN_DIR: paths.pluginDir, MSI_CHAT_PYTHON: paths.python };
  if (testMode) {
    for (const [name, value] of Object.entries(env)) {
      if (TEST_ENV_NAME.test(name) && typeof value === "string" && value !== "") out[name] = value;
    }
    if (out.MSI_CHAT_TEST !== "1" || testRootProblem(out[TEST_ROOT_NAME]) !== null) {
      return { ok: false, reason: "MSI_CHAT_TEST without " + TEST_ROOT_NAME };
    }
  }
  return { ok: true, env: Object.freeze(out) };
}

export function buildPlan(hub: HubFiles, paths: MacPaths, env: Readonly<Record<string, string>>, testMode: boolean,
  testArgs: readonly string[], made: string): { readonly ok: true; readonly text: string } | { readonly ok: false; readonly reason: string } {
  const base = testMode ? hub.installArgs.filter((a) => a !== "--real") : [...hub.installArgs];
  const args = [...base, ...testArgs];
  if (!args.includes("--yes")) args.push("--yes");
  const problem = installArgsProblem(args, !testMode);
  if (problem !== null) return { ok: false, reason: "the Hub plan: " + problem };
  const plan = { schema: 1, stage_id: hub.stageId, made, installer: paths.installer, run_dir: paths.runDir, home: paths.home,
    python: paths.python, node: paths.node, settings: paths.settings, bootstrap: { path: paths.bootstrap, sha256: hub.bootstrapSha256 },
    files: hub.files, install_args: args, real: !testMode, env, max_per_day: hub.maxPerDay,
    hub: { owner: paths.owner, name: paths.name, revision: hub.revision } };
  return { ok: true, text: JSON.stringify(plan) };
}

export function ticketText(hub: HubFiles, paths: MacPaths, made: string): string {
  return JSON.stringify({ schema: 1, stage_id: hub.stageId, made, state: "pending", attempts: [], done: null,
    max_per_day: hub.maxPerDay, hub: { owner: paths.owner, name: paths.name, revision: hub.revision } }, null, 1) + "\n";
}

// --- the ticket, the lock, the decision ---------------------------------------------------------------------------------

export interface Attempt {
  readonly t: string;
  readonly ppid: number | null;
}

export interface Ticket {
  readonly stageId: string;
  readonly state: string;
  readonly attempts: readonly Attempt[];
}

export function parseTicket(text: string | null, stageId: string): Ticket | null {
  if (text === null) return null;
  let raw: unknown;
  try {
    raw = JSON.parse(text);
  } catch {
    return null;
  }
  if (!isObject(raw) || raw.stage_id !== stageId || !STAGE.test(stageId) || typeof raw.state !== "string") return null;
  const attempts = Array.isArray(raw.attempts) ? raw.attempts.filter(isObject).map((a) => ({
    t: typeof a.t === "string" ? a.t : "", ppid: typeof a.ppid === "number" ? a.ppid : null })) : [];
  return { stageId, state: raw.state, attempts };
}

export function attemptsToday(ticket: Ticket, now: Date): number {
  const day = now.toISOString().slice(0, 10);
  return ticket.attempts.filter((a) => a.t.slice(0, 10) === day).length;
}

export type LockState = "none" | "fresh" | "stale";

// The bootstrap's lock {pid, started, stage_id, ppid}: stale when its pid is gone, it is older than 45 min, its start
// lies in the future, or it has been unreadable for over 60 s. bootstrap.js holds the same table.
export function lockState(text: string | null, mtimeMs: number | null, nowMs: number, alive: (pid: number) => boolean): LockState {
  if (text === null) return "none";
  let raw: unknown;
  try {
    raw = JSON.parse(text);
  } catch {
    raw = null;
  }
  if (!isObject(raw) || typeof raw.pid !== "number" || typeof raw.started !== "string" || Number.isNaN(Date.parse(raw.started))) {
    return mtimeMs !== null && nowMs - mtimeMs <= LOCK_UNREADABLE_MS ? "fresh" : "stale";
  }
  const started = Date.parse(raw.started);
  if (started - nowMs > 60_000 || nowMs - started > LOCK_MAX_AGE_MS) return "stale";
  return alive(raw.pid) ? "fresh" : "stale";
}

export type Decision = { readonly action: "start" } | { readonly action: "install"; readonly attempt: number }
  | { readonly action: "wait"; readonly result: "install-running" | "install-waiting"; readonly reason: string };

export function decide(input: { readonly installed: boolean; readonly ticket: Ticket | null; readonly lock: LockState;
  readonly ppid: number; readonly now: Date; readonly maxPerDay: number }): Decision {
  const { installed, ticket, lock, ppid, now, maxPerDay } = input;
  if (installed) return { action: "start" };
  if (lock === "fresh") return { action: "wait", result: "install-running", reason: "a bootstrap is installing Locus right now" };
  if (ticket === null) return { action: "install", attempt: 1 };
  if (ticket.state === "done") return { action: "start" };
  if (ticket.state === "pending" && ticket.attempts.length === 0) return { action: "install", attempt: 1 };
  if (ticket.attempts.some((a) => a.ppid === ppid)) {
    return { action: "wait", result: "install-waiting", reason: "this LM Studio session already tried: the next start of LM Studio tries again" };
  }
  if (attemptsToday(ticket, now) >= maxPerDay) {
    return { action: "wait", result: "install-waiting", reason: maxPerDay + " attempts today: tomorrow, or run the installer by hand" };
  }
  return { action: "install", attempt: ticket.attempts.length + 1 };
}