main
Caleb 0.4.0: wiki page runs the live calculator (README.html loads the current source from the page repo), UI static mode, sh… fc3ee8f
#!/usr/bin/env node
/* hwcalc server — zero dependencies. Serves the UI, the calculator API, settings, and a live SSE channel.
 * Lifecycle per app-creator-server-lifecycle: registry entry, 24 h idle reaper, per-thread snapshot, --port auto. */
'use strict';
const http = require('http'), fs = require('fs'), path = require('path'), os = require('os'), { execFile } = require('child_process');
const H = require('./calcs.js'), S = require('./schematics.js');
const PKG = require('./package.json');

const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
const THREAD = arg('--ai-thread', process.env.ADOM_AI_THREAD || 'hwcalc');
const KEEP_ALIVE = process.argv.includes('--keep-alive');
const APP = 'hwcalc';
const HOME = path.join(os.homedir(), '.adom', 'instances', APP);
const slug = s => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'default';
fs.mkdirSync(path.join(HOME, 'snapshots'), { recursive: true });
const REG = path.join(HOME, slug(THREAD) + '.json'), SNAP = path.join(HOME, 'snapshots', slug(THREAD) + '.json'), SETF = path.join(HOME, 'settings.json');

// ---------------------------------------------------------------- settings (server-side, persisted)
const SETTINGS_SPEC = H.SETTINGS_SPEC;
let settings = Object.fromEntries(Object.entries(SETTINGS_SPEC).map(([k, s]) => [k, s.def]));
try { Object.assign(settings, JSON.parse(fs.readFileSync(SETF, 'utf8'))); } catch {}
const argTtl = arg('--ttl'); if (argTtl) settings.ttl_hours = Number(argTtl);
function validateSettings(patch) {
  const bad = [];
  for (const [k, v] of Object.entries(patch)) {
    const s = SETTINGS_SPEC[k]; if (!s) { bad.push(`unknown setting "${k}" (valid: ${Object.keys(SETTINGS_SPEC).join(', ')})`); continue; }
    if (s.type === 'enum' && !s.values.includes(v)) bad.push(`${k} must be one of ${s.values.join(', ')}`);
    if (s.type === 'number' && !(Number(v) >= s.min && Number(v) <= s.max)) bad.push(`${k} must be a number ${s.min}–${s.max}`);
    if (s.type === 'bool' && typeof v !== 'boolean') bad.push(`${k} must be true or false`);
  }
  return bad;
}

// ---------------------------------------------------------------- UI state + per-thread snapshot
let ui = { calc: 'divider', inputs: {} }; let openRev = 0, openBy = '';
try { const s = JSON.parse(fs.readFileSync(SNAP, 'utf8')); ui = { ...ui, ...s.ui }; console.log(`restored snapshot for thread "${THREAD}"`); } catch {}
let snapTimer = null;
const saveSnapshot = () => { try { fs.writeFileSync(SNAP, JSON.stringify({ thread: THREAD, savedAt: new Date().toISOString(), ui }, null, 1)); } catch (e) { log('snapshot write failed: ' + e.message); } };
const saveSoon = () => { clearTimeout(snapTimer); snapTimer = setTimeout(saveSnapshot, 1000); };

// ---------------------------------------------------------------- console ring buffer + SSE
const ring = []; const log = m => { const l = `${new Date().toISOString()} ${m}`; ring.push(l); if (ring.length > 300) ring.shift(); console.log(l); };
const clients = new Set();
const broadcast = msg => { const d = `data: ${JSON.stringify(msg)}\n\n`; for (const c of clients) c.write(d); };

// ---------------------------------------------------------------- lifecycle
let lastActivity = Date.now(), PORT = 0;
const writeReg = () => { try { fs.writeFileSync(REG, JSON.stringify({ pid: process.pid, port: PORT, thread: THREAD, task: 'hardware calculations', version: PKG.version,
  startedAt: START, lastActivity: new Date(lastActivity).toISOString(), dir: __dirname }, null, 1)); } catch {} };
const START = new Date().toISOString();
function reap(why) {
  log(`reaping (${why})`); saveSnapshot();
  try { fs.unlinkSync(REG); } catch {}
  execFile('adom-cli', ['hydrogen', 'workspace', 'remove-tab', '--name', 'Hardware Calculator'], () => process.exit(0));
  setTimeout(() => process.exit(0), 5000).unref();
}
if (!KEEP_ALIVE) setInterval(() => { if (Date.now() - lastActivity > settings.ttl_hours * 3600e3) reap(`idle ${settings.ttl_hours} h`); }, 60e3).unref();
setInterval(writeReg, 60e3).unref();
process.on('SIGTERM', () => reap('SIGTERM')); process.on('SIGINT', () => reap('SIGINT'));

// ---------------------------------------------------------------- http
const READ_ONLY = new Set(['/state', '/console', '/settings', '/events', '/version', '/api/catalog', '/api/calc', '/api/schematic']);
const UI_ONLY = new Set(['/ui/state']);          // posted by the page itself (the human), not by an AI
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png' };
const json = (res, code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(obj)); };
const body = req => new Promise(r => { let b = ''; req.on('data', c => b += c); req.on('end', () => { try { r(b ? JSON.parse(b) : {}); } catch { r({ __bad: true }); } }); });

const server = http.createServer(async (req, res) => {
  lastActivity = Date.now();
  const url = new URL(req.url, 'http://x'), p = url.pathname;
  try {
    if (req.method === 'GET') {
      if (p === '/' || p === '/index.html') return file(res, path.join(__dirname, 'public', 'index.html'));
      if (p === '/calcs.js') return file(res, path.join(__dirname, 'calcs.js'));
      if (p === '/schematics.js') return file(res, path.join(__dirname, 'schematics.js'));
      if (p === '/api/schematic') {                 // GET /api/schematic?calc=<id>&key=value… -> image/svg+xml
        const q = Object.fromEntries(url.searchParams), id = q.calc; delete q.calc;
        const svg = S.draw(id, q, settings); if (!svg) return json(res, 404, { ok: false, error: `No schematic for "${id}".`, known: S.ids });
        res.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-store' }); return res.end(svg);
      }
      if (p.startsWith('/static/')) return file(res, path.join(__dirname, 'public', path.normalize(p.slice(8)).replace(/^(\.\.[/\\])+/, '')));
      if (p === '/version') return json(res, 200, { app: APP, version: PKG.version });
      if (p === '/state') return json(res, 200, { ok: true, app: APP, version: PKG.version, thread: THREAD, port: PORT, ui, openRev, openBy, clients: clients.size, settings, result: H.run(ui.calc, ui.inputs, settings) });
      if (p === '/settings') return json(res, 200, { ok: true, settings, spec: SETTINGS_SPEC });
      if (p === '/console') return json(res, 200, { ok: true, lines: ring.slice(-100) });
      if (p === '/api/catalog') return json(res, 200, { ok: true, calcs: H.catalog() });
      if (p === '/events') {
        res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
        res.write(`data: ${JSON.stringify({ type: 'hello', ui, settings })}\n\n`); clients.add(res);
        const ka = setInterval(() => res.write(': ka\n\n'), 25e3); req.on('close', () => { clearInterval(ka); clients.delete(res); }); return;
      }
      return json(res, 404, { ok: false, error: 'not found' });
    }
    if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method not allowed' });
    const b = await body(req); if (b.__bad) return json(res, 400, { ok: false, error: 'body is not valid JSON' });

    if (!READ_ONLY.has(p) && !UI_ONLY.has(p) && !b.aiThread)
      return json(res, 400, { ok: false, errorCode: 'caller_identity_required', error: 'This app requires every AI caller to give its ai-thread name.',
        hint: 'Re-run with the global flag: hwcalc --ai-thread "<name>" <verb>, or add a top-level "aiThread" field if POSTing directly. Use a short human-recognizable name for THIS conversation and reuse it everywhere.' });

    if (p === '/api/calc') {                        // pure computation: open to everyone
      const r = H.run(b.calc, b.inputs || {}, settings); return json(res, r.ok || r.error ? 200 : 404, r);
    }
    if (p === '/api/open') {                        // drive the UI: select a calculator and fill inputs
      if (!H.CALCS.find(c => c.id === b.calc)) return json(res, 400, { ok: false, error: `Unknown calculator "${b.calc}".`, known: H.CALCS.map(c => c.id) });
      ui = { calc: b.calc, inputs: { ...(b.inputs || {}) } }; openRev++; openBy = b.aiThread; saveSoon();
      log(`thread "${b.aiThread}": open ${b.calc} ${JSON.stringify(b.inputs || {})}`);
      broadcast({ type: 'open', ui, by: b.aiThread, rev: openRev }); return json(res, 200, { ok: true, ui, result: H.run(ui.calc, ui.inputs, settings), clients: clients.size });
    }
    if (p === '/ui/state') { ui = { calc: b.calc, inputs: b.inputs || {} }; saveSoon(); return json(res, 200, { ok: true }); }
    if (p === '/settings') {
      const patch = { ...b }; delete patch.aiThread; delete patch.reason;
      const bad = validateSettings(patch); if (bad.length) return json(res, 400, { ok: false, errorCode: 'invalid_setting', error: bad.join('; '), spec: SETTINGS_SPEC });
      for (const [k, v] of Object.entries(patch)) settings[k] = SETTINGS_SPEC[k].type === 'number' ? Number(v) : v;
      fs.writeFileSync(SETF, JSON.stringify(settings, null, 1)); log(`settings ${JSON.stringify(patch)} by ${b.aiThread || 'ui'}`);
      broadcast({ type: 'settings', settings }); return json(res, 200, { ok: true, settings });
    }
    if (p === '/shutdown') {
      if (!b.reason) return json(res, 400, { ok: false, errorCode: 'reason_required', error: 'Shutting down closes the user\'s calculator tab.',
        hint: 'Re-run with --reason "<why>" (for example "user asked to close it"). The server also shuts itself down after the idle TTL.' });
      json(res, 200, { ok: true, bye: true }); log(`shutdown by "${b.aiThread}": ${b.reason}`); return setTimeout(() => reap('shutdown'), 200);
    }
    return json(res, 404, { ok: false, error: 'not found' });
  } catch (e) { log('error ' + e.stack); json(res, 500, { ok: false, error: String(e.message) }); }
});
function file(res, f) {
  fs.readFile(f, (err, d) => { if (err) return json(res, 404, { ok: false, error: 'not found' });
    res.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream', 'Cache-Control': 'no-store' }); res.end(d); });
}

const want = arg('--port', 'auto');
server.listen(want === 'auto' ? 0 : Number(want), '0.0.0.0', () => {
  PORT = server.address().port; writeReg();
  log(`hwcalc ${PKG.version} listening on ${PORT} (thread "${THREAD}", ttl ${KEEP_ALIVE ? 'off' : settings.ttl_hours + ' h'})`);
  console.log(JSON.stringify({ ok: true, port: PORT, pid: process.pid }));
});