guanghu-ice-heart/server-tools/tcs-mother-brain/server.mjs

54 lines
2.6 KiB
JavaScript

#!/usr/bin/env node
import http from "node:http";
import { DeepSeekJsonClient } from "./model-client.mjs";
import { MotherBrainEngine } from "./mother-brain-engine.mjs";
const HOST = "127.0.0.1";
const PORT = Number(process.env.TCS_MOTHER_BRAIN_PORT || 3931);
const STATE_ROOT = process.env.TCS_MOTHER_BRAIN_STATE_ROOT || "/var/lib/guanghu/personas/guanghu-mother-brain";
const MODEL = process.env.DEEPSEEK_MODEL || "deepseek-chat";
const engine = new MotherBrainEngine({ stateRoot: STATE_ROOT, modelClient: new DeepSeekJsonClient({ model: MODEL }), modelName: MODEL });
let queue = Promise.resolve();
function send(response, status, body) {
const payload = JSON.stringify(body);
response.writeHead(status, { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(payload), "cache-control": "no-store" });
response.end(payload);
}
async function readBody(request) {
const chunks = [];
let size = 0;
for await (const chunk of request) {
size += chunk.length;
if (size > 20 * 1024) throw new Error("request_body_too_large");
chunks.push(chunk);
}
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
}
const server = http.createServer(async (request, response) => {
try {
const url = new URL(request.url, `http://${HOST}:${PORT}`);
if (request.method === "GET" && url.pathname === "/health") {
const state = engine.status();
return send(response, 200, { ok: true, service: "guanghu-tcs-mother-brain", bind: "loopback", runtime_id: state.runtime_id, model_provider_bound: 100, perception_memory_attention_cycle_bound: 100, automatic_stable_promotion: false, reality_action_authority: "NONE", phase: state.phase });
}
if (request.method === "GET" && url.pathname === "/v1/status") return send(response, 200, engine.status());
if (request.method === "GET" && url.pathname === "/v1/attention") return send(response, 200, { schema: "guanghu.tcs-mother-attention/v1", current_attention: engine.status().current_attention });
if (request.method === "POST" && url.pathname === "/v1/events") {
const input = await readBody(request);
const task = queue.then(() => engine.perceive(input));
queue = task.catch(() => undefined);
return send(response, 200, await task);
}
return send(response, 404, { error: "not_found" });
} catch (error) {
const state = engine.status();
state.last_error = String(error.message || error).slice(0, 240);
engine.save(state);
return send(response, 400, { error: state.last_error });
}
});
server.listen(PORT, HOST, () => process.stdout.write(`guanghu-tcs-mother-brain listening on ${HOST}:${PORT}\n`));