src / start.ts

// Locus for macOS, the plugin's work at every main() (docs/build/MAC_REPORT.md), the Linux plugin's src/start.ts with
// the Mac places: LM Studio (on the owner's Mac: Bionic.app) runs main() when it starts (and at the plugin's install).
// main() finds its own folder, derives the places (src/mac.ts), then:
// - Locus installed (it answers /health, or its settings say start with LM Studio and install.json is there): start it
//   unless it runs, the owner stopped it (stopped.flag) or turned autostart off. It starts the verifier -> keepalive
//   through `/bin/sh -c '... &'`, so the keepalive is re-parented away from LM Studio's process tree at once;
// - not installed, the installer on this machine: the ticket (one per Hub revision), the lock and the retry rules, then
//   bootstrap.js detached (verify every installer file against HUB_FILES, install.sh --from-plugin, the release check,
//   start);
// - not installed, no installer: one marker line, nothing else.
// Every run appends a marker line {t, event, mode, result, pid, ppid} to <plugin folder>/locus-plugin.log (names only),
// and, when the run folder is known, one line to <run>/logs/plugin.jsonl. Never throws.
import { spawn as nodeSpawn } from "node:child_process";
import type { SpawnOptions } from "node:child_process";
import { createHash } from "node:crypto";
import * as nodeFs from "node:fs";
import * as nodeHttp from "node:http";
import * as nodeOs from "node:os";
import { HUB_FILES } from "./baked.ts";
import {
  LOCK_FILE, PLAN_FILE, PLUGIN_LOG, TEST_HUB_ARGS_NAME, TEST_ROOT_NAME, TICKET_FILE, UNINSTALLED_MARKER, buildPlan, decide,
  findPluginFolder, hubShape, installerMissing, isAbsPosix, isUnder, lockState, macPaths, parseHubFiles, parseTestHubArgs,
  parseTicket, planEnv, pluginFolderCandidates, testRootProblem, ticketText,
} from "./mac.ts";
import type { MacPaths, PluginPlace } from "./mac.ts";

export type Result = "inert" | "no-installer" | "installing" | "install-running" | "install-waiting" | "already-running"
  | "started" | "disabled" | "stopped" | "not-installed" | "error";

export const WAIT_MS = 10_000;
const HEALTH_TIMEOUT_MS = 1_500;

export interface Fs {
  readFileSync(path: string, encoding: "utf8"): string;
  readFileSync(path: string): Buffer;
  existsSync(path: string): boolean;
  appendFileSync(path: string, data: string): void;
  writeFileSync(path: string, data: string): void;
  mkdirSync(path: string, options: { recursive: true }): unknown;
  statSync(path: string): { mtimeMs: number };
}

export interface ChildLike {
  readonly pid?: number | undefined;
  once(event: "exit", listener: (code: number | null) => void): unknown;
  once(event: "error", listener: (err: Error) => void): unknown;
  unref(): void;
  kill?(): boolean;
}

export type SpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildLike;
export type HealthGet = (port: number, timeoutMs: number) => Promise<string | null>;

export interface Deps {
  readonly env?: Readonly<Record<string, string | undefined>>;
  readonly fs?: Fs;
  readonly spawn?: SpawnFn;
  readonly healthGet?: HealthGet;
  readonly now?: () => Date;
  readonly pid?: number;
  readonly ppid?: number;
  readonly nodePath?: string;
  readonly hubFilesText?: string;
  readonly candidates?: readonly string[];
  readonly alive?: (pid: number) => boolean;
  readonly waitMs?: number;
}

type Note = Record<string, unknown>;

interface Outcome {
  readonly result: Result;
  readonly note: Note;
}

// GET /health on 127.0.0.1:<port>: the body of a 200 answer, else null. Never throws.
export function httpHealthGet(port: number, timeoutMs: number): Promise<string | null> {
  return new Promise((resolve) => {
    let done = false;
    const finish = (value: string | null): void => {
      if (!done) {
        done = true;
        resolve(value);
      }
    };
    const req = nodeHttp.get({ host: "127.0.0.1", port, path: "/health", agent: false, timeout: timeoutMs }, (res) => {
      let body = "";
      res.setEncoding("utf8");
      res.on("data", (chunk: string) => {
        body += chunk;
        if (body.length > 65_536) req.destroy();
      });
      res.on("end", () => finish(res.statusCode === 200 ? body : null));
      res.on("error", () => finish(null));
    });
    const timer = setTimeout(() => {
      req.destroy();
      finish(null);
    }, timeoutMs);
    req.on("timeout", () => req.destroy());
    req.on("error", () => finish(null));
    req.on("close", () => clearTimeout(timer));
  });
}

function isLocus(body: string | null): boolean {
  if (body === null) return false;
  try {
    const parsed: unknown = JSON.parse(body);
    return typeof parsed === "object" && parsed !== null && (parsed as { app?: unknown }).app === "msi-chat";
  } catch {
    return false;
  }
}

interface Installed {
  readonly runDir: string;
  readonly stateDir: string;
  readonly logsDir: string;
  readonly secretsDir: string;
  readonly python: string;
  readonly keepalive: string;
  readonly launchEnv: Readonly<Record<string, string>>;
  readonly adminPort: number;
  readonly startWithLmstudio: boolean;
}

// The few fields of settings.json main() uses, checked: the run folder is the derived one, everything under HOME, the
// keepalive is the verifier in the secrets folder, python is a python3, launch_env is text without LMS_*.
export function readSettings(text: string | null, paths: MacPaths): Installed | null {
  if (text === null) return null;
  let raw: unknown;
  try {
    raw = JSON.parse(text);
  } catch {
    return null;
  }
  if (typeof raw !== "object" || raw === null) return null;
  const s = raw as Record<string, unknown>;
  const admin = s.admin as Record<string, unknown> | undefined;
  const env = s.launch_env as Record<string, unknown> | undefined;
  const secrets = s.secrets_dir;
  if (s.run_dir !== paths.runDir || s.state_dir !== paths.stateDir || s.logs_dir !== paths.logsDir) return null;
  if (!isAbsPosix(secrets) || !isUnder(secrets, paths.home) || s.keepalive !== secrets + "/msi_verify.py") return null;
  if (!isAbsPosix(s.python) || !/\/python3(\.[0-9]{1,2})?$/.test(s.python)) return null;
  if (typeof admin !== "object" || admin === null || admin.host !== "127.0.0.1" || typeof admin.port !== "number") return null;
  if (typeof env !== "object" || env === null || !Object.entries(env).every(([k, v]) => typeof v === "string" && !/^LMS_/i.test(k))) return null;
  if (typeof s.start_with_lmstudio !== "boolean") return null;
  return { runDir: paths.runDir, stateDir: paths.stateDir, logsDir: paths.logsDir, secretsDir: secrets, python: s.python,
    keepalive: s.keepalive as string, launchEnv: env as Record<string, string>, adminPort: admin.port, startWithLmstudio: s.start_with_lmstudio };
}

function readText(fs: Fs, p: string): string | null {
  try {
    return fs.existsSync(p) ? fs.readFileSync(p, "utf8") : null;
  } catch {
    return null;
  }
}

function mtime(fs: Fs, p: string): number | null {
  try {
    return fs.statSync(p).mtimeMs;
  } catch {
    return null;
  }
}

function errorName(err: unknown): string {
  return err instanceof Error ? String((err as NodeJS.ErrnoException).code ?? err.name) : "error";
}

function waitExit(child: ChildLike, waitMs: number): Promise<{ code?: number | null; error?: string; timedOut?: boolean }> {
  return new Promise((resolve) => {
    const timer = setTimeout(() => resolve({ timedOut: true }), waitMs);
    child.once("exit", (code) => {
      clearTimeout(timer);
      resolve({ code });
    });
    child.once("error", (err) => {
      clearTimeout(timer);
      resolve({ error: errorName(err) });
    });
  });
}

async function spawnAndWait(deps: Deps, command: string, args: readonly string[], options: SpawnOptions, what: string): Promise<string | null> {
  let child: ChildLike;
  try {
    child = (deps.spawn ?? (nodeSpawn as unknown as SpawnFn))(command, args, options);
  } catch (err) {
    return what + " could not be started " + errorName(err);
  }
  const outcome = await waitExit(child, deps.waitMs ?? WAIT_MS);
  if (outcome.timedOut) child.kill?.();
  child.unref();
  if (outcome.timedOut) return what + " did not return in time";
  if (outcome.error !== undefined) return what + " spawn error " + outcome.error;
  if (outcome.code !== 0) return what + " ended with exit " + String(outcome.code);
  return null;
}

// The keepalive through the verifier, re-parented at once: sh starts it in the background and exits.
async function startInstalled(s: Installed, paths: MacPaths, deps: Deps, fs: Fs): Promise<Outcome> {
  if (!s.startWithLmstudio) return { result: "disabled", note: {} };
  if (fs.existsSync(s.stateDir + "/stopped.flag")) return { result: "stopped", note: {} };
  try {
    fs.mkdirSync(s.logsDir, { recursive: true });
  } catch {
    // the keepalive makes it too
  }
  const script = "log=$1; shift; \"$@\" </dev/null >>\"$log\" 2>&1 &";
  const problem = await spawnAndWait(deps, "/bin/sh", ["-c", script, "locus-start", s.logsDir + "/keepalive_stdio.log", s.python, "-I",
    "-B", "-X", "utf8", s.keepalive, "--settings", paths.settings],
  { detached: true, stdio: "ignore", env: { ...s.launchEnv }, cwd: s.runDir }, "the keepalive's starter");
  if (problem !== null) return { result: "error", note: { reason: problem } };
  return { result: "started", note: { launchEnvNames: Object.keys(s.launchEnv).sort() } };
}

async function startBootstrap(planText: string, paths: MacPaths, deps: Deps, fs: Fs, ppid: number, env: Readonly<Record<string, string>>,
  expectedSha: string, attempt: number): Promise<Outcome> {
  let actual: string | null = null;
  try {
    actual = createHash("sha256").update(fs.readFileSync(paths.bootstrap)).digest("hex");
  } catch {
    actual = null;
  }
  if (actual !== expectedSha) {
    return { result: "error", note: { reason: "bootstrap.js differs from the digest baked into this plugin: install the plugin again" } };
  }
  const planFile = paths.stateDir + "/" + PLAN_FILE;
  try {
    fs.mkdirSync(paths.stateDir, { recursive: true });
    fs.mkdirSync(paths.logsDir, { recursive: true });
    fs.writeFileSync(planFile, planText);
  } catch (err) {
    return { result: "error", note: { reason: "the plan could not be written " + errorName(err) } };
  }
  const sha = createHash("sha256").update(planText, "utf8").digest("hex");
  const problem = await spawnAndWait(deps, deps.nodePath ?? process.execPath, [paths.bootstrap, "detach", "--plan", planFile, "--plan-sha256", sha,
    "--ppid", String(ppid)], { detached: true, stdio: "ignore", env: { ...env }, cwd: paths.home }, "the bootstrap's detacher");
  if (problem !== null) return { result: "error", note: { reason: problem } };
  return { result: "installing", note: { attempt, bootstrapEnvNames: Object.keys(env).sort() } };
}

async function decideHub(hubText: string, place: PluginPlace, deps: Deps, fs: Fs, env: Readonly<Record<string, string | undefined>>,
  testMode: boolean): Promise<Outcome & { readonly paths: MacPaths | null }> {
  const fail = (reason: string, paths: MacPaths | null = null) => ({ result: "error" as Result, note: { reason }, paths });
  const paths = macPaths(place, env, deps.nodePath ?? process.execPath);
  if (paths === null) return fail("HOME is not a usable folder (or the plugin does not lie under it)");
  if (testMode && !isUnder(paths.home, env[TEST_ROOT_NAME] as string)) return fail("refused under MSI_CHAT_TEST: HOME is outside " + TEST_ROOT_NAME);
  const parsed = parseHubFiles(hubText);
  if (!parsed.ok) return fail(parsed.reason, paths);
  const hub = parsed.hub;
  const settings = readSettings(readText(fs, paths.settings), paths);
  const running = settings !== null && isLocus(await (deps.healthGet ?? httpHealthGet)(settings.adminPort, HEALTH_TIMEOUT_MS));
  const installed = running || (settings !== null && settings.startWithLmstudio && fs.existsSync(settings.secretsDir + "/install.json"));
  const startPath = async (): Promise<Outcome & { readonly paths: MacPaths }> => {
    if (running) return { result: "already-running", note: {}, paths };
    if (settings === null) return { result: "not-installed", note: { reason: "no usable settings.json at " + paths.settings }, paths };
    return { ...(await startInstalled(settings, paths, deps, fs)), paths };
  };
  if (fs.existsSync(place.pluginDir + "/" + UNINSTALLED_MARKER)) {
    const out = await startPath();
    return { ...out, note: { ...out.note, uninstalled: true } };
  }
  const now = (deps.now ?? (() => new Date()))();
  const ppid = deps.ppid ?? process.ppid;
  const ticketPath = paths.stateDir + "/" + TICKET_FILE;
  const lockPath = paths.stateDir + "/" + LOCK_FILE;
  const ticket = parseTicket(readText(fs, ticketPath), hub.stageId);
  const alive = deps.alive ?? ((pid: number) => {
    try {
      process.kill(pid, 0);
      return true;
    } catch (err) {
      return (err as NodeJS.ErrnoException).code === "EPERM";
    }
  });
  const lock = lockState(readText(fs, lockPath), mtime(fs, lockPath), now.getTime(), alive);
  const d = decide({ installed, ticket, lock, ppid, now, maxPerDay: hub.maxPerDay });
  const pf: Note = { stage: hub.stageId.slice(0, 8), ticket: ticket === null ? "none" : ticket.state, installed };
  if (d.action === "start") {
    const out = await startPath();
    return { ...out, note: { ...out.note, pluginFirst: pf } };
  }
  if (d.action === "wait") return { result: d.result, note: { reason: d.reason, pluginFirst: pf }, paths };
  const missing = installerMissing(paths, (p) => fs.existsSync(p));
  if (missing !== null) return { result: "no-installer", note: { note: missing }, paths: null };
  const penv = planEnv(env, paths, testMode);
  if (!penv.ok) return fail(penv.reason, paths);
  const testArgs = testMode ? parseTestHubArgs(env[TEST_HUB_ARGS_NAME]) : { ok: true as const, args: [] as readonly string[] };
  if (!testArgs.ok) return fail(testArgs.reason, paths);
  const made = now.toISOString();
  const built = buildPlan(hub, paths, penv.env, testMode, testArgs.args, made);
  if (!built.ok) return fail(built.reason, paths);
  if (ticket === null) {
    try {
      fs.mkdirSync(paths.stateDir, { recursive: true });
      fs.writeFileSync(ticketPath, ticketText(hub, paths, made));
    } catch (err) {
      return fail("the install ticket could not be written " + errorName(err), paths);
    }
  }
  const out = await startBootstrap(built.text, paths, deps, fs, ppid, penv.env, hub.bootstrapSha256, d.attempt);
  return { ...out, note: { ...out.note, pluginFirst: pf }, paths };
}

function readManifest(fs: Fs, dir: string): unknown {
  try {
    const file = dir + "/manifest.json";
    return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
  } catch {
    return null;
  }
}

function append(fs: Fs, file: string, line: Note): void {
  try {
    fs.appendFileSync(file, JSON.stringify(line) + "\n");
  } catch {
    // never makes main() fail
  }
}

// The plugin's whole job. Never throws.
export async function startLocusMac(deps: Deps = {}): Promise<Result> {
  const fs: Fs = deps.fs ?? (nodeFs as unknown as Fs);
  const given = deps.env ?? process.env;
  // a plugin process may get no HOME: then the user database's (os.homedir())
  const env: Readonly<Record<string, string | undefined>> = typeof given.HOME === "string" && given.HOME !== "" ? given
    : { ...given, HOME: nodeOs.homedir() };
  const now = (deps.now ?? (() => new Date()))().toISOString();
  const pid = deps.pid ?? process.pid;
  const ppid = deps.ppid ?? process.ppid;
  const hubText = deps.hubFilesText ?? HUB_FILES;
  const testMode = env.MSI_CHAT_TEST === "1" || process.env.MSI_CHAT_TEST === "1";
  const root = env.MSI_CHAT_TEST === "1" ? env[TEST_ROOT_NAME] : process.env[TEST_ROOT_NAME];
  if (testMode && testRootProblem(root) !== null) return "error";            // a refused test reads and writes nothing
  let place: PluginPlace | null = null;
  try {
    const all = deps.candidates ?? pluginFolderCandidates(import.meta.url, process.argv[1], process.cwd());
    const candidates = testMode ? all.filter((c) => isUnder(c, root as string)) : all;
    place = hubShape(findPluginFolder(candidates, (dir) => readManifest(fs, dir)), env.HOME);
  } catch {
    place = null;
  }
  let outcome: Outcome & { readonly paths: MacPaths | null };
  if (hubText === "" || place === null) {
    outcome = { result: "inert", note: { reason: place === null ? "not a Hub install folder ([apps/<app>/]extensions/plugins/<owner>/<name> under HOME)" : "nothing baked" }, paths: null };
  } else {
    try {
      outcome = await decideHub(hubText, place, deps, fs, env, testMode && env.MSI_CHAT_TEST === "1");
    } catch (err) {
      outcome = { result: "error", note: { reason: "unexpected " + errorName(err) }, paths: null };
    }
  }
  const line: Note = { t: now, event: "main", mode: place !== null && hubText !== "" ? "hub" : "inert", result: outcome.result, pid, ppid };
  for (const key of ["reason", "note", "uninstalled", "attempt"]) {
    if (outcome.note[key] !== undefined) line[key] = outcome.note[key];
  }
  if (place !== null) append(fs, place.pluginDir + "/" + PLUGIN_LOG, line);
  if (outcome.paths !== null && fs.existsSync(outcome.paths.runDir)) {
    try {
      fs.mkdirSync(outcome.paths.logsDir, { recursive: true });
      append(fs, outcome.paths.logsDir + "/plugin.jsonl", { ...line, ...outcome.note, envNames: Object.keys(env).sort() });
    } catch {
      // never makes main() fail
    }
  }
  return outcome.result;
}