Source index

src/server.mjs

import {createServer} from 'node:http';
import {readFile} from 'node:fs/promises';
import {resolve, sep} from 'node:path';
import {fileURLToPath} from 'node:url';
import {runAgent} from './agent.mjs';
const publicRoot = resolve(fileURLToPath(new URL('../public', import.meta.url)));
let busy = false;
const server = createServer(async (request, response) => {
  try {
    const url = new URL(request.url, 'http://127.0.0.1');
    if (url.pathname === '/api/ask' && request.method === 'POST') {
      if (busy) {response.writeHead(429, {'Content-Type': 'application/json'}); response.end(JSON.stringify({error: 'One local question is already running.'})); return;}
      let body = '';
      for await (const chunk of request) {body += chunk; if (body.length > 4000) throw new Error('Question is too long.');}
      const {question} = JSON.parse(body);
      busy = true;
      try {const result = await runAgent(question); response.writeHead(200, {'Content-Type': 'application/json', 'Cache-Control': 'no-store'}); response.end(JSON.stringify(result));}
      finally {busy = false;}
      return;
    }
    if (url.pathname === '/api/status') {response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify({mode: 'local-agent', model: process.env.OLLAMA_MODEL || 'qwen2.5:7b', contextConfigured: Boolean(process.env.SANITY_CONTEXT_TOKEN), busy})); return;}
    const relative = decodeURIComponent(url.pathname === '/' ? '/index.html' : url.pathname);
    const path = resolve(publicRoot, '.' + relative);
    if (!path.startsWith(publicRoot + sep)) throw new Error('Unknown file.');
    const body = await readFile(path);
    const types = {'.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json', '.png': 'image/png', '.zip': 'application/zip'};
    const extension = path.slice(path.lastIndexOf('.'));
    response.writeHead(200, {'Content-Type': types[extension] || 'application/octet-stream', 'X-Content-Type-Options': 'nosniff'}); response.end(body);
  } catch {response.writeHead(400, {'Content-Type': 'application/json'}); response.end(JSON.stringify({error: 'Request failed. Check the question, local model and Context setup.'}));}
});
server.listen(Number(process.env.PORT || 4340), '127.0.0.1', () => console.log('Access Atlas listening at http://127.0.0.1:4340 (local only).'));