feat: initial release of plugin_sglang (v1.0.0)
AuthorSCORPIOX INC <dev@scorpiox.net>
Date2026-11-22 23:41:13
Commit36f686e1
Changed files
.gitignore+8−0■■■■■
LICENSE+21−0■■■■■
Makefile+59−0■■■■■
README.md+21−0■■■■■
build.ps1+45−0■■■■■
plugin.json+12−0■■■■■
src/bot_theme_plugin.h+129−0■■■■■
src/plugin_sglang.c+1118−0■■■■■
tests/run.sh+91−0■■■■■
9 files+1504−0
Diff
.gitignore+8−0■■■■■
11new file mode 100644
index 0000000..377f998
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
1+plugin_sglang
2+plugin_sglang.exe
3+plugin_sglang.musl
4+plugin_sglang.arm64
5+plugin_sglang.macos-*
6+*.o
7+bin/
8+dist/
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+59−0■■■■■
11new file mode 100644
index 0000000..c150a45
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,59 @@
1+# plugin_sglang - SCORPIOX BOT open-source SGLang server metrics monitor
2+#
3+# Targets:
4+# make native build -> ./plugin_sglang
5+# make musl static musl x86_64 -> ./plugin_sglang.musl
6+# make arm64 static aarch64 musl -> ./plugin_sglang.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_sglang.exe
8+# make macos Apple clang (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+
12+CC ?= cc
13+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings
14+MUSL_CC ?= musl-gcc
15+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
16+ARM_CC ?= aarch64-linux-gnu-gcc
17+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
18+WIN_CC ?= x86_64-w64-mingw32-gcc
19+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
20+SRC := src/plugin_sglang.c
21+HDR := src/bot_theme_plugin.h
22+BIN := plugin_sglang
23+EXE := plugin_sglang.exe
24+
25+.PHONY: all native musl arm64 win64 macos test clean help
26+
27+all: native
28+
29+native: $(BIN)
30+
31+$(BIN): $(SRC) $(HDR)
32+ @echo "==> native build ($(CC))"
33+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
34+
35+musl: $(SRC) $(HDR)
36+ @echo "==> static musl build ($(MUSL_CC))"
37+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
38+
39+arm64: $(SRC) $(HDR)
40+ @echo "==> static arm64 build ($(ARM_CC))"
41+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
42+
43+win64: $(SRC) $(HDR)
44+ @echo "==> MinGW-w64 build ($(WIN_CC))"
45+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
46+
47+macos: $(SRC) $(HDR)
48+ @echo "==> Apple clang build"
49+ $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o $(BIN) $(SRC)
50+
51+test: native
52+ @sh tests/run.sh
53+
54+clean:
55+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64
56+ rm -rf bin
57+
58+help:
59+ @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean"
README.md+21−0■■■■■
11new file mode 100644
index 0000000..39eb127
--- /dev/null
+++ b/README.md
@@ -0,0 +1,21 @@
1+# plugin_sglang — SGLang Server Monitor for SCORPIOX BOT
2+
3+Zero-dependency pure C99 dynamic plugin for **SCORPIOX BOT** showing live SGLang inference telemetry for the active session or any custom SGLang server URL.
4+
5+## Features
6+- **Auto-tracks active `/chat` session**: reads `OPENAI_BASE_URL` from the session's `config-snapshot.txt` and polls `scorpiox-sglang-metrics` (cached 4 s per session).
7+- **Works from Hub, Session Cards & Chat**: includes a live session picker and custom SGLang URL override bar.
8+- **Full telemetry**: model name, running/queued/max requests, `tg` / `pp` / `gen` tok/s, KV cache fill bar (`used / total`, `%`, `ctx`), prefix cache hit rate (current & lifetime), speculative decoding (`method`, `len`, `acc %`), latencies (`ITL`, `TTFT`, `queue`), and cumulative token counters.
9+- **Native dual theme**: honors SCORPIOX BOT dark/light theme handoff (`?theme=`, `postMessage('sx-theme')`, `?embed=1`).
10+
11+## Build & Test
12+```sh
13+make
14+make test
15+```
16+
17+## Install
18+Install from **Settings → Plugins → Marketplace** in SCORPIOX BOT, or copy `plugin_sglang` into `~/.scorpiox/plugins/`.
19+
20+## License
21+MIT License — Copyright (c) 2026 SCORPIOX INC
build.ps1+45−0■■■■■
11new file mode 100644
index 0000000..0c21723
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,45 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_sglang
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+
6+$ErrorActionPreference = "Stop"
7+$ScriptDir = $PSScriptRoot
8+Push-Location $ScriptDir
9+try {
10+ $Src = Join-Path $ScriptDir "src\plugin_sglang.c"
11+ $Out = Join-Path $ScriptDir "plugin_sglang.exe"
12+ $Cc = "x86_64-w64-mingw32-gcc"
13+
14+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
15+
16+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
17+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
18+ $Cc = "C:\gcc16\bin\gcc.exe"
19+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
20+ $Cc = "gcc"
21+ } else {
22+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
23+ }
24+ }
25+
26+ Write-Host "==> building plugin_sglang.exe with $Cc"
27+ & $Cc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src
28+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
29+ if (-not (Test-Path $Out)) { throw "build produced no output" }
30+
31+ $bytes = [System.IO.File]::ReadAllBytes($Out)
32+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
33+ throw "output is not a PE executable (missing MZ header)"
34+ }
35+
36+ Write-Host "==> metadata check"
37+ & $Out --meta
38+ if ($LASTEXITCODE -ne 0) { throw "--meta failed" }
39+
40+ $size = (Get-Item $Out).Length
41+ Write-Host ""
42+ Write-Host "Built $Out ($size bytes)"
43+} finally {
44+ Pop-Location
45+}
plugin.json+12−0■■■■■
11new file mode 100644
index 0000000..77120f2
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,12 @@
1+{
2+ "slug": "sglang",
3+ "id": "plugin_sglang",
4+ "title": "SGLang Server Monitor",
5+ "summary": "Live SGLang inference telemetry for SCORPIOX BOT sessions: running/queued requests, generation and prefill tok/s, KV cache fill bar, prefix cache hit rate, speculative decoding acceptance, ITL/TTFT/queue latency and token counters. Auto-tracks the active chat session's OPENAI_BASE_URL or probes any custom SGLang URL.",
6+ "category": "sessions",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_read", "session_store_read", "http_metrics_poll"],
9+ "trust_notice": "Executes native C code on your node. Reads the active session's config-snapshot.txt for OPENAI_BASE_URL and invokes scorpiox-sglang-metrics to issue read-only GET /metrics and GET /get_server_info probes.",
10+ "author": "SCORPIOX INC",
11+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-sglang"
12+}
src/bot_theme_plugin.h+129−0■■■■■
11new file mode 100644
index 0000000..0dd243b
--- /dev/null
+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_sglang.c+1118−0■■■■■
11new file mode 100644
index 0000000..869786f
--- /dev/null
+++ b/src/plugin_sglang.c
@@ -0,0 +1,1118 @@
1+/*
2+ * plugin_sglang.c -- SCORPIOX BOT open-source SGLang Server 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":"sglang","desc":"SGLang metrics",...}
6+ * 2. GET ?action=sessions : lists active node sessions + OPENAI_BASE_URL
7+ * GET ?action=metrics : polls scorpiox-sglang-metrics for session or ?url=
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 before command execution
13+ * - Read-only telemetry only (scorpiox-sglang-metrics issues GET /metrics + /get_server_info)
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 CACHE_SECS 4
52+#define CACHE_NAME "sglang_metrics.json"
53+#define MAX_SESSIONS 128
54+
55+/* ------------------------------------------------------------------ */
56+/* Small utilities */
57+/* ------------------------------------------------------------------ */
58+
59+static void str_copy(char *dst, size_t dstsz, const char *src)
60+{
61+ size_t n;
62+ if (!dst || dstsz == 0) return;
63+ if (!src) { dst[0] = '\0'; return; }
64+ n = strlen(src);
65+ if (n >= dstsz) n = dstsz - 1;
66+ memcpy(dst, src, n);
67+ dst[n] = '\0';
68+}
69+
70+static int hex_val(char c)
71+{
72+ if (c >= '0' && c <= '9') return c - '0';
73+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
74+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
75+ return -1;
76+}
77+
78+static void url_decode(const char *src, char *dst, size_t dstsz)
79+{
80+ size_t i = 0;
81+ if (!dst || dstsz == 0) return;
82+ if (!src) { dst[0] = '\0'; return; }
83+ while (*src && i + 1 < dstsz) {
84+ if (*src == '%' && src[1] && src[2]) {
85+ int hi = hex_val(src[1]), lo = hex_val(src[2]);
86+ if (hi >= 0 && lo >= 0) {
87+ dst[i++] = (char)((hi << 4) | lo);
88+ src += 3;
89+ continue;
90+ }
91+ }
92+ if (*src == '+') dst[i++] = ' ';
93+ else dst[i++] = *src;
94+ src++;
95+ }
96+ dst[i] = '\0';
97+}
98+
99+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
100+{
101+ size_t klen;
102+ const char *p;
103+ if (out && outsz) out[0] = '\0';
104+ if (!qs || !*qs || !key || !*key || !out || outsz == 0) return 0;
105+ klen = strlen(key);
106+ p = qs;
107+ while (*p) {
108+ const char *amp = strchr(p, '&');
109+ size_t len = amp ? (size_t)(amp - p) : strlen(p);
110+ if (len > klen && strncmp(p, key, klen) == 0 && p[klen] == '=') {
111+ char raw[1024];
112+ size_t vlen = len - klen - 1;
113+ if (vlen >= sizeof raw) vlen = sizeof raw - 1;
114+ memcpy(raw, p + klen + 1, vlen);
115+ raw[vlen] = '\0';
116+ url_decode(raw, out, outsz);
117+ return 1;
118+ }
119+ if (!amp) break;
120+ p = amp + 1;
121+ }
122+ return 0;
123+}
124+
125+static void json_print_str(const char *s)
126+{
127+ const unsigned char *p = (const unsigned char *)(s ? s : "");
128+ fputc('"', stdout);
129+ for (; *p; p++) {
130+ unsigned char c = *p;
131+ if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); }
132+ else if (c == '\n') fputs("\\n", stdout);
133+ else if (c == '\r') fputs("\\r", stdout);
134+ else if (c == '\t') fputs("\\t", stdout);
135+ else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout);
136+ }
137+ fputc('"', stdout);
138+}
139+
140+static int safe_id(const char *s)
141+{
142+ size_t i;
143+ if (!s || !*s) return 0;
144+ for (i = 0; s[i]; i++) {
145+ unsigned char c = (unsigned char)s[i];
146+ if (i >= 160) return 0;
147+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == ':') continue;
148+ return 0;
149+ }
150+ if (strstr(s, "..") != NULL) return 0;
151+ return 1;
152+}
153+
154+static int url_ok(const char *u)
155+{
156+ const char *p;
157+ if (!u || !*u || strlen(u) > 512) return 0;
158+ if (strncmp(u, "http://", 7) != 0 && strncmp(u, "https://", 8) != 0) return 0;
159+ for (p = u; *p; p++) {
160+ unsigned char c = (unsigned char)*p;
161+ if (isalnum(c) || strchr(":/.-_~%?&#=+@,", (int)c) != NULL) continue;
162+ return 0;
163+ }
164+ return 1;
165+}
166+
167+static int is_dir(const char *p)
168+{
169+ struct stat st;
170+ if (!p || !*p) return 0;
171+ if (stat(p, &st) != 0) return 0;
172+ return (st.st_mode & S_IFMT) == S_IFDIR;
173+}
174+
175+static char *read_file_all(const char *path, size_t *len_out)
176+{
177+ FILE *f;
178+ char *buf;
179+ size_t cap = 4096, len = 0, n;
180+ if (len_out) *len_out = 0;
181+ f = fopen(path, "rb");
182+ if (!f) return NULL;
183+ buf = (char *)malloc(cap);
184+ if (!buf) { fclose(f); return NULL; }
185+ while ((n = fread(buf + len, 1, cap - len - 1, f)) > 0) {
186+ len += n;
187+ if (cap - len < 512) {
188+ char *nb;
189+ if (cap > (4 * 1024 * 1024)) break;
190+ cap *= 2;
191+ nb = (char *)realloc(buf, cap);
192+ if (!nb) break;
193+ buf = nb;
194+ }
195+ }
196+ fclose(f);
197+ buf[len] = '\0';
198+ if (len_out) *len_out = len;
199+ return buf;
200+}
201+
202+static char *read_pipe_all(FILE *p, size_t *len_out)
203+{
204+ size_t cap = 16384, len = 0, n;
205+ char *buf;
206+ if (len_out) *len_out = 0;
207+ if (!p) return NULL;
208+ buf = (char *)malloc(cap);
209+ if (!buf) return NULL;
210+ while ((n = fread(buf + len, 1, cap - len - 1, p)) > 0) {
211+ len += n;
212+ if (cap - len < 1024) {
213+ char *nb;
214+ if (cap > (4 * 1024 * 1024)) break;
215+ cap *= 2;
216+ nb = (char *)realloc(buf, cap);
217+ if (!nb) break;
218+ buf = nb;
219+ }
220+ }
221+ buf[len] = '\0';
222+ if (len_out) *len_out = len;
223+ return buf;
224+}
225+
226+/* ------------------------------------------------------------------ */
227+/* Node security */
228+/* ------------------------------------------------------------------ */
229+
230+static void require_node_auth(void)
231+{
232+ const char *np = getenv("BOT_PASSWORD");
233+ const char *xp, *auth, *ref;
234+ char qpwd[128] = {0};
235+
236+ if (!np || !*np) return;
237+
238+ xp = getenv("HTTP_X_BOT_PASSWORD");
239+ if (xp && strcmp(xp, np) == 0) return;
240+
241+ auth = getenv("HTTP_AUTHORIZATION");
242+ if (auth) {
243+ while (*auth == ' ') auth++;
244+ if (sx_strncasecmp(auth, "Bearer ", 7) == 0) {
245+ auth += 7;
246+ while (*auth == ' ') auth++;
247+ if (strcmp(auth, np) == 0) return;
248+ }
249+ }
250+
251+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd)
252+ && strcmp(qpwd, np) == 0) return;
253+
254+ ref = getenv("HTTP_REFERER");
255+ if (ref) {
256+ const char *rq = strchr(ref, '?');
257+ if (rq && get_query_val(rq + 1, "pwd", qpwd, sizeof qpwd)
258+ && strcmp(qpwd, np) == 0) return;
259+ }
260+
261+ fputs("Status: 401 Unauthorized\r\n"
262+ "Content-Type: application/json; charset=utf-8\r\n\r\n"
263+ "{\"ok\":false,\"error\":\"unauthorized\"}\n", stdout);
264+ exit(0);
265+}
266+
267+/* ------------------------------------------------------------------ */
268+/* Lightweight JSON string extractor */
269+/* ------------------------------------------------------------------ */
270+
271+static int json_extract_str_after(const char *obj, const char *end, const char *key,
272+ char *out, size_t outsz)
273+{
274+ char pat[128];
275+ const char *p;
276+ size_t plen, i = 0;
277+ if (out && outsz) out[0] = '\0';
278+ if (!obj || !key || !out || outsz == 0) return 0;
279+ snprintf(pat, sizeof pat, "\"%s\"", key);
280+ plen = strlen(pat);
281+ p = obj;
282+ while (p && (!end || p < end)) {
283+ const char *hit = strstr(p, pat);
284+ const char *q;
285+ if (!hit || (end && hit >= end)) return 0;
286+ q = hit + plen;
287+ while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
288+ if ((!end || q < end) && *q == ':') {
289+ q++;
290+ while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
291+ if ((!end || q < end) && *q == '"') {
292+ q++;
293+ while ((!end || q < end) && *q && *q != '"' && i + 1 < outsz) {
294+ if (*q == '\\' && q[1]) {
295+ q++;
296+ if (*q == 'n') out[i++] = '\n';
297+ else if (*q == 'r') out[i++] = '\r';
298+ else if (*q == 't') out[i++] = '\t';
299+ else out[i++] = *q;
300+ q++;
301+ } else {
302+ out[i++] = *q++;
303+ }
304+ }
305+ out[i] = '\0';
306+ return 1;
307+ }
308+ }
309+ p = hit + plen;
310+ }
311+ return 0;
312+}
313+
314+/* ------------------------------------------------------------------ */
315+/* Binary discovery (scorpiox-tmux & scorpiox-sglang-metrics) */
316+/* ------------------------------------------------------------------ */
317+
318+static const char *tmux_bin(void)
319+{
320+ static char path[512] = {0};
321+ const char *env;
322+ if (path[0]) return path;
323+ env = getenv("SCORPIOX_TMUX_BIN");
324+ if (env && *env) { str_copy(path, sizeof path, env); return path; }
325+#ifdef _WIN32
326+ {
327+ const char *lad = getenv("LOCALAPPDATA");
328+ if (lad && *lad) {
329+ snprintf(path, sizeof path, "%s\\scorpiox\\scorpiox-tmux.exe", lad);
330+ if (sx_access(path, 0) == 0) return path;
331+ }
332+ str_copy(path, sizeof path, "scorpiox-tmux.exe");
333+ }
334+#else
335+ if (sx_access("/usr/local/bin/scorpiox-tmux", X_OK) == 0)
336+ str_copy(path, sizeof path, "/usr/local/bin/scorpiox-tmux");
337+ else
338+ str_copy(path, sizeof path, "scorpiox-tmux");
339+#endif
340+ return path;
341+}
342+
343+static const char *sgm_bin(void)
344+{
345+ static char path[1024] = {0};
346+ const char *env, *tb, *base;
347+#ifdef _WIN32
348+ const char *name = "scorpiox-sglang-metrics.exe";
349+#else
350+ const char *name = "scorpiox-sglang-metrics";
351+#endif
352+ if (path[0]) return path;
353+ env = getenv("SCORPIOX_SGLANG_METRICS_BIN");
354+ if (env && *env) { str_copy(path, sizeof path, env); return path; }
355+
356+ tb = tmux_bin();
357+ base = strstr(tb, "scorpiox-tmux");
358+ if (base && base != tb) {
359+ size_t n = (size_t)(base - tb);
360+ if (n + strlen(name) + 2 < sizeof path) {
361+ memcpy(path, tb, n);
362+ snprintf(path + n, sizeof path - n, "%s", name);
363+ if (sx_access(path, 0) == 0) return path;
364+ }
365+ }
366+#ifndef _WIN32
367+ {
368+ char cand[256];
369+ snprintf(cand, sizeof cand, "/usr/local/bin/%s", name);
370+ if (sx_access(cand, X_OK) == 0) { str_copy(path, sizeof path, cand); return path; }
371+ }
372+#endif
373+ str_copy(path, sizeof path, name);
374+ return path;
375+}
376+
377+/* ------------------------------------------------------------------ */
378+/* Session discovery & config-snapshot.txt reader */
379+/* ------------------------------------------------------------------ */
380+
381+static int snapshot_get(const char *path, const char *key, char *out, size_t outsz)
382+{
383+ FILE *f;
384+ char line[2048];
385+ size_t klen = strlen(key);
386+ int found = 0;
387+ if (out && outsz) out[0] = '\0';
388+ f = fopen(path, "rb");
389+ if (!f) return 0;
390+ while (fgets(line, sizeof line, f)) {
391+ char *p = line;
392+ char *val, *end;
393+ while (*p == ' ' || *p == '\t') p++;
394+ if (*p == '#' || *p == '\0' || *p == '\r' || *p == '\n') continue;
395+ if (strncmp(p, "export ", 7) == 0) {
396+ p += 7;
397+ while (*p == ' ' || *p == '\t') p++;
398+ }
399+ if (strncmp(p, key, klen) != 0 || p[klen] != '=') continue;
400+ val = p + klen + 1;
401+ while (*val == ' ' || *val == '\t') val++;
402+ end = val + strlen(val);
403+ while (end > val && (end[-1] == '\r' || end[-1] == '\n' || end[-1] == ' ' || end[-1] == '\t'))
404+ *--end = '\0';
405+ if (end - val >= 2 && ((val[0] == '"' && end[-1] == '"') || (val[0] == '\'' && end[-1] == '\''))) {
406+ val++;
407+ *--end = '\0';
408+ }
409+ if (*val) {
410+ str_copy(out, outsz, val);
411+ found = 1;
412+ }
413+ }
414+ fclose(f);
415+ return found;
416+}
417+
418+static int pick_newest_session(const char *sessions_dir, char *sid_out, size_t sidsz)
419+{
420+ time_t best_t = 0;
421+ char best_name[256] = {0};
422+#ifdef _WIN32
423+ char pat[1200];
424+ WIN32_FIND_DATAA fd;
425+ HANDLE h;
426+ snprintf(pat, sizeof pat, "%s\\*", sessions_dir);
427+ h = FindFirstFileA(pat, &fd);
428+ if (h == INVALID_HANDLE_VALUE) return 0;
429+ do {
430+ char probe[1600];
431+ struct stat st;
432+ if (fd.cFileName[0] == '.') continue;
433+ if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
434+ snprintf(probe, sizeof probe, "%s\\%s\\config-snapshot.txt", sessions_dir, fd.cFileName);
435+ if (stat(probe, &st) != 0) {
436+ snprintf(probe, sizeof probe, "%s\\%s\\meta.json", sessions_dir, fd.cFileName);
437+ if (stat(probe, &st) != 0) continue;
438+ }
439+ if (st.st_mtime >= best_t) {
440+ best_t = st.st_mtime;
441+ str_copy(best_name, sizeof best_name, fd.cFileName);
442+ }
443+ } while (FindNextFileA(h, &fd));
444+ FindClose(h);
445+#else
446+ DIR *d = opendir(sessions_dir);
447+ struct dirent *de;
448+ if (!d) return 0;
449+ while ((de = readdir(d)) != NULL) {
450+ char probe[1600];
451+ struct stat st;
452+ if (de->d_name[0] == '.') continue;
453+ snprintf(probe, sizeof probe, "%s/%s/config-snapshot.txt", sessions_dir, de->d_name);
454+ if (stat(probe, &st) != 0) {
455+ snprintf(probe, sizeof probe, "%s/%s/meta.json", sessions_dir, de->d_name);
456+ if (stat(probe, &st) != 0) continue;
457+ }
458+ if (st.st_mtime >= best_t) {
459+ best_t = st.st_mtime;
460+ str_copy(best_name, sizeof best_name, de->d_name);
461+ }
462+ }
463+ closedir(d);
464+#endif
465+ if (!best_name[0]) return 0;
466+ str_copy(sid_out, sidsz, best_name);
467+ return 1;
468+}
469+
470+typedef struct {
471+ char name[160];
472+ char worktree[768];
473+ char session_dir[1280];
474+ char sid[160];
475+ char base_url[512];
476+} sess_entry_t;
477+
478+static int list_tmux_sessions(sess_entry_t *out, int max_n)
479+{
480+ char cmd[768];
481+ FILE *p;
482+ size_t len = 0;
483+ char *buf;
484+ int count = 0;
485+ const char *arr, *cur;
486+
487+ if (!out || max_n <= 0) return 0;
488+#ifdef _WIN32
489+ snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>NUL", tmux_bin());
490+#else
491+ snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>/dev/null", tmux_bin());
492+#endif
493+ p = sx_popen(cmd, "r");
494+ if (!p) return 0;
495+ buf = read_pipe_all(p, &len);
496+ sx_pclose(p);
497+ if (!buf || len == 0) { free(buf); return 0; }
498+
499+ arr = strstr(buf, "\"sessions\"");
500+ if (!arr) { free(buf); return 0; }
501+ arr = strchr(arr, '[');
502+ if (!arr) { free(buf); return 0; }
503+ cur = arr + 1;
504+
505+ while (*cur && count < max_n) {
506+ const char *ob = strchr(cur, '{');
507+ const char *cb;
508+ int depth = 0;
509+ const char *q;
510+ sess_entry_t *e;
511+ if (!ob) break;
512+ cb = ob;
513+ for (q = ob; *q; q++) {
514+ if (*q == '"') {
515+ q++;
516+ while (*q && *q != '"') { if (*q == '\\' && q[1]) q++; q++; }
517+ if (!*q) break;
518+ } else if (*q == '{') depth++;
519+ else if (*q == '}') { depth--; if (depth == 0) { cb = q; break; } }
520+ }
521+ if (cb <= ob) break;
522+ e = &out[count];
523+ memset(e, 0, sizeof *e);
524+ if (json_extract_str_after(ob, cb, "name", e->name, sizeof e->name) && e->name[0]) {
525+ json_extract_str_after(ob, cb, "worktree", e->worktree, sizeof e->worktree);
526+ if (!e->worktree[0]) {
527+ char proj[768] = {0};
528+ if (json_extract_str_after(ob, cb, "project", proj, sizeof proj) && proj[0])
529+ str_copy(e->worktree, sizeof e->worktree, proj);
530+ }
531+ if (e->worktree[0]) {
532+ char sroot[960];
533+ snprintf(sroot, sizeof sroot, "%s%c.scorpiox%csessions", e->worktree, SX_SEP, SX_SEP);
534+ if (pick_newest_session(sroot, e->sid, sizeof e->sid)) {
535+ char snap[1400];
536+ snprintf(e->session_dir, sizeof e->session_dir, "%.959s%c%.159s", sroot, SX_SEP, e->sid);
537+ snprintf(snap, sizeof snap, "%.1279s%cconfig-snapshot.txt", e->session_dir, SX_SEP);
538+ snapshot_get(snap, "OPENAI_BASE_URL", e->base_url, sizeof e->base_url);
539+ }
540+ }
541+ count++;
542+ }
543+ cur = cb + 1;
544+ }
545+ free(buf);
546+ return count;
547+}
548+
549+static int collect_default_roots(char roots[][512], int max_roots)
550+{
551+ int n = 0;
552+ const char *env;
553+ env = getenv("SX_SESSIONS_DIR");
554+ if (env && *env && is_dir(env) && n < max_roots)
555+ str_copy(roots[n++], 512, env);
556+#ifdef _WIN32
557+ {
558+ const char *lad = getenv("LOCALAPPDATA");
559+ const char *up = getenv("USERPROFILE");
560+ char cand[512];
561+ if (lad && *lad && n < max_roots) {
562+ snprintf(cand, sizeof cand, "%s\\scorpiox\\sessions", lad);
563+ if (is_dir(cand)) str_copy(roots[n++], 512, cand);
564+ }
565+ if (up && *up && n < max_roots) {
566+ snprintf(cand, sizeof cand, "%s\\.scorpiox\\sessions", up);
567+ if (is_dir(cand)) str_copy(roots[n++], 512, cand);
568+ }
569+ }
570+#else
571+ {
572+ const char *home = getenv("HOME");
573+ char cand[512];
574+ if (home && *home && n < max_roots) {
575+ snprintf(cand, sizeof cand, "%s/.scorpiox/sessions", home);
576+ if (is_dir(cand)) str_copy(roots[n++], 512, cand);
577+ }
578+ if (is_dir("/workspace/.scorpiox/sessions") && n < max_roots)
579+ str_copy(roots[n++], 512, "/workspace/.scorpiox/sessions");
580+ }
581+#endif
582+ return n;
583+}
584+
585+static int resolve_session_dir(const char *id, char *dir_out, size_t dirsz, char *sid_out, size_t sidsz)
586+{
587+ char roots[8][512];
588+ int nroots, i;
589+ sess_entry_t *list;
590+ int n;
591+
592+ if (dir_out && dirsz) dir_out[0] = '\0';
593+ if (sid_out && sidsz) sid_out[0] = '\0';
594+ if (!id || !*id || !safe_id(id)) return 0;
595+
596+ /* 1. Direct folder match inside SX_SESSIONS_DIR / default session roots */
597+ nroots = collect_default_roots(roots, 8);
598+ for (i = 0; i < nroots; i++) {
599+ char cand[1024];
600+ snprintf(cand, sizeof cand, "%.511s%c%.255s", roots[i], SX_SEP, id);
601+ if (is_dir(cand)) {
602+ str_copy(dir_out, dirsz, cand);
603+ str_copy(sid_out, sidsz, id);
604+ return 1;
605+ }
606+ }
607+
608+ /* 2. Active tmux sessions via scorpiox-tmux --list --output-json */
609+ list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list);
610+ if (list) {
611+ n = list_tmux_sessions(list, MAX_SESSIONS);
612+ for (i = 0; i < n; i++) {
613+ if (strcmp(list[i].name, id) == 0 && list[i].session_dir[0]) {
614+ str_copy(dir_out, dirsz, list[i].session_dir);
615+ str_copy(sid_out, sidsz, list[i].sid);
616+ free(list);
617+ return 1;
618+ }
619+ }
620+ for (i = 0; i < n; i++) {
621+ if (strstr(list[i].name, id) != NULL && list[i].session_dir[0]) {
622+ str_copy(dir_out, dirsz, list[i].session_dir);
623+ str_copy(sid_out, sidsz, list[i].sid);
624+ free(list);
625+ return 1;
626+ }
627+ }
628+ free(list);
629+ }
630+
631+#ifndef _WIN32
632+ /* 3. Common workspace/codebase fallback (/codebases/<id> or /codebases/.worktrees/<id>) */
633+ {
634+ char cand[640], sid[160];
635+ snprintf(cand, sizeof cand, "/codebases/.worktrees/%.255s/.scorpiox/sessions", id);
636+ if (pick_newest_session(cand, sid, sizeof sid)) {
637+ snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid);
638+ str_copy(sid_out, sidsz, sid);
639+ return 1;
640+ }
641+ snprintf(cand, sizeof cand, "/codebases/%.255s/.scorpiox/sessions", id);
642+ if (pick_newest_session(cand, sid, sizeof sid)) {
643+ snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid);
644+ str_copy(sid_out, sidsz, sid);
645+ return 1;
646+ }
647+ }
648+#endif
649+ return 0;
650+}
651+
652+/* ------------------------------------------------------------------ */
653+/* Action: sessions */
654+/* ------------------------------------------------------------------ */
655+
656+static void handle_sessions(void)
657+{
658+ sess_entry_t *list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list);
659+ int n = 0, i, emitted = 0;
660+ fputs("Content-Type: application/json; charset=utf-8\r\n\r\n{\"ok\":true,\"sessions\":[", stdout);
661+ if (list) {
662+ n = list_tmux_sessions(list, MAX_SESSIONS);
663+ for (i = 0; i < n; i++) {
664+ if (emitted++) fputc(',', stdout);
665+ fputs("{\"name\":", stdout); json_print_str(list[i].name);
666+ fputs(",\"sid\":", stdout); json_print_str(list[i].sid);
667+ fputs(",\"url\":", stdout); json_print_str(list[i].base_url);
668+ fputs(",\"has_url\":", stdout); fputs(list[i].base_url[0] ? "true" : "false", stdout);
669+ fputc('}', stdout);
670+ }
671+ free(list);
672+ }
673+ /* Fallback: if no tmux sessions found, enumerate SX_SESSIONS_DIR folders */
674+ if (emitted == 0) {
675+ char roots[4][512];
676+ int nr = collect_default_roots(roots, 4);
677+ if (nr > 0) {
678+#ifdef _WIN32
679+ char pat[600];
680+ WIN32_FIND_DATAA fd;
681+ HANDLE h;
682+ snprintf(pat, sizeof pat, "%s\\*", roots[0]);
683+ h = FindFirstFileA(pat, &fd);
684+ if (h != INVALID_HANDLE_VALUE) {
685+ do {
686+ char snap[1024], burl[512] = {0};
687+ if (fd.cFileName[0] == '.' || !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
688+ snprintf(snap, sizeof snap, "%s\\%s\\config-snapshot.txt", roots[0], fd.cFileName);
689+ snapshot_get(snap, "OPENAI_BASE_URL", burl, sizeof burl);
690+ if (emitted++) fputc(',', stdout);
691+ fputs("{\"name\":", stdout); json_print_str(fd.cFileName);
692+ fputs(",\"sid\":", stdout); json_print_str(fd.cFileName);
693+ fputs(",\"url\":", stdout); json_print_str(burl);
694+ fputs(",\"has_url\":", stdout); fputs(burl[0] ? "true" : "false", stdout);
695+ fputc('}', stdout);
696+ } while (FindNextFileA(h, &fd) && emitted < MAX_SESSIONS);
697+ FindClose(h);
698+ }
699+#else
700+ DIR *d = opendir(roots[0]);
701+ struct dirent *de;
702+ if (d) {
703+ while ((de = readdir(d)) != NULL && emitted < MAX_SESSIONS) {
704+ char cand[1024], snap[1200], burl[512] = {0};
705+ if (de->d_name[0] == '.') continue;
706+ snprintf(cand, sizeof cand, "%s/%s", roots[0], de->d_name);
707+ if (!is_dir(cand)) continue;
708+ snprintf(snap, sizeof snap, "%s/config-snapshot.txt", cand);
709+ snapshot_get(snap, "OPENAI_BASE_URL", burl, sizeof burl);
710+ if (emitted++) fputc(',', stdout);
711+ fputs("{\"name\":", stdout); json_print_str(de->d_name);
712+ fputs(",\"sid\":", stdout); json_print_str(de->d_name);
713+ fputs(",\"url\":", stdout); json_print_str(burl);
714+ fputs(",\"has_url\":", stdout); fputs(burl[0] ? "true" : "false", stdout);
715+ fputc('}', stdout);
716+ }
717+ closedir(d);
718+ }
719+#endif
720+ }
721+ }
722+ fputs("]}\n", stdout);
723+}
724+
725+/* ------------------------------------------------------------------ */
726+/* Action: metrics */
727+/* ------------------------------------------------------------------ */
728+
729+static void reply_json_err(const char *status, const char *msg, const char *url)
730+{
731+ printf("Status: %s\r\nContent-Type: application/json; charset=utf-8\r\n\r\n", status);
732+ fputs("{\"ok\":false,\"error\":", stdout);
733+ json_print_str(msg);
734+ if (url && *url) {
735+ fputs(",\"url\":", stdout);
736+ json_print_str(url);
737+ }
738+ fputs("}\n", stdout);
739+}
740+
741+static void strip_url_v1(const char *in, char *out, size_t outsz)
742+{
743+ size_t wl;
744+ str_copy(out, outsz, in);
745+ wl = strlen(out);
746+ while (wl > 0 && out[wl - 1] == '/') out[--wl] = '\0';
747+ if (wl >= 3 && strcmp(out + wl - 3, "/v1") == 0) out[wl - 3] = '\0';
748+}
749+
750+static void handle_metrics(const char *qs)
751+{
752+ char id[256] = {0}, url_q[512] = {0}, fresh[16] = {0};
753+ char sdir[1024] = {0}, rid[160] = {0}, base[512] = {0};
754+ const char *source = "session";
755+ char cache[1280] = {0};
756+ int use_cache = 0;
757+ char cmd[2048];
758+ FILE *p;
759+ char *out = NULL;
760+ size_t len = 0;
761+ int rc;
762+ char *last_brace;
763+
764+ get_query_val(qs, "id", id, sizeof id);
765+ get_query_val(qs, "url", url_q, sizeof url_q);
766+ get_query_val(qs, "fresh", fresh, sizeof fresh);
767+
768+ if (url_q[0]) {
769+ if (!url_ok(url_q)) {
770+ reply_json_err("400 Bad Request", "invalid url (must be http:// or https://)", url_q);
771+ return;
772+ }
773+ str_copy(base, sizeof base, url_q);
774+ source = "query";
775+ } else {
776+ char snap[1280];
777+ if (!id[0] || !safe_id(id)) {
778+ reply_json_err("400 Bad Request", "select a session or enter an SGLang URL", NULL);
779+ return;
780+ }
781+ if (!resolve_session_dir(id, sdir, sizeof sdir, rid, sizeof rid)) {
782+ reply_json_err("404 Not Found", "session not found on this node", NULL);
783+ return;
784+ }
785+ snprintf(snap, sizeof snap, "%s%cconfig-snapshot.txt", sdir, SX_SEP);
786+ if (!snapshot_get(snap, "OPENAI_BASE_URL", base, sizeof base)) {
787+ reply_json_err("404 Not Found", "session has no OPENAI_BASE_URL (not an OpenAI-compatible provider)", NULL);
788+ return;
789+ }
790+ if (!url_ok(base)) {
791+ reply_json_err("400 Bad Request", "session OPENAI_BASE_URL is not usable", base);
792+ return;
793+ }
794+ snprintf(cache, sizeof cache, "%s%c%s", sdir, SX_SEP, CACHE_NAME);
795+ use_cache = (strcmp(fresh, "1") != 0);
796+ }
797+
798+ if (use_cache && cache[0]) {
799+ struct stat st;
800+ if (stat(cache, &st) == 0 && (time(NULL) - st.st_mtime) < CACHE_SECS) {
801+ size_t clen = 0;
802+ char *cbuf = read_file_all(cache, &clen);
803+ if (cbuf && clen > 2) {
804+ char cached_url[512] = {0}, want_url[512] = {0};
805+ strip_url_v1(base, want_url, sizeof want_url);
806+ if (json_extract_str_after(cbuf, cbuf + clen, "url", cached_url, sizeof cached_url)
807+ && strcmp(cached_url, want_url) == 0) {
808+ fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout);
809+ fwrite(cbuf, 1, clen, stdout);
810+ if (cbuf[clen - 1] != '\n') fputc('\n', stdout);
811+ free(cbuf);
812+ return;
813+ }
814+ }
815+ free(cbuf);
816+ }
817+ }
818+
819+ /* url_ok() guarantees base contains no quotes, spaces, or shell metacharacters. */
820+#ifdef _WIN32
821+ snprintf(cmd, sizeof cmd, "\"%s\" \"%s\" 2>NUL", sgm_bin(), base);
822+#else
823+ snprintf(cmd, sizeof cmd, "\"%s\" '%s' 2>/dev/null", sgm_bin(), base);
824+#endif
825+ p = sx_popen(cmd, "r");
826+ if (!p) {
827+ reply_json_err("502 Bad Gateway", "failed to run scorpiox-sglang-metrics", base);
828+ return;
829+ }
830+ out = read_pipe_all(p, &len);
831+ rc = sx_pclose(p);
832+
833+ while (len > 0 && (out[len - 1] == '\n' || out[len - 1] == '\r' || out[len - 1] == ' ' || out[len - 1] == '\t'))
834+ out[--len] = '\0';
835+
836+ if (rc != 0 || !out || len < 2 || out[0] != '{' || out[len - 1] != '}') {
837+ free(out);
838+ reply_json_err("502 Bad Gateway",
839+ "no SGLang metrics at this URL (not SGLang, unreachable, or API-key gated)", base);
840+ return;
841+ }
842+
843+ /* Splice ok/updated_epoch/source/session before closing '}' */
844+ last_brace = out + len - 1;
845+ *last_brace = '\0';
846+ {
847+ size_t extra_cap = len + 512;
848+ char *final_json = (char *)malloc(extra_cap);
849+ if (!final_json) {
850+ free(out);
851+ reply_json_err("500 Internal Server Error", "out of memory", base);
852+ return;
853+ }
854+ snprintf(final_json, extra_cap,
855+ "%s,\"ok\":true,\"updated_epoch\":%lld,\"source\":\"%s\",\"session\":\"%s\"}\n",
856+ out, (long long)time(NULL), source, rid[0] ? rid : id);
857+ if (cache[0] && strcmp(source, "session") == 0) {
858+ char tmp[1344];
859+ FILE *cf;
860+ snprintf(tmp, sizeof tmp, "%s.tmp", cache);
861+ cf = fopen(tmp, "wb");
862+ if (cf) {
863+ fputs(final_json, cf);
864+ fclose(cf);
865+ rename(tmp, cache);
866+ }
867+ }
868+ fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout);
869+ fputs(final_json, stdout);
870+ free(final_json);
871+ }
872+ free(out);
873+}
874+
875+/* ------------------------------------------------------------------ */
876+/* HTML UI */
877+/* ------------------------------------------------------------------ */
878+
879+static const char *UI_CSS =
880+"body{font-family:var(--font);font-size:13px;line-height:1.4;min-height:100vh;display:flex;flex-direction:column}\n"
881+".wrap{max-width:680px;width:100%;margin:0 auto;padding:14px 16px 24px;display:flex;flex-direction:column;gap:10px}\n"
882+"html.embedded .wrap{max-width:none;padding:10px 12px 14px;gap:8px}\n"
883+".hdr{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}\n"
884+".hdr-l{display:flex;align-items:center;gap:8px;min-width:0;flex:1}\n"
885+".dot{width:8px;height:8px;border-radius:50%;background:var(--gray);flex-shrink:0;transition:background .25s var(--ease)}\n"
886+".dot.live{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.18)}\n"
887+".dot.stale{background:var(--orange);box-shadow:0 0 0 3px rgba(255,159,10,.18)}\n"
888+".dot.err{background:var(--red);box-shadow:0 0 0 3px rgba(255,69,58,.18)}\n"
889+".title{font-size:14px;font-weight:700;letter-spacing:-.015em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
890+".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"
891+".bar{display:flex;align-items:center;gap:6px;flex-wrap:wrap}\n"
892+".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"
893+".ctl:focus{border-color:var(--blue)}\n"
894+"select.ctl{flex:0 1 180px;cursor:pointer}\n"
895+"input.ctl{flex:1 1 170px;font-family:var(--mono);font-size:11px}\n"
896+".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"
897+".btn:hover{border-color:var(--line-2);background:var(--surface-hover)}\n"
898+".btn.pri{background:var(--blue);border-color:transparent;color:#fff}\n"
899+".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"
900+".card.stale{opacity:.6}\n"
901+".sg-row{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n"
902+".sg-dim{color:var(--text-2)}\n"
903+".sg-hot{color:var(--green);font-weight:700}\n"
904+".sg-bar{height:5px;border-radius:3px;background:var(--line);overflow:hidden;margin:3px 0 5px}\n"
905+".sg-bar>i{display:block;height:100%;background:var(--green);transition:width .3s var(--ease)}\n"
906+".sg-bar.warn>i{background:var(--orange)}\n"
907+".sg-bar.full>i{background:var(--red)}\n"
908+".sg-msg{color:var(--text-2);white-space:normal;font-family:var(--font);font-size:12.5px}\n"
909+".sg-err{color:var(--red);white-space:normal;font-family:var(--font);font-size:12.5px}\n"
910+".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";
911+
912+static const char *UI_BODY =
913+"<div class='wrap'>\n"
914+" <div class='hdr'>\n"
915+" <div class='hdr-l'>\n"
916+" <span class='dot' id='dot'></span>\n"
917+" <span class='title' id='title'>SGLang Monitor</span>\n"
918+" <span class='badge' id='srcBadge' style='display:none'></span>\n"
919+" </div>\n"
920+" <button class='btn' id='btnRefresh' type='button' title='Force fresh poll'>Refresh</button>\n"
921+" <button class='btn embed-hide' id='themeToggle' type='button' title='Toggle dark / light'>Theme</button>\n"
922+" </div>\n"
923+" <div class='bar'>\n"
924+" <select class='ctl' id='sessSel' aria-label='Session'><option value=''>Active session&#8230;</option></select>\n"
925+" <input class='ctl' id='urlIn' type='text' placeholder='Optional SGLang URL override (http://host:port)' autocomplete='off'>\n"
926+" <button class='btn pri' id='btnGo' type='button'>Probe</button>\n"
927+" </div>\n"
928+" <div class='card' id='card'><div class='sg-msg'>Connecting&#8230;</div></div>\n"
929+" <div class='meta-foot'><span id='urlLbl'></span><span id='tsLbl'></span></div>\n"
930+"</div>\n"
931+"<script>\n"
932+"(function(){\n"
933+" var sp = new URLSearchParams(location.search);\n"
934+" var curSid = sp.get('id') || '';\n"
935+" var curUrl = sp.get('url') || '';\n"
936+" var timer = null, busy = false, lastOk = 0;\n"
937+" var $=function(id){return document.getElementById(id);};\n"
938+" function apiUrl(extra){\n"
939+" var out = new URLSearchParams();\n"
940+" ['plugin','node','pwd'].forEach(function(k){ if(sp.get(k)) out.set(k, sp.get(k)); });\n"
941+" Object.keys(extra||{}).forEach(function(k){\n"
942+" if(extra[k]!==undefined && extra[k]!==null && extra[k]!=='') out.set(k, String(extra[k]));\n"
943+" });\n"
944+" return location.pathname + '?' + out.toString();\n"
945+" }\n"
946+" function sgK(n){n=Number(n)||0;if(n>=1e6)return (n/1e6).toFixed(1)+'M';if(n>=1e3)return Math.round(n/1e3)+'K';return String(Math.round(n));}\n"
947+" function sgN(n){return (Number(n)||0).toLocaleString('en-US');}\n"
948+" function sgF(n,d){return (Number(n)||0).toFixed(d);}\n"
949+" function row(cls,txt){var el=document.createElement('div');el.className='sg-row '+(cls||'');el.textContent=txt;return el;}\n"
950+" function render(d){\n"
951+" var card=$('card'), dot=$('dot'), title=$('title'), badge=$('srcBadge');\n"
952+" card.innerHTML='';\n"
953+" if(!d || d.error){\n"
954+" dot.className='dot err';\n"
955+" title.textContent='SGLang Monitor';\n"
956+" card.classList.remove('stale');\n"
957+" var e=document.createElement('div'); e.className='sg-err';\n"
958+" e.textContent=(d&&d.error)?String(d.error):'No SGLang metrics';\n"
959+" card.appendChild(e);\n"
960+" if(d&&d.url){$('urlLbl').textContent=d.url;}\n"
961+" return;\n"
962+" }\n"
963+" var age = (typeof d.updated_epoch==='number') ? Math.max(0, Math.floor(Date.now()/1000)-d.updated_epoch) : 0;\n"
964+" var stale = age > 20;\n"
965+" dot.className = 'dot ' + (stale ? 'stale' : 'live');\n"
966+" card.classList.toggle('stale', stale);\n"
967+" var model = (d.model||'').split('/').pop() || 'SGLang';\n"
968+" title.textContent = 'SGLang \\u00b7 ' + model + (stale ? ' (stale)' : '');\n"
969+" if(d.source){badge.style.display='';badge.textContent=d.source==='query'?'URL':(curSid||d.session||'session');}\n"
970+" var run=Number(d.num_running_reqs||0), q=Number(d.num_queue_reqs||0), mx=Number(d.max_running_reqs||0);\n"
971+" card.appendChild(row(run>0?'sg-hot':'', 'run '+run+' queue '+q+(mx?(' max '+mx):'')));\n"
972+" var tg=Number(d.gen_throughput||0), pp=Number(d.pp_tok_s||0), gen=Number(d.gen_tok_s||0);\n"
973+" card.appendChild(row(tg>0?'sg-hot':'', 'tg '+sgF(tg,1)+' t/s pp '+sgF(pp,0)+' t/s gen '+sgF(gen,0)+' t/s'));\n"
974+" var kv=Number(d.token_usage||0), pct=Math.round(kv*100), used=Number(d.num_used_tokens||0), cap=Number(d.max_total_num_tokens||0), ctx=Number(d.context_len||0);\n"
975+" if(cap>0||kv>0){\n"
976+" card.appendChild(row('', 'KV '+sgK(used)+'/'+sgK(cap)+' ('+pct+'%)'+(ctx?(' ctx '+sgK(ctx)):'')));\n"
977+" var bar=document.createElement('div'); bar.className='sg-bar'+(pct>=90?' full':pct>=70?' warn':'');\n"
978+" var fill=document.createElement('i'); fill.style.width=Math.max(0,Math.min(100,pct))+'%'; bar.appendChild(fill); card.appendChild(bar);\n"
979+" }\n"
980+" var cr=d.cache_hit_rate, crL=d.cache_hit_rate_lifetime;\n"
981+" if(typeof cr==='number'||typeof crL==='number'){\n"
982+" var cs='cache '+(typeof cr==='number'?(Math.round(cr*100)+'%'):'\\u2014');\n"
983+" if(typeof crL==='number') cs+=' (life '+Math.round(crL*100)+'%)';\n"
984+" card.appendChild(row('', cs));\n"
985+" }\n"
986+" if(d.spec_algo||typeof d.spec_accept_length==='number'){\n"
987+" var spTxt='spec '+(d.spec_algo||'on');\n"
988+" if(typeof d.spec_accept_length==='number') spTxt+=' len '+sgF(d.spec_accept_length,2);\n"
989+" if(typeof d.spec_accept_rate==='number') spTxt+=' acc '+Math.round(d.spec_accept_rate*100)+'%';\n"
990+" card.appendChild(row('', spTxt));\n"
991+" }\n"
992+" var itl=d.itl_ms, ttft=d.ttft_ms, ql=d.queue_ms;\n"
993+" if(typeof itl==='number'||typeof ttft==='number'||typeof ql==='number'){\n"
994+" var lt=[];\n"
995+" if(typeof itl==='number') lt.push('itl '+sgF(itl,1)+' ms');\n"
996+" if(typeof ttft==='number') lt.push('ttft '+sgF(ttft,0)+' ms');\n"
997+" if(typeof ql==='number') lt.push('queue '+sgF(ql,0)+' ms');\n"
998+" card.appendChild(row('sg-dim', lt.join(' ')));\n"
999+" }\n"
1000+" var reqs=Number(d.requests_total||0), pt=Number(d.prompt_tokens_total||0), gt=Number(d.generation_tokens_total||0);\n"
1001+" if(reqs||pt||gt) card.appendChild(row('sg-dim', 'reqs '+sgN(reqs)+' prompt '+sgK(pt)+' gen '+sgK(gt)));\n"
1002+" $('urlLbl').textContent = d.url || '';\n"
1003+" $('tsLbl').textContent = 'updated ' + new Date().toLocaleTimeString();\n"
1004+" }\n"
1005+" async function poll(fresh){\n"
1006+" if(busy) return;\n"
1007+" if(!curUrl && !curSid){\n"
1008+" render({error:'Pick a session above or enter an SGLang server URL.'});\n"
1009+" return;\n"
1010+" }\n"
1011+" busy = true;\n"
1012+" try{\n"
1013+" var q = {action:'metrics'};\n"
1014+" if(curUrl) q.url = curUrl; else q.id = curSid;\n"
1015+" if(fresh) q.fresh = '1';\n"
1016+" var r = await fetch(apiUrl(q));\n"
1017+" var d = null; try{ d = await r.json(); }catch(e){}\n"
1018+" if(!r.ok || !d || d.error){\n"
1019+" if(!lastOk || fresh || Date.now()-lastOk > 15000) render(d||{error:'HTTP '+r.status});\n"
1020+" }else{\n"
1021+" lastOk = Date.now();\n"
1022+" render(d);\n"
1023+" }\n"
1024+" }catch(e){\n"
1025+" if(!lastOk) render({error:'Network error polling SGLang metrics'});\n"
1026+" }finally{ busy = false; }\n"
1027+" }\n"
1028+" async function loadSessions(){\n"
1029+" try{\n"
1030+" var r = await fetch(apiUrl({action:'sessions'}));\n"
1031+" var d = await r.json();\n"
1032+" var sel = $('sessSel'); sel.innerHTML = '';\n"
1033+" var list = (d && Array.isArray(d.sessions)) ? d.sessions : [];\n"
1034+" if(!list.length){\n"
1035+" var o = document.createElement('option'); o.value=''; o.textContent='No sessions'; sel.appendChild(o);\n"
1036+" }else{\n"
1037+" var ph = document.createElement('option'); ph.value=''; ph.textContent='Select session\\u2026'; sel.appendChild(ph);\n"
1038+" list.forEach(function(s){\n"
1039+" var o = document.createElement('option');\n"
1040+" o.value = s.name; o.textContent = s.name + (s.has_url ? '' : ' (no url)');\n"
1041+" if(curSid && s.name === curSid) o.selected = true;\n"
1042+" sel.appendChild(o);\n"
1043+" });\n"
1044+" if(!curSid && !curUrl){\n"
1045+" var pick = list.find(function(s){return s.has_url;}) || list[0];\n"
1046+" if(pick){ curSid = pick.name; sel.value = curSid; }\n"
1047+" }\n"
1048+" }\n"
1049+" }catch(e){}\n"
1050+" }\n"
1051+" $('sessSel').onchange = function(){ curSid = this.value; curUrl = ''; $('urlIn').value = ''; lastOk = 0; poll(true); };\n"
1052+" $('btnGo').onclick = function(){ curUrl = $('urlIn').value.trim(); lastOk = 0; poll(true); };\n"
1053+" $('urlIn').onkeydown = function(e){ if(e.key==='Enter'){ curUrl = this.value.trim(); lastOk = 0; poll(true); } };\n"
1054+" $('btnRefresh').onclick = function(){ poll(true); };\n"
1055+" var tt = $('themeToggle');\n"
1056+" if(tt) tt.onclick = function(){\n"
1057+" var c = document.documentElement.getAttribute('data-theme')==='light'?'dark':'light';\n"
1058+" document.documentElement.setAttribute('data-theme', c);\n"
1059+" try{localStorage.setItem('bot_theme', c);}catch(e){}\n"
1060+" };\n"
1061+" if(curUrl) $('urlIn').value = curUrl;\n"
1062+" document.addEventListener('visibilitychange', function(){\n"
1063+" if(document.visibilityState==='visible') poll(false);\n"
1064+" });\n"
1065+" loadSessions().then(function(){\n"
1066+" poll(false);\n"
1067+" timer = setInterval(function(){ if(document.visibilityState==='visible') poll(false); }, 5000);\n"
1068+" });\n"
1069+"})();\n"
1070+"</script>\n";
1071+
1072+static void handle_html(void)
1073+{
1074+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1075+ "Cache-Control: no-cache, no-store, must-revalidate\r\n\r\n"
1076+ "<!DOCTYPE html><html lang='en'><head>\n"
1077+ "<meta charset='utf-8'>\n"
1078+ "<meta name='viewport' content='width=device-width,initial-scale=1'>\n"
1079+ "<title>SGLang Monitor · SCORPIOX BOT</title>\n", stdout);
1080+ fputs(SX_BOT_THEME_PREPAINT, stdout);
1081+ fputs("<style>\n", stdout);
1082+ fputs(SX_BOT_THEME_TOKENS, stdout);
1083+ fputs("\n", stdout);
1084+ fputs(UI_CSS, stdout);
1085+ fputs("</style></head><body>\n", stdout);
1086+ fputs(UI_BODY, stdout);
1087+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1088+ fputs("</body></html>\n", stdout);
1089+}
1090+
1091+int main(int argc, char **argv)
1092+{
1093+ const char *qs;
1094+ char action[64] = {0}, fmt[32] = {0};
1095+
1096+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1097+ fputs("{\"name\":\"sglang\",\"desc\":\"SGLang metrics\",\"kind\":\"ui\",\"version\":\"" PLUGIN_VERSION "\"}\n", stdout);
1098+ return 0;
1099+ }
1100+
1101+ require_node_auth();
1102+
1103+ qs = getenv("QUERY_STRING");
1104+ get_query_val(qs, "action", action, sizeof action);
1105+ get_query_val(qs, "format", fmt, sizeof fmt);
1106+
1107+ if (strcmp(action, "sessions") == 0) {
1108+ handle_sessions();
1109+ return 0;
1110+ }
1111+ if (strcmp(action, "metrics") == 0 || strcmp(fmt, "json") == 0) {
1112+ handle_metrics(qs);
1113+ return 0;
1114+ }
1115+
1116+ handle_html();
1117+ return 0;
1118+}
tests/run.sh+91−0■■■■■
11new file mode 100755
index 0000000..08746b1
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,91 @@
1+#!/bin/sh
2+# tests/run.sh -- offline test suite for plugin_sglang
3+set -eu
4+
5+BIN="./plugin_sglang"
6+PASS=0
7+FAIL=0
8+
9+ok() { PASS=$((PASS + 1)); printf ' PASS %s\n' "$1"; }
10+fail() { FAIL=$((FAIL + 1)); printf ' FAIL %s\n' "$1"; }
11+
12+assert_contains() {
13+ case "$1" in
14+ *"$2"*) ok "$3" ;;
15+ *) fail "$3 (missing: $2)" ;;
16+ esac
17+}
18+
19+TMP=$(mktemp -d)
20+trap 'rm -rf "$TMP"' EXIT
21+
22+# Mock scorpiox-sglang-metrics binary
23+cat > "$TMP/mock-sgm" << 'EOF'
24+#!/bin/sh
25+URL="$1"
26+URL="${URL%/}"
27+URL="${URL%/v1}"
28+printf '{"url":"%s","model":"org/demo-model","num_running_reqs":2,"num_queue_reqs":1,"max_running_reqs":64,"gen_throughput":142.5,"pp_tok_s":3200,"gen_tok_s":285,"token_usage":0.42,"num_used_tokens":42000,"max_total_num_tokens":100000,"context_len":131072,"cache_hit_rate":0.78,"cache_hit_rate_lifetime":0.65,"spec_algo":"EAGLE","spec_accept_length":3.12,"spec_accept_rate":0.74,"itl_ms":6.8,"ttft_ms":85,"queue_ms":4,"requests_total":120,"prompt_tokens_total":510000,"generation_tokens_total":88000}\n' "$URL"
29+EOF
30+chmod +x "$TMP/mock-sgm"
31+
32+# Mock session store
33+mkdir -p "$TMP/sessions/demo-sess"
34+cat > "$TMP/sessions/demo-sess/config-snapshot.txt" << 'EOF'
35+OPENAI_BASE_URL=http://127.0.0.1:30000/v1
36+EOF
37+cat > "$TMP/sessions/demo-sess/meta.json" << 'EOF'
38+{"id":"demo-sess","cwd":"/tmp"}
39+EOF
40+
41+echo "==> plugin_sglang offline tests"
42+
43+# 1. --meta
44+OUT=$("$BIN" --meta)
45+assert_contains "$OUT" '"name":"sglang"' "meta name"
46+assert_contains "$OUT" '"desc":"SGLang metrics"' "meta desc"
47+assert_contains "$OUT" '"kind":"ui"' "meta kind"
48+
49+# 2. SX_PLUGIN_META=1
50+OUT=$(SX_PLUGIN_META=1 "$BIN")
51+assert_contains "$OUT" '"name":"sglang"' "SX_PLUGIN_META=1"
52+
53+# 3. Auth gate (401 without pwd, 200 with header)
54+OUT=$(BOT_PASSWORD="demo-auth-val" QUERY_STRING="action=sessions" "$BIN")
55+assert_contains "$OUT" 'Status: 401 Unauthorized' "auth rejects missing password"
56+
57+OUT=$(BOT_PASSWORD="demo-auth-val" HTTP_X_BOT_PASSWORD="demo-auth-val" SX_SESSIONS_DIR="$TMP/sessions" SCORPIOX_TMUX_BIN="/nonexistent" QUERY_STRING="action=sessions" "$BIN")
58+assert_contains "$OUT" '"ok":true' "auth accepts X-Bot-Password"
59+assert_contains "$OUT" '"demo-sess"' "sessions lists SX_SESSIONS_DIR fallback"
60+
61+# 4. Metrics from session config-snapshot.txt
62+OUT=$(SX_SESSIONS_DIR="$TMP/sessions" SCORPIOX_TMUX_BIN="/nonexistent" SCORPIOX_SGLANG_METRICS_BIN="$TMP/mock-sgm" QUERY_STRING="action=metrics&id=demo-sess" "$BIN")
63+assert_contains "$OUT" '"ok":true' "metrics ok"
64+assert_contains "$OUT" '"model":"org/demo-model"' "metrics model"
65+assert_contains "$OUT" '"source":"session"' "metrics source=session"
66+
67+# 5. Cache file written and reused
68+if [ -f "$TMP/sessions/demo-sess/sglang_metrics.json" ]; then
69+ ok "cache file created"
70+else
71+ fail "cache file created"
72+fi
73+OUT=$(SX_SESSIONS_DIR="$TMP/sessions" SCORPIOX_TMUX_BIN="/nonexistent" SCORPIOX_SGLANG_METRICS_BIN="/nonexistent" QUERY_STRING="action=metrics&id=demo-sess" "$BIN")
74+assert_contains "$OUT" '"model":"org/demo-model"' "cache hit serves without spawning binary"
75+
76+# 6. Direct ?url= override
77+OUT=$(SCORPIOX_SGLANG_METRICS_BIN="$TMP/mock-sgm" QUERY_STRING="action=metrics&url=http%3A%2F%2F127.0.0.1%3A30001" "$BIN")
78+assert_contains "$OUT" '"source":"query"' "url override source=query"
79+
80+# 7. Bad URL rejected (400)
81+OUT=$(SCORPIOX_SGLANG_METRICS_BIN="$TMP/mock-sgm" QUERY_STRING="action=metrics&url=file%3A%2F%2F%2Fetc%2Fpasswd" "$BIN")
82+assert_contains "$OUT" 'Status: 400 Bad Request' "rejects non-http scheme"
83+
84+# 8. HTML UI & theme handoff
85+OUT=$(QUERY_STRING="embed=1&theme=light" "$BIN")
86+assert_contains "$OUT" 'Content-Type: text/html' "html content-type"
87+assert_contains "$OUT" 'sx-theme-request' "theme handoff script present"
88+assert_contains "$OUT" 'SGLang Monitor' "html title present"
89+
90+printf '\nTotal: %d passed, %d failed\n' "$PASS" "$FAIL"
91+[ "$FAIL" -eq 0 ]
092
.gitignore+8−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..377f998index 0000000..377f998
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,8 @@@@ -0,0 +1,8 @@
1+plugin_sglang
2+plugin_sglang.exe
3+plugin_sglang.musl
4+plugin_sglang.arm64
5+plugin_sglang.macos-*
6+*.o
7+bin/
8+dist/
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /dev/null--- /dev/null
+++ b/LICENSE+++ b/LICENSE
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+59−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..c150a45index 0000000..c150a45
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,59 @@@@ -0,0 +1,59 @@
1+# plugin_sglang - SCORPIOX BOT open-source SGLang server metrics monitor
2+#
3+# Targets:
4+# make native build -> ./plugin_sglang
5+# make musl static musl x86_64 -> ./plugin_sglang.musl
6+# make arm64 static aarch64 musl -> ./plugin_sglang.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_sglang.exe
8+# make macos Apple clang (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+
12+CC ?= cc
13+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings
14+MUSL_CC ?= musl-gcc
15+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
16+ARM_CC ?= aarch64-linux-gnu-gcc
17+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
18+WIN_CC ?= x86_64-w64-mingw32-gcc
19+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
20+SRC := src/plugin_sglang.c
21+HDR := src/bot_theme_plugin.h
22+BIN := plugin_sglang
23+EXE := plugin_sglang.exe
24+
25+.PHONY: all native musl arm64 win64 macos test clean help
26+
27+all: native
28+
29+native: $(BIN)
30+
31+$(BIN): $(SRC) $(HDR)
32+ @echo "==> native build ($(CC))"
33+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
34+
35+musl: $(SRC) $(HDR)
36+ @echo "==> static musl build ($(MUSL_CC))"
37+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
38+
39+arm64: $(SRC) $(HDR)
40+ @echo "==> static arm64 build ($(ARM_CC))"
41+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
42+
43+win64: $(SRC) $(HDR)
44+ @echo "==> MinGW-w64 build ($(WIN_CC))"
45+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
46+
47+macos: $(SRC) $(HDR)
48+ @echo "==> Apple clang build"
49+ $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o $(BIN) $(SRC)
50+
51+test: native
52+ @sh tests/run.sh
53+
54+clean:
55+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64
56+ rm -rf bin
57+
58+help:
59+ @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean"
README.md+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..39eb127index 0000000..39eb127
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+# plugin_sglang — SGLang Server Monitor for SCORPIOX BOT
2+
3+Zero-dependency pure C99 dynamic plugin for **SCORPIOX BOT** showing live SGLang inference telemetry for the active session or any custom SGLang server URL.
4+
5+## Features
6+- **Auto-tracks active `/chat` session**: reads `OPENAI_BASE_URL` from the session's `config-snapshot.txt` and polls `scorpiox-sglang-metrics` (cached 4 s per session).
7+- **Works from Hub, Session Cards & Chat**: includes a live session picker and custom SGLang URL override bar.
8+- **Full telemetry**: model name, running/queued/max requests, `tg` / `pp` / `gen` tok/s, KV cache fill bar (`used / total`, `%`, `ctx`), prefix cache hit rate (current & lifetime), speculative decoding (`method`, `len`, `acc %`), latencies (`ITL`, `TTFT`, `queue`), and cumulative token counters.
9+- **Native dual theme**: honors SCORPIOX BOT dark/light theme handoff (`?theme=`, `postMessage('sx-theme')`, `?embed=1`).
10+
11+## Build & Test
12+```sh
13+make
14+make test
15+```
16+
17+## Install
18+Install from **Settings → Plugins → Marketplace** in SCORPIOX BOT, or copy `plugin_sglang` into `~/.scorpiox/plugins/`.
19+
20+## License
21+MIT License — Copyright (c) 2026 SCORPIOX INC
build.ps1+45−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0c21723index 0000000..0c21723
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,45 @@@@ -0,0 +1,45 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_sglang
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+
6+$ErrorActionPreference = "Stop"
7+$ScriptDir = $PSScriptRoot
8+Push-Location $ScriptDir
9+try {
10+ $Src = Join-Path $ScriptDir "src\plugin_sglang.c"
11+ $Out = Join-Path $ScriptDir "plugin_sglang.exe"
12+ $Cc = "x86_64-w64-mingw32-gcc"
13+
14+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
15+
16+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
17+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
18+ $Cc = "C:\gcc16\bin\gcc.exe"
19+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
20+ $Cc = "gcc"
21+ } else {
22+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
23+ }
24+ }
25+
26+ Write-Host "==> building plugin_sglang.exe with $Cc"
27+ & $Cc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src
28+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
29+ if (-not (Test-Path $Out)) { throw "build produced no output" }
30+
31+ $bytes = [System.IO.File]::ReadAllBytes($Out)
32+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
33+ throw "output is not a PE executable (missing MZ header)"
34+ }
35+
36+ Write-Host "==> metadata check"
37+ & $Out --meta
38+ if ($LASTEXITCODE -ne 0) { throw "--meta failed" }
39+
40+ $size = (Get-Item $Out).Length
41+ Write-Host ""
42+ Write-Host "Built $Out ($size bytes)"
43+} finally {
44+ Pop-Location
45+}
plugin.json+12−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..77120f2index 0000000..77120f2
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,12 @@@@ -0,0 +1,12 @@
1+{
2+ "slug": "sglang",
3+ "id": "plugin_sglang",
4+ "title": "SGLang Server Monitor",
5+ "summary": "Live SGLang inference telemetry for SCORPIOX BOT sessions: running/queued requests, generation and prefill tok/s, KV cache fill bar, prefix cache hit rate, speculative decoding acceptance, ITL/TTFT/queue latency and token counters. Auto-tracks the active chat session's OPENAI_BASE_URL or probes any custom SGLang URL.",
6+ "category": "sessions",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_read", "session_store_read", "http_metrics_poll"],
9+ "trust_notice": "Executes native C code on your node. Reads the active session's config-snapshot.txt for OPENAI_BASE_URL and invokes scorpiox-sglang-metrics to issue read-only GET /metrics and GET /get_server_info probes.",
10+ "author": "SCORPIOX INC",
11+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-sglang"
12+}
src/bot_theme_plugin.h+129−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0dd243bindex 0000000..0dd243b
--- /dev/null--- /dev/null
+++ b/src/bot_theme_plugin.h+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_sglang.c+1118−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..869786findex 0000000..869786f
--- /dev/null--- /dev/null
+++ b/src/plugin_sglang.c+++ b/src/plugin_sglang.c
@@ -0,0 +1,1118 @@@@ -0,0 +1,1118 @@
1+/*
2+ * plugin_sglang.c -- SCORPIOX BOT open-source SGLang Server 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":"sglang","desc":"SGLang metrics",...}
6+ * 2. GET ?action=sessions : lists active node sessions + OPENAI_BASE_URL
7+ * GET ?action=metrics : polls scorpiox-sglang-metrics for session or ?url=
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 before command execution
13+ * - Read-only telemetry only (scorpiox-sglang-metrics issues GET /metrics + /get_server_info)
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 CACHE_SECS 4
52+#define CACHE_NAME "sglang_metrics.json"
53+#define MAX_SESSIONS 128
54+
55+/* ------------------------------------------------------------------ */
56+/* Small utilities */
57+/* ------------------------------------------------------------------ */
58+
59+static void str_copy(char *dst, size_t dstsz, const char *src)
60+{
61+ size_t n;
62+ if (!dst || dstsz == 0) return;
63+ if (!src) { dst[0] = '\0'; return; }
64+ n = strlen(src);
65+ if (n >= dstsz) n = dstsz - 1;
66+ memcpy(dst, src, n);
67+ dst[n] = '\0';
68+}
69+
70+static int hex_val(char c)
71+{
72+ if (c >= '0' && c <= '9') return c - '0';
73+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
74+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
75+ return -1;
76+}
77+
78+static void url_decode(const char *src, char *dst, size_t dstsz)
79+{
80+ size_t i = 0;
81+ if (!dst || dstsz == 0) return;
82+ if (!src) { dst[0] = '\0'; return; }
83+ while (*src && i + 1 < dstsz) {
84+ if (*src == '%' && src[1] && src[2]) {
85+ int hi = hex_val(src[1]), lo = hex_val(src[2]);
86+ if (hi >= 0 && lo >= 0) {
87+ dst[i++] = (char)((hi << 4) | lo);
88+ src += 3;
89+ continue;
90+ }
91+ }
92+ if (*src == '+') dst[i++] = ' ';
93+ else dst[i++] = *src;
94+ src++;
95+ }
96+ dst[i] = '\0';
97+}
98+
99+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
100+{
101+ size_t klen;
102+ const char *p;
103+ if (out && outsz) out[0] = '\0';
104+ if (!qs || !*qs || !key || !*key || !out || outsz == 0) return 0;
105+ klen = strlen(key);
106+ p = qs;
107+ while (*p) {
108+ const char *amp = strchr(p, '&');
109+ size_t len = amp ? (size_t)(amp - p) : strlen(p);
110+ if (len > klen && strncmp(p, key, klen) == 0 && p[klen] == '=') {
111+ char raw[1024];
112+ size_t vlen = len - klen - 1;
113+ if (vlen >= sizeof raw) vlen = sizeof raw - 1;
114+ memcpy(raw, p + klen + 1, vlen);
115+ raw[vlen] = '\0';
116+ url_decode(raw, out, outsz);
117+ return 1;
118+ }
119+ if (!amp) break;
120+ p = amp + 1;
121+ }
122+ return 0;
123+}
124+
125+static void json_print_str(const char *s)
126+{
127+ const unsigned char *p = (const unsigned char *)(s ? s : "");
128+ fputc('"', stdout);
129+ for (; *p; p++) {
130+ unsigned char c = *p;
131+ if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); }
132+ else if (c == '\n') fputs("\\n", stdout);
133+ else if (c == '\r') fputs("\\r", stdout);
134+ else if (c == '\t') fputs("\\t", stdout);
135+ else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout);
136+ }
137+ fputc('"', stdout);
138+}
139+
140+static int safe_id(const char *s)
141+{
142+ size_t i;
143+ if (!s || !*s) return 0;
144+ for (i = 0; s[i]; i++) {
145+ unsigned char c = (unsigned char)s[i];
146+ if (i >= 160) return 0;
147+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == ':') continue;
148+ return 0;
149+ }
150+ if (strstr(s, "..") != NULL) return 0;
151+ return 1;
152+}
153+
154+static int url_ok(const char *u)
155+{
156+ const char *p;
157+ if (!u || !*u || strlen(u) > 512) return 0;
158+ if (strncmp(u, "http://", 7) != 0 && strncmp(u, "https://", 8) != 0) return 0;
159+ for (p = u; *p; p++) {
160+ unsigned char c = (unsigned char)*p;
161+ if (isalnum(c) || strchr(":/.-_~%?&#=+@,", (int)c) != NULL) continue;
162+ return 0;
163+ }
164+ return 1;
165+}
166+
167+static int is_dir(const char *p)
168+{
169+ struct stat st;
170+ if (!p || !*p) return 0;
171+ if (stat(p, &st) != 0) return 0;
172+ return (st.st_mode & S_IFMT) == S_IFDIR;
173+}
174+
175+static char *read_file_all(const char *path, size_t *len_out)
176+{
177+ FILE *f;
178+ char *buf;
179+ size_t cap = 4096, len = 0, n;
180+ if (len_out) *len_out = 0;
181+ f = fopen(path, "rb");
182+ if (!f) return NULL;
183+ buf = (char *)malloc(cap);
184+ if (!buf) { fclose(f); return NULL; }
185+ while ((n = fread(buf + len, 1, cap - len - 1, f)) > 0) {
186+ len += n;
187+ if (cap - len < 512) {
188+ char *nb;
189+ if (cap > (4 * 1024 * 1024)) break;
190+ cap *= 2;
191+ nb = (char *)realloc(buf, cap);
192+ if (!nb) break;
193+ buf = nb;
194+ }
195+ }
196+ fclose(f);
197+ buf[len] = '\0';
198+ if (len_out) *len_out = len;
199+ return buf;
200+}
201+
202+static char *read_pipe_all(FILE *p, size_t *len_out)
203+{
204+ size_t cap = 16384, len = 0, n;
205+ char *buf;
206+ if (len_out) *len_out = 0;
207+ if (!p) return NULL;
208+ buf = (char *)malloc(cap);
209+ if (!buf) return NULL;
210+ while ((n = fread(buf + len, 1, cap - len - 1, p)) > 0) {
211+ len += n;
212+ if (cap - len < 1024) {
213+ char *nb;
214+ if (cap > (4 * 1024 * 1024)) break;
215+ cap *= 2;
216+ nb = (char *)realloc(buf, cap);
217+ if (!nb) break;
218+ buf = nb;
219+ }
220+ }
221+ buf[len] = '\0';
222+ if (len_out) *len_out = len;
223+ return buf;
224+}
225+
226+/* ------------------------------------------------------------------ */
227+/* Node security */
228+/* ------------------------------------------------------------------ */
229+
230+static void require_node_auth(void)
231+{
232+ const char *np = getenv("BOT_PASSWORD");
233+ const char *xp, *auth, *ref;
234+ char qpwd[128] = {0};
235+
236+ if (!np || !*np) return;
237+
238+ xp = getenv("HTTP_X_BOT_PASSWORD");
239+ if (xp && strcmp(xp, np) == 0) return;
240+
241+ auth = getenv("HTTP_AUTHORIZATION");
242+ if (auth) {
243+ while (*auth == ' ') auth++;
244+ if (sx_strncasecmp(auth, "Bearer ", 7) == 0) {
245+ auth += 7;
246+ while (*auth == ' ') auth++;
247+ if (strcmp(auth, np) == 0) return;
248+ }
249+ }
250+
251+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd)
252+ && strcmp(qpwd, np) == 0) return;
253+
254+ ref = getenv("HTTP_REFERER");
255+ if (ref) {
256+ const char *rq = strchr(ref, '?');
257+ if (rq && get_query_val(rq + 1, "pwd", qpwd, sizeof qpwd)
258+ && strcmp(qpwd, np) == 0) return;
259+ }
260+
261+ fputs("Status: 401 Unauthorized\r\n"
262+ "Content-Type: application/json; charset=utf-8\r\n\r\n"
263+ "{\"ok\":false,\"error\":\"unauthorized\"}\n", stdout);
264+ exit(0);
265+}
266+
267+/* ------------------------------------------------------------------ */
268+/* Lightweight JSON string extractor */
269+/* ------------------------------------------------------------------ */
270+
271+static int json_extract_str_after(const char *obj, const char *end, const char *key,
272+ char *out, size_t outsz)
273+{
274+ char pat[128];
275+ const char *p;
276+ size_t plen, i = 0;
277+ if (out && outsz) out[0] = '\0';
278+ if (!obj || !key || !out || outsz == 0) return 0;
279+ snprintf(pat, sizeof pat, "\"%s\"", key);
280+ plen = strlen(pat);
281+ p = obj;
282+ while (p && (!end || p < end)) {
283+ const char *hit = strstr(p, pat);
284+ const char *q;
285+ if (!hit || (end && hit >= end)) return 0;
286+ q = hit + plen;
287+ while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
288+ if ((!end || q < end) && *q == ':') {
289+ q++;
290+ while ((!end || q < end) && (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
291+ if ((!end || q < end) && *q == '"') {
292+ q++;
293+ while ((!end || q < end) && *q && *q != '"' && i + 1 < outsz) {
294+ if (*q == '\\' && q[1]) {
295+ q++;
296+ if (*q == 'n') out[i++] = '\n';
297+ else if (*q == 'r') out[i++] = '\r';
298+ else if (*q == 't') out[i++] = '\t';
299+ else out[i++] = *q;
300+ q++;
301+ } else {
302+ out[i++] = *q++;
303+ }
304+ }
305+ out[i] = '\0';
306+ return 1;
307+ }
308+ }
309+ p = hit + plen;
310+ }
311+ return 0;
312+}
313+
314+/* ------------------------------------------------------------------ */
315+/* Binary discovery (scorpiox-tmux & scorpiox-sglang-metrics) */
316+/* ------------------------------------------------------------------ */
317+
318+static const char *tmux_bin(void)
319+{
320+ static char path[512] = {0};
321+ const char *env;
322+ if (path[0]) return path;
323+ env = getenv("SCORPIOX_TMUX_BIN");
324+ if (env && *env) { str_copy(path, sizeof path, env); return path; }
325+#ifdef _WIN32
326+ {
327+ const char *lad = getenv("LOCALAPPDATA");
328+ if (lad && *lad) {
329+ snprintf(path, sizeof path, "%s\\scorpiox\\scorpiox-tmux.exe", lad);
330+ if (sx_access(path, 0) == 0) return path;
331+ }
332+ str_copy(path, sizeof path, "scorpiox-tmux.exe");
333+ }
334+#else
335+ if (sx_access("/usr/local/bin/scorpiox-tmux", X_OK) == 0)
336+ str_copy(path, sizeof path, "/usr/local/bin/scorpiox-tmux");
337+ else
338+ str_copy(path, sizeof path, "scorpiox-tmux");
339+#endif
340+ return path;
341+}
342+
343+static const char *sgm_bin(void)
344+{
345+ static char path[1024] = {0};
346+ const char *env, *tb, *base;
347+#ifdef _WIN32
348+ const char *name = "scorpiox-sglang-metrics.exe";
349+#else
350+ const char *name = "scorpiox-sglang-metrics";
351+#endif
352+ if (path[0]) return path;
353+ env = getenv("SCORPIOX_SGLANG_METRICS_BIN");
354+ if (env && *env) { str_copy(path, sizeof path, env); return path; }
355+
356+ tb = tmux_bin();
357+ base = strstr(tb, "scorpiox-tmux");
358+ if (base && base != tb) {
359+ size_t n = (size_t)(base - tb);
360+ if (n + strlen(name) + 2 < sizeof path) {
361+ memcpy(path, tb, n);
362+ snprintf(path + n, sizeof path - n, "%s", name);
363+ if (sx_access(path, 0) == 0) return path;
364+ }
365+ }
366+#ifndef _WIN32
367+ {
368+ char cand[256];
369+ snprintf(cand, sizeof cand, "/usr/local/bin/%s", name);
370+ if (sx_access(cand, X_OK) == 0) { str_copy(path, sizeof path, cand); return path; }
371+ }
372+#endif
373+ str_copy(path, sizeof path, name);
374+ return path;
375+}
376+
377+/* ------------------------------------------------------------------ */
378+/* Session discovery & config-snapshot.txt reader */
379+/* ------------------------------------------------------------------ */
380+
381+static int snapshot_get(const char *path, const char *key, char *out, size_t outsz)
382+{
383+ FILE *f;
384+ char line[2048];
385+ size_t klen = strlen(key);
386+ int found = 0;
387+ if (out && outsz) out[0] = '\0';
388+ f = fopen(path, "rb");
389+ if (!f) return 0;
390+ while (fgets(line, sizeof line, f)) {
391+ char *p = line;
392+ char *val, *end;
393+ while (*p == ' ' || *p == '\t') p++;
394+ if (*p == '#' || *p == '\0' || *p == '\r' || *p == '\n') continue;
395+ if (strncmp(p, "export ", 7) == 0) {
396+ p += 7;
397+ while (*p == ' ' || *p == '\t') p++;
398+ }
399+ if (strncmp(p, key, klen) != 0 || p[klen] != '=') continue;
400+ val = p + klen + 1;
401+ while (*val == ' ' || *val == '\t') val++;
402+ end = val + strlen(val);
403+ while (end > val && (end[-1] == '\r' || end[-1] == '\n' || end[-1] == ' ' || end[-1] == '\t'))
404+ *--end = '\0';
405+ if (end - val >= 2 && ((val[0] == '"' && end[-1] == '"') || (val[0] == '\'' && end[-1] == '\''))) {
406+ val++;
407+ *--end = '\0';
408+ }
409+ if (*val) {
410+ str_copy(out, outsz, val);
411+ found = 1;
412+ }
413+ }
414+ fclose(f);
415+ return found;
416+}
417+
418+static int pick_newest_session(const char *sessions_dir, char *sid_out, size_t sidsz)
419+{
420+ time_t best_t = 0;
421+ char best_name[256] = {0};
422+#ifdef _WIN32
423+ char pat[1200];
424+ WIN32_FIND_DATAA fd;
425+ HANDLE h;
426+ snprintf(pat, sizeof pat, "%s\\*", sessions_dir);
427+ h = FindFirstFileA(pat, &fd);
428+ if (h == INVALID_HANDLE_VALUE) return 0;
429+ do {
430+ char probe[1600];
431+ struct stat st;
432+ if (fd.cFileName[0] == '.') continue;
433+ if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
434+ snprintf(probe, sizeof probe, "%s\\%s\\config-snapshot.txt", sessions_dir, fd.cFileName);
435+ if (stat(probe, &st) != 0) {
436+ snprintf(probe, sizeof probe, "%s\\%s\\meta.json", sessions_dir, fd.cFileName);
437+ if (stat(probe, &st) != 0) continue;
438+ }
439+ if (st.st_mtime >= best_t) {
440+ best_t = st.st_mtime;
441+ str_copy(best_name, sizeof best_name, fd.cFileName);
442+ }
443+ } while (FindNextFileA(h, &fd));
444+ FindClose(h);
445+#else
446+ DIR *d = opendir(sessions_dir);
447+ struct dirent *de;
448+ if (!d) return 0;
449+ while ((de = readdir(d)) != NULL) {
450+ char probe[1600];
451+ struct stat st;
452+ if (de->d_name[0] == '.') continue;
453+ snprintf(probe, sizeof probe, "%s/%s/config-snapshot.txt", sessions_dir, de->d_name);
454+ if (stat(probe, &st) != 0) {
455+ snprintf(probe, sizeof probe, "%s/%s/meta.json", sessions_dir, de->d_name);
456+ if (stat(probe, &st) != 0) continue;
457+ }
458+ if (st.st_mtime >= best_t) {
459+ best_t = st.st_mtime;
460+ str_copy(best_name, sizeof best_name, de->d_name);
461+ }
462+ }
463+ closedir(d);
464+#endif
465+ if (!best_name[0]) return 0;
466+ str_copy(sid_out, sidsz, best_name);
467+ return 1;
468+}
469+
470+typedef struct {
471+ char name[160];
472+ char worktree[768];
473+ char session_dir[1280];
474+ char sid[160];
475+ char base_url[512];
476+} sess_entry_t;
477+
478+static int list_tmux_sessions(sess_entry_t *out, int max_n)
479+{
480+ char cmd[768];
481+ FILE *p;
482+ size_t len = 0;
483+ char *buf;
484+ int count = 0;
485+ const char *arr, *cur;
486+
487+ if (!out || max_n <= 0) return 0;
488+#ifdef _WIN32
489+ snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>NUL", tmux_bin());
490+#else
491+ snprintf(cmd, sizeof cmd, "\"%s\" --list --output-json 2>/dev/null", tmux_bin());
492+#endif
493+ p = sx_popen(cmd, "r");
494+ if (!p) return 0;
495+ buf = read_pipe_all(p, &len);
496+ sx_pclose(p);
497+ if (!buf || len == 0) { free(buf); return 0; }
498+
499+ arr = strstr(buf, "\"sessions\"");
500+ if (!arr) { free(buf); return 0; }
501+ arr = strchr(arr, '[');
502+ if (!arr) { free(buf); return 0; }
503+ cur = arr + 1;
504+
505+ while (*cur && count < max_n) {
506+ const char *ob = strchr(cur, '{');
507+ const char *cb;
508+ int depth = 0;
509+ const char *q;
510+ sess_entry_t *e;
511+ if (!ob) break;
512+ cb = ob;
513+ for (q = ob; *q; q++) {
514+ if (*q == '"') {
515+ q++;
516+ while (*q && *q != '"') { if (*q == '\\' && q[1]) q++; q++; }
517+ if (!*q) break;
518+ } else if (*q == '{') depth++;
519+ else if (*q == '}') { depth--; if (depth == 0) { cb = q; break; } }
520+ }
521+ if (cb <= ob) break;
522+ e = &out[count];
523+ memset(e, 0, sizeof *e);
524+ if (json_extract_str_after(ob, cb, "name", e->name, sizeof e->name) && e->name[0]) {
525+ json_extract_str_after(ob, cb, "worktree", e->worktree, sizeof e->worktree);
526+ if (!e->worktree[0]) {
527+ char proj[768] = {0};
528+ if (json_extract_str_after(ob, cb, "project", proj, sizeof proj) && proj[0])
529+ str_copy(e->worktree, sizeof e->worktree, proj);
530+ }
531+ if (e->worktree[0]) {
532+ char sroot[960];
533+ snprintf(sroot, sizeof sroot, "%s%c.scorpiox%csessions", e->worktree, SX_SEP, SX_SEP);
534+ if (pick_newest_session(sroot, e->sid, sizeof e->sid)) {
535+ char snap[1400];
536+ snprintf(e->session_dir, sizeof e->session_dir, "%.959s%c%.159s", sroot, SX_SEP, e->sid);
537+ snprintf(snap, sizeof snap, "%.1279s%cconfig-snapshot.txt", e->session_dir, SX_SEP);
538+ snapshot_get(snap, "OPENAI_BASE_URL", e->base_url, sizeof e->base_url);
539+ }
540+ }
541+ count++;
542+ }
543+ cur = cb + 1;
544+ }
545+ free(buf);
546+ return count;
547+}
548+
549+static int collect_default_roots(char roots[][512], int max_roots)
550+{
551+ int n = 0;
552+ const char *env;
553+ env = getenv("SX_SESSIONS_DIR");
554+ if (env && *env && is_dir(env) && n < max_roots)
555+ str_copy(roots[n++], 512, env);
556+#ifdef _WIN32
557+ {
558+ const char *lad = getenv("LOCALAPPDATA");
559+ const char *up = getenv("USERPROFILE");
560+ char cand[512];
561+ if (lad && *lad && n < max_roots) {
562+ snprintf(cand, sizeof cand, "%s\\scorpiox\\sessions", lad);
563+ if (is_dir(cand)) str_copy(roots[n++], 512, cand);
564+ }
565+ if (up && *up && n < max_roots) {
566+ snprintf(cand, sizeof cand, "%s\\.scorpiox\\sessions", up);
567+ if (is_dir(cand)) str_copy(roots[n++], 512, cand);
568+ }
569+ }
570+#else
571+ {
572+ const char *home = getenv("HOME");
573+ char cand[512];
574+ if (home && *home && n < max_roots) {
575+ snprintf(cand, sizeof cand, "%s/.scorpiox/sessions", home);
576+ if (is_dir(cand)) str_copy(roots[n++], 512, cand);
577+ }
578+ if (is_dir("/workspace/.scorpiox/sessions") && n < max_roots)
579+ str_copy(roots[n++], 512, "/workspace/.scorpiox/sessions");
580+ }
581+#endif
582+ return n;
583+}
584+
585+static int resolve_session_dir(const char *id, char *dir_out, size_t dirsz, char *sid_out, size_t sidsz)
586+{
587+ char roots[8][512];
588+ int nroots, i;
589+ sess_entry_t *list;
590+ int n;
591+
592+ if (dir_out && dirsz) dir_out[0] = '\0';
593+ if (sid_out && sidsz) sid_out[0] = '\0';
594+ if (!id || !*id || !safe_id(id)) return 0;
595+
596+ /* 1. Direct folder match inside SX_SESSIONS_DIR / default session roots */
597+ nroots = collect_default_roots(roots, 8);
598+ for (i = 0; i < nroots; i++) {
599+ char cand[1024];
600+ snprintf(cand, sizeof cand, "%.511s%c%.255s", roots[i], SX_SEP, id);
601+ if (is_dir(cand)) {
602+ str_copy(dir_out, dirsz, cand);
603+ str_copy(sid_out, sidsz, id);
604+ return 1;
605+ }
606+ }
607+
608+ /* 2. Active tmux sessions via scorpiox-tmux --list --output-json */
609+ list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list);
610+ if (list) {
611+ n = list_tmux_sessions(list, MAX_SESSIONS);
612+ for (i = 0; i < n; i++) {
613+ if (strcmp(list[i].name, id) == 0 && list[i].session_dir[0]) {
614+ str_copy(dir_out, dirsz, list[i].session_dir);
615+ str_copy(sid_out, sidsz, list[i].sid);
616+ free(list);
617+ return 1;
618+ }
619+ }
620+ for (i = 0; i < n; i++) {
621+ if (strstr(list[i].name, id) != NULL && list[i].session_dir[0]) {
622+ str_copy(dir_out, dirsz, list[i].session_dir);
623+ str_copy(sid_out, sidsz, list[i].sid);
624+ free(list);
625+ return 1;
626+ }
627+ }
628+ free(list);
629+ }
630+
631+#ifndef _WIN32
632+ /* 3. Common workspace/codebase fallback (/codebases/<id> or /codebases/.worktrees/<id>) */
633+ {
634+ char cand[640], sid[160];
635+ snprintf(cand, sizeof cand, "/codebases/.worktrees/%.255s/.scorpiox/sessions", id);
636+ if (pick_newest_session(cand, sid, sizeof sid)) {
637+ snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid);
638+ str_copy(sid_out, sidsz, sid);
639+ return 1;
640+ }
641+ snprintf(cand, sizeof cand, "/codebases/%.255s/.scorpiox/sessions", id);
642+ if (pick_newest_session(cand, sid, sizeof sid)) {
643+ snprintf(dir_out, dirsz, "%.639s/%.159s", cand, sid);
644+ str_copy(sid_out, sidsz, sid);
645+ return 1;
646+ }
647+ }
648+#endif
649+ return 0;
650+}
651+
652+/* ------------------------------------------------------------------ */
653+/* Action: sessions */
654+/* ------------------------------------------------------------------ */
655+
656+static void handle_sessions(void)
657+{
658+ sess_entry_t *list = (sess_entry_t *)calloc(MAX_SESSIONS, sizeof *list);
659+ int n = 0, i, emitted = 0;
660+ fputs("Content-Type: application/json; charset=utf-8\r\n\r\n{\"ok\":true,\"sessions\":[", stdout);
661+ if (list) {
662+ n = list_tmux_sessions(list, MAX_SESSIONS);
663+ for (i = 0; i < n; i++) {
664+ if (emitted++) fputc(',', stdout);
665+ fputs("{\"name\":", stdout); json_print_str(list[i].name);
666+ fputs(",\"sid\":", stdout); json_print_str(list[i].sid);
667+ fputs(",\"url\":", stdout); json_print_str(list[i].base_url);
668+ fputs(",\"has_url\":", stdout); fputs(list[i].base_url[0] ? "true" : "false", stdout);
669+ fputc('}', stdout);
670+ }
671+ free(list);
672+ }
673+ /* Fallback: if no tmux sessions found, enumerate SX_SESSIONS_DIR folders */
674+ if (emitted == 0) {
675+ char roots[4][512];
676+ int nr = collect_default_roots(roots, 4);
677+ if (nr > 0) {
678+#ifdef _WIN32
679+ char pat[600];
680+ WIN32_FIND_DATAA fd;
681+ HANDLE h;
682+ snprintf(pat, sizeof pat, "%s\\*", roots[0]);
683+ h = FindFirstFileA(pat, &fd);
684+ if (h != INVALID_HANDLE_VALUE) {
685+ do {
686+ char snap[1024], burl[512] = {0};
687+ if (fd.cFileName[0] == '.' || !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
688+ snprintf(snap, sizeof snap, "%s\\%s\\config-snapshot.txt", roots[0], fd.cFileName);
689+ snapshot_get(snap, "OPENAI_BASE_URL", burl, sizeof burl);
690+ if (emitted++) fputc(',', stdout);
691+ fputs("{\"name\":", stdout); json_print_str(fd.cFileName);
692+ fputs(",\"sid\":", stdout); json_print_str(fd.cFileName);
693+ fputs(",\"url\":", stdout); json_print_str(burl);
694+ fputs(",\"has_url\":", stdout); fputs(burl[0] ? "true" : "false", stdout);
695+ fputc('}', stdout);
696+ } while (FindNextFileA(h, &fd) && emitted < MAX_SESSIONS);
697+ FindClose(h);
698+ }
699+#else
700+ DIR *d = opendir(roots[0]);
701+ struct dirent *de;
702+ if (d) {
703+ while ((de = readdir(d)) != NULL && emitted < MAX_SESSIONS) {
704+ char cand[1024], snap[1200], burl[512] = {0};
705+ if (de->d_name[0] == '.') continue;
706+ snprintf(cand, sizeof cand, "%s/%s", roots[0], de->d_name);
707+ if (!is_dir(cand)) continue;
708+ snprintf(snap, sizeof snap, "%s/config-snapshot.txt", cand);
709+ snapshot_get(snap, "OPENAI_BASE_URL", burl, sizeof burl);
710+ if (emitted++) fputc(',', stdout);
711+ fputs("{\"name\":", stdout); json_print_str(de->d_name);
712+ fputs(",\"sid\":", stdout); json_print_str(de->d_name);
713+ fputs(",\"url\":", stdout); json_print_str(burl);
714+ fputs(",\"has_url\":", stdout); fputs(burl[0] ? "true" : "false", stdout);
715+ fputc('}', stdout);
716+ }
717+ closedir(d);
718+ }
719+#endif
720+ }
721+ }
722+ fputs("]}\n", stdout);
723+}
724+
725+/* ------------------------------------------------------------------ */
726+/* Action: metrics */
727+/* ------------------------------------------------------------------ */
728+
729+static void reply_json_err(const char *status, const char *msg, const char *url)
730+{
731+ printf("Status: %s\r\nContent-Type: application/json; charset=utf-8\r\n\r\n", status);
732+ fputs("{\"ok\":false,\"error\":", stdout);
733+ json_print_str(msg);
734+ if (url && *url) {
735+ fputs(",\"url\":", stdout);
736+ json_print_str(url);
737+ }
738+ fputs("}\n", stdout);
739+}
740+
741+static void strip_url_v1(const char *in, char *out, size_t outsz)
742+{
743+ size_t wl;
744+ str_copy(out, outsz, in);
745+ wl = strlen(out);
746+ while (wl > 0 && out[wl - 1] == '/') out[--wl] = '\0';
747+ if (wl >= 3 && strcmp(out + wl - 3, "/v1") == 0) out[wl - 3] = '\0';
748+}
749+
750+static void handle_metrics(const char *qs)
751+{
752+ char id[256] = {0}, url_q[512] = {0}, fresh[16] = {0};
753+ char sdir[1024] = {0}, rid[160] = {0}, base[512] = {0};
754+ const char *source = "session";
755+ char cache[1280] = {0};
756+ int use_cache = 0;
757+ char cmd[2048];
758+ FILE *p;
759+ char *out = NULL;
760+ size_t len = 0;
761+ int rc;
762+ char *last_brace;
763+
764+ get_query_val(qs, "id", id, sizeof id);
765+ get_query_val(qs, "url", url_q, sizeof url_q);
766+ get_query_val(qs, "fresh", fresh, sizeof fresh);
767+
768+ if (url_q[0]) {
769+ if (!url_ok(url_q)) {
770+ reply_json_err("400 Bad Request", "invalid url (must be http:// or https://)", url_q);
771+ return;
772+ }
773+ str_copy(base, sizeof base, url_q);
774+ source = "query";
775+ } else {
776+ char snap[1280];
777+ if (!id[0] || !safe_id(id)) {
778+ reply_json_err("400 Bad Request", "select a session or enter an SGLang URL", NULL);
779+ return;
780+ }
781+ if (!resolve_session_dir(id, sdir, sizeof sdir, rid, sizeof rid)) {
782+ reply_json_err("404 Not Found", "session not found on this node", NULL);
783+ return;
784+ }
785+ snprintf(snap, sizeof snap, "%s%cconfig-snapshot.txt", sdir, SX_SEP);
786+ if (!snapshot_get(snap, "OPENAI_BASE_URL", base, sizeof base)) {
787+ reply_json_err("404 Not Found", "session has no OPENAI_BASE_URL (not an OpenAI-compatible provider)", NULL);
788+ return;
789+ }
790+ if (!url_ok(base)) {
791+ reply_json_err("400 Bad Request", "session OPENAI_BASE_URL is not usable", base);
792+ return;
793+ }
794+ snprintf(cache, sizeof cache, "%s%c%s", sdir, SX_SEP, CACHE_NAME);
795+ use_cache = (strcmp(fresh, "1") != 0);
796+ }
797+
798+ if (use_cache && cache[0]) {
799+ struct stat st;
800+ if (stat(cache, &st) == 0 && (time(NULL) - st.st_mtime) < CACHE_SECS) {
801+ size_t clen = 0;
802+ char *cbuf = read_file_all(cache, &clen);
803+ if (cbuf && clen > 2) {
804+ char cached_url[512] = {0}, want_url[512] = {0};
805+ strip_url_v1(base, want_url, sizeof want_url);
806+ if (json_extract_str_after(cbuf, cbuf + clen, "url", cached_url, sizeof cached_url)
807+ && strcmp(cached_url, want_url) == 0) {
808+ fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout);
809+ fwrite(cbuf, 1, clen, stdout);
810+ if (cbuf[clen - 1] != '\n') fputc('\n', stdout);
811+ free(cbuf);
812+ return;
813+ }
814+ }
815+ free(cbuf);
816+ }
817+ }
818+
819+ /* url_ok() guarantees base contains no quotes, spaces, or shell metacharacters. */
820+#ifdef _WIN32
821+ snprintf(cmd, sizeof cmd, "\"%s\" \"%s\" 2>NUL", sgm_bin(), base);
822+#else
823+ snprintf(cmd, sizeof cmd, "\"%s\" '%s' 2>/dev/null", sgm_bin(), base);
824+#endif
825+ p = sx_popen(cmd, "r");
826+ if (!p) {
827+ reply_json_err("502 Bad Gateway", "failed to run scorpiox-sglang-metrics", base);
828+ return;
829+ }
830+ out = read_pipe_all(p, &len);
831+ rc = sx_pclose(p);
832+
833+ while (len > 0 && (out[len - 1] == '\n' || out[len - 1] == '\r' || out[len - 1] == ' ' || out[len - 1] == '\t'))
834+ out[--len] = '\0';
835+
836+ if (rc != 0 || !out || len < 2 || out[0] != '{' || out[len - 1] != '}') {
837+ free(out);
838+ reply_json_err("502 Bad Gateway",
839+ "no SGLang metrics at this URL (not SGLang, unreachable, or API-key gated)", base);
840+ return;
841+ }
842+
843+ /* Splice ok/updated_epoch/source/session before closing '}' */
844+ last_brace = out + len - 1;
845+ *last_brace = '\0';
846+ {
847+ size_t extra_cap = len + 512;
848+ char *final_json = (char *)malloc(extra_cap);
849+ if (!final_json) {
850+ free(out);
851+ reply_json_err("500 Internal Server Error", "out of memory", base);
852+ return;
853+ }
854+ snprintf(final_json, extra_cap,
855+ "%s,\"ok\":true,\"updated_epoch\":%lld,\"source\":\"%s\",\"session\":\"%s\"}\n",
856+ out, (long long)time(NULL), source, rid[0] ? rid : id);
857+ if (cache[0] && strcmp(source, "session") == 0) {
858+ char tmp[1344];
859+ FILE *cf;
860+ snprintf(tmp, sizeof tmp, "%s.tmp", cache);
861+ cf = fopen(tmp, "wb");
862+ if (cf) {
863+ fputs(final_json, cf);
864+ fclose(cf);
865+ rename(tmp, cache);
866+ }
867+ }
868+ fputs("Content-Type: application/json; charset=utf-8\r\n\r\n", stdout);
869+ fputs(final_json, stdout);
870+ free(final_json);
871+ }
872+ free(out);
873+}
874+
875+/* ------------------------------------------------------------------ */
876+/* HTML UI */
877+/* ------------------------------------------------------------------ */
878+
879+static const char *UI_CSS =
880+"body{font-family:var(--font);font-size:13px;line-height:1.4;min-height:100vh;display:flex;flex-direction:column}\n"
881+".wrap{max-width:680px;width:100%;margin:0 auto;padding:14px 16px 24px;display:flex;flex-direction:column;gap:10px}\n"
882+"html.embedded .wrap{max-width:none;padding:10px 12px 14px;gap:8px}\n"
883+".hdr{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}\n"
884+".hdr-l{display:flex;align-items:center;gap:8px;min-width:0;flex:1}\n"
885+".dot{width:8px;height:8px;border-radius:50%;background:var(--gray);flex-shrink:0;transition:background .25s var(--ease)}\n"
886+".dot.live{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.18)}\n"
887+".dot.stale{background:var(--orange);box-shadow:0 0 0 3px rgba(255,159,10,.18)}\n"
888+".dot.err{background:var(--red);box-shadow:0 0 0 3px rgba(255,69,58,.18)}\n"
889+".title{font-size:14px;font-weight:700;letter-spacing:-.015em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
890+".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"
891+".bar{display:flex;align-items:center;gap:6px;flex-wrap:wrap}\n"
892+".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"
893+".ctl:focus{border-color:var(--blue)}\n"
894+"select.ctl{flex:0 1 180px;cursor:pointer}\n"
895+"input.ctl{flex:1 1 170px;font-family:var(--mono);font-size:11px}\n"
896+".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"
897+".btn:hover{border-color:var(--line-2);background:var(--surface-hover)}\n"
898+".btn.pri{background:var(--blue);border-color:transparent;color:#fff}\n"
899+".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"
900+".card.stale{opacity:.6}\n"
901+".sg-row{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n"
902+".sg-dim{color:var(--text-2)}\n"
903+".sg-hot{color:var(--green);font-weight:700}\n"
904+".sg-bar{height:5px;border-radius:3px;background:var(--line);overflow:hidden;margin:3px 0 5px}\n"
905+".sg-bar>i{display:block;height:100%;background:var(--green);transition:width .3s var(--ease)}\n"
906+".sg-bar.warn>i{background:var(--orange)}\n"
907+".sg-bar.full>i{background:var(--red)}\n"
908+".sg-msg{color:var(--text-2);white-space:normal;font-family:var(--font);font-size:12.5px}\n"
909+".sg-err{color:var(--red);white-space:normal;font-family:var(--font);font-size:12.5px}\n"
910+".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";
911+
912+static const char *UI_BODY =
913+"<div class='wrap'>\n"
914+" <div class='hdr'>\n"
915+" <div class='hdr-l'>\n"
916+" <span class='dot' id='dot'></span>\n"
917+" <span class='title' id='title'>SGLang Monitor</span>\n"
918+" <span class='badge' id='srcBadge' style='display:none'></span>\n"
919+" </div>\n"
920+" <button class='btn' id='btnRefresh' type='button' title='Force fresh poll'>Refresh</button>\n"
921+" <button class='btn embed-hide' id='themeToggle' type='button' title='Toggle dark / light'>Theme</button>\n"
922+" </div>\n"
923+" <div class='bar'>\n"
924+" <select class='ctl' id='sessSel' aria-label='Session'><option value=''>Active session&#8230;</option></select>\n"
925+" <input class='ctl' id='urlIn' type='text' placeholder='Optional SGLang URL override (http://host:port)' autocomplete='off'>\n"
926+" <button class='btn pri' id='btnGo' type='button'>Probe</button>\n"
927+" </div>\n"
928+" <div class='card' id='card'><div class='sg-msg'>Connecting&#8230;</div></div>\n"
929+" <div class='meta-foot'><span id='urlLbl'></span><span id='tsLbl'></span></div>\n"
930+"</div>\n"
931+"<script>\n"
932+"(function(){\n"
933+" var sp = new URLSearchParams(location.search);\n"
934+" var curSid = sp.get('id') || '';\n"
935+" var curUrl = sp.get('url') || '';\n"
936+" var timer = null, busy = false, lastOk = 0;\n"
937+" var $=function(id){return document.getElementById(id);};\n"
938+" function apiUrl(extra){\n"
939+" var out = new URLSearchParams();\n"
940+" ['plugin','node','pwd'].forEach(function(k){ if(sp.get(k)) out.set(k, sp.get(k)); });\n"
941+" Object.keys(extra||{}).forEach(function(k){\n"
942+" if(extra[k]!==undefined && extra[k]!==null && extra[k]!=='') out.set(k, String(extra[k]));\n"
943+" });\n"
944+" return location.pathname + '?' + out.toString();\n"
945+" }\n"
946+" function sgK(n){n=Number(n)||0;if(n>=1e6)return (n/1e6).toFixed(1)+'M';if(n>=1e3)return Math.round(n/1e3)+'K';return String(Math.round(n));}\n"
947+" function sgN(n){return (Number(n)||0).toLocaleString('en-US');}\n"
948+" function sgF(n,d){return (Number(n)||0).toFixed(d);}\n"
949+" function row(cls,txt){var el=document.createElement('div');el.className='sg-row '+(cls||'');el.textContent=txt;return el;}\n"
950+" function render(d){\n"
951+" var card=$('card'), dot=$('dot'), title=$('title'), badge=$('srcBadge');\n"
952+" card.innerHTML='';\n"
953+" if(!d || d.error){\n"
954+" dot.className='dot err';\n"
955+" title.textContent='SGLang Monitor';\n"
956+" card.classList.remove('stale');\n"
957+" var e=document.createElement('div'); e.className='sg-err';\n"
958+" e.textContent=(d&&d.error)?String(d.error):'No SGLang metrics';\n"
959+" card.appendChild(e);\n"
960+" if(d&&d.url){$('urlLbl').textContent=d.url;}\n"
961+" return;\n"
962+" }\n"
963+" var age = (typeof d.updated_epoch==='number') ? Math.max(0, Math.floor(Date.now()/1000)-d.updated_epoch) : 0;\n"
964+" var stale = age > 20;\n"
965+" dot.className = 'dot ' + (stale ? 'stale' : 'live');\n"
966+" card.classList.toggle('stale', stale);\n"
967+" var model = (d.model||'').split('/').pop() || 'SGLang';\n"
968+" title.textContent = 'SGLang \\u00b7 ' + model + (stale ? ' (stale)' : '');\n"
969+" if(d.source){badge.style.display='';badge.textContent=d.source==='query'?'URL':(curSid||d.session||'session');}\n"
970+" var run=Number(d.num_running_reqs||0), q=Number(d.num_queue_reqs||0), mx=Number(d.max_running_reqs||0);\n"
971+" card.appendChild(row(run>0?'sg-hot':'', 'run '+run+' queue '+q+(mx?(' max '+mx):'')));\n"
972+" var tg=Number(d.gen_throughput||0), pp=Number(d.pp_tok_s||0), gen=Number(d.gen_tok_s||0);\n"
973+" card.appendChild(row(tg>0?'sg-hot':'', 'tg '+sgF(tg,1)+' t/s pp '+sgF(pp,0)+' t/s gen '+sgF(gen,0)+' t/s'));\n"
974+" var kv=Number(d.token_usage||0), pct=Math.round(kv*100), used=Number(d.num_used_tokens||0), cap=Number(d.max_total_num_tokens||0), ctx=Number(d.context_len||0);\n"
975+" if(cap>0||kv>0){\n"
976+" card.appendChild(row('', 'KV '+sgK(used)+'/'+sgK(cap)+' ('+pct+'%)'+(ctx?(' ctx '+sgK(ctx)):'')));\n"
977+" var bar=document.createElement('div'); bar.className='sg-bar'+(pct>=90?' full':pct>=70?' warn':'');\n"
978+" var fill=document.createElement('i'); fill.style.width=Math.max(0,Math.min(100,pct))+'%'; bar.appendChild(fill); card.appendChild(bar);\n"
979+" }\n"
980+" var cr=d.cache_hit_rate, crL=d.cache_hit_rate_lifetime;\n"
981+" if(typeof cr==='number'||typeof crL==='number'){\n"
982+" var cs='cache '+(typeof cr==='number'?(Math.round(cr*100)+'%'):'\\u2014');\n"
983+" if(typeof crL==='number') cs+=' (life '+Math.round(crL*100)+'%)';\n"
984+" card.appendChild(row('', cs));\n"
985+" }\n"
986+" if(d.spec_algo||typeof d.spec_accept_length==='number'){\n"
987+" var spTxt='spec '+(d.spec_algo||'on');\n"
988+" if(typeof d.spec_accept_length==='number') spTxt+=' len '+sgF(d.spec_accept_length,2);\n"
989+" if(typeof d.spec_accept_rate==='number') spTxt+=' acc '+Math.round(d.spec_accept_rate*100)+'%';\n"
990+" card.appendChild(row('', spTxt));\n"
991+" }\n"
992+" var itl=d.itl_ms, ttft=d.ttft_ms, ql=d.queue_ms;\n"
993+" if(typeof itl==='number'||typeof ttft==='number'||typeof ql==='number'){\n"
994+" var lt=[];\n"
995+" if(typeof itl==='number') lt.push('itl '+sgF(itl,1)+' ms');\n"
996+" if(typeof ttft==='number') lt.push('ttft '+sgF(ttft,0)+' ms');\n"
997+" if(typeof ql==='number') lt.push('queue '+sgF(ql,0)+' ms');\n"
998+" card.appendChild(row('sg-dim', lt.join(' ')));\n"
999+" }\n"
1000+" var reqs=Number(d.requests_total||0), pt=Number(d.prompt_tokens_total||0), gt=Number(d.generation_tokens_total||0);\n"
1001+" if(reqs||pt||gt) card.appendChild(row('sg-dim', 'reqs '+sgN(reqs)+' prompt '+sgK(pt)+' gen '+sgK(gt)));\n"
1002+" $('urlLbl').textContent = d.url || '';\n"
1003+" $('tsLbl').textContent = 'updated ' + new Date().toLocaleTimeString();\n"
1004+" }\n"
1005+" async function poll(fresh){\n"
1006+" if(busy) return;\n"
1007+" if(!curUrl && !curSid){\n"
1008+" render({error:'Pick a session above or enter an SGLang server URL.'});\n"
1009+" return;\n"
1010+" }\n"
1011+" busy = true;\n"
1012+" try{\n"
1013+" var q = {action:'metrics'};\n"
1014+" if(curUrl) q.url = curUrl; else q.id = curSid;\n"
1015+" if(fresh) q.fresh = '1';\n"
1016+" var r = await fetch(apiUrl(q));\n"
1017+" var d = null; try{ d = await r.json(); }catch(e){}\n"
1018+" if(!r.ok || !d || d.error){\n"
1019+" if(!lastOk || fresh || Date.now()-lastOk > 15000) render(d||{error:'HTTP '+r.status});\n"
1020+" }else{\n"
1021+" lastOk = Date.now();\n"
1022+" render(d);\n"
1023+" }\n"
1024+" }catch(e){\n"
1025+" if(!lastOk) render({error:'Network error polling SGLang metrics'});\n"
1026+" }finally{ busy = false; }\n"
1027+" }\n"
1028+" async function loadSessions(){\n"
1029+" try{\n"
1030+" var r = await fetch(apiUrl({action:'sessions'}));\n"
1031+" var d = await r.json();\n"
1032+" var sel = $('sessSel'); sel.innerHTML = '';\n"
1033+" var list = (d && Array.isArray(d.sessions)) ? d.sessions : [];\n"
1034+" if(!list.length){\n"
1035+" var o = document.createElement('option'); o.value=''; o.textContent='No sessions'; sel.appendChild(o);\n"
1036+" }else{\n"
1037+" var ph = document.createElement('option'); ph.value=''; ph.textContent='Select session\\u2026'; sel.appendChild(ph);\n"
1038+" list.forEach(function(s){\n"
1039+" var o = document.createElement('option');\n"
1040+" o.value = s.name; o.textContent = s.name + (s.has_url ? '' : ' (no url)');\n"
1041+" if(curSid && s.name === curSid) o.selected = true;\n"
1042+" sel.appendChild(o);\n"
1043+" });\n"
1044+" if(!curSid && !curUrl){\n"
1045+" var pick = list.find(function(s){return s.has_url;}) || list[0];\n"
1046+" if(pick){ curSid = pick.name; sel.value = curSid; }\n"
1047+" }\n"
1048+" }\n"
1049+" }catch(e){}\n"
1050+" }\n"
1051+" $('sessSel').onchange = function(){ curSid = this.value; curUrl = ''; $('urlIn').value = ''; lastOk = 0; poll(true); };\n"
1052+" $('btnGo').onclick = function(){ curUrl = $('urlIn').value.trim(); lastOk = 0; poll(true); };\n"
1053+" $('urlIn').onkeydown = function(e){ if(e.key==='Enter'){ curUrl = this.value.trim(); lastOk = 0; poll(true); } };\n"
1054+" $('btnRefresh').onclick = function(){ poll(true); };\n"
1055+" var tt = $('themeToggle');\n"
1056+" if(tt) tt.onclick = function(){\n"
1057+" var c = document.documentElement.getAttribute('data-theme')==='light'?'dark':'light';\n"
1058+" document.documentElement.setAttribute('data-theme', c);\n"
1059+" try{localStorage.setItem('bot_theme', c);}catch(e){}\n"
1060+" };\n"
1061+" if(curUrl) $('urlIn').value = curUrl;\n"
1062+" document.addEventListener('visibilitychange', function(){\n"
1063+" if(document.visibilityState==='visible') poll(false);\n"
1064+" });\n"
1065+" loadSessions().then(function(){\n"
1066+" poll(false);\n"
1067+" timer = setInterval(function(){ if(document.visibilityState==='visible') poll(false); }, 5000);\n"
1068+" });\n"
1069+"})();\n"
1070+"</script>\n";
1071+
1072+static void handle_html(void)
1073+{
1074+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1075+ "Cache-Control: no-cache, no-store, must-revalidate\r\n\r\n"
1076+ "<!DOCTYPE html><html lang='en'><head>\n"
1077+ "<meta charset='utf-8'>\n"
1078+ "<meta name='viewport' content='width=device-width,initial-scale=1'>\n"
1079+ "<title>SGLang Monitor · SCORPIOX BOT</title>\n", stdout);
1080+ fputs(SX_BOT_THEME_PREPAINT, stdout);
1081+ fputs("<style>\n", stdout);
1082+ fputs(SX_BOT_THEME_TOKENS, stdout);
1083+ fputs("\n", stdout);
1084+ fputs(UI_CSS, stdout);
1085+ fputs("</style></head><body>\n", stdout);
1086+ fputs(UI_BODY, stdout);
1087+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1088+ fputs("</body></html>\n", stdout);
1089+}
1090+
1091+int main(int argc, char **argv)
1092+{
1093+ const char *qs;
1094+ char action[64] = {0}, fmt[32] = {0};
1095+
1096+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1097+ fputs("{\"name\":\"sglang\",\"desc\":\"SGLang metrics\",\"kind\":\"ui\",\"version\":\"" PLUGIN_VERSION "\"}\n", stdout);
1098+ return 0;
1099+ }
1100+
1101+ require_node_auth();
1102+
1103+ qs = getenv("QUERY_STRING");
1104+ get_query_val(qs, "action", action, sizeof action);
1105+ get_query_val(qs, "format", fmt, sizeof fmt);
1106+
1107+ if (strcmp(action, "sessions") == 0) {
1108+ handle_sessions();
1109+ return 0;
1110+ }
1111+ if (strcmp(action, "metrics") == 0 || strcmp(fmt, "json") == 0) {
1112+ handle_metrics(qs);
1113+ return 0;
1114+ }
1115+
1116+ handle_html();
1117+ return 0;
1118+}
tests/run.sh+91−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..08746b1index 0000000..08746b1
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,91 @@@@ -0,0 +1,91 @@
1+#!/bin/sh
2+# tests/run.sh -- offline test suite for plugin_sglang
3+set -eu
4+
5+BIN="./plugin_sglang"
6+PASS=0
7+FAIL=0
8+
9+ok() { PASS=$((PASS + 1)); printf ' PASS %s\n' "$1"; }
10+fail() { FAIL=$((FAIL + 1)); printf ' FAIL %s\n' "$1"; }
11+
12+assert_contains() {
13+ case "$1" in
14+ *"$2"*) ok "$3" ;;
15+ *) fail "$3 (missing: $2)" ;;
16+ esac
17+}
18+
19+TMP=$(mktemp -d)
20+trap 'rm -rf "$TMP"' EXIT
21+
22+# Mock scorpiox-sglang-metrics binary
23+cat > "$TMP/mock-sgm" << 'EOF'
24+#!/bin/sh
25+URL="$1"
26+URL="${URL%/}"
27+URL="${URL%/v1}"
28+printf '{"url":"%s","model":"org/demo-model","num_running_reqs":2,"num_queue_reqs":1,"max_running_reqs":64,"gen_throughput":142.5,"pp_tok_s":3200,"gen_tok_s":285,"token_usage":0.42,"num_used_tokens":42000,"max_total_num_tokens":100000,"context_len":131072,"cache_hit_rate":0.78,"cache_hit_rate_lifetime":0.65,"spec_algo":"EAGLE","spec_accept_length":3.12,"spec_accept_rate":0.74,"itl_ms":6.8,"ttft_ms":85,"queue_ms":4,"requests_total":120,"prompt_tokens_total":510000,"generation_tokens_total":88000}\n' "$URL"
29+EOF
30+chmod +x "$TMP/mock-sgm"
31+
32+# Mock session store
33+mkdir -p "$TMP/sessions/demo-sess"
34+cat > "$TMP/sessions/demo-sess/config-snapshot.txt" << 'EOF'
35+OPENAI_BASE_URL=http://127.0.0.1:30000/v1
36+EOF
37+cat > "$TMP/sessions/demo-sess/meta.json" << 'EOF'
38+{"id":"demo-sess","cwd":"/tmp"}
39+EOF
40+
41+echo "==> plugin_sglang offline tests"
42+
43+# 1. --meta
44+OUT=$("$BIN" --meta)
45+assert_contains "$OUT" '"name":"sglang"' "meta name"
46+assert_contains "$OUT" '"desc":"SGLang metrics"' "meta desc"
47+assert_contains "$OUT" '"kind":"ui"' "meta kind"
48+
49+# 2. SX_PLUGIN_META=1
50+OUT=$(SX_PLUGIN_META=1 "$BIN")
51+assert_contains "$OUT" '"name":"sglang"' "SX_PLUGIN_META=1"
52+
53+# 3. Auth gate (401 without pwd, 200 with header)
54+OUT=$(BOT_PASSWORD="demo-auth-val" QUERY_STRING="action=sessions" "$BIN")
55+assert_contains "$OUT" 'Status: 401 Unauthorized' "auth rejects missing password"
56+
57+OUT=$(BOT_PASSWORD="demo-auth-val" HTTP_X_BOT_PASSWORD="demo-auth-val" SX_SESSIONS_DIR="$TMP/sessions" SCORPIOX_TMUX_BIN="/nonexistent" QUERY_STRING="action=sessions" "$BIN")
58+assert_contains "$OUT" '"ok":true' "auth accepts X-Bot-Password"
59+assert_contains "$OUT" '"demo-sess"' "sessions lists SX_SESSIONS_DIR fallback"
60+
61+# 4. Metrics from session config-snapshot.txt
62+OUT=$(SX_SESSIONS_DIR="$TMP/sessions" SCORPIOX_TMUX_BIN="/nonexistent" SCORPIOX_SGLANG_METRICS_BIN="$TMP/mock-sgm" QUERY_STRING="action=metrics&id=demo-sess" "$BIN")
63+assert_contains "$OUT" '"ok":true' "metrics ok"
64+assert_contains "$OUT" '"model":"org/demo-model"' "metrics model"
65+assert_contains "$OUT" '"source":"session"' "metrics source=session"
66+
67+# 5. Cache file written and reused
68+if [ -f "$TMP/sessions/demo-sess/sglang_metrics.json" ]; then
69+ ok "cache file created"
70+else
71+ fail "cache file created"
72+fi
73+OUT=$(SX_SESSIONS_DIR="$TMP/sessions" SCORPIOX_TMUX_BIN="/nonexistent" SCORPIOX_SGLANG_METRICS_BIN="/nonexistent" QUERY_STRING="action=metrics&id=demo-sess" "$BIN")
74+assert_contains "$OUT" '"model":"org/demo-model"' "cache hit serves without spawning binary"
75+
76+# 6. Direct ?url= override
77+OUT=$(SCORPIOX_SGLANG_METRICS_BIN="$TMP/mock-sgm" QUERY_STRING="action=metrics&url=http%3A%2F%2F127.0.0.1%3A30001" "$BIN")
78+assert_contains "$OUT" '"source":"query"' "url override source=query"
79+
80+# 7. Bad URL rejected (400)
81+OUT=$(SCORPIOX_SGLANG_METRICS_BIN="$TMP/mock-sgm" QUERY_STRING="action=metrics&url=file%3A%2F%2F%2Fetc%2Fpasswd" "$BIN")
82+assert_contains "$OUT" 'Status: 400 Bad Request' "rejects non-http scheme"
83+
84+# 8. HTML UI & theme handoff
85+OUT=$(QUERY_STRING="embed=1&theme=light" "$BIN")
86+assert_contains "$OUT" 'Content-Type: text/html' "html content-type"
87+assert_contains "$OUT" 'sx-theme-request' "theme handoff script present"
88+assert_contains "$OUT" 'SGLang Monitor' "html title present"
89+
90+printf '\nTotal: %d passed, %d failed\n' "$PASS" "$FAIL"
91+[ "$FAIL" -eq 0 ]
092