/* * plugin_sglang.c -- SCORPIOX BOT open-source SGLang Server Monitor plugin * * Single-binary zero-dependency C99 plugin serving all 3 SCORPIOX BOT modes: * 1. --meta / SX_PLUGIN_META=1 : emits {"name":"sglang","desc":"SGLang metrics",...} * 2. GET ?action=sessions : lists active node sessions + OPENAI_BASE_URL * GET ?action=metrics : polls scorpiox-sglang-metrics for session or ?url= * 3. GET (default) : serves responsive dual-theme HTML UI (?embed=1 ready) * * Security: * - Enforces BOT_PASSWORD via X-Bot-Password, Bearer token, or ?pwd= * - Strictly validates session IDs and http(s):// URLs before command execution * - Read-only telemetry only (scorpiox-sglang-metrics issues GET /metrics + /get_server_info) * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #ifndef _WIN32 #define _POSIX_C_SOURCE 200809L #define _DEFAULT_SOURCE #endif #include #include #include #include #include #include #ifdef _WIN32 #include #include #define SX_SEP '\\' #define sx_popen _popen #define sx_pclose _pclose #define sx_access _access #define sx_strncasecmp _strnicmp #else #include #include #include #define SX_SEP '/' #define sx_popen popen #define sx_pclose pclose #define sx_access access #define sx_strncasecmp strncasecmp #endif #include "bot_theme_plugin.h" #define PLUGIN_VERSION "1.0.1" #define CACHE_SECS 4 #define CACHE_NAME "sglang_metrics.json" #define MAX_SESSIONS 128 /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ static void str_copy(char *dst, size_t dstsz, const char *src) { size_t n; if (!dst || dstsz == 0) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= dstsz) n = dstsz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static int hex_val(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static void url_decode(const char *src, char *dst, size_t dstsz) { size_t i = 0; if (!dst || dstsz == 0) return; if (!src) { dst[0] = '\0'; return; } while (*src && i + 1 < dstsz) { if (*src == '%' && src[1] && src[2]) { int hi = hex_val(src[1]), lo = hex_val(src[2]); if (hi >= 0 && lo >= 0) { dst[i++] = (char)((hi << 4) | lo); src += 3; continue; } } if (*src == '+') dst[i++] = ' '; else dst[i++] = *src; src++; } dst[i] = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (out && outsz) out[0] = '\0'; if (!qs || !*qs || !key || !*key || !out || outsz == 0) return 0; klen = strlen(key); p = qs; while (*p) { const char *amp = strchr(p, '&'); size_t len = amp ? (size_t)(amp - p) : strlen(p); if (len > klen && strncmp(p, key, klen) == 0 && p[klen] == '=') { char raw[1024]; size_t vlen = len - klen - 1; if (vlen >= sizeof raw) vlen = sizeof raw - 1; memcpy(raw, p + klen + 1, vlen); raw[vlen] = '\0'; url_decode(raw, out, outsz); return 1; } if (!amp) break; p = amp + 1; } return 0; } static void json_print_str(const char *s) { const unsigned char *p = (const unsigned char *)(s ? s : ""); fputc('"', stdout); for (; *p; p++) { unsigned char c = *p; if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); } else if (c == '\n') fputs("\\n", stdout); else if (c == '\r') fputs("\\r", stdout); else if (c == '\t') fputs("\\t", stdout); else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout); } fputc('"', stdout); } static int safe_id(const char *s) { size_t i; if (!s || !*s) return 0; for (i = 0; s[i]; i++) { unsigned char c = (unsigned char)s[i]; if (i >= 160) return 0; if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == ':') continue; return 0; } if (strstr(s, "..") != NULL) return 0; return 1; } static int url_ok(const char *u) { const char *p; if (!u || !*u || strlen(u) > 512) return 0; if (strncmp(u, "http://", 7) != 0 && strncmp(u, "https://", 8) != 0) return 0; for (p = u; *p; p++) { unsigned char c = (unsigned char)*p; if (isalnum(c) || strchr(":/.-_~%?&#=+@,", (int)c) != NULL) continue; return 0; } return 1; } static int is_dir(const char *p) { struct stat st; if (!p || !*p) return 0; if (stat(p, &st) != 0) return 0; return (st.st_mode & S_IFMT) == S_IFDIR; } static char *read_file_all(const char *path, size_t *len_out) { FILE *f; char *buf; size_t cap = 4096, len = 0, n; if (len_out) *len_out = 0; f = fopen(path, "rb"); if (!f) return NULL; buf = (char *)malloc(cap); if (!buf) { fclose(f); return NULL; } while ((n = fread(buf + len, 1, cap - len - 1, f)) > 0) { len += n; if (cap - len < 512) { char *nb; if (cap > (4 * 1024 * 1024)) break; cap *= 2; nb = (char *)realloc(buf, cap); if (!nb) break; buf = nb; } } fclose(f); buf[len] = '\0'; if (len_out) *len_out = len; return buf; } static char *read_pipe_all(FILE *p, size_t *len_out) { size_t cap = 16384, len = 0, n; char *buf; if (len_out) *len_out = 0; if (!p) return NULL; buf = (char *)malloc(cap); if (!buf) return NULL; while ((n = fread(buf + len, 1, cap - len - 1, p)) > 0) { len += n; if (cap - len < 1024) { char *nb; if (cap > (4 * 1024 * 1024)) break; cap *= 2; nb = (char *)realloc(buf, cap); if (!nb) break; buf = nb; } } buf[len] = '\0'; if (len_out) *len_out = len; return buf; } /* ------------------------------------------------------------------ */ /* Node security */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp, *auth, *ref; char qpwd[128] = {0}; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (sx_strncasecmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; ref = getenv("HTTP_REFERER"); if (ref) { const char *rq = strchr(ref, '?'); if (rq && get_query_val(rq + 1, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; } fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n\r\n" "{\"ok\":false,\"error\":\"unauthorized\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Lightweight JSON string extractor */ /* ------------------------------------------------------------------ */ static int json_extract_str_after(const char *obj, const char *end, const char *key, char *out, size_t outsz) { char pat[128]; const char *p; size_t plen, i = 0; if (out && outsz) out[0] = '\0'; if (!obj || !key || !out || outsz == 0) return 0; snprintf(pat, sizeof pat, "\"%s\"", key); plen = strlen(pat); p = obj; while (p && (!end || p < end)) { const char *hit = strstr(p, pat); const char *q; if (!hit || (end && hit >= end)) return 0; q = hit + plen; while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++; if ((!end || q < end) && *q == ':') { q++; while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++; if ((!end || q < end) && *q == '"') { q++; while ((!end || q < end) && *q && *q != '"' && i + 1 < outsz) { if (*q == '\\' && q[1]) { q++; if (*q == 'n') out[i++] = '\n'; else if (*q == 'r') out[i++] = '\r'; else if (*q == 't') out[i++] = '\t'; else out[i++] = *q; q++; } else { out[i++] = *q++; } } out[i] = '\0'; return 1; } } p = hit + plen; } return 0; } /* ------------------------------------------------------------------ */ /* Binary discovery (scorpiox-tmux & scorpiox-sglang-metrics) */ /* ------------------------------------------------------------------ */ static const char *tmux_bin(void) { static char path[512] = {0}; const char *env; if (path[0]) return path; env = getenv("SCORPIOX_TMUX_BIN"); if (env && *env) { str_copy(path, sizeof path, env); return path; } #ifdef _WIN32 { const char *lad = getenv("LOCALAPPDATA"); if (lad && *lad) { snprintf(path, sizeof path, "%s\\scorpiox\\scorpiox-tmux.exe", lad); if (sx_access(path, 0) == 0) return path; } str_copy(path, sizeof path, "scorpiox-tmux.exe"); } #else if (sx_access("/usr/local/bin/scorpiox-tmux", X_OK) == 0) str_copy(path, sizeof path, "/usr/local/bin/scorpiox-tmux"); else str_copy(path, sizeof path, "scorpiox-tmux"); #endif return path; } static const char *sgm_bin(void) { static char path[1024] = {0}; const char *env, *tb, *base; #ifdef _WIN32 const char *name = "scorpiox-sglang-metrics.exe"; #else const char *name = "scorpiox-sglang-metrics"; #endif if (path[0]) return path; env = getenv("SCORPIOX_SGLANG_METRICS_BIN"); if (env && *env) { str_copy(path, sizeof path, env); return path; } tb = tmux_bin(); base = strstr(tb, "scorpiox-tmux"); if (base && base != tb) { size_t n = (size_t)(base - tb); if (n + strlen(name) + 2 < sizeof path) { memcpy(path, tb, n); snprintf(path + n, sizeof path - n, "%s", name); if (sx_access(path, 0) == 0) return path; } } #ifndef _WIN32 { char cand[256]; snprintf(cand, sizeof cand, "/usr/local/bin/%s", name); if (sx_access(cand, X_OK) == 0) { str_copy(path, sizeof path, cand); return path; } } #endif str_copy(path, sizeof path, name); return path; } /* ------------------------------------------------------------------ */ /* Session discovery & config-snapshot.txt reader */ /* ------------------------------------------------------------------ */ static int snapshot_get(const char *path, const char *key, char *out, size_t outsz) { FILE *f; char line[2048]; size_t klen = strlen(key); int found = 0; if (out && outsz) out[0] = '\0'; f = fopen(path, "rb"); if (!f) return 0; while (fgets(line, sizeof line, f)) { char *p = line; char *val, *end; while (*p == ' ' || *p == '\t') p++; if (*p == '#' || *p == '\0' || *p == '\r' || *p == '\n') continue; if (strncmp(p, "export ", 7) == 0) { p += 7; while (*p == ' ' || *p == '\t') p++; } if (strncmp(p, key, klen) != 0 || p[klen] != '=') continue; val = p + klen + 1; while (*val == ' ' || *val == '\t') val++; end = val + strlen(val); while (end > val && (end[-1] == '\r' || end[-1] == '\n' || end[-1] == ' ' || end[-1] == '\t')) *--end = '\0'; if (end - val >= 2 && ((val[0] == '"' && end[-1] == '"') || (val[0] == '\'' && end[-1] == '\''))) { val++; *--end = '\0'; } if (*val) { str_copy(out, outsz, val); found = 1; } } fclose(f); return found; } static int resolve_session_url(const char *sdir, char *out, size_t outsz) { char snap[1400], ibpath[1400], prof[160] = {0}; char *ib; size_t iblen = 0; if (out && outsz) out[0] = '\0'; if (!sdir || !*sdir) return 0; snprintf(snap, sizeof snap, "%.1279s%cconfig-snapshot.txt", sdir, SX_SEP); if (snapshot_get(snap, "OPENAI_BASE_URL", out, outsz) && out[0]) return 1; /* Fallback: named profile recorded in infobox.json or config-snapshot.txt */ snprintf(ibpath, sizeof ibpath, "%.1279s%cinfobox.json", sdir, SX_SEP); ib = read_file_all(ibpath, &iblen); if (ib && iblen > 2) { json_extract_str_after(ib, ib + iblen, "profile", prof, sizeof prof); } free(ib); if (!prof[0]) snapshot_get(snap, "ACTIVE_PROFILE", prof, sizeof prof); if (!prof[0] || !safe_id(prof)) return 0; { char ppath[1024]; #ifdef _WIN32 const char *up = getenv("USERPROFILE"); const char *lad = getenv("LOCALAPPDATA"); if (up && *up) { snprintf(ppath, sizeof ppath, "%.500s\\.claude\\scorpiox-env\\%.159s.txt", up, prof); if (snapshot_get(ppath, "OPENAI_BASE_URL", out, outsz) && out[0]) return 1; } if (lad && *lad) { snprintf(ppath, sizeof ppath, "%.500s\\scorpiox\\scorpiox-env\\%.159s.txt", lad, prof); if (snapshot_get(ppath, "OPENAI_BASE_URL", out, outsz) && out[0]) return 1; } #else const char *home = getenv("HOME"); if (home && *home) { snprintf(ppath, sizeof ppath, "%.500s/.claude/scorpiox-env/%.159s.txt", home, prof); if (snapshot_get(ppath, "OPENAI_BASE_URL", out, outsz) && out[0]) return 1; snprintf(ppath, sizeof ppath, "%.500s/.scorpiox/scorpiox-env/%.159s.txt", home, prof); if (snapshot_get(ppath, "OPENAI_BASE_URL", out, outsz) && out[0]) return 1; } snprintf(ppath, sizeof ppath, "/usr/local/bin/scorpiox-env/%.159s.txt", prof); if (snapshot_get(ppath, "OPENAI_BASE_URL", out, outsz) && out[0]) return 1; #endif } return 0; } static int pick_newest_session(const char *sessions_dir, char *sid_out, size_t sidsz) { time_t best_t = 0; char best_name[256] = {0}; #ifdef _WIN32 char pat[1200]; WIN32_FIND_DATAA fd; HANDLE h; snprintf(pat, sizeof pat, "%.950s\\*", sessions_dir); h = FindFirstFileA(pat, &fd); if (h == INVALID_HANDLE_VALUE) return 0; do { char probe[1400]; struct stat st; if (fd.cFileName[0] == '.') continue; if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; snprintf(probe, sizeof probe, "%.950s\\%.200s\\infobox.json", sessions_dir, fd.cFileName); if (stat(probe, &st) != 0) { snprintf(probe, sizeof probe, "%.950s\\%.200s\\config-snapshot.txt", sessions_dir, fd.cFileName); if (stat(probe, &st) != 0) { snprintf(probe, sizeof probe, "%.950s\\%.200s\\meta.json", sessions_dir, fd.cFileName); if (stat(probe, &st) != 0) continue; } } if (st.st_mtime >= best_t) { best_t = st.st_mtime; str_copy(best_name, sizeof best_name, fd.cFileName); } } while (FindNextFileA(h, &fd)); FindClose(h); #else DIR *d = opendir(sessions_dir); struct dirent *de; if (!d) return 0; while ((de = readdir(d)) != NULL) { char probe[1400]; struct stat st; if (de->d_name[0] == '.') continue; snprintf(probe, sizeof probe, "%.950s/%.200s/infobox.json", sessions_dir, de->d_name); if (stat(probe, &st) != 0) { snprintf(probe, sizeof probe, "%.950s/%.200s/config-snapshot.txt", sessions_dir, de->d_name); if (stat(probe, &st) != 0) { snprintf(probe, sizeof probe, "%.950s/%.200s/meta.json", sessions_dir, de->d_name); if (stat(probe, &st) != 0) continue; } } if (st.st_mtime >= best_t) { best_t = st.st_mtime; str_copy(best_name, sizeof best_name, de->d_name); } } closedir(d); #endif if (!best_name[0]) return 0; str_copy(sid_out, sidsz, best_name); return 1; } typedef struct { char name[160]; char worktree[768]; char session_dir[1280]; char sid[160]; char base_url[512]; } sess_entry_t; static int list_tmux_sessions(sess_entry_t *out, int max_n) { char cmd[768]; FILE *p; size_t len = 0; char *buf; int count = 0; const char *arr, *cur; if (!out || max_n <= 0) return 0; #ifdef _WIN32 snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>NUL", tmux_bin()); #else snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>/dev/null", tmux_bin()); #endif p = sx_popen(cmd, "r"); if (!p) return 0; buf = read_pipe_all(p, &len); sx_pclose(p); if (!buf || len == 0) { free(buf); return 0; } arr = strstr(buf, "\"sessions\""); if (!arr) { free(buf); return 0; } arr = strchr(arr, '['); if (!arr) { free(buf); return 0; } cur = arr + 1; while (*cur && count < max_n) { const char *ob = strchr(cur, '{'); const char *cb; int depth = 0; const char *q; sess_entry_t *e; if (!ob) break; cb = ob; for (q = ob; *q; q++) { if (*q == '"') { q++; while (*q && *q != '"') { if (*q == '\\' && q[1]) q++; q++; } if (!*q) break; } else if (*q == '{') depth++; else if (*q == '}') { depth--; if (depth == 0) { cb = q; break; } } } if (cb <= ob) break; e = &out[count]; memset(e, 0, sizeof *e); if (json_extract_str_after(ob, cb, "name", e->name, sizeof e->name) && e->name[0]) { json_extract_str_after(ob, cb, "worktree", e->worktree, sizeof e->worktree); if (!e->worktree[0]) { char proj[768] = {0}; if (json_extract_str_after(ob, cb, "project", proj, sizeof proj) && proj[0]) str_copy(e->worktree, sizeof e->worktree, proj); } if (e->worktree[0]) { char sroot[960]; snprintf(sroot, sizeof sroot, "%s%c.scorpiox%csessions", e->worktree, SX_SEP, SX_SEP); if (pick_newest_session(sroot, e->sid, sizeof e->sid)) { snprintf(e->session_dir, sizeof e->session_dir, "%.959s%c%.159s", sroot, SX_SEP, e->sid); resolve_session_url(e->session_dir, e->base_url, sizeof e->base_url); } } count++; } cur = cb + 1; } free(buf); return count; } static int collect_default_roots(char roots[][512], int max_roots) { int n = 0; const char *env; env = getenv("SX_SESSIONS_DIR"); if (env && *env && is_dir(env) && n < max_roots) str_copy(roots[n++], 512, env); #ifdef _WIN32 { const char *lad = getenv("LOCALAPPDATA"); const char *up = getenv("USERPROFILE"); char cand[512]; if (lad && *lad && n < max_roots) { snprintf(cand, sizeof cand, "%s\\scorpiox\\sessions", lad); if (is_dir(cand)) str_copy(roots[n++], 512, cand); } if (up && *up && n < max_roots) { snprintf(cand, sizeof cand, "%s\\.scorpiox\\sessions", up); if (is_dir(cand)) str_copy(roots[n++], 512, cand); } } #else { const char *home = getenv("HOME"); char cand[512]; if (home && *home && n < max_roots) { snprintf(cand, sizeof cand, "%s/.scorpiox/sessions", home); if (is_dir(cand)) str_copy(roots[n++], 512, cand); } if (is_dir("/workspace/.scorpiox/sessions") && n < max_roots) str_copy(roots[n++], 512, "/workspace/.scorpiox/sessions"); } #endif return n; } static int resolve_session_dir(const char *id, char *dir_out, size_t dirsz, char *sid_out, size_t sidsz) { char roots[8][512]; int nroots, i; sess_entry_t *list; int n; if (dir_out && dirsz) dir_out[0] = '\0'; if (sid_out && sidsz) sid_out[0] = '\0'; if (!id || !*id || !safe_id(id)) return 0; /* 1. Direct folder match inside SX_SESSIONS_DIR / default session roots */ nroots = collect_default_roots(roots, 8); for (i = 0; i < nroots; i++) { char cand[1024]; snprintf(cand, sizeof cand, "%.511s%c%.255s", roots[i], SX_SEP, id); if (is_dir(cand)) { str_copy(dir_out, dirsz, cand); str_copy(sid_out, sidsz, id); return 1; } } /* 2. Active tmux sessions via scorpiox-tmux --list --output-json */ list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list); if (list) { n = list_tmux_sessions(list, MAX_SESSIONS); for (i = 0; i < n; i++) { if (strcmp(list[i].name, id) == 0 && list[i].session_dir[0]) { str_copy(dir_out, dirsz, list[i].session_dir); str_copy(sid_out, sidsz, list[i].sid); free(list); return 1; } } for (i = 0; i < n; i++) { if (strstr(list[i].name, id) != NULL && list[i].session_dir[0]) { str_copy(dir_out, dirsz, list[i].session_dir); str_copy(sid_out, sidsz, list[i].sid); free(list); return 1; } } free(list); } #ifndef _WIN32 /* 3. Common workspace/codebase fallback (/codebases/ or /codebases/.worktrees/) */ { char cand[640], sid[160]; snprintf(cand, sizeof cand, "/codebases/.worktrees/%.255s/.scorpiox/sessions", id); if (pick_newest_session(cand, sid, sizeof sid)) { snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid); str_copy(sid_out, sidsz, sid); return 1; } snprintf(cand, sizeof cand, "/codebases/%.255s/.scorpiox/sessions", id); if (pick_newest_session(cand, sid, sizeof sid)) { snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid); str_copy(sid_out, sidsz, sid); return 1; } } #endif return 0; } /* ------------------------------------------------------------------ */ /* Action: sessions */ /* ------------------------------------------------------------------ */ static void handle_sessions(void) { sess_entry_t *list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list); int n = 0, i, emitted = 0; fputs("Content-Type: application/json; charset=utf-8\r\n\r\n{\"ok\":true,\"sessions\":[", stdout); if (list) { n = list_tmux_sessions(list, MAX_SESSIONS); for (i = 0; i < n; i++) { if (emitted++) fputc(',', stdout); fputs("{\"name\":", stdout); json_print_str(list[i].name); fputs(",\"sid\":", stdout); json_print_str(list[i].sid); fputs(",\"url\":", stdout); json_print_str(list[i].base_url); fputs(",\"has_url\":", stdout); fputs(list[i].base_url[0] ? "true" : "false", stdout); fputc('}', stdout); } free(list); } /* Fallback: if no tmux sessions found, enumerate SX_SESSIONS_DIR folders */ if (emitted == 0) { char roots[4][512]; int nr = collect_default_roots(roots, 4); if (nr > 0) { #ifdef _WIN32 char pat[600]; WIN32_FIND_DATAA fd; HANDLE h; snprintf(pat, sizeof pat, "%s\\*", roots[0]); h = FindFirstFileA(pat, &fd); if (h != INVALID_HANDLE_VALUE) { do { char snap[1024], burl[512] = {0}; if (fd.cFileName[0] == '.' || !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; snprintf(snap, sizeof snap, "%s\\%s\\config-snapshot.txt", roots[0], fd.cFileName); snapshot_get(snap, "OPENAI_BASE_URL", burl, sizeof burl); if (emitted++) fputc(',', stdout); fputs("{\"name\":", stdout); json_print_str(fd.cFileName); fputs(",\"sid\":", stdout); json_print_str(fd.cFileName); fputs(",\"url\":", stdout); json_print_str(burl); fputs(",\"has_url\":", stdout); fputs(burl[0] ? "true" : "false", stdout); fputc('}', stdout); } while (FindNextFileA(h, &fd) && emitted < MAX_SESSIONS); FindClose(h); } #else DIR *d = opendir(roots[0]); struct dirent *de; if (d) { while ((de = readdir(d)) != NULL && emitted < MAX_SESSIONS) { char cand[1024], burl[512] = {0}; if (de->d_name[0] == '.') continue; snprintf(cand, sizeof cand, "%.511s/%.200s", roots[0], de->d_name); if (!is_dir(cand)) continue; resolve_session_url(cand, burl, sizeof burl); fputs("{\"name\":", stdout); json_print_str(de->d_name); fputs(",\"sid\":", stdout); json_print_str(de->d_name); fputs(",\"url\":", stdout); json_print_str(burl); fputs(",\"has_url\":", stdout); fputs(burl[0] ? "true" : "false", stdout); fputc('}', stdout); } closedir(d); } #endif } } fputs("]}\n", stdout); } /* ------------------------------------------------------------------ */ /* Action: metrics */ /* ------------------------------------------------------------------ */ static void reply_json_err(const char *status, const char *msg, const char *url) { printf("Status: %s\r\nContent-Type: application/json; charset=utf-8\r\n\r\n", status); fputs("{\"ok\":false,\"error\":", stdout); json_print_str(msg); if (url && *url) { fputs(",\"url\":", stdout); json_print_str(url); } fputs("}\n", stdout); } static void strip_url_v1(const char *in, char *out, size_t outsz) { size_t wl; str_copy(out, outsz, in); wl = strlen(out); while (wl > 0 && out[wl - 1] == '/') out[--wl] = '\0'; if (wl >= 3 && strcmp(out + wl - 3, "/v1") == 0) out[wl - 3] = '\0'; } static void handle_metrics(const char *qs) { char id[256] = {0}, url_q[512] = {0}, fresh[16] = {0}; char sdir[1024] = {0}, rid[160] = {0}, base[512] = {0}; const char *source = "session"; char cache[1280] = {0}; int use_cache = 0; char cmd[2048]; FILE *p; char *out = NULL; size_t len = 0; int rc; char *last_brace; get_query_val(qs, "id", id, sizeof id); get_query_val(qs, "url", url_q, sizeof url_q); get_query_val(qs, "fresh", fresh, sizeof fresh); if (url_q[0]) { if (!url_ok(url_q)) { reply_json_err("400 Bad Request", "invalid url (must be http:// or https://)", url_q); return; } str_copy(base, sizeof base, url_q); source = "query"; } else { if (!id[0] || !safe_id(id)) { reply_json_err("400 Bad Request", "select a session or enter an SGLang URL", NULL); return; } if (!resolve_session_dir(id, sdir, sizeof sdir, rid, sizeof rid)) { reply_json_err("404 Not Found", "session not found on this node", NULL); return; } if (!resolve_session_url(sdir, base, sizeof base)) { reply_json_err("404 Not Found", "session has no OPENAI_BASE_URL (not an OpenAI-compatible provider)", NULL); return; } if (!url_ok(base)) { reply_json_err("400 Bad Request", "session OPENAI_BASE_URL is not usable", base); return; } snprintf(cache, sizeof cache, "%s%c%s", sdir, SX_SEP, CACHE_NAME); use_cache = (strcmp(fresh, "1") != 0); } if (use_cache && cache[0]) { struct stat st; if (stat(cache, &st) == 0 && (time(NULL) - st.st_mtime) < CACHE_SECS) { size_t clen = 0; char *cbuf = read_file_all(cache, &clen); if (cbuf && clen > 2) { char cached_url[512] = {0}, want_url[512] = {0}; strip_url_v1(base, want_url, sizeof want_url); if (json_extract_str_after(cbuf, cbuf + clen, "url", cached_url, sizeof cached_url) && strcmp(cached_url, want_url) == 0) { fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout); fwrite(cbuf, 1, clen, stdout); if (cbuf[clen - 1] != '\n') fputc('\n', stdout); free(cbuf); return; } } free(cbuf); } } /* url_ok() guarantees base contains no quotes, spaces, or shell metacharacters. */ #ifdef _WIN32 snprintf(cmd, sizeof cmd, "\"%s\" \"%s\" 2>NUL", sgm_bin(), base); #else snprintf(cmd, sizeof cmd, "\"%s\" '%s' 2>/dev/null", sgm_bin(), base); #endif p = sx_popen(cmd, "r"); if (!p) { reply_json_err("502 Bad Gateway", "failed to run scorpiox-sglang-metrics", base); return; } out = read_pipe_all(p, &len); rc = sx_pclose(p); while (len > 0 && (out[len - 1] == '\n' || out[len - 1] == '\r' || out[len - 1] == ' ' || out[len - 1] == '\t')) out[--len] = '\0'; if (rc != 0 || !out || len < 2 || out[0] != '{' || out[len - 1] != '}') { free(out); reply_json_err("502 Bad Gateway", "no SGLang metrics at this URL (not SGLang, unreachable, or API-key gated)", base); return; } /* Splice ok/updated_epoch/source/session before closing '}' */ last_brace = out + len - 1; *last_brace = '\0'; { size_t extra_cap = len + 512; char *final_json = (char *)malloc(extra_cap); if (!final_json) { free(out); reply_json_err("500 Internal Server Error", "out of memory", base); return; } snprintf(final_json, extra_cap, "%s,\"ok\":true,\"updated_epoch\":%lld,\"source\":\"%s\",\"session\":\"%s\"}\n", out, (long long)time(NULL), source, rid[0] ? rid : id); if (cache[0] && strcmp(source, "session") == 0) { char tmp[1344]; FILE *cf; snprintf(tmp, sizeof tmp, "%s.tmp", cache); cf = fopen(tmp, "wb"); if (cf) { fputs(final_json, cf); fclose(cf); rename(tmp, cache); } } fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout); fputs(final_json, stdout); free(final_json); } free(out); } /* ------------------------------------------------------------------ */ /* HTML UI */ /* ------------------------------------------------------------------ */ static const char *UI_CSS = "body{font-family:var(--font);font-size:13px;line-height:1.4;min-height:100vh;display:flex;flex-direction:column}\n" ".wrap{max-width:680px;width:100%;margin:0 auto;padding:14px 16px 24px;display:flex;flex-direction:column;gap:10px}\n" "html.embedded .wrap{max-width:none;padding:10px 12px 14px;gap:8px}\n" ".hdr{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}\n" ".hdr-l{display:flex;align-items:center;gap:8px;min-width:0;flex:1}\n" ".dot{width:8px;height:8px;border-radius:50%;background:var(--gray);flex-shrink:0;transition:background .25s var(--ease)}\n" ".dot.live{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.18)}\n" ".dot.stale{background:var(--orange);box-shadow:0 0 0 3px rgba(255,159,10,.18)}\n" ".dot.err{background:var(--red);box-shadow:0 0 0 3px rgba(255,69,58,.18)}\n" ".title{font-size:14px;font-weight:700;letter-spacing:-.015em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" ".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" ".bar{display:flex;align-items:center;gap:6px;flex-wrap:wrap}\n" ".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" ".ctl:focus{border-color:var(--blue)}\n" "select.ctl{flex:0 1 180px;cursor:pointer}\n" "input.ctl{flex:1 1 170px;font-family:var(--mono);font-size:11px}\n" ".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" ".btn:hover{border-color:var(--line-2);background:var(--surface-hover)}\n" ".btn.pri{background:var(--blue);border-color:transparent;color:#fff}\n" ".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" ".card.stale{opacity:.6}\n" ".sg-row{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n" ".sg-dim{color:var(--text-2)}\n" ".sg-hot{color:var(--green);font-weight:700}\n" ".sg-bar{height:5px;border-radius:3px;background:var(--line);overflow:hidden;margin:3px 0 5px}\n" ".sg-bar>i{display:block;height:100%;background:var(--green);transition:width .3s var(--ease)}\n" ".sg-bar.warn>i{background:var(--orange)}\n" ".sg-bar.full>i{background:var(--red)}\n" ".sg-msg{color:var(--text-2);white-space:normal;font-family:var(--font);font-size:12.5px}\n" ".sg-err{color:var(--red);white-space:normal;font-family:var(--font);font-size:12.5px}\n" ".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"; static const char *UI_BODY = "
\n" "
\n" "
\n" " \n" " SGLang Monitor\n" " \n" "
\n" " \n" " \n" "
\n" "
\n" " \n" " \n" " \n" "
\n" "
Connecting…
\n" "
\n" "
\n" "\n"; static void handle_html(void) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-cache, no-store, must-revalidate\r\n\r\n" "\n" "\n" "\n" "SGLang Monitor ยท SCORPIOX BOT\n", stdout); fputs(SX_BOT_THEME_PREPAINT, stdout); fputs("\n", stdout); fputs(UI_BODY, stdout); fputs(SX_BOT_THEME_HANDOFF, stdout); fputs("\n", stdout); } int main(int argc, char **argv) { const char *qs; char action[64] = {0}, fmt[32] = {0}; if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { fputs("{\"name\":\"sglang\",\"desc\":\"SGLang metrics\",\"kind\":\"ui\",\"version\":\"" PLUGIN_VERSION "\"}\n", stdout); return 0; } require_node_auth(); qs = getenv("QUERY_STRING"); get_query_val(qs, "action", action, sizeof action); get_query_val(qs, "format", fmt, sizeof fmt); if (strcmp(action, "sessions") == 0) { handle_sessions(); return 0; } if (strcmp(action, "metrics") == 0 || strcmp(fmt, "json") == 0) { handle_metrics(qs); return 0; } handle_html(); return 0; }