Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

7.2 KB
Raw Blame
// Settings → Reload from the desktop menu: config.json, edited by hand, read again into the running server. Nothing is
// written, a bad file leaves the running settings as they were, and no reply ever carries a value from the file.
import { isDeepStrictEqual } from "node:util";

import { parseStoredConfig, type AppConfig } from "./config.ts";
import { parseJson } from "./schema.ts";

export type ConfigReloadResult =
  | { ok: true; applied: string[]; restart: string[] }
  | { ok: false; code: "missing" | "unreadable" | "json" | "schema"; error: string };

/** Sections a save changes with more than the new value (closing browsers, ending sign-ins, restarting engines or
 * timers, server/routes/config.ts after the save and the onConfigSaved listeners) or that only starting reads. A
 * reload leaves them as they run now; quitting and reopening applies them. */
export const RESTART_SECTIONS: ReadonlySet<string> = new Set([
  "instances", "opencodeGo", // engines are started with them
  "browserEngine", "browserProfiles", // a running browser is closed or moved
  "localVm", "vpsIdle", "vps", "vpsServers", "box", // computers and their idle timers
  "signIn", // signed-in people are checked again
  "cacheKeepWarm", "threads", "postiz", // their own timers and queues
  "customDomain", "cliStartup", // read when the server starts
]);
/** features.* flags whose change closes something that is open (a viewer, a lent computer, a phone being watched). */
const RESTART_FEATURES = ["browser", "sharedComputers", "usbPhoneTakeover"] as const;

const NAME = "config.json";

/** The offset of the first character strict JSON rejects, or -1. Written out so the error never quotes the file: a
 * JSON.parse message can carry a piece of it, and config.json holds keys. */
export function jsonErrorOffset(text: string): number {
  let at = 0;
  const fail = (): never => { throw new JsonStop(at); };
  const space = () => { while (at < text.length && " \t\n\r".includes(text[at]!)) at++; };
  const expect = (char: string) => { if (text[at] !== char) fail(); at++; };
  const string = () => {
    expect('"');
    while (at < text.length) {
      const char = text[at]!;
      if (char === '"') { at++; return; }
      if (char < " ") fail();
      if (char === "\\") {
        const next = text[at + 1];
        if (next !== undefined && '"\\/bfnrt'.includes(next)) at += 2;
        else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(at + 2, at + 6))) at += 6;
        else { at++; fail(); }
        continue;
      }
      at++;
    }
    fail();
  };
  const value = (): void => {
    space();
    const char = text[at];
    if (char === "{" || char === "[") {
      const close = char === "{" ? "}" : "]";
      at++; space();
      if (text[at] === close) { at++; return; }
      for (;;) {
        if (close === "}") { space(); string(); space(); expect(":"); }
        value(); space();
        if (text[at] === ",") { at++; continue; }
        expect(close);
        return;
      }
    }
    if (char === '"') return string();
    const number = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
    number.lastIndex = at;
    const matched = number.exec(text)?.[0];
    if (matched) { at += matched.length; return; }
    for (const word of ["true", "false", "null"]) if (text.startsWith(word, at)) { at += word.length; return; }
    fail();
  };
  try {
    value(); space();
    if (at < text.length) fail();
    return -1;
  } catch (error) {
    if (error instanceof JsonStop) return error.at;
    throw error;
  }
}
class JsonStop { readonly at: number; constructor(at: number) { this.at = at; } }

/** "config.json line 12, column 5: …", from where the JSON breaks, in words that never quote it. */
export function jsonErrorMessage(text: string): string {
  const offset = Math.max(0, jsonErrorOffset(text));
  const before = text.slice(0, offset);
  const line = before.split("\n").length;
  const column = offset - (before.lastIndexOf("\n") + 1) + 1;
  const reason = offset >= text.length ? "the file ends before the settings do (a } or ] may be missing)"
    : text[offset] === "}" || text[offset] === "]" ? `unexpected ${text[offset]} (a comma before it may be extra)`
      : text[offset] === "," ? "unexpected comma"
        : text[offset] === '"' ? "unexpected quote (a comma before it may be missing)"
          : "this is not valid JSON here (check for a missing comma, quote or bracket)";
  return `${NAME} line ${line}, column ${column}: ${reason}`;
}

export interface ConfigReloadDeps {
  /** The live settings every request reads; changed in place. */
  cfg: AppConfig;
  /** config.json's text; throws ENOENT when there is none. */
  read(): string;
  /** The settings as the server builds them from the file and its environment (loadConfig). */
  load(): AppConfig;
  /** What the server would launch for each engine under these settings (engineLaunches). */
  engines(config: AppConfig): Record<string, unknown>;
}

export function reloadConfig({ cfg, read, load, engines }: ConfigReloadDeps): ConfigReloadResult {
  let text: string;
  try {
    text = read();
  } catch (error) {
    const missing = (error as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
    return missing
      ? { ok: false, code: "missing", error: `There is no ${NAME} on this computer yet.` }
      : { ok: false, code: "unreadable", error: `${NAME} could not be read (${(error as NodeJS.ErrnoException | undefined)?.code ?? "unknown error"}).` };
  }
  let parsed;
  try {
    parsed = parseJson(text);
  } catch {
    return { ok: false, code: "json", error: jsonErrorMessage(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) };
  }
  try {
    parseStoredConfig(parsed);
  } catch (error) {
    return { ok: false, code: "schema", error: `${NAME}: ${error instanceof Error ? error.message : "a setting is not valid"}` };
  }
  const next = load() as Record<string, unknown>;
  // load() reads the file again and falls back to defaults on a bad one: only the text checked above is applied.
  if (readAgain(read) !== text) return { ok: false, code: "unreadable", error: `${NAME} changed while it was being read. Try again.` };
  const live = cfg as Record<string, unknown>;
  const enginesBefore = engines(cfg);
  const applied: string[] = [];
  const restart: string[] = [];
  for (const key of [...new Set([...Object.keys(live), ...Object.keys(next)])].sort()) {
    if (isDeepStrictEqual(live[key], next[key])) continue;
    const trial = { ...live, [key]: next[key] } as AppConfig;
    if (RESTART_SECTIONS.has(key) || heldFeature(key, live[key], next[key]) || !isDeepStrictEqual(engines(trial), enginesBefore)) {
      restart.push(key);
      continue;
    }
    if (Object.hasOwn(next, key)) live[key] = next[key];
    else delete live[key];
    applied.push(key);
  }
  return { ok: true, applied, restart };
}

function readAgain(read: () => string): string | null {
  try { return read(); } catch { return null; }
}

function heldFeature(key: string, before: unknown, after: unknown): boolean {
  if (key !== "features") return false;
  const flag = (features: unknown, name: string) => (typeof features === "object" && features !== null ? (features as Record<string, unknown>)[name] : undefined);
  return RESTART_FEATURES.some((name) => !isDeepStrictEqual(flag(before, name), flag(after, name)));
}