| 1 | /* |
| 2 | * plugin_slots.c -- SCORPIOX BOT open-source llama.cpp Slots Monitor plugin |
| 3 | * |
| 4 | * Single-binary zero-dependency C99 plugin serving all 3 SCORPIOX BOT modes: |
| 5 | * 1. --meta / SX_PLUGIN_META=1 : emits {"name":"slots","desc":"llama.cpp slots",...} |
| 6 | * 2. GET ?action=sessions : lists active node sessions + slots.json presence |
| 7 | * GET ?action=slots : reads <session>/slots.json or probes <url>/slots |
| 8 | * 3. GET (default) : serves responsive dual-theme HTML UI (?embed=1 ready) |
| 9 | * |
| 10 | * Security: |
| 11 | * - Enforces BOT_PASSWORD via X-Bot-Password, Bearer token, or ?pwd= |
| 12 | * - Strictly validates session IDs and http(s):// URLs |
| 13 | * - Read-only telemetry only |
| 14 | * |
| 15 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 16 | */ |
| 17 | #ifndef _WIN32 |
| 18 | #define _POSIX_C_SOURCE 200809L |
| 19 | #define _DEFAULT_SOURCE |
| 20 | #endif |
| 21 | |
| 22 | #include <ctype.h> |
| 23 | #include <stdio.h> |
| 24 | #include <stdlib.h> |
| 25 | #include <string.h> |
| 26 | #include <sys/stat.h> |
| 27 | #include <time.h> |
| 28 | |
| 29 | #ifdef _WIN32 |
| 30 | #include <io.h> |
| 31 | #include <windows.h> |
| 32 | #define SX_SEP '\\' |
| 33 | #define sx_popen _popen |
| 34 | #define sx_pclose _pclose |
| 35 | #define sx_access _access |
| 36 | #define sx_strncasecmp _strnicmp |
| 37 | #else |
| 38 | #include <dirent.h> |
| 39 | #include <strings.h> |
| 40 | #include <unistd.h> |
| 41 | #define SX_SEP '/' |
| 42 | #define sx_popen popen |
| 43 | #define sx_pclose pclose |
| 44 | #define sx_access access |
| 45 | #define sx_strncasecmp strncasecmp |
| 46 | #endif |
| 47 | |
| 48 | #include "bot_theme_plugin.h" |
| 49 | |
| 50 | #define PLUGIN_VERSION "1.0.0" |
| 51 | #define MAX_SESSIONS 128 |
| 52 | |
| 53 | /* ------------------------------------------------------------------ */ |
| 54 | /* Small utilities */ |
| 55 | /* ------------------------------------------------------------------ */ |
| 56 | |
| 57 | static void str_copy(char *dst, size_t dstsz, const char *src) |
| 58 | { |
| 59 | size_t n; |
| 60 | if (!dst || dstsz == 0) return; |
| 61 | if (!src) { dst[0] = '\0'; return; } |
| 62 | n = strlen(src); |
| 63 | if (n >= dstsz) n = dstsz - 1; |
| 64 | memcpy(dst, src, n); |
| 65 | dst[n] = '\0'; |
| 66 | } |
| 67 | |
| 68 | static int hex_val(char c) |
| 69 | { |
| 70 | if (c >= '0' && c <= '9') return c - '0'; |
| 71 | if (c >= 'a' && c <= 'f') return c - 'a' + 10; |
| 72 | if (c >= 'A' && c <= 'F') return c - 'A' + 10; |
| 73 | return -1; |
| 74 | } |
| 75 | |
| 76 | static void url_decode(const char *src, char *dst, size_t dstsz) |
| 77 | { |
| 78 | size_t i = 0; |
| 79 | if (!dst || dstsz == 0) return; |
| 80 | if (!src) { dst[0] = '\0'; return; } |
| 81 | while (*src && i + 1 < dstsz) { |
| 82 | if (*src == '%' && src[1] && src[2]) { |
| 83 | int hi = hex_val(src[1]), lo = hex_val(src[2]); |
| 84 | if (hi >= 0 && lo >= 0) { |
| 85 | dst[i++] = (char)((hi << 4) | lo); |
| 86 | src += 3; |
| 87 | continue; |
| 88 | } |
| 89 | } |
| 90 | if (*src == '+') dst[i++] = ' '; |
| 91 | else dst[i++] = *src; |
| 92 | src++; |
| 93 | } |
| 94 | dst[i] = '\0'; |
| 95 | } |
| 96 | |
| 97 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 98 | { |
| 99 | size_t klen; |
| 100 | const char *p; |
| 101 | if (out && outsz) out[0] = '\0'; |
| 102 | if (!qs || !*qs || !key || !*key || !out || outsz == 0) return 0; |
| 103 | klen = strlen(key); |
| 104 | p = qs; |
| 105 | while (*p) { |
| 106 | const char *amp = strchr(p, '&'); |
| 107 | size_t len = amp ? (size_t)(amp - p) : strlen(p); |
| 108 | if (len > klen && strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 109 | char raw[1024]; |
| 110 | size_t vlen = len - klen - 1; |
| 111 | if (vlen >= sizeof raw) vlen = sizeof raw - 1; |
| 112 | memcpy(raw, p + klen + 1, vlen); |
| 113 | raw[vlen] = '\0'; |
| 114 | url_decode(raw, out, outsz); |
| 115 | return 1; |
| 116 | } |
| 117 | if (!amp) break; |
| 118 | p = amp + 1; |
| 119 | } |
| 120 | return 0; |
| 121 | } |
| 122 | |
| 123 | static void json_print_str(const char *s) |
| 124 | { |
| 125 | const unsigned char *p = (const unsigned char *)(s ? s : ""); |
| 126 | fputc('"', stdout); |
| 127 | for (; *p; p++) { |
| 128 | unsigned char c = *p; |
| 129 | if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); } |
| 130 | else if (c == '\n') fputs("\\n", stdout); |
| 131 | else if (c == '\r') fputs("\\r", stdout); |
| 132 | else if (c == '\t') fputs("\\t", stdout); |
| 133 | else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout); |
| 134 | } |
| 135 | fputc('"', stdout); |
| 136 | } |
| 137 | |
| 138 | static int safe_id(const char *s) |
| 139 | { |
| 140 | size_t i; |
| 141 | if (!s || !*s) return 0; |
| 142 | for (i = 0; s[i]; i++) { |
| 143 | unsigned char c = (unsigned char)s[i]; |
| 144 | if (i >= 160) return 0; |
| 145 | if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == ':') continue; |
| 146 | return 0; |
| 147 | } |
| 148 | if (strstr(s, "..") != NULL) return 0; |
| 149 | return 1; |
| 150 | } |
| 151 | |
| 152 | static int url_ok(const char *u) |
| 153 | { |
| 154 | const char *p; |
| 155 | if (!u || !*u || strlen(u) > 512) return 0; |
| 156 | if (strncmp(u, "http://", 7) != 0 && strncmp(u, "https://", 8) != 0) return 0; |
| 157 | for (p = u; *p; p++) { |
| 158 | unsigned char c = (unsigned char)*p; |
| 159 | if (isalnum(c) || strchr(":/.-_~%?&#=+@,", (int)c) != NULL) continue; |
| 160 | return 0; |
| 161 | } |
| 162 | return 1; |
| 163 | } |
| 164 | |
| 165 | static int is_dir(const char *p) |
| 166 | { |
| 167 | struct stat st; |
| 168 | if (!p || !*p) return 0; |
| 169 | if (stat(p, &st) != 0) return 0; |
| 170 | return (st.st_mode & S_IFMT) == S_IFDIR; |
| 171 | } |
| 172 | |
| 173 | static int file_exists(const char *p) |
| 174 | { |
| 175 | struct stat st; |
| 176 | if (!p || !*p) return 0; |
| 177 | return stat(p, &st) == 0 && (st.st_mode & S_IFMT) == S_IFREG; |
| 178 | } |
| 179 | |
| 180 | static char *read_file_all(const char *path, size_t *len_out) |
| 181 | { |
| 182 | FILE *f; |
| 183 | char *buf; |
| 184 | size_t cap = 4096, len = 0, n; |
| 185 | if (len_out) *len_out = 0; |
| 186 | f = fopen(path, "rb"); |
| 187 | if (!f) return NULL; |
| 188 | buf = (char *)malloc(cap); |
| 189 | if (!buf) { fclose(f); return NULL; } |
| 190 | while ((n = fread(buf + len, 1, cap - len - 1, f)) > 0) { |
| 191 | len += n; |
| 192 | if (cap - len < 512) { |
| 193 | char *nb; |
| 194 | if (cap > (4 * 1024 * 1024)) break; |
| 195 | cap *= 2; |
| 196 | nb = (char *)realloc(buf, cap); |
| 197 | if (!nb) break; |
| 198 | buf = nb; |
| 199 | } |
| 200 | } |
| 201 | fclose(f); |
| 202 | buf[len] = '\0'; |
| 203 | if (len_out) *len_out = len; |
| 204 | return buf; |
| 205 | } |
| 206 | |
| 207 | static char *read_pipe_all(FILE *p, size_t *len_out) |
| 208 | { |
| 209 | size_t cap = 16384, len = 0, n; |
| 210 | char *buf; |
| 211 | if (len_out) *len_out = 0; |
| 212 | if (!p) return NULL; |
| 213 | buf = (char *)malloc(cap); |
| 214 | if (!buf) return NULL; |
| 215 | while ((n = fread(buf + len, 1, cap - len - 1, p)) > 0) { |
| 216 | len += n; |
| 217 | if (cap - len < 1024) { |
| 218 | char *nb; |
| 219 | if (cap > (4 * 1024 * 1024)) break; |
| 220 | cap *= 2; |
| 221 | nb = (char *)realloc(buf, cap); |
| 222 | if (!nb) break; |
| 223 | buf = nb; |
| 224 | } |
| 225 | } |
| 226 | buf[len] = '\0'; |
| 227 | if (len_out) *len_out = len; |
| 228 | return buf; |
| 229 | } |
| 230 | |
| 231 | /* ------------------------------------------------------------------ */ |
| 232 | /* Node security */ |
| 233 | /* ------------------------------------------------------------------ */ |
| 234 | |
| 235 | static void require_node_auth(void) |
| 236 | { |
| 237 | const char *np = getenv("BOT_PASSWORD"); |
| 238 | const char *xp, *auth, *ref; |
| 239 | char qpwd[128] = {0}; |
| 240 | |
| 241 | if (!np || !*np) return; |
| 242 | |
| 243 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 244 | if (xp && strcmp(xp, np) == 0) return; |
| 245 | |
| 246 | auth = getenv("HTTP_AUTHORIZATION"); |
| 247 | if (auth) { |
| 248 | while (*auth == ' ') auth++; |
| 249 | if (sx_strncasecmp(auth, "Bearer ", 7) == 0) { |
| 250 | auth += 7; |
| 251 | while (*auth == ' ') auth++; |
| 252 | if (strcmp(auth, np) == 0) return; |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd) |
| 257 | && strcmp(qpwd, np) == 0) return; |
| 258 | |
| 259 | ref = getenv("HTTP_REFERER"); |
| 260 | if (ref) { |
| 261 | const char *rq = strchr(ref, '?'); |
| 262 | if (rq && get_query_val(rq + 1, "pwd", qpwd, sizeof qpwd) |
| 263 | && strcmp(qpwd, np) == 0) return; |
| 264 | } |
| 265 | |
| 266 | fputs("Status: 401 Unauthorized\r\n" |
| 267 | "Content-Type: application/json; charset=utf-8\r\n\r\n" |
| 268 | "{\"ok\":false,\"error\":\"unauthorized\"}\n", stdout); |
| 269 | exit(0); |
| 270 | } |
| 271 | |
| 272 | /* ------------------------------------------------------------------ */ |
| 273 | /* Lightweight JSON string extractor & tmux discovery */ |
| 274 | /* ------------------------------------------------------------------ */ |
| 275 | |
| 276 | static int json_extract_str_after(const char *obj, const char *end, const char *key, |
| 277 | char *out, size_t outsz) |
| 278 | { |
| 279 | char pat[128]; |
| 280 | const char *p; |
| 281 | size_t plen, i = 0; |
| 282 | if (out && outsz) out[0] = '\0'; |
| 283 | if (!obj || !key || !out || outsz == 0) return 0; |
| 284 | snprintf(pat, sizeof pat, "\"%s\"", key); |
| 285 | plen = strlen(pat); |
| 286 | p = obj; |
| 287 | while (p && (!end || p < end)) { |
| 288 | const char *hit = strstr(p, pat); |
| 289 | const char *q; |
| 290 | if (!hit || (end && hit >= end)) return 0; |
| 291 | q = hit + plen; |
| 292 | while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++; |
| 293 | if ((!end || q < end) && *q == ':') { |
| 294 | q++; |
| 295 | while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++; |
| 296 | if ((!end || q < end) && *q == '"') { |
| 297 | q++; |
| 298 | while ((!end || q < end) && *q && *q != '"' && i + 1 < outsz) { |
| 299 | if (*q == '\\' && q[1]) { |
| 300 | q++; |
| 301 | if (*q == 'n') out[i++] = '\n'; |
| 302 | else if (*q == 'r') out[i++] = '\r'; |
| 303 | else if (*q == 't') out[i++] = '\t'; |
| 304 | else out[i++] = *q; |
| 305 | q++; |
| 306 | } else { |
| 307 | out[i++] = *q++; |
| 308 | } |
| 309 | } |
| 310 | out[i] = '\0'; |
| 311 | return 1; |
| 312 | } |
| 313 | } |
| 314 | p = hit + plen; |
| 315 | } |
| 316 | return 0; |
| 317 | } |
| 318 | |
| 319 | static const char *tmux_bin(void) |
| 320 | { |
| 321 | static char path[512] = {0}; |
| 322 | const char *env; |
| 323 | if (path[0]) return path; |
| 324 | env = getenv("SCORPIOX_TMUX_BIN"); |
| 325 | if (env && *env) { str_copy(path, sizeof path, env); return path; } |
| 326 | #ifdef _WIN32 |
| 327 | { |
| 328 | const char *lad = getenv("LOCALAPPDATA"); |
| 329 | if (lad && *lad) { |
| 330 | snprintf(path, sizeof path, "%s\\scorpiox\\scorpiox-tmux.exe", lad); |
| 331 | if (sx_access(path, 0) == 0) return path; |
| 332 | } |
| 333 | str_copy(path, sizeof path, "scorpiox-tmux.exe"); |
| 334 | } |
| 335 | #else |
| 336 | if (sx_access("/usr/local/bin/scorpiox-tmux", X_OK) == 0) |
| 337 | str_copy(path, sizeof path, "/usr/local/bin/scorpiox-tmux"); |
| 338 | else |
| 339 | str_copy(path, sizeof path, "scorpiox-tmux"); |
| 340 | #endif |
| 341 | return path; |
| 342 | } |
| 343 | |
| 344 | static int pick_newest_session(const char *sessions_dir, char *sid_out, size_t sidsz) |
| 345 | { |
| 346 | time_t best_t = 0; |
| 347 | char best_name[256] = {0}; |
| 348 | #ifdef _WIN32 |
| 349 | char pat[1200]; |
| 350 | WIN32_FIND_DATAA fd; |
| 351 | HANDLE h; |
| 352 | snprintf(pat, sizeof pat, "%.950s\\*", sessions_dir); |
| 353 | h = FindFirstFileA(pat, &fd); |
| 354 | if (h == INVALID_HANDLE_VALUE) return 0; |
| 355 | do { |
| 356 | char probe[1400]; |
| 357 | struct stat st; |
| 358 | if (fd.cFileName[0] == '.') continue; |
| 359 | if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; |
| 360 | snprintf(probe, sizeof probe, "%.950s\\%.200s\\slots.json", sessions_dir, fd.cFileName); |
| 361 | if (stat(probe, &st) != 0) { |
| 362 | snprintf(probe, sizeof probe, "%.950s\\%.200s\\meta.json", sessions_dir, fd.cFileName); |
| 363 | if (stat(probe, &st) != 0) continue; |
| 364 | } |
| 365 | if (st.st_mtime >= best_t) { |
| 366 | best_t = st.st_mtime; |
| 367 | str_copy(best_name, sizeof best_name, fd.cFileName); |
| 368 | } |
| 369 | } while (FindNextFileA(h, &fd)); |
| 370 | FindClose(h); |
| 371 | #else |
| 372 | DIR *d = opendir(sessions_dir); |
| 373 | struct dirent *de; |
| 374 | if (!d) return 0; |
| 375 | while ((de = readdir(d)) != NULL) { |
| 376 | char probe[1400]; |
| 377 | struct stat st; |
| 378 | if (de->d_name[0] == '.') continue; |
| 379 | snprintf(probe, sizeof probe, "%.950s/%.200s/slots.json", sessions_dir, de->d_name); |
| 380 | if (stat(probe, &st) != 0) { |
| 381 | snprintf(probe, sizeof probe, "%.950s/%.200s/meta.json", sessions_dir, de->d_name); |
| 382 | if (stat(probe, &st) != 0) continue; |
| 383 | } |
| 384 | if (st.st_mtime >= best_t) { |
| 385 | best_t = st.st_mtime; |
| 386 | str_copy(best_name, sizeof best_name, de->d_name); |
| 387 | } |
| 388 | } |
| 389 | closedir(d); |
| 390 | #endif |
| 391 | if (!best_name[0]) return 0; |
| 392 | str_copy(sid_out, sidsz, best_name); |
| 393 | return 1; |
| 394 | } |
| 395 | |
| 396 | typedef struct { |
| 397 | char name[160]; |
| 398 | char worktree[768]; |
| 399 | char session_dir[1280]; |
| 400 | char sid[160]; |
| 401 | int has_slots; |
| 402 | } sess_entry_t; |
| 403 | |
| 404 | static int list_tmux_sessions(sess_entry_t *out, int max_n) |
| 405 | { |
| 406 | char cmd[768]; |
| 407 | FILE *p; |
| 408 | size_t len = 0; |
| 409 | char *buf; |
| 410 | int count = 0; |
| 411 | const char *arr, *cur; |
| 412 | |
| 413 | if (!out || max_n <= 0) return 0; |
| 414 | #ifdef _WIN32 |
| 415 | snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>NUL", tmux_bin()); |
| 416 | #else |
| 417 | snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>/dev/null", tmux_bin()); |
| 418 | #endif |
| 419 | p = sx_popen(cmd, "r"); |
| 420 | if (!p) return 0; |
| 421 | buf = read_pipe_all(p, &len); |
| 422 | sx_pclose(p); |
| 423 | if (!buf || len == 0) { free(buf); return 0; } |
| 424 | |
| 425 | arr = strstr(buf, "\"sessions\""); |
| 426 | if (!arr) { free(buf); return 0; } |
| 427 | arr = strchr(arr, '['); |
| 428 | if (!arr) { free(buf); return 0; } |
| 429 | cur = arr + 1; |
| 430 | |
| 431 | while (*cur && count < max_n) { |
| 432 | const char *ob = strchr(cur, '{'); |
| 433 | const char *cb; |
| 434 | int depth = 0; |
| 435 | const char *q; |
| 436 | sess_entry_t *e; |
| 437 | if (!ob) break; |
| 438 | cb = ob; |
| 439 | for (q = ob; *q; q++) { |
| 440 | if (*q == '"') { |
| 441 | q++; |
| 442 | while (*q && *q != '"') { if (*q == '\\' && q[1]) q++; q++; } |
| 443 | if (!*q) break; |
| 444 | } else if (*q == '{') depth++; |
| 445 | else if (*q == '}') { depth--; if (depth == 0) { cb = q; break; } } |
| 446 | } |
| 447 | if (cb <= ob) break; |
| 448 | e = &out[count]; |
| 449 | memset(e, 0, sizeof *e); |
| 450 | if (json_extract_str_after(ob, cb, "name", e->name, sizeof e->name) && e->name[0]) { |
| 451 | json_extract_str_after(ob, cb, "worktree", e->worktree, sizeof e->worktree); |
| 452 | if (!e->worktree[0]) { |
| 453 | char proj[768] = {0}; |
| 454 | if (json_extract_str_after(ob, cb, "project", proj, sizeof proj) && proj[0]) |
| 455 | str_copy(e->worktree, sizeof e->worktree, proj); |
| 456 | } |
| 457 | if (e->worktree[0]) { |
| 458 | char sroot[960]; |
| 459 | snprintf(sroot, sizeof sroot, "%.767s%c.scorpiox%csessions", e->worktree, SX_SEP, SX_SEP); |
| 460 | if (pick_newest_session(sroot, e->sid, sizeof e->sid)) { |
| 461 | char spath[1400]; |
| 462 | snprintf(e->session_dir, sizeof e->session_dir, "%.959s%c%.159s", sroot, SX_SEP, e->sid); |
| 463 | snprintf(spath, sizeof spath, "%.1279s%cslots.json", e->session_dir, SX_SEP); |
| 464 | e->has_slots = file_exists(spath); |
| 465 | } |
| 466 | } |
| 467 | count++; |
| 468 | } |
| 469 | cur = cb + 1; |
| 470 | } |
| 471 | free(buf); |
| 472 | return count; |
| 473 | } |
| 474 | |
| 475 | static int collect_default_roots(char roots[][512], int max_roots) |
| 476 | { |
| 477 | int n = 0; |
| 478 | const char *env = getenv("SX_SESSIONS_DIR"); |
| 479 | if (env && *env && is_dir(env) && n < max_roots) |
| 480 | str_copy(roots[n++], 512, env); |
| 481 | #ifdef _WIN32 |
| 482 | { |
| 483 | const char *lad = getenv("LOCALAPPDATA"); |
| 484 | const char *up = getenv("USERPROFILE"); |
| 485 | char cand[512]; |
| 486 | if (lad && *lad && n < max_roots) { |
| 487 | snprintf(cand, sizeof cand, "%.460s\\scorpiox\\sessions", lad); |
| 488 | if (is_dir(cand)) str_copy(roots[n++], 512, cand); |
| 489 | } |
| 490 | if (up && *up && n < max_roots) { |
| 491 | snprintf(cand, sizeof cand, "%.460s\\.scorpiox\\sessions", up); |
| 492 | if (is_dir(cand)) str_copy(roots[n++], 512, cand); |
| 493 | } |
| 494 | } |
| 495 | #else |
| 496 | { |
| 497 | const char *home = getenv("HOME"); |
| 498 | char cand[512]; |
| 499 | if (home && *home && n < max_roots) { |
| 500 | snprintf(cand, sizeof cand, "%.460s/.scorpiox/sessions", home); |
| 501 | if (is_dir(cand)) str_copy(roots[n++], 512, cand); |
| 502 | } |
| 503 | if (is_dir("/workspace/.scorpiox/sessions") && n < max_roots) |
| 504 | str_copy(roots[n++], 512, "/workspace/.scorpiox/sessions"); |
| 505 | } |
| 506 | #endif |
| 507 | return n; |
| 508 | } |
| 509 | |
| 510 | static int resolve_session_dir(const char *id, char *dir_out, size_t dirsz, char *sid_out, size_t sidsz) |
| 511 | { |
| 512 | char roots[8][512]; |
| 513 | int nroots, i, n; |
| 514 | sess_entry_t *list; |
| 515 | |
| 516 | if (dir_out && dirsz) dir_out[0] = '\0'; |
| 517 | if (sid_out && sidsz) sid_out[0] = '\0'; |
| 518 | if (!id || !*id || !safe_id(id)) return 0; |
| 519 | |
| 520 | nroots = collect_default_roots(roots, 8); |
| 521 | for (i = 0; i < nroots; i++) { |
| 522 | char cand[1024]; |
| 523 | snprintf(cand, sizeof cand, "%.511s%c%.255s", roots[i], SX_SEP, id); |
| 524 | if (is_dir(cand)) { |
| 525 | str_copy(dir_out, dirsz, cand); |
| 526 | str_copy(sid_out, sidsz, id); |
| 527 | return 1; |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list); |
| 532 | if (list) { |
| 533 | n = list_tmux_sessions(list, MAX_SESSIONS); |
| 534 | for (i = 0; i < n; i++) { |
| 535 | if (strcmp(list[i].name, id) == 0 && list[i].session_dir[0]) { |
| 536 | str_copy(dir_out, dirsz, list[i].session_dir); |
| 537 | str_copy(sid_out, sidsz, list[i].sid); |
| 538 | free(list); |
| 539 | return 1; |
| 540 | } |
| 541 | } |
| 542 | for (i = 0; i < n; i++) { |
| 543 | if (strstr(list[i].name, id) != NULL && list[i].session_dir[0]) { |
| 544 | str_copy(dir_out, dirsz, list[i].session_dir); |
| 545 | str_copy(sid_out, sidsz, list[i].sid); |
| 546 | free(list); |
| 547 | return 1; |
| 548 | } |
| 549 | } |
| 550 | free(list); |
| 551 | } |
| 552 | |
| 553 | #ifndef _WIN32 |
| 554 | { |
| 555 | char cand[640], sid[160]; |
| 556 | snprintf(cand, sizeof cand, "/codebases/.worktrees/%.255s/.scorpiox/sessions", id); |
| 557 | if (pick_newest_session(cand, sid, sizeof sid)) { |
| 558 | snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid); |
| 559 | str_copy(sid_out, sidsz, sid); |
| 560 | return 1; |
| 561 | } |
| 562 | snprintf(cand, sizeof cand, "/codebases/%.255s/.scorpiox/sessions", id); |
| 563 | if (pick_newest_session(cand, sid, sizeof sid)) { |
| 564 | snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid); |
| 565 | str_copy(sid_out, sidsz, sid); |
| 566 | return 1; |
| 567 | } |
| 568 | } |
| 569 | #endif |
| 570 | return 0; |
| 571 | } |
| 572 | |
| 573 | /* ------------------------------------------------------------------ */ |
| 574 | /* Action: sessions */ |
| 575 | /* ------------------------------------------------------------------ */ |
| 576 | |
| 577 | static void handle_sessions(void) |
| 578 | { |
| 579 | sess_entry_t *list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list); |
| 580 | int n = 0, i, emitted = 0; |
| 581 | fputs("Content-Type: application/json; charset=utf-8\r\n\r\n{\"ok\":true,\"sessions\":[", stdout); |
| 582 | if (list) { |
| 583 | n = list_tmux_sessions(list, MAX_SESSIONS); |
| 584 | for (i = 0; i < n; i++) { |
| 585 | if (emitted++) fputc(',', stdout); |
| 586 | fputs("{\"name\":", stdout); json_print_str(list[i].name); |
| 587 | fputs(",\"sid\":", stdout); json_print_str(list[i].sid); |
| 588 | fputs(",\"has_slots\":", stdout); fputs(list[i].has_slots ? "true" : "false", stdout); |
| 589 | fputc('}', stdout); |
| 590 | } |
| 591 | free(list); |
| 592 | } |
| 593 | if (emitted == 0) { |
| 594 | char roots[4][512]; |
| 595 | int nr = collect_default_roots(roots, 4); |
| 596 | if (nr > 0) { |
| 597 | #ifdef _WIN32 |
| 598 | char pat[600]; |
| 599 | WIN32_FIND_DATAA fd; |
| 600 | HANDLE h; |
| 601 | snprintf(pat, sizeof pat, "%.511s\\*", roots[0]); |
| 602 | h = FindFirstFileA(pat, &fd); |
| 603 | if (h != INVALID_HANDLE_VALUE) { |
| 604 | do { |
| 605 | char spath[1024]; |
| 606 | if (fd.cFileName[0] == '.' || !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; |
| 607 | snprintf(spath, sizeof spath, "%.511s\\%.200s\\slots.json", roots[0], fd.cFileName); |
| 608 | if (emitted++) fputc(',', stdout); |
| 609 | fputs("{\"name\":", stdout); json_print_str(fd.cFileName); |
| 610 | fputs(",\"sid\":", stdout); json_print_str(fd.cFileName); |
| 611 | fputs(",\"has_slots\":", stdout); fputs(file_exists(spath) ? "true" : "false", stdout); |
| 612 | fputc('}', stdout); |
| 613 | } while (FindNextFileA(h, &fd) && emitted < MAX_SESSIONS); |
| 614 | FindClose(h); |
| 615 | } |
| 616 | #else |
| 617 | DIR *d = opendir(roots[0]); |
| 618 | struct dirent *de; |
| 619 | if (d) { |
| 620 | while ((de = readdir(d)) != NULL && emitted < MAX_SESSIONS) { |
| 621 | char cand[900], spath[1024]; |
| 622 | if (de->d_name[0] == '.') continue; |
| 623 | snprintf(cand, sizeof cand, "%.511s/%.200s", roots[0], de->d_name); |
| 624 | if (!is_dir(cand)) continue; |
| 625 | snprintf(spath, sizeof spath, "%.899s/slots.json", cand); |
| 626 | if (emitted++) fputc(',', stdout); |
| 627 | fputs("{\"name\":", stdout); json_print_str(de->d_name); |
| 628 | fputs(",\"sid\":", stdout); json_print_str(de->d_name); |
| 629 | fputs(",\"has_slots\":", stdout); fputs(file_exists(spath) ? "true" : "false", stdout); |
| 630 | fputc('}', stdout); |
| 631 | } |
| 632 | closedir(d); |
| 633 | } |
| 634 | #endif |
| 635 | } |
| 636 | } |
| 637 | fputs("]}\n", stdout); |
| 638 | } |
| 639 | |
| 640 | /* ------------------------------------------------------------------ */ |
| 641 | /* Action: slots */ |
| 642 | /* ------------------------------------------------------------------ */ |
| 643 | |
| 644 | static void reply_json_err(const char *status, const char *msg, const char *url) |
| 645 | { |
| 646 | printf("Status: %s\r\nContent-Type: application/json; charset=utf-8\r\n\r\n", status); |
| 647 | fputs("{\"ok\":false,\"error\":", stdout); |
| 648 | json_print_str(msg); |
| 649 | if (url && *url) { |
| 650 | fputs(",\"url\":", stdout); |
| 651 | json_print_str(url); |
| 652 | } |
| 653 | fputs("}\n", stdout); |
| 654 | } |
| 655 | |
| 656 | static void handle_slots_url(const char *raw_url) |
| 657 | { |
| 658 | char target[640], cmd[1024]; |
| 659 | size_t tl; |
| 660 | FILE *p; |
| 661 | char *buf; |
| 662 | size_t len = 0; |
| 663 | int rc; |
| 664 | |
| 665 | if (!url_ok(raw_url)) { |
| 666 | reply_json_err("400 Bad Request", "invalid url (must be http:// or https://)", raw_url); |
| 667 | return; |
| 668 | } |
| 669 | str_copy(target, sizeof target, raw_url); |
| 670 | tl = strlen(target); |
| 671 | while (tl > 0 && target[tl - 1] == '/') target[--tl] = '\0'; |
| 672 | if (tl < 6 || strcmp(target + tl - 6, "/slots") != 0) { |
| 673 | if (tl >= 3 && strcmp(target + tl - 3, "/v1") == 0) target[tl - 3] = '\0'; |
| 674 | snprintf(target + strlen(target), sizeof target - strlen(target), "/slots"); |
| 675 | } |
| 676 | |
| 677 | #ifdef _WIN32 |
| 678 | snprintf(cmd, sizeof cmd, "curl.exe -sk --max-time 4 \"%s\" 2>NUL", target); |
| 679 | #else |
| 680 | snprintf(cmd, sizeof cmd, "curl -sk --max-time 4 '%s' 2>/dev/null", target); |
| 681 | #endif |
| 682 | p = sx_popen(cmd, "r"); |
| 683 | if (!p) { |
| 684 | reply_json_err("502 Bad Gateway", "failed to invoke curl", target); |
| 685 | return; |
| 686 | } |
| 687 | buf = read_pipe_all(p, &len); |
| 688 | rc = sx_pclose(p); |
| 689 | while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r' || buf[len - 1] == ' ' || buf[len - 1] == '\t')) |
| 690 | buf[--len] = '\0'; |
| 691 | |
| 692 | if (rc != 0 || !buf || len < 2) { |
| 693 | free(buf); |
| 694 | reply_json_err("502 Bad Gateway", "unable to fetch /slots from llama.cpp server", target); |
| 695 | return; |
| 696 | } |
| 697 | |
| 698 | if (buf[0] == '[') { |
| 699 | printf("Content-Type: application/json; charset=utf-8\r\n\r\n" |
| 700 | "{\"ok\":true,\"source\":\"query\",\"url\":"); |
| 701 | json_print_str(target); |
| 702 | printf(",\"updated_epoch\":%lld,\"slots\":%s}\n", (long long)time(NULL), buf); |
| 703 | } else if (buf[0] == '{') { |
| 704 | fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout); |
| 705 | fwrite(buf, 1, len, stdout); |
| 706 | fputc('\n', stdout); |
| 707 | } else { |
| 708 | reply_json_err("502 Bad Gateway", "unexpected non-JSON response from /slots", target); |
| 709 | } |
| 710 | free(buf); |
| 711 | } |
| 712 | |
| 713 | static void handle_slots(const char *qs) |
| 714 | { |
| 715 | char id[256] = {0}, url_q[512] = {0}; |
| 716 | char sdir[1024] = {0}, rid[160] = {0}, spath[1280]; |
| 717 | char *buf; |
| 718 | size_t len = 0; |
| 719 | |
| 720 | get_query_val(qs, "id", id, sizeof id); |
| 721 | get_query_val(qs, "url", url_q, sizeof url_q); |
| 722 | |
| 723 | if (url_q[0]) { |
| 724 | handle_slots_url(url_q); |
| 725 | return; |
| 726 | } |
| 727 | |
| 728 | if (!id[0] || !safe_id(id)) { |
| 729 | reply_json_err("400 Bad Request", "select a session or enter a llama.cpp URL", NULL); |
| 730 | return; |
| 731 | } |
| 732 | |
| 733 | if (!resolve_session_dir(id, sdir, sizeof sdir, rid, sizeof rid)) { |
| 734 | reply_json_err("404 Not Found", "session not found on this node", NULL); |
| 735 | return; |
| 736 | } |
| 737 | |
| 738 | snprintf(spath, sizeof spath, "%.1023s%cslots.json", sdir, SX_SEP); |
| 739 | buf = read_file_all(spath, &len); |
| 740 | if (!buf || len < 2) { |
| 741 | free(buf); |
| 742 | reply_json_err("404 Not Found", "no slots.json for this session (not using llama.cpp slots publisher)", NULL); |
| 743 | return; |
| 744 | } |
| 745 | |
| 746 | fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout); |
| 747 | fwrite(buf, 1, len, stdout); |
| 748 | if (buf[len - 1] != '\n') fputc('\n', stdout); |
| 749 | free(buf); |
| 750 | } |
| 751 | |
| 752 | /* ------------------------------------------------------------------ */ |
| 753 | /* HTML UI */ |
| 754 | /* ------------------------------------------------------------------ */ |
| 755 | |
| 756 | static const char *UI_CSS = |
| 757 | "body{font-family:var(--font);font-size:13px;line-height:1.4;min-height:100vh;display:flex;flex-direction:column}\n" |
| 758 | ".wrap{max-width:680px;width:100%;margin:0 auto;padding:14px 16px 24px;display:flex;flex-direction:column;gap:10px}\n" |
| 759 | "html.embedded .wrap{max-width:none;padding:10px 12px 14px;gap:8px}\n" |
| 760 | ".hdr{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}\n" |
| 761 | ".hdr-l{display:flex;align-items:center;gap:8px;min-width:0;flex:1}\n" |
| 762 | ".dot{width:8px;height:8px;border-radius:50%;background:var(--gray);flex-shrink:0;transition:background .25s var(--ease)}\n" |
| 763 | ".dot.live{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.18)}\n" |
| 764 | ".dot.stale{background:var(--orange);box-shadow:0 0 0 3px rgba(255,159,10,.18)}\n" |
| 765 | ".dot.err{background:var(--red);box-shadow:0 0 0 3px rgba(255,69,58,.18)}\n" |
| 766 | ".title{font-size:14px;font-weight:700;letter-spacing:-.015em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" |
| 767 | ".badge{font-size:10px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;padding:2px 7px;border-radius:980px;background:var(--surface-2);border:1px solid var(--line);color:var(--text-2);flex-shrink:0}\n" |
| 768 | ".badge.dspark{background:rgba(10,132,255,.12);border-color:rgba(10,132,255,.28);color:var(--blue)}\n" |
| 769 | ".bar{display:flex;align-items:center;gap:6px;flex-wrap:wrap}\n" |
| 770 | ".ctl{height:30px;background:var(--input-bg);border:1px solid var(--line);border-radius:9px;color:var(--text);padding:0 9px;font-size:12px;font-family:inherit;outline:0;min-width:0}\n" |
| 771 | ".ctl:focus{border-color:var(--blue)}\n" |
| 772 | "select.ctl{flex:0 1 180px;cursor:pointer}\n" |
| 773 | "input.ctl{flex:1 1 170px;font-family:var(--mono);font-size:11px}\n" |
| 774 | ".btn{height:30px;padding:0 10px;border-radius:9px;border:1px solid var(--line);background:var(--surface-2);color:var(--text);font-size:12px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:4px;white-space:nowrap}\n" |
| 775 | ".btn:hover{border-color:var(--line-2);background:var(--surface-hover)}\n" |
| 776 | ".btn.pri{background:var(--blue);border-color:transparent;color:#fff}\n" |
| 777 | ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;padding:12px 14px;display:flex;flex-direction:column;gap:4px;font-family:var(--mono);font-size:12px;line-height:1.45;transition:opacity .25s var(--ease)}\n" |
| 778 | ".card.stale{opacity:.6}\n" |
| 779 | ".sl-slot{padding:6px 0;border-bottom:1px solid var(--line);display:flex;flex-direction:column;gap:2px}\n" |
| 780 | ".sl-slot:first-child{padding-top:0}\n" |
| 781 | ".sl-slot:last-child{border-bottom:0;padding-bottom:0}\n" |
| 782 | ".sl-row{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n" |
| 783 | ".sl-idle{color:var(--text-2);display:flex;justify-content:space-between;gap:8px}\n" |
| 784 | ".sl-act-head{font-weight:700;display:flex;align-items:center;gap:6px;flex-wrap:wrap}\n" |
| 785 | ".sl-gen{color:var(--green)}\n" |
| 786 | ".sl-detail{color:var(--text-2);padding-left:14px;font-size:11.5px}\n" |
| 787 | ".sl-bar{height:4px;border-radius:2px;background:var(--line);overflow:hidden;margin:3px 0 1px 14px}\n" |
| 788 | ".sl-bar>i{display:block;height:100%;background:var(--blue);transition:width .25s var(--ease)}\n" |
| 789 | ".sl-bar.warn>i{background:var(--orange)}\n" |
| 790 | ".sl-bar.full>i{background:var(--red)}\n" |
| 791 | ".sl-msg{color:var(--text-2);white-space:normal;font-family:var(--font);font-size:12.5px}\n" |
| 792 | ".sl-err{color:var(--red);white-space:normal;font-family:var(--font);font-size:12.5px}\n" |
| 793 | ".meta-foot{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:var(--text-2);font-family:var(--mono);flex-wrap:wrap}\n"; |
| 794 | |
| 795 | static const char *UI_BODY = |
| 796 | "<div class='wrap'>\n" |
| 797 | " <div class='hdr'>\n" |
| 798 | " <div class='hdr-l'>\n" |
| 799 | " <span class='dot' id='dot'></span>\n" |
| 800 | " <span class='title' id='title'>Slots Monitor</span>\n" |
| 801 | " <span class='badge dspark' id='dsparkBadge' style='display:none'>DSpark</span>\n" |
| 802 | " <span class='badge' id='srcBadge' style='display:none'></span>\n" |
| 803 | " </div>\n" |
| 804 | " <button class='btn' id='btnRefresh' type='button'>Refresh</button>\n" |
| 805 | " <button class='btn embed-hide' id='themeToggle' type='button'>Theme</button>\n" |
| 806 | " </div>\n" |
| 807 | " <div class='bar'>\n" |
| 808 | " <select class='ctl' id='sessSel' aria-label='Session'><option value=''>Active session…</option></select>\n" |
| 809 | " <input class='ctl' id='urlIn' type='text' placeholder='Optional llama.cpp URL (http://host:port)' autocomplete='off'>\n" |
| 810 | " <button class='btn pri' id='btnGo' type='button'>Probe</button>\n" |
| 811 | " </div>\n" |
| 812 | " <div class='card' id='card'><div class='sl-msg'>Connecting…</div></div>\n" |
| 813 | " <div class='meta-foot'><span id='srcLbl'></span><span id='tsLbl'></span></div>\n" |
| 814 | "</div>\n" |
| 815 | "<script>\n" |
| 816 | "(function(){\n" |
| 817 | " var sp = new URLSearchParams(location.search);\n" |
| 818 | " var curSid = sp.get('id') || '';\n" |
| 819 | " var curUrl = sp.get('url') || '';\n" |
| 820 | " var busy = false;\n" |
| 821 | " var $=function(id){return document.getElementById(id);};\n" |
| 822 | " function apiUrl(extra){\n" |
| 823 | " var out = new URLSearchParams();\n" |
| 824 | " ['plugin','node','pwd'].forEach(function(k){ if(sp.get(k)) out.set(k, sp.get(k)); });\n" |
| 825 | " Object.keys(extra||{}).forEach(function(k){\n" |
| 826 | " if(extra[k]!==undefined && extra[k]!==null && extra[k]!=='') out.set(k, String(extra[k]));\n" |
| 827 | " });\n" |
| 828 | " return location.pathname + '?' + out.toString();\n" |
| 829 | " }\n" |
| 830 | " function fmtCtx(n){n=Number(n)||0;if(n>=1024)return Math.round(n/1024)+'K';return String(n);}\n" |
| 831 | " function fmtNum(n){return (Number(n)||0).toLocaleString('en-US');}\n" |
| 832 | " function normSlot(s){\n" |
| 833 | " /* Handle both scorpiox slots.json and raw llama-server /slots schema */\n" |
| 834 | " var nt = (s.next_token && s.next_token[0]) ? s.next_token[0] : {};\n" |
| 835 | " return {\n" |
| 836 | " id: s.id,\n" |
| 837 | " is_processing: !!s.is_processing,\n" |
| 838 | " n_ctx: Number(s.n_ctx || 0),\n" |
| 839 | " tg: Number(s.tg != null ? s.tg : (s.timings && s.timings.predicted_per_second) || 0),\n" |
| 840 | " pp: Number(s.pp != null ? s.pp : (s.timings && s.timings.prompt_per_second) || 0),\n" |
| 841 | " n_prompt_tokens: Number(s.n_prompt_tokens != null ? s.n_prompt_tokens : (s.n_past || 0)),\n" |
| 842 | " n_prompt_tokens_processed: Number(s.n_prompt_tokens_processed != null ? s.n_prompt_tokens_processed : 0),\n" |
| 843 | " n_decoded: Number(s.n_decoded != null ? s.n_decoded : (nt.n_decoded || 0))\n" |
| 844 | " };\n" |
| 845 | " }\n" |
| 846 | " function render(d){\n" |
| 847 | " var card=$('card'), dot=$('dot'), title=$('title'), ds=$('dsparkBadge'), badge=$('srcBadge');\n" |
| 848 | " card.innerHTML='';\n" |
| 849 | " if(!d || d.error || !Array.isArray(d.slots) || !d.slots.length){\n" |
| 850 | " dot.className = 'dot ' + (d && d.error ? 'err' : '');\n" |
| 851 | " title.textContent = 'Slots Monitor';\n" |
| 852 | " ds.style.display = 'none';\n" |
| 853 | " card.classList.remove('stale');\n" |
| 854 | " var m = document.createElement('div');\n" |
| 855 | " m.className = (d && d.error) ? 'sl-err' : 'sl-msg';\n" |
| 856 | " m.textContent = (d && d.error) ? String(d.error) : 'No slots data';\n" |
| 857 | " card.appendChild(m);\n" |
| 858 | " return;\n" |
| 859 | " }\n" |
| 860 | " var stale = (typeof d.updated_epoch==='number') && (Math.floor(Date.now()/1000) - d.updated_epoch > 15);\n" |
| 861 | " dot.className = 'dot ' + (stale ? 'stale' : 'live');\n" |
| 862 | " card.classList.toggle('stale', stale);\n" |
| 863 | " title.textContent = 'Slots (' + d.slots.length + ')' + (stale ? ' \\u00b7 stale' : '');\n" |
| 864 | " ds.style.display = d.dspark ? '' : 'none';\n" |
| 865 | " badge.style.display = '';\n" |
| 866 | " badge.textContent = curUrl ? 'URL' : (curSid || 'session');\n" |
| 867 | " d.slots.forEach(function(raw){\n" |
| 868 | " if(!raw) return;\n" |
| 869 | " var s = normSlot(raw);\n" |
| 870 | " var box = document.createElement('div'); box.className = 'sl-slot';\n" |
| 871 | " if(!s.is_processing){\n" |
| 872 | " var r = document.createElement('div'); r.className = 'sl-row sl-idle';\n" |
| 873 | " var l = document.createElement('span'); l.textContent = '#' + s.id + ' idle';\n" |
| 874 | " var rt = document.createElement('span'); rt.textContent = fmtCtx(s.n_ctx) + ' ctx';\n" |
| 875 | " r.appendChild(l); r.appendChild(rt); box.appendChild(r);\n" |
| 876 | " }else{\n" |
| 877 | " var h = document.createElement('div'); h.className = 'sl-row sl-act-head';\n" |
| 878 | " h.innerHTML = '<span>#' + s.id + '</span><span class=\"sl-gen\">\\u25cf gen</span><span>tg: ' + s.tg.toFixed(1) + ' t/s</span><span>pp: ' + Math.round(s.pp) + ' t/s</span>';\n" |
| 879 | " box.appendChild(h);\n" |
| 880 | " var cached = Math.max(0, s.n_prompt_tokens - s.n_prompt_tokens_processed);\n" |
| 881 | " var cachePct = s.n_prompt_tokens > 0 ? (cached / s.n_prompt_tokens * 100) : 0;\n" |
| 882 | " var d1 = document.createElement('div'); d1.className = 'sl-row sl-detail';\n" |
| 883 | " d1.textContent = 'prompt: ' + fmtNum(s.n_prompt_tokens) + ' cache: ' + cachePct.toFixed(1) + '%';\n" |
| 884 | " box.appendChild(d1);\n" |
| 885 | " var used = s.n_prompt_tokens + s.n_decoded;\n" |
| 886 | " var remain = Math.max(0, s.n_ctx - used);\n" |
| 887 | " var d2 = document.createElement('div'); d2.className = 'sl-row sl-detail';\n" |
| 888 | " d2.textContent = 'decoded: ' + fmtNum(s.n_decoded) + ' remain: ' + fmtNum(remain) + ' / ' + fmtCtx(s.n_ctx);\n" |
| 889 | " box.appendChild(d2);\n" |
| 890 | " if(s.n_ctx > 0){\n" |
| 891 | " var pct = Math.min(100, Math.round(used / s.n_ctx * 100));\n" |
| 892 | " var bar = document.createElement('div'); bar.className = 'sl-bar' + (pct >= 90 ? ' full' : pct >= 70 ? ' warn' : '');\n" |
| 893 | " var fi = document.createElement('i'); fi.style.width = pct + '%'; bar.appendChild(fi); box.appendChild(bar);\n" |
| 894 | " }\n" |
| 895 | " }\n" |
| 896 | " card.appendChild(box);\n" |
| 897 | " });\n" |
| 898 | " $('srcLbl').textContent = d.url || (curSid ? ('session: ' + curSid) : '');\n" |
| 899 | " $('tsLbl').textContent = 'updated ' + new Date().toLocaleTimeString();\n" |
| 900 | " }\n" |
| 901 | " async function poll(){\n" |
| 902 | " if(busy) return;\n" |
| 903 | " if(!curUrl && !curSid){ render({error:'Pick a session above or enter a llama.cpp server URL.'}); return; }\n" |
| 904 | " busy = true;\n" |
| 905 | " try{\n" |
| 906 | " var q = {action:'slots'};\n" |
| 907 | " if(curUrl) q.url = curUrl; else q.id = curSid;\n" |
| 908 | " var r = await fetch(apiUrl(q));\n" |
| 909 | " var d = null; try{ d = await r.json(); }catch(e){}\n" |
| 910 | " render(d || {error:'HTTP ' + r.status});\n" |
| 911 | " }catch(e){\n" |
| 912 | " render({error:'Network error polling slots'});\n" |
| 913 | " }finally{ busy = false; }\n" |
| 914 | " }\n" |
| 915 | " async function loadSessions(){\n" |
| 916 | " try{\n" |
| 917 | " var r = await fetch(apiUrl({action:'sessions'}));\n" |
| 918 | " var d = await r.json();\n" |
| 919 | " var sel = $('sessSel'); sel.innerHTML = '';\n" |
| 920 | " var list = (d && Array.isArray(d.sessions)) ? d.sessions : [];\n" |
| 921 | " if(!list.length){\n" |
| 922 | " var o = document.createElement('option'); o.value=''; o.textContent='No sessions'; sel.appendChild(o);\n" |
| 923 | " }else{\n" |
| 924 | " var ph = document.createElement('option'); ph.value=''; ph.textContent='Select session\\u2026'; sel.appendChild(ph);\n" |
| 925 | " list.forEach(function(s){\n" |
| 926 | " var o = document.createElement('option');\n" |
| 927 | " o.value = s.name; o.textContent = s.name + (s.has_slots ? ' (slots)' : '');\n" |
| 928 | " if(curSid && s.name === curSid) o.selected = true;\n" |
| 929 | " sel.appendChild(o);\n" |
| 930 | " });\n" |
| 931 | " if(!curSid && !curUrl){\n" |
| 932 | " var pick = list.find(function(s){return s.has_slots;}) || list[0];\n" |
| 933 | " if(pick){ curSid = pick.name; sel.value = curSid; }\n" |
| 934 | " }\n" |
| 935 | " }\n" |
| 936 | " }catch(e){}\n" |
| 937 | " }\n" |
| 938 | " $('sessSel').onchange = function(){ curSid = this.value; curUrl = ''; $('urlIn').value = ''; poll(); };\n" |
| 939 | " $('btnGo').onclick = function(){ curUrl = $('urlIn').value.trim(); poll(); };\n" |
| 940 | " $('urlIn').onkeydown = function(e){ if(e.key==='Enter'){ curUrl = this.value.trim(); poll(); } };\n" |
| 941 | " $('btnRefresh').onclick = function(){ poll(); };\n" |
| 942 | " var tt = $('themeToggle');\n" |
| 943 | " if(tt) tt.onclick = function(){\n" |
| 944 | " var c = document.documentElement.getAttribute('data-theme')==='light'?'dark':'light';\n" |
| 945 | " document.documentElement.setAttribute('data-theme', c);\n" |
| 946 | " try{localStorage.setItem('bot_theme', c);}catch(e){}\n" |
| 947 | " };\n" |
| 948 | " if(curUrl) $('urlIn').value = curUrl;\n" |
| 949 | " document.addEventListener('visibilitychange', function(){ if(document.visibilityState==='visible') poll(); });\n" |
| 950 | " loadSessions().then(function(){\n" |
| 951 | " poll();\n" |
| 952 | " setInterval(function(){ if(document.visibilityState==='visible') poll(); }, 1500);\n" |
| 953 | " });\n" |
| 954 | "})();\n" |
| 955 | "</script>\n"; |
| 956 | |
| 957 | static void handle_html(void) |
| 958 | { |
| 959 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 960 | "Cache-Control: no-cache, no-store, must-revalidate\r\n\r\n" |
| 961 | "<!DOCTYPE html><html lang='en'><head>\n" |
| 962 | "<meta charset='utf-8'>\n" |
| 963 | "<meta name='viewport' content='width=device-width,initial-scale=1'>\n" |
| 964 | "<title>Slots Monitor · SCORPIOX BOT</title>\n", stdout); |
| 965 | fputs(SX_BOT_THEME_PREPAINT, stdout); |
| 966 | fputs("<style>\n", stdout); |
| 967 | fputs(SX_BOT_THEME_TOKENS, stdout); |
| 968 | fputs("\n", stdout); |
| 969 | fputs(UI_CSS, stdout); |
| 970 | fputs("</style></head><body>\n", stdout); |
| 971 | fputs(UI_BODY, stdout); |
| 972 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 973 | fputs("</body></html>\n", stdout); |
| 974 | } |
| 975 | |
| 976 | int main(int argc, char **argv) |
| 977 | { |
| 978 | const char *qs; |
| 979 | char action[64] = {0}, fmt[32] = {0}; |
| 980 | |
| 981 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { |
| 982 | fputs("{\"name\":\"slots\",\"desc\":\"llama.cpp slots\",\"kind\":\"ui\",\"version\":\"" PLUGIN_VERSION "\"}\n", stdout); |
| 983 | return 0; |
| 984 | } |
| 985 | |
| 986 | require_node_auth(); |
| 987 | |
| 988 | qs = getenv("QUERY_STRING"); |
| 989 | get_query_val(qs, "action", action, sizeof action); |
| 990 | get_query_val(qs, "format", fmt, sizeof fmt); |
| 991 | |
| 992 | if (strcmp(action, "sessions") == 0) { |
| 993 | handle_sessions(); |
| 994 | return 0; |
| 995 | } |
| 996 | if (strcmp(action, "slots") == 0 || strcmp(fmt, "json") == 0) { |
| 997 | handle_slots(qs); |
| 998 | return 0; |
| 999 | } |
| 1000 | |
| 1001 | handle_html(); |
| 1002 | return 0; |
| 1003 | } |