repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

skills/super/brainstorming/scripts/start-server.mjs

Raw
File outline
#!/usr/bin/env node
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';

const scriptDir = path.dirname(fileURLToPath(import.meta.url));

const registryFile = path.join(os.homedir(), '.local', 'state', 'pi', 'brainstorm-companion', 'servers.jsonl');

function usage(error) {
  const message = error ? { error } : { usage: 'start-server.mjs [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--owner-pid <pid>] [--no-browser-timeout-ms <ms>]' };
  console.log(JSON.stringify(message));
  process.exit(error ? 1 : 0);
}

function parentPid(pid) {
  try {
    const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
    const afterName = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
    return Number(afterName[1]);
  } catch {
    return null;
  }
}

function defaultOwnerPid() {
  return parentPid(process.ppid) || process.ppid;
}

function parseArgs(argv) {
  const options = { projectDir: '', host: '127.0.0.1', urlHost: '', ownerPid: defaultOwnerPid(), noBrowserTimeoutMs: 60_000 };

  for (let i = 0; i < argv.length; i++) {
    const arg = argv[i];
    if (arg === '--project-dir') options.projectDir = argv[++i] ?? usage('Missing value for --project-dir');
    else if (arg === '--host') options.host = argv[++i] ?? usage('Missing value for --host');
    else if (arg === '--url-host') options.urlHost = argv[++i] ?? usage('Missing value for --url-host');
    else if (arg === '--owner-pid') options.ownerPid = Number(argv[++i] ?? usage('Missing value for --owner-pid'));
    else if (arg === '--no-browser-timeout-ms') options.noBrowserTimeoutMs = Number(argv[++i] ?? usage('Missing value for --no-browser-timeout-ms'));
    else if (arg === '--help' || arg === '-h') usage();
    else usage(`Unknown argument: ${arg}`);
  }

  if (!options.urlHost) {
    options.urlHost = options.host === '127.0.0.1' || options.host === 'localhost' ? 'localhost' : options.host;
  }

  return options;
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function appendRegistry(entry) {
  fs.mkdirSync(path.dirname(registryFile), { recursive: true });
  fs.appendFileSync(registryFile, `${JSON.stringify(entry)}\n`);
}

async function waitForStart(stateDir, child, logFile) {
  const infoFile = path.join(stateDir, 'server-info');

  for (let i = 0; i < 50; i++) {
    if (fs.existsSync(infoFile)) return fs.readFileSync(infoFile, 'utf8').trim();
    if (child.exitCode !== null) break;
    await sleep(100);
  }

  const log = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8').trim() : '';
  const suffix = log ? `: ${log}` : '';
  throw new Error(`Server failed to start within 5 seconds${suffix}`);
}

async function startServer(argv = process.argv.slice(2)) {
  const options = parseArgs(argv);
  const sessionId = `${process.pid}-${Math.floor(Date.now() / 1000)}`;
  const sessionDir = options.projectDir
    ? path.join(options.projectDir, '.superpowers', 'brainstorm', sessionId)
    : path.join(os.tmpdir(), `brainstorm-${sessionId}`);
  const contentDir = path.join(sessionDir, 'content');
  const stateDir = path.join(sessionDir, 'state');
  const pidFile = path.join(stateDir, 'server.pid');
  const logFile = path.join(stateDir, 'server.log');

  fs.mkdirSync(contentDir, { recursive: true });
  fs.mkdirSync(stateDir, { recursive: true });

  const log = fs.openSync(logFile, 'a');
  const child = spawn(process.execPath, [path.join(scriptDir, 'server.mjs')], {
    detached: true,
    stdio: ['ignore', log, log],
    env: {
      ...process.env,
      BRAINSTORM_DIR: sessionDir,
      BRAINSTORM_HOST: options.host,
      BRAINSTORM_URL_HOST: options.urlHost,
      BRAINSTORM_OWNER_PID: String(options.ownerPid),
      BRAINSTORM_NO_BROWSER_TIMEOUT_MS: String(options.noBrowserTimeoutMs),
    },
  });

  child.unref();
  fs.writeFileSync(pidFile, `${child.pid}\n`);

  try {
    const info = JSON.parse(await waitForStart(stateDir, child, logFile));
    fs.writeFileSync(path.join(stateDir, 'owner'), `${options.ownerPid}\n`);
    appendRegistry({ pid: child.pid, owner_pid: options.ownerPid, session_dir: sessionDir, url: info.url, started_at: Date.now() });
    return info;
  } finally {
    fs.closeSync(log);
  }
}

async function main() {
  console.log(JSON.stringify({ error: 'start-server.mjs is internal. Use companion.mjs start-choice or companion.mjs start-screen.' }));
  process.exit(1);
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  main().catch(error => {
    console.log(JSON.stringify({ error: error.message }));
    process.exit(1);
  });
}

export { defaultOwnerPid, main, parentPid, parseArgs, startServer };