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