interplane.Get Omega
Read in your language

aien-train

AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.

Brought by drakestapleton

branch main Branches Tags History

aien-train / tools / omegallm-ui / bridge.cpp

412 lines · 21577 bytes Raw Blame History
1// Opt-in interoperability bridge. Inference remains in the Omega runner.
2// Reuses the pinned llama.cpp UI, cpp-httplib and nlohmann/json.
3#include "httplib.h"
4#include "json.hpp"
5#include <atomic>
6#include <chrono>
7#include <csignal>
8#include <fcntl.h>
9#include <iostream>
10#include <poll.h>
11#include <spawn.h>
12#include <sys/wait.h>
13#include <sys/socket.h>
14#include <sys/un.h>
15#include <cstring>
16#include <unistd.h>
17
18using json = nlohmann::json;
19using Clock = std::chrono::steady_clock;
20extern char **environ;
21static const char *OMEGA = "Omega-Astra-2026-11-04";
22static constexpr auto QWEN = "build-mac/qwen.gguf";
23static constexpr auto LIMA = "/opt/homebrew/bin/limactl";
24static std::atomic<bool> busy{false};
25static std::atomic<unsigned> sequence{0};
26static bool firmware = false;
27static int ui_port = 8098;
28
29static int firmware_socket(const char *name) {
30 const char *home = getenv("HOME");
31 if (!home) throw std::runtime_error("Home directory is unavailable");
32 std::string path = std::string(home) + "/Applications/Omega/Aienux/" + name;
33 sockaddr_un addr{};
34 addr.sun_family = AF_UNIX;
35 if (path.size() >= sizeof(addr.sun_path)) throw std::runtime_error("Aienux socket path is too long");
36 std::strcpy(addr.sun_path, path.c_str());
37 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
38 if (fd < 0 || connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr))) {
39 if (fd >= 0) close(fd);
40 throw std::runtime_error("Open Aienux Omega.command to start the firmware model");
41 }
42 return fd;
43}
44
45static void reply(httplib::Response &res, const json &j, int status = 200) {
46 res.status = status;
47 res.set_content(j.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
48}
49static void error(httplib::Response &res, int status, const std::string &message) {
50 reply(res, {{"error", {{"message", message}, {"type", "invalid_request_error"}, {"code", status}}}}, status);
51}
52static pid_t spawn(std::vector<std::string> args, int *output = nullptr) {
53 int pipes[2] = {-1, -1};
54 if (output && pipe(pipes)) throw std::runtime_error("Cannot create model output pipe");
55 posix_spawn_file_actions_t actions;
56 posix_spawn_file_actions_init(&actions);
57 posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0);
58 posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
59 if (output) {
60 posix_spawn_file_actions_adddup2(&actions, pipes[1], 1);
61 posix_spawn_file_actions_addclose(&actions, pipes[0]);
62 posix_spawn_file_actions_addclose(&actions, pipes[1]);
63 } else posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0);
64 std::vector<char *> argv;
65 for (auto &arg : args) argv.push_back(arg.data());
66 argv.push_back(nullptr);
67 pid_t pid = -1;
68 int rc = posix_spawn(&pid, argv[0], &actions, nullptr, argv.data(), environ);
69 posix_spawn_file_actions_destroy(&actions);
70 if (output) {
71 close(pipes[1]);
72 if (rc) close(pipes[0]);
73 else *output = pipes[0];
74 }
75 if (rc) throw std::runtime_error("Cannot start local model process");
76 return pid;
77}
78
79struct Lease { ~Lease() { busy = false; } };
80struct ModelProcess {
81 pid_t pid = -1;
82 int fd = -1;
83 bool finished = false;
84 std::string ticket = std::to_string(getpid()) + "-" + std::to_string(++sequence);
85 unsigned wire_id = sequence.load();
86 ~ModelProcess() {
87 if (firmware) {
88 if (fd < 0) return;
89 // A disconnected generation cannot be reused as another request. Stop only this
90 // experiment's private VM. Its read-only model disk survives; the launcher restarts it.
91 try {
92 int monitor = firmware_socket("monitor.sock");
93 // UEFI Stall can busy-wait under TCG. Pause a completed VM between requests.
94 write(monitor, finished ? "stop\n" : "quit\n", 5);
95 close(monitor);
96 } catch (...) {}
97 close(fd);
98 return;
99 }
100 if (pid < 0) return;
101 try {
102 // Only our generated ticket names a process group. User text is never shell code.
103 auto cleanup = spawn({LIMA, "shell", "omega-llm", "sh", "-c",
104 "f=/tmp/omega-ui-$1.pid; if [ -f \"$f\" ]; then "
105 "p=$(cat \"$f\"); if [ \"$2\" = cancel ]; then /bin/kill -TERM -- \"-$p\" 2>/dev/null; fi; "
106 "rm -f \"$f\"; fi", "sh", ticket, finished ? "done" : "cancel"});
107 waitpid(cleanup, nullptr, 0);
108 } catch (...) {}
109 if (!finished) { kill(pid, SIGTERM); waitpid(pid, nullptr, 0); }
110 if (fd >= 0) close(fd);
111 }
112 void start(const std::string &prompt, int tokens, int temp, unsigned seed) {
113 if (firmware) {
114 fd = firmware_socket("serial.sock");
115 int monitor = firmware_socket("monitor.sock");
116 if (write(monitor, "cont\n", 5) != 5) { close(monitor); throw std::runtime_error("Cannot resume Aienux"); }
117 close(monitor);
118 std::string hex;
119 for (unsigned char c : prompt) { hex += "0123456789abcdef"[c >> 4]; hex += "0123456789abcdef"[c & 15]; }
120 std::string command = "LM1 " + std::to_string(wire_id) + " " + std::to_string(tokens) + " " +
121 std::to_string(temp) + " " + std::to_string(seed) + " " + hex + "\r";
122 size_t sent = 0;
123 while (sent < command.size()) {
124 auto n = write(fd, command.data() + sent, command.size() - sent);
125 if (n <= 0) throw std::runtime_error("Aienux console disconnected");
126 sent += n;
127 }
128 return;
129 }
130 pid = spawn({LIMA, "shell", "omega-llm", "sh", "-c",
131 "cd ~/omega && exec setsid --wait sh -c 'echo $$ > \"$1\"; shift; "
132 "exec timeout --foreground -k 2 120 ./ollm-ui sample omega-v2-edited-20261104.ck \"$@\" merges4096.bin' "
133 "sh \"/tmp/omega-ui-$1.pid\" \"$2\" \"$3\" \"$4\" \"$5\"",
134 "sh", ticket, std::to_string(seed), std::to_string(tokens), std::to_string(temp), prompt}, &fd);
135 }
136};
137
138// Keep incomplete UTF-8 sequences until the next pipe read.
139static size_t complete_utf8(const std::string &s) {
140 if (s.empty()) return 0;
141 size_t start = s.size() - 1;
142 while (start && (static_cast<unsigned char>(s[start]) & 0xc0) == 0x80) --start;
143 unsigned char c = s[start];
144 size_t need = c >= 0xf0 ? 4 : c >= 0xe0 ? 3 : c >= 0xc0 ? 2 : 1;
145 return s.size() - start < need ? start : s.size();
146}
147
148// Calls emit with new decoded text and with empty strings for keep-alives.
149static int generate(ModelProcess &p, const std::function<bool(const std::string &)> &emit) {
150 auto begin = Clock::now();
151 auto heartbeat = begin;
152 std::string pending;
153 std::string wire;
154 auto data_prefix = "LMDATA " + std::to_string(p.wire_id) + " ";
155 for (;;) {
156 if (Clock::now() - begin > std::chrono::seconds(firmware ? 1200 : 125)) return 124;
157 pollfd poller{p.fd, POLLIN, 0};
158 int ready = poll(&poller, 1, 200);
159 if (ready < 0 && errno != EINTR) return 1;
160 if (ready > 0) {
161 char buf[4096];
162 auto count = read(p.fd, buf, sizeof(buf));
163 if (count <= 0) { if (firmware) return 1; break; }
164 if (firmware) {
165 wire.append(buf, count);
166 if (wire.size() > 32768) return 1;
167 size_t end;
168 while ((end = wire.find('\n')) != std::string::npos) {
169 auto line = wire.substr(0, end); wire.erase(0, end + 1);
170 if (!line.empty() && line.back() == '\r') line.pop_back();
171 if (line == "LMDONE " + std::to_string(p.wire_id)) {
172 p.finished = true;
173 if (!pending.empty() && !emit(pending)) return 130;
174 return 0;
175 }
176 if (line.rfind("LMERR ", 0) == 0) { p.finished = true; return 1; }
177 if (line.rfind(data_prefix, 0) != 0) continue;
178 auto hex = line.substr(data_prefix.size());
179 if (hex.size() % 2) return 1;
180 auto nibble = [](char c) -> int { return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; };
181 for (size_t k = 0; k < hex.size(); k += 2) {
182 int a = nibble(hex[k]), b = nibble(hex[k + 1]);
183 if (a < 0 || b < 0) return 1;
184 pending += char(a * 16 + b);
185 }
186 }
187 } else pending.append(buf, count);
188 auto length = complete_utf8(pending);
189 if (length && !emit(pending.substr(0, length))) return 130;
190 pending.erase(0, length);
191 }
192 if (Clock::now() - heartbeat >= std::chrono::seconds(1)) {
193 if (!emit("")) return 130;
194 heartbeat = Clock::now();
195 }
196 }
197 int status = 0;
198 waitpid(p.pid, &status, 0);
199 p.finished = true;
200 if (!pending.empty() && !emit(pending)) return 130;
201 return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
202}
203
204static json model(const std::string &id) {
205 return {{"id", id}, {"name", id}, {"object", "model"}, {"owned_by", "local"},
206 {"created", 0}, {"path", ""}, {"in_cache", false}, {"aliases", json::array({id})},
207 {"status", {{"value", "loaded"}, {"args", json::array()}}},
208 {"architecture", {{"input_modalities", {"text"}}, {"output_modalities", {"text"}}}}};
209}
210static json upstream_props() {
211 httplib::Client client("127.0.0.1", 8097);
212 client.set_connection_timeout(2);
213 auto r = client.Get("/props");
214 if (!r || r->status != 200) throw std::runtime_error("Start Qwen through Omega to load the llama UI");
215 return json::parse(r->body);
216}
217
218static void completion(const httplib::Request &req, httplib::Response &res) {
219 json body = json::parse(req.body);
220 auto selected = body.value("model", std::string(OMEGA));
221 if (selected == QWEN) {
222 const bool streaming = body.value("stream", false);
223 if (streaming) {
224 auto data = body.dump();
225 res.set_chunked_content_provider("text/event-stream", [data](size_t, httplib::DataSink &sink) {
226 httplib::Client client("127.0.0.1", 8097);
227 client.set_read_timeout(130);
228 auto r = client.Post("/v1/chat/completions", {}, data, "application/json",
229 [&](const char *bytes, size_t count) { return sink.write(bytes, count); });
230 if (!r || r->status != 200) {
231 std::string e = "data: " + json({{"error", {{"message", "Qwen request failed"}}}}).dump() + "\n\n";
232 sink.write(e.data(), e.size());
233 }
234 sink.done();
235 return true;
236 });
237 } else {
238 httplib::Client client("127.0.0.1", 8097);
239 client.set_read_timeout(130);
240 auto r = client.Post("/v1/chat/completions", body.dump(), "application/json");
241 if (!r) { error(res, 502, "Qwen is unavailable"); return; }
242 res.status = r->status;
243 res.set_content(r->body, "application/json");
244 }
245 return;
246 }
247 if (selected != OMEGA) { error(res, 404, "Unknown local model"); return; }
248 for (auto key : {"tools", "stop", "grammar", "response_format"}) {
249 if (body.contains(key) && !body[key].is_null() && !body[key].empty()) {
250 error(res, 400, std::string("Omega's story model does not support ") + key); return;
251 }
252 }
253 if (body.value("n", 1) != 1) { error(res, 400, "Omega supports one completion at a time"); return; }
254 std::string prompt;
255 if (!body.contains("messages") || !body["messages"].is_array()) { error(res, 400, "messages must be an array"); return; }
256 for (const auto &message : body["messages"]) {
257 auto role = message.value("role", std::string());
258 if (role != "user" && role != "assistant" && role != "system") { error(res, 400, "Omega accepts text messages only"); return; }
259 auto content = message.at("content");
260 std::string text;
261 if (content.is_string()) text = content.get<std::string>();
262 else if (content.is_array()) {
263 for (const auto &part : content) {
264 if (part.value("type", "") != "text") { error(res, 400, "Omega accepts text only"); return; }
265 text += part.at("text").get<std::string>();
266 }
267 } else { error(res, 400, "Message content must be text"); return; }
268 if (text.empty()) continue;
269 if (!prompt.empty()) prompt += "\n";
270 prompt += text;
271 }
272 if (prompt.empty() || prompt.size() > 4000 || prompt.find('\0') != std::string::npos) {
273 error(res, 400, "Enter a story beginning or shorten this conversation to at most 4000 UTF-8 bytes"); return;
274 }
275 if (firmware && (prompt.size() > 159 || std::any_of(prompt.begin(), prompt.end(), [](unsigned char c) { return c < 32 || c > 126; }))) {
276 error(res, 400, "Aienux currently accepts one story beginning of up to 159 plain ASCII characters. Start a new chat for each prompt."); return;
277 }
278 int tokens = body.value("max_tokens", 64);
279 if (body.contains("max_completion_tokens") && !body["max_completion_tokens"].is_null()) tokens = body["max_completion_tokens"].get<int>();
280 if (tokens == -1) tokens = 64;
281 if (tokens < 1 || tokens > 128) { error(res, 400, "Set maximum output tokens between 1 and 128 for Omega"); return; }
282 if (firmware) tokens = std::min(tokens, 8);
283 double temperature = body.value("temperature", 0.8);
284 if (!std::isfinite(temperature) || temperature < 0 || temperature > 2) { error(res, 400, "Temperature must be between 0 and 2"); return; }
285 int seed = body.value("seed", 42);
286 if (seed < 0) seed = 42;
287 bool streaming = body.value("stream", false);
288 bool expected = false;
289 if (!busy.compare_exchange_strong(expected, true)) { error(res, 429, "Omega is already generating. Stop that response or wait for it to finish."); return; }
290 auto lease = std::make_shared<Lease>();
291 auto child = std::make_shared<ModelProcess>();
292 child->start(prompt, tokens, int(temperature * 1000), unsigned(seed));
293 std::string id = "omega-" + child->ticket;
294 auto created = std::time(nullptr);
295 auto chunk = [id, created](const json &delta, const json &reason = nullptr) {
296 return json{{"id", id}, {"object", "chat.completion.chunk"}, {"created", created}, {"model", OMEGA},
297 {"choices", json::array({{{"index", 0}, {"delta", delta}, {"finish_reason", reason}}})}};
298 };
299 if (streaming) {
300 res.set_header("Cache-Control", "no-cache");
301 auto closed = req.is_connection_closed;
302 res.set_chunked_content_provider("text/event-stream", [lease, child, chunk, closed](size_t, httplib::DataSink &sink) {
303 auto send = [&](const json &j) {
304 auto s = "data: " + j.dump(-1, ' ', false, json::error_handler_t::replace) + "\n\n";
305 return !closed() && sink.write(s.data(), s.size());
306 };
307 if (!send(chunk({{"role", "assistant"}, {"content", ""}}))) return false;
308 int rc = generate(*child, [&](const std::string &text) {
309 if (closed()) return false;
310 return text.empty() ? sink.write(": generating\n\n", 14) : send(chunk({{"content", text}}));
311 });
312 if (rc == 130) return false;
313 if (rc) send(chunk({{"content", "\n\n[Omega runtime error: generation failed or timed out. Try a shorter story beginning.]"}}));
314 else send(chunk(json::object(), "stop"));
315 sink.write("data: [DONE]\n\n", 14);
316 sink.done();
317 return true;
318 });
319 } else {
320 std::string text;
321 int rc = generate(*child, [&](const std::string &part) { text += part; return !req.is_connection_closed(); });
322 if (rc) { error(res, 502, "Omega generation failed or timed out"); return; }
323 reply(res, {{"id", id}, {"object", "chat.completion"}, {"created", created}, {"model", OMEGA},
324 {"choices", json::array({{{"index", 0}, {"message", {{"role", "assistant"}, {"content", text}}}, {"finish_reason", "stop"}}})}});
325 }
326}
327
328int main(int argc, char **argv) {
329 if ((argc != 2 && argc != 3) || std::string(argv[1]) != "--enable-local-ui-bridge" ||
330 (argc == 3 && std::string(argv[2]) != "--aienux")) {
331 std::cerr << "Opt in with --enable-local-ui-bridge\n"; return 2;
332 }
333 firmware = argc == 3;
334 if (firmware) { ui_port = 8099; OMEGA = "Omega-Astra-Aienux"; }
335 signal(SIGPIPE, SIG_IGN);
336 httplib::Server server;
337 server.set_payload_max_length(65536);
338 server.set_read_timeout(10);
339 server.set_write_timeout(10);
340 server.set_exception_handler([](const auto &, auto &res, std::exception_ptr exception) {
341 try { std::rethrow_exception(exception); }
342 catch (const json::exception &) { error(res, 400, "Invalid JSON or parameter type"); }
343 catch (const std::exception &e) { error(res, 503, e.what()); }
344 });
345 server.set_pre_routing_handler([](const auto &req, auto &res) {
346 // Local UI only. Do not admit arbitrary websites through permissive CORS.
347 auto host = req.get_header_value("Host");
348 if (host != "127.0.0.1:" + std::to_string(ui_port) && host != "localhost:" + std::to_string(ui_port)) {
349 error(res, 403, "Only the local Omega host is allowed");
350 return httplib::Server::HandlerResponse::Handled;
351 }
352 if (req.has_header("Origin")) {
353 auto origin = req.get_header_value("Origin");
354 if (origin != "http://127.0.0.1:" + std::to_string(ui_port) && origin != "http://localhost:" + std::to_string(ui_port)) {
355 error(res, 403, "Only the local Omega UI is allowed");
356 return httplib::Server::HandlerResponse::Handled;
357 }
358 }
359 return httplib::Server::HandlerResponse::Unhandled;
360 });
361 server.Get("/health", [](const auto &, auto &res) { reply(res, {{"status", "ok"}, {"service", "omega-ui-bridge"}, {"runtime", firmware ? "aienux-firmware" : "linux"}, {"omega_busy", busy.load()}}); });
362 server.Get("/v1/models", [](const auto &, auto &res) { reply(res, {{"object", "list"}, {"data", {model(OMEGA), model(QWEN)}}}); });
363 server.Get("/props", [](const auto &req, auto &res) {
364 auto props = upstream_props();
365 auto selected = req.get_param_value("model");
366 if (selected.empty()) props["role"] = "router";
367 else if (selected != OMEGA && selected != QWEN) { error(res, 404, "Unknown model"); return; }
368 if (selected != QWEN) {
369 props["model_alias"] = OMEGA;
370 props["model_path"] = OMEGA;
371 props.erase("model_ftype");
372 props["bos_token"] = "";
373 props["eos_token"] = "";
374 props["default_generation_settings"]["params"]["max_tokens"] = firmware ? 8 : 64;
375 props["default_generation_settings"]["params"]["n_predict"] = firmware ? 8 : 64;
376 props["default_generation_settings"]["params"]["seed"] = 42;
377 props["default_generation_settings"]["n_ctx"] = 256;
378 props["chat_template"] = "{% for message in messages %}{{ message.content }}{% endfor %}";
379 props["chat_template_caps"] = {{"supports_tools", false}, {"supports_tool_calls", false}, {"supports_system_role", false}};
380 props["ui_settings"] = {{"max_tokens", firmware ? 8 : 64}, {"enableDiscoverModels", false}, {"titleGenerationUseLLM", false}};
381 }
382 props["endpoint_slots"] = false;
383 reply(res, props);
384 });
385 server.Get("/slots", [](const auto &, auto &res) { reply(res, json::array()); });
386 server.Get("/tools", [](const auto &, auto &res) { reply(res, {{"tools", json::array()}}); });
387 server.Get("/models/sse", [](const auto &req, auto &res) {
388 auto closed = req.is_connection_closed;
389 res.set_chunked_content_provider("text/event-stream", [closed](size_t, httplib::DataSink &sink) {
390 if (closed()) return false;
391 if (!sink.write(": local models ready\n\n", 22)) return false;
392 std::this_thread::sleep_for(std::chrono::seconds(2));
393 return true;
394 });
395 });
396 server.Post("/v1/chat/completions", completion);
397 server.Post("/models/load", [](const auto &, auto &res) { reply(res, {{"success", true}}); });
398 // Reuse the already-running llama UI assets without changing its files.
399 server.Get("/.*", [](const auto &req, auto &res) {
400 if (req.path.rfind("/v1/", 0) == 0 || req.path.rfind("/models/", 0) == 0) { error(res, 404, "Endpoint unavailable in local bridge"); return; }
401 httplib::Client client("127.0.0.1", 8097);
402 client.set_decompress(false);
403 httplib::Headers headers{{"Accept-Encoding", "gzip"}};
404 auto r = client.Get(req.target, headers);
405 if (!r) { error(res, 502, "Start Qwen through Omega to load the llama UI"); return; }
406 res.status = r->status;
407 res.set_content(r->body, r->get_header_value("Content-Type"));
408 if (r->has_header("Content-Encoding")) res.set_header("Content-Encoding", r->get_header_value("Content-Encoding"));
409 });
410 std::cout << "Omega + Qwen llama UI: http://127.0.0.1:" << ui_port << (firmware ? " (Aienux firmware)" : " (Linux)") << "\n" << std::flush;
411 return server.listen("127.0.0.1", ui_port) ? 0 : 1;
412}