The Kurgan 1.0.0: one process for the LCD, fans, lighting, local LLM servers and the web UI

This commit is contained in:
paul committed 2026-12-05 16:20:49 +13:00
commit f631386618
71 files changed
+14616

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""AI: the local LLM servers (Strata or llama.cpp), one running at a time."""
+497
View File
@@ -0,0 +1,497 @@
"""The two LLM servers: how to start and stop each one, and how to watch it.
Both monitors report the same shape, so the web UI shows either one the same way:
model: {"state": offline|unloaded|loading|idle|sleeping|reading|generating|failed, "detail", "id", "context"}
live: the request in progress: {"phase", "progress", "read", "total", "generated", "tok_s", "elapsed"}
requests: the latest finished requests, newest first
averages: prompt-reading and generation speed over those requests
Polling never wakes a model: Strata's /health and /metrics and llama-server's /models and
/metrics don't count as use. llama's live progress comes from its log, because polling
/slots would reset its idle timer.
"""
from __future__ import annotations
import collections
import ctypes
import ctypes.wintypes as wt
import json
import logging
import os
import re
import threading
import time
import urllib.error
import urllib.request
from datetime import datetime
from kurgan import paths
from kurgan.ai import config
log = logging.getLogger(__name__)
LOG_DIR = os.path.join(paths.DATA_DIR, "logs")
KEEP_REQUESTS = 20
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_k32.OpenEventW.argtypes, _k32.OpenEventW.restype = [wt.DWORD, wt.BOOL, wt.LPCWSTR], wt.HANDLE
_k32.SetEvent.argtypes, _k32.SetEvent.restype = [wt.HANDLE], wt.BOOL
_k32.CloseHandle.argtypes = [wt.HANDLE]
EVENT_MODIFY_STATE = 0x2
def http(method: str, url: str, body: dict | None = None, headers: dict | None = None,
timeout: float = 3) -> tuple[int, bytes]:
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(url, data=data, method=method, headers={
**({"Content-Type": "application/json"} if body is not None else {}), **(headers or {})})
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, response.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def _clock(epoch: float | None) -> str | None:
return None if epoch is None else datetime.fromtimestamp(epoch).strftime("%H:%M:%S")
def _rate(tokens: float, ms: float) -> float | None:
return round(tokens / ms * 1000, 1) if ms and tokens else None
class Backend:
key = "" # also its path on The Kurgan's web server: /<key>/
label = ""
stop_timeout = 10.0
def __init__(self, settings):
self.settings = settings
self.lock = threading.Lock()
self.status: dict = self.offline()
self.public = "http://127.0.0.1:8080" # The Kurgan's web server; set by the service
# -- configuration
@property
def port(self) -> int:
"""Where the server listens, on 127.0.0.1, behind The Kurgan."""
raise NotImplementedError
@property
def prefix(self) -> str:
"""The path the server itself serves under ("" = the root)."""
return ""
def proxy_headers(self) -> dict:
"""Headers The Kurgan's proxy sets on every request it passes to this server."""
return {}
def variants(self) -> list[dict]:
return []
def variant(self) -> str | None:
return None
def model_label(self) -> str:
raise NotImplementedError
def model_ids(self) -> list[str]:
"""The model ids its /v1/models lists (answered by The Kurgan while the server is stopped)."""
raise NotImplementedError
def links(self) -> dict:
return {"chat": f"{self.public}/{self.key}/", "api": f"{self.public}/{self.key}/v1",
"internal": f"http://127.0.0.1:{self.port}{self.prefix}/"}
def check_files(self) -> str | None:
"""A reason it can't start (missing file), or None."""
return None
# -- process
def command(self) -> tuple[list[str], str, str]:
"""(argv, working directory, log file for stdout/stderr)."""
raise NotImplementedError
def before_start(self) -> None:
pass
def request_stop(self, child) -> None:
child.kill()
# -- monitoring
@staticmethod
def offline() -> dict:
return {"model": {"state": "offline", "detail": "", "id": None, "context": None},
"live": None, "requests": [], "averages": {"prefill_tps": None, "decode_tps": None, "requests": 0}}
def poll(self) -> None:
raise NotImplementedError
def mark_offline(self) -> None:
with self.lock:
self.status = self.offline()
def snapshot(self) -> dict:
with self.lock:
return json.loads(json.dumps(self.status))
def load(self) -> None:
raise NotImplementedError
def unload(self) -> None:
raise NotImplementedError
class StrataBackend(Backend):
key = "strata"
label = "Strata"
stop_timeout = 45.0 # Strata's own --shutdown-timeout is 30 s
def __init__(self, settings):
super().__init__(settings)
self._stop_name: str | None = None
self._starts = 0
@property
def root(self) -> str:
return self.settings.get("ai", "strata_root", config.STRATA_ROOT)
@property
def port(self) -> int:
return self.settings.get("ai", "strata_port", config.STRATA_PORT)
def variant(self) -> str:
return self.settings.get("ai", "strata_model")
def variants(self) -> list[dict]:
return [{"key": k, "label": label} for k, (label, _, _) in config.STRATA_MODELS.items()]
def model_label(self) -> str:
return config.STRATA_MODELS[self.variant()][0]
def model_ids(self) -> list[str]:
return [config.STRATA_MODELS[self.variant()][2]]
def _python(self) -> str:
return os.path.join(self.root, "terminal", ".venv", "Scripts", "pythonw.exe")
def check_files(self) -> str | None:
config_file = os.path.join(self.root, "terminal", config.STRATA_MODELS[self.variant()][1])
for path in (self._python(), config_file):
if not os.path.exists(path):
return f"Not found: {path}"
return None
def command(self) -> tuple[list[str], str, str]:
self._starts += 1
self._stop_name = f"Local\\KurganStrataStop-{os.getpid()}-{self._starts}"
host = os.path.join(paths.PACKAGE_DIR, "ai", "strata_host.py")
argv = [self._python(), host, "--root", self.root, "--config", config.STRATA_MODELS[self.variant()][1],
"--port", str(self.port), "--idle-unload", str(config.STRATA_IDLE_UNLOAD),
"--stop-event", self._stop_name]
return argv, os.path.join(self.root, "terminal"), os.path.join(LOG_DIR, "strata-host.log")
def request_stop(self, child) -> None:
"""Ask Strata to shut down cleanly; the service kills it if it takes too long."""
handle = _k32.OpenEventW(EVENT_MODIFY_STATE, False, self._stop_name) if self._stop_name else None
if not handle:
log.warning("Strata's stop event isn't available; ending it instead")
child.kill()
return
try:
_k32.SetEvent(handle)
finally:
_k32.CloseHandle(handle)
def _url(self, path: str) -> str:
return f"http://127.0.0.1:{self.port}{path}"
def poll(self) -> None:
code, body = http("GET", self._url("/health"))
if code != 200:
raise ValueError(f"/health returned HTTP {code}")
health = json.loads(body)
code, body = http("GET", self._url("/metrics"), headers={"Accept": "application/json"})
metrics = json.loads(body) if code == 200 else {}
live_in = metrics.get("live") or {}
state = live_in.get("state") or ("idle" if health.get("loaded") else "unloaded")
live = None
if state in ("reading", "generating"):
read, total = live_in.get("prompt_read"), live_in.get("prompt_total")
live = {"phase": state, "read": read, "total": total or live_in.get("prompt_tokens"),
"progress": round(read / total, 3) if read is not None and total else None,
"generated": live_in.get("generated"), "tok_s": live_in.get("tok_s"),
"elapsed": live_in.get("elapsed_s"), "queued": live_in.get("queued")}
requests = []
for r in (metrics.get("requests") or [])[:KEEP_REQUESTS]:
prompt, reused = r.get("prompt_tokens") or 0, r.get("reused") or 0
requests.append({"time": _clock(r.get("time")), "status": r.get("finish") or "ok",
"prompt": prompt, "reused": reused, "output": r.get("output_tokens") or 0,
"prefill_tps": _rate(prompt - reused, r.get("prompt_ms") or 0),
"decode_tps": r.get("decode_tok_s"), "duration": r.get("duration_s")})
totals = metrics.get("totals") or {}
engine = metrics.get("engine") or {}
status = {
"model": {"state": state, "detail": "", "id": health.get("model"),
"context": health.get("max_context"), "engine": engine.get("version")},
"live": live, "requests": requests,
"averages": {"prefill_tps": _rate((totals.get("prompt_tokens") or 0) - (totals.get("reused") or 0),
totals.get("prompt_ms") or 0),
"decode_tps": _rate(totals.get("output_tokens") or 0, totals.get("decode_ms") or 0),
"requests": totals.get("requests") or 0},
}
with self.lock:
self.status = status
def load(self) -> None:
code, body = http("POST", self._url("/load"), {}, timeout=600)
log.info("Strata load: HTTP %s %s", code, body[:200])
if code != 200:
raise RuntimeError(_error_text(body) or f"Strata load failed (HTTP {code})")
def unload(self) -> None:
code, body = http("POST", self._url("/unload"), {}, timeout=120)
log.info("Strata unload: HTTP %s %s", code, body[:200])
if code == 409:
raise RuntimeError("Strata is answering a request; unload it when it finishes.")
if code != 200:
raise RuntimeError(_error_text(body) or f"Strata unload failed (HTTP {code})")
def _error_text(body: bytes) -> str | None:
try:
error = json.loads(body).get("error")
return error.get("message") if isinstance(error, dict) else str(error) if error else None
except (ValueError, AttributeError):
return None
# --- llama.cpp log parsing (ported from the Qwen4 service) -------------------------------
RE_START = re.compile(r"task (\d+) \| processing task")
RE_PREFILL = re.compile(r"task (\d+) \| prompt processing, n_tokens =\s*(\d+), progress =\s*([\d.]+), "
r"t =\s*([\d.]+) s / ([\d.]+) tokens per second")
RE_GEN = re.compile(r"task (\d+) \| n_gen =\s*(\d+), tg =\s*([\d.]+) t/s, tg_3s =\s*([\d.]+) t/s")
RE_PROMPT_DONE = re.compile(r"task (\d+) \| prompt eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second")
RE_EVAL_DONE = re.compile(r"task (\d+) \|\s+eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second")
RE_STOP = re.compile(r"task (\d+) \| stop processing: n_tokens =\s*(\d+), truncated = (\d)")
class LlamaLog:
"""Follows llama-server's log for the request in progress and the finished ones."""
def __init__(self) -> None:
self.lock = threading.Lock()
self.current: dict | None = None
self.requests: collections.deque[dict] = collections.deque(maxlen=KEEP_REQUESTS)
def feed(self, line: str, now: float | None = None) -> None:
now = time.time() if now is None else now
with self.lock:
if match := RE_START.search(line):
self.current = {"start": now, "phase": "reading", "progress": 0.0, "read": 0, "generated": 0,
"prefill_tps": None, "decode_tps": None}
return
current = self.current
if current is None:
return
if match := RE_PREFILL.search(line):
current.update(phase="reading", read=int(match[2]), progress=float(match[3]),
prefill_tps=float(match[5]))
elif match := RE_GEN.search(line):
current.update(phase="generating", generated=int(match[2]), decode_tps=float(match[4]))
elif match := RE_PROMPT_DONE.search(line):
current.update(prompt_ms=float(match[2]), read=int(match[3]), prefill_final=float(match[4]))
elif match := RE_EVAL_DONE.search(line):
current.update(decode_ms=float(match[2]), generated=int(match[3]), decode_final=float(match[4]))
elif match := RE_STOP.search(line):
context = int(match[2])
read, generated = current.get("read", 0), current.get("generated", 0)
cached = max(0, context - read - generated)
self.requests.appendleft({
"time": datetime.fromtimestamp(now).strftime("%H:%M:%S"),
"status": "truncated" if match[3] == "1" else "ok",
"prompt": cached + read, "reused": cached, "output": generated,
"prefill_tps": current.get("prefill_final"), "decode_tps": current.get("decode_final"),
"duration": round(now - current["start"], 1),
"prompt_ms": current.get("prompt_ms", 0.0), "decode_ms": current.get("decode_ms", 0.0),
})
self.current = None
def reset(self) -> None:
with self.lock:
self.current = None
def snapshot(self) -> tuple[dict | None, list[dict], dict]:
with self.lock:
requests = list(self.requests)
current = dict(self.current) if self.current else None
live = None
if current:
live = {"phase": current["phase"], "progress": current.get("progress"), "read": current.get("read"),
"total": None, "generated": current.get("generated"),
"tok_s": current.get("decode_tps") if current["phase"] == "generating" else current.get("prefill_tps"),
"elapsed": round(time.time() - current["start"], 1), "queued": None}
prompt_ms = sum(r["prompt_ms"] for r in requests)
decode_ms = sum(r["decode_ms"] for r in requests)
averages = {"prefill_tps": _rate(sum(r["prompt"] - r["reused"] for r in requests), prompt_ms),
"decode_tps": _rate(sum(r["output"] for r in requests), decode_ms),
"requests": len(requests)}
public = [{k: v for k, v in r.items() if k not in ("prompt_ms", "decode_ms")} for r in requests]
return live, public, averages
def follow(self, path_fn, stop: threading.Event) -> None:
"""Tail the file path_fn() returns, reopening it when it is replaced or truncated."""
handle, identity, buffer, path = None, None, b"", None
while not stop.is_set():
try:
wanted = path_fn()
if wanted != path:
if handle:
handle.close()
handle, identity, buffer, path = None, None, b"", wanted
stat = os.stat(path)
if handle is None or (stat.st_ino, stat.st_ctime_ns) != identity or stat.st_size < handle.tell():
if handle:
handle.close()
handle = open(path, "rb")
if identity is None:
handle.seek(0, os.SEEK_END) # don't replay an old log when first attaching
identity, buffer = (stat.st_ino, stat.st_ctime_ns), b""
chunk = handle.read()
except (OSError, TypeError):
chunk = b""
if not chunk:
stop.wait(0.5)
continue
buffer += chunk
*lines, buffer = buffer.split(b"\n")
for line in lines:
self.feed(line.decode("utf-8", "replace"))
if handle:
handle.close()
class LlamaBackend(Backend):
key = "llama"
label = "llama.cpp"
stop_timeout = 10.0
LEGACY_LOG = r"D:\AI\models\qwen4-35b-a3b\service\logs\llama-server.log" # while the Qwen4 service runs it
def __init__(self, settings):
super().__init__(settings)
self.logparser = LlamaLog()
self.owned = False # set by the service: True when The Kurgan started the running server
self.load_started: float | None = None
self.last_load_seconds: float | None = None
@property
def port(self) -> int:
return self.settings.get("ai", "llama_port", config.LLAMA_PORT)
@property
def server(self) -> str:
return self.settings.get("ai", "llama_server", config.LLAMA_SERVER)
@property
def presets(self) -> str:
return self.settings.get("ai", "llama_presets", config.LLAMA_PRESETS)
@property
def model(self) -> str:
return self.settings.get("ai", "llama_model", config.LLAMA_MODEL)
@property
def prefix(self) -> str:
# The Qwen4 service's own server (before it was retired) serves from the root.
return config.LLAMA_PREFIX if self.owned else ""
def proxy_headers(self) -> dict:
# The proxy is the gate (see kurgan/web/proxy.py), so clients there need no key; the key
# stays on the server's own port, where a web page could otherwise reach it.
return {"Authorization": f"Bearer {config.LLAMA_API_KEY}"}
def model_label(self) -> str:
return config.LLAMA_LABEL if self.model == config.LLAMA_MODEL else self.model
def model_ids(self) -> list[str]:
return [self.model]
@property
def log_path(self) -> str:
return os.path.join(LOG_DIR, "llama-server.log")
def current_log(self) -> str:
return self.log_path if self.owned else self.LEGACY_LOG
def check_files(self) -> str | None:
for path in (self.server, self.presets):
if not os.path.exists(path):
return f"Not found: {path}"
return None
def before_start(self) -> None:
os.makedirs(LOG_DIR, exist_ok=True)
try:
if os.path.exists(self.log_path):
os.replace(self.log_path, os.path.join(LOG_DIR, "llama-server.prev.log"))
except OSError as e:
log.warning("Could not rotate llama-server.log: %s", e)
self.logparser.reset()
def command(self) -> tuple[list[str], str, str]:
argv = [self.server, "--models-preset", self.presets, "--models-max", "1", "--host", "127.0.0.1",
"--port", str(self.port), "--api-prefix", config.LLAMA_PREFIX, "--api-key", config.LLAMA_API_KEY,
"--metrics"]
return argv, os.path.dirname(self.presets), self.log_path
def _api(self, path: str, body: dict | None = None, timeout: float = 3) -> tuple[int, bytes]:
return http("GET" if body is None else "POST", f"http://127.0.0.1:{self.port}{self.prefix}{path}", body,
{"Authorization": f"Bearer {config.LLAMA_API_KEY}"}, timeout)
def _model_entry(self) -> dict:
code, body = self._api("/models")
if code != 200:
raise ValueError(f"/models returned HTTP {code}")
return next(m for m in json.loads(body)["data"] if m["id"] == self.model)
def poll(self) -> None:
entry = self._model_entry()
state = entry["status"]["value"]
live, requests, averages = self.logparser.snapshot()
if state == "loading" and self.load_started is None:
self.load_started = time.time()
elif state != "loading" and self.load_started is not None:
if state == "loaded":
self.last_load_seconds = round(time.time() - self.load_started, 1)
self.load_started = None
if state == "loaded":
state = live["phase"] if live else "idle"
else:
live = None
detail = entry["status"].get("failed_reason", "") if state == "failed" else ""
if state == "loading" and self.load_started:
detail = f"{time.time() - self.load_started:.0f} s"
status = {"model": {"state": state, "detail": detail, "id": self.model, "context": 262144,
"last_load_seconds": self.last_load_seconds},
"live": live, "requests": requests, "averages": averages}
with self.lock:
self.status = status
def load(self) -> None:
if self._model_entry()["status"]["value"] == "sleeping":
# A sleeping instance only wakes on a task, so restart it to load immediately.
self._api("/models/unload", {"model": self.model}, timeout=30)
for _ in range(60):
if self._model_entry()["status"]["value"] == "unloaded":
break
time.sleep(0.5)
code, body = self._api("/models/load", {"model": self.model}, timeout=30)
log.info("llama load: HTTP %s %s", code, body[:200])
if code != 200:
raise RuntimeError(_error_text(body) or f"llama.cpp load failed (HTTP {code})")
def unload(self) -> None:
code, body = self._api("/models/unload", {"model": self.model}, timeout=30)
log.info("llama unload: HTTP %s %s", code, body[:200])
if code != 200:
raise RuntimeError(_error_text(body) or f"llama.cpp unload failed (HTTP {code})")
+35
View File
@@ -0,0 +1,35 @@
"""Defaults for the two local LLM servers. Paths and ports can be overridden in settings.json ("ai").
Clients reach both through The Kurgan's web server: http://127.0.0.1:8080/strata/v1 and
http://127.0.0.1:8080/llama/v1 (see kurgan/web/proxy.py). The ports below are where each server
listens on 127.0.0.1 behind it; clients shouldn't use them directly.
"""
import os
BACKENDS = ("strata", "llama") # also each server's path on The Kurgan's web server: /strata/, /llama/
# A server nobody has used for this long is stopped; the next request starts it again (0 = never).
IDLE_STOP_MINUTES = 40
# Strata (github.com/Niko1221/Strata), a git clone with its own venv in terminal\.
STRATA_ROOT = r"D:\AI\Strata"
STRATA_PORT = 8082
STRATA_MODELS = { # key: (label, run config in terminal\, model id it serves)
"q5": ("OrcaRouter Qwen3.8 Flash Next Q5_K_M", "strata-orca-q5_k_m.json",
"orcarouter-qwen3.8-flash-next-uncensored-q5_k_m"),
"iq3": ("OrcaRouter Qwen3.8 Flash Next IQ3_XXS", "strata-orca-iq3_xxs.json",
"orcarouter-qwen3.8-flash-next-uncensored-iq3_xxs"),
}
STRATA_DEFAULT_MODEL = "q5"
STRATA_IDLE_UNLOAD = 2000 # seconds idle before the model leaves VRAM; it reloads on the next request
# llama.cpp's llama-server in router mode, with the model defined in a presets file.
LLAMA_SERVER = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "llama.cpp", "b12977",
"llama-server.exe")
LLAMA_PRESETS = r"D:\AI\models\qwen4-35b-a3b\service\presets.ini"
LLAMA_MODEL = "qwen4-35b-a3b-q5"
LLAMA_LABEL = "Qwen4 35B-A3B UD-Q5_K_XL"
LLAMA_PORT = 8083
LLAMA_API_KEY = "sk-local"
LLAMA_PREFIX = "/llama" # --api-prefix: llama-server serves its API and chat page under this path
+449
View File
@@ -0,0 +1,449 @@
"""Start the AI servers as ordinary, non-elevated processes, even though The Kurgan runs elevated.
The Kurgan needs admin rights for PawnIO (CPU sensors, top fans, RAM lighting), but the LLM
servers never did: they ran from non-elevated tasks before. How a server is started:
- The Kurgan elevated (the normal case): with a copy of the desktop shell's (Explorer's) own
token, through CreateProcessWithTokenW. The server is then exactly what Explorer would have
started: medium integrity, not elevated, in the desktop's logon session.
- No desktop shell yet (just after logon; see desktop_ready) or The Kurgan not elevated (tests,
--demo): a "normal user" token from the Safer API (Administrators made deny-only, admin
privileges removed, medium integrity). Windows still counts that token as part of the elevated
logon session, so the shell's token is preferred.
Each server gets its own job object that kills everything in it when The Kurgan closes the
job, including the model processes the server starts itself; a crashed Kurgan leaves no
orphan holding VRAM or a port. stdout/stderr go to a log file. The Safer path passes an explicit
handle list, so only the log and NUL handles are inherited. CreateProcessWithTokenW can't take
one; Python makes its handles non-inheritable, and launches are serialised, so in practice the
same two are all the child gets.
"""
from __future__ import annotations
import ctypes
import ctypes.wintypes as wt
import logging
import os
import subprocess
import threading
log = logging.getLogger(__name__)
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
SAFER_SCOPEID_USER = 2
SAFER_LEVELID_NORMALUSER = 0x20000
SAFER_LEVEL_OPEN = 1
TOKEN_INTEGRITY_LEVEL = 25
TOKEN_ELEVATION = 20
SE_GROUP_INTEGRITY = 0x20
MEDIUM_INTEGRITY_SID = "S-1-16-8192"
CREATE_SUSPENDED = 0x4
CREATE_NEW_PROCESS_GROUP = 0x200
CREATE_UNICODE_ENVIRONMENT = 0x400
EXTENDED_STARTUPINFO_PRESENT = 0x80000
CREATE_NO_WINDOW = 0x08000000
STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES = 0x1, 0x100
SW_HIDE = 0
PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x20002
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
GENERIC_READ, GENERIC_WRITE = 0x80000000, 0x40000000
FILE_APPEND_DATA = 0x4
SYNCHRONIZE = 0x100000
FILE_SHARE_ALL = 0x7
OPEN_EXISTING, OPEN_ALWAYS = 3, 4
INVALID_HANDLE = wt.HANDLE(-1).value
WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
STILL_ACTIVE = 259
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
TOKEN_QUERY = 0x8
TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_ADJUST_DEFAULT, TOKEN_ADJUST_SESSIONID = 0x1, 0x2, 0x80, 0x100
SECURITY_IMPERSONATION, TOKEN_PRIMARY = 2, 1
ERROR_INVALID_PARAMETER = 87
class SecurityAttributes(ctypes.Structure):
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", wt.LPVOID), ("bInheritHandle", wt.BOOL)]
class StartupInfo(ctypes.Structure):
_fields_ = [("cb", wt.DWORD), ("lpReserved", wt.LPWSTR), ("lpDesktop", wt.LPWSTR), ("lpTitle", wt.LPWSTR),
("dwX", wt.DWORD), ("dwY", wt.DWORD), ("dwXSize", wt.DWORD), ("dwYSize", wt.DWORD),
("dwXCountChars", wt.DWORD), ("dwYCountChars", wt.DWORD), ("dwFillAttribute", wt.DWORD),
("dwFlags", wt.DWORD), ("wShowWindow", wt.WORD), ("cbReserved2", wt.WORD),
("lpReserved2", ctypes.c_void_p), ("hStdInput", wt.HANDLE), ("hStdOutput", wt.HANDLE),
("hStdError", wt.HANDLE)]
class StartupInfoEx(ctypes.Structure):
_fields_ = [("StartupInfo", StartupInfo), ("lpAttributeList", ctypes.c_void_p)]
class ProcessInformation(ctypes.Structure):
_fields_ = [("hProcess", wt.HANDLE), ("hThread", wt.HANDLE), ("dwProcessId", wt.DWORD),
("dwThreadId", wt.DWORD)]
class SidAndAttributes(ctypes.Structure):
_fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)]
class BasicLimits(ctypes.Structure):
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),
("LimitFlags", wt.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wt.DWORD),
("Affinity", ctypes.c_size_t), ("PriorityClass", wt.DWORD), ("SchedulingClass", wt.DWORD)]
class ExtendedLimits(ctypes.Structure):
_fields_ = [("BasicLimitInformation", BasicLimits), ("IoInfo", ctypes.c_uint64 * 6),
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
_adv.SaferCreateLevel.argtypes = [wt.DWORD, wt.DWORD, wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.LPVOID]
_adv.SaferCreateLevel.restype = wt.BOOL
_adv.SaferComputeTokenFromLevel.argtypes = [wt.HANDLE, wt.HANDLE, ctypes.POINTER(wt.HANDLE), wt.DWORD, wt.LPVOID]
_adv.SaferComputeTokenFromLevel.restype = wt.BOOL
_adv.SaferCloseLevel.argtypes = [wt.HANDLE]
_adv.SaferCloseLevel.restype = wt.BOOL
_adv.ConvertStringSidToSidW.argtypes = [wt.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)]
_adv.ConvertStringSidToSidW.restype = wt.BOOL
_adv.GetLengthSid.argtypes = [ctypes.c_void_p]
_adv.GetLengthSid.restype = wt.DWORD
_adv.SetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD]
_adv.SetTokenInformation.restype = wt.BOOL
_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD, ctypes.POINTER(wt.DWORD)]
_adv.GetTokenInformation.restype = wt.BOOL
_adv.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
_adv.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte)
_adv.GetSidSubAuthority.argtypes = [ctypes.c_void_p, wt.DWORD]
_adv.GetSidSubAuthority.restype = ctypes.POINTER(wt.DWORD)
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
_adv.OpenProcessToken.restype = wt.BOOL
_adv.CreateProcessAsUserW.argtypes = [wt.HANDLE, wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD,
wt.LPVOID, wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
_adv.CreateProcessAsUserW.restype = wt.BOOL
_k32.LocalFree.argtypes = [wt.HLOCAL]
_k32.LocalFree.restype = wt.HLOCAL
_k32.CloseHandle.argtypes = [wt.HANDLE]
_k32.CloseHandle.restype = wt.BOOL
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.POINTER(SecurityAttributes), wt.DWORD,
wt.DWORD, wt.HANDLE]
_k32.CreateFileW.restype = wt.HANDLE
_k32.CreateJobObjectW.argtypes = [wt.LPVOID, wt.LPCWSTR]
_k32.CreateJobObjectW.restype = wt.HANDLE
_k32.SetInformationJobObject.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD]
_k32.SetInformationJobObject.restype = wt.BOOL
_k32.AssignProcessToJobObject.argtypes = [wt.HANDLE, wt.HANDLE]
_k32.AssignProcessToJobObject.restype = wt.BOOL
_k32.TerminateJobObject.argtypes = [wt.HANDLE, wt.UINT]
_k32.TerminateJobObject.restype = wt.BOOL
_k32.TerminateProcess.argtypes = [wt.HANDLE, wt.UINT]
_k32.TerminateProcess.restype = wt.BOOL
_k32.ResumeThread.argtypes = [wt.HANDLE]
_k32.ResumeThread.restype = wt.DWORD
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
_k32.WaitForSingleObject.restype = wt.DWORD
_k32.GetExitCodeProcess.argtypes = [wt.HANDLE, ctypes.POINTER(wt.DWORD)]
_k32.GetExitCodeProcess.restype = wt.BOOL
_k32.InitializeProcThreadAttributeList.argtypes = [ctypes.c_void_p, wt.DWORD, wt.DWORD, ctypes.POINTER(ctypes.c_size_t)]
_k32.InitializeProcThreadAttributeList.restype = wt.BOOL
_k32.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wt.DWORD, ctypes.c_size_t, wt.LPVOID, ctypes.c_size_t,
wt.LPVOID, wt.LPVOID]
_k32.UpdateProcThreadAttribute.restype = wt.BOOL
_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
_k32.DeleteProcThreadAttributeList.restype = None
_k32.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD]
_k32.OpenProcess.restype = wt.HANDLE
_k32.GetCurrentProcess.restype = wt.HANDLE
_adv.DuplicateTokenEx.argtypes = [wt.HANDLE, wt.DWORD, wt.LPVOID, ctypes.c_int, ctypes.c_int, ctypes.POINTER(wt.HANDLE)]
_adv.DuplicateTokenEx.restype = wt.BOOL
_adv.CreateProcessWithTokenW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPCWSTR, wt.LPWSTR, wt.DWORD, wt.LPVOID, wt.LPCWSTR,
ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
_adv.CreateProcessWithTokenW.restype = wt.BOOL
_u32 = ctypes.WinDLL("user32", use_last_error=True)
_u32.GetShellWindow.restype = wt.HWND
_u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)]
_u32.GetWindowThreadProcessId.restype = wt.DWORD
_launch_lock = threading.Lock()
def _check(ok, what: str):
if not ok:
raise ctypes.WinError(ctypes.get_last_error(), f"{what} failed")
return ok
def _normal_user_token() -> wt.HANDLE:
"""A primary token like this process's, minus admin rights, at medium integrity."""
level, token = wt.HANDLE(), wt.HANDLE()
_check(_adv.SaferCreateLevel(SAFER_SCOPEID_USER, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN,
ctypes.byref(level), None), "SaferCreateLevel")
try:
_check(_adv.SaferComputeTokenFromLevel(level, None, ctypes.byref(token), 0, None),
"SaferComputeTokenFromLevel")
finally:
_adv.SaferCloseLevel(level)
sid = ctypes.c_void_p()
try:
_check(_adv.ConvertStringSidToSidW(MEDIUM_INTEGRITY_SID, ctypes.byref(sid)), "ConvertStringSidToSid")
label = SidAndAttributes(sid, SE_GROUP_INTEGRITY)
_check(_adv.SetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, ctypes.byref(label),
ctypes.sizeof(label) + _adv.GetLengthSid(sid)), "SetTokenInformation")
except OSError:
_k32.CloseHandle(token)
raise
finally:
if sid:
_k32.LocalFree(sid)
return token
def _describe_token(token: wt.HANDLE) -> dict:
size = wt.DWORD()
_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size))
buf = ctypes.create_string_buffer(size.value)
_check(_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, buf, size, ctypes.byref(size)),
"GetTokenInformation(IntegrityLevel)")
sid = SidAndAttributes.from_buffer(buf).Sid
rid = _adv.GetSidSubAuthority(sid, _adv.GetSidSubAuthorityCount(sid)[0] - 1)[0]
elevated = wt.DWORD()
_check(_adv.GetTokenInformation(token, TOKEN_ELEVATION, ctypes.byref(elevated), 4, ctypes.byref(size)),
"GetTokenInformation(Elevation)")
names = {0x1000: "low", 0x2000: "medium", 0x2100: "medium-plus", 0x3000: "high", 0x4000: "system"}
return {"integrity": names.get(rid, hex(rid)), "elevated": bool(elevated.value)}
def token_info(process_handle=None) -> dict:
"""{"integrity": "medium"|"high"|..., "elevated": bool} for a process (default: this one)."""
token = wt.HANDLE()
handle = process_handle if process_handle is not None else _k32.GetCurrentProcess()
_check(_adv.OpenProcessToken(handle, TOKEN_QUERY, ctypes.byref(token)), "OpenProcessToken")
try:
return _describe_token(token)
finally:
_k32.CloseHandle(token)
_ELEVATED: bool | None = None
def elevated() -> bool:
global _ELEVATED
if _ELEVATED is None:
_ELEVATED = token_info()["elevated"]
return _ELEVATED
def _desktop_token() -> wt.HANDLE | None:
"""A primary copy of the desktop shell's token, or None if there is no (non-elevated) shell."""
hwnd = _u32.GetShellWindow()
if not hwnd:
return None
pid = wt.DWORD()
_u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
process = _k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value)
if not process:
return None
shell, token = wt.HANDLE(), wt.HANDLE()
try:
if not _adv.OpenProcessToken(process, TOKEN_DUPLICATE | TOKEN_QUERY, ctypes.byref(shell)):
return None
try:
_check(_adv.DuplicateTokenEx(shell, TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE
| TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID, None,
SECURITY_IMPERSONATION, TOKEN_PRIMARY, ctypes.byref(token)),
"DuplicateTokenEx")
finally:
_k32.CloseHandle(shell)
finally:
_k32.CloseHandle(process)
if _describe_token(token)["elevated"]: # someone runs Explorer elevated: no better than our own
_k32.CloseHandle(token)
return None
return token
def desktop_ready() -> bool:
"""True once servers can be started with the desktop's own token (always true when not elevated)."""
if not elevated():
return True
token = _desktop_token()
if token is None:
return False
_k32.CloseHandle(token)
return True
def _inheritable(path: str, access: int, disposition: int) -> wt.HANDLE:
sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True)
handle = _k32.CreateFileW(path, access, FILE_SHARE_ALL, ctypes.byref(sa), disposition, 0x80, None)
if handle == INVALID_HANDLE or not handle:
raise ctypes.WinError(ctypes.get_last_error(), f"Opening {path} failed")
return handle
def _environment_block(env: dict[str, str]) -> ctypes.Array:
items = sorted(env.items(), key=lambda kv: kv[0].upper())
text = "".join(f"{k}={v}\0" for k, v in items) + "\0"
return ctypes.create_unicode_buffer(text, len(text))
def child_environment(extra: dict[str, str] | None = None) -> dict[str, str]:
env = dict(os.environ)
# The Kurgan pins OpenBLAS to one thread for itself (see kurgan/__init__.py); the servers get the default.
if env.get("KURGAN_PINNED_OPENBLAS") == "1":
env.pop("OPENBLAS_NUM_THREADS", None)
env.pop("KURGAN_PINNED_OPENBLAS", None)
env.update(extra or {})
return env
class ChildProcess:
"""A launched server: poll/wait/kill like subprocess.Popen, plus the job it runs in."""
def __init__(self, pid: int, process: wt.HANDLE, job: wt.HANDLE, argv: list[str]):
self.pid = pid
self.argv = argv
self._process = process
self._job = job
self.returncode: int | None = None
try:
self.token = token_info(process)
except OSError as e:
log.warning("Could not read the token of process %s: %s", pid, e)
self.token = {"integrity": "unknown", "elevated": None}
def poll(self) -> int | None:
return self.wait(0)
def wait(self, timeout: float | None = None) -> int | None:
if self.returncode is not None:
return self.returncode
if self._process is None:
return None
ms = 0xFFFFFFFF if timeout is None else max(0, int(timeout * 1000))
if _k32.WaitForSingleObject(self._process, ms) != WAIT_OBJECT_0:
return None
code = wt.DWORD()
_check(_k32.GetExitCodeProcess(self._process, ctypes.byref(code)), "GetExitCodeProcess")
self.returncode = code.value
return self.returncode
def kill(self) -> None:
"""End the server and everything it started."""
if self._job:
_k32.TerminateJobObject(self._job, 1)
elif self._process:
_k32.TerminateProcess(self._process, 1)
def close(self) -> None:
"""Release the handles; closing the job also kills anything still in it."""
for name in ("_process", "_job"):
handle = getattr(self, name)
if handle:
_k32.CloseHandle(handle)
setattr(self, name, None)
def __del__(self):
try:
self.close()
except Exception:
pass
def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str] | None = None,
contained: bool = True) -> ChildProcess:
"""Start argv as a normal user, windowless, with stdout/stderr appended to log_path (None: discarded).
contained: put it in its own kill-on-close job (servers). Without it the process outlives
the returned handle (used to open the browser)."""
if log_path is not None:
os.makedirs(os.path.dirname(log_path), exist_ok=True)
with _launch_lock:
desktop = _desktop_token() if elevated() else None
token = desktop or _normal_user_token()
job = out = nul = None
attributes = None
try:
if contained:
job = _check(_k32.CreateJobObjectW(None, None), "CreateJobObject")
limits = ExtendedLimits()
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
_check(_k32.SetInformationJobObject(job, JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
ctypes.byref(limits), ctypes.sizeof(limits)),
"SetInformationJobObject")
out = (_inheritable(log_path, FILE_APPEND_DATA | SYNCHRONIZE, OPEN_ALWAYS) if log_path is not None
else _inheritable("NUL", GENERIC_WRITE, OPEN_EXISTING))
nul = _inheritable("NUL", GENERIC_READ, OPEN_EXISTING)
command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
block = _environment_block(env if env is not None else child_environment())
flags = CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP
pi = ProcessInformation()
if desktop:
info = StartupInfo()
info.cb = ctypes.sizeof(StartupInfo)
info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
info.wShowWindow = SW_HIDE
info.hStdInput, info.hStdOutput, info.hStdError = nul, out, out
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags, block, cwd,
ctypes.byref(info), ctypes.byref(pi))
if not ok and ctypes.get_last_error() == ERROR_INVALID_PARAMETER:
# Not every creation flag is accepted here; SW_HIDE still hides a console window.
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags & ~CREATE_NO_WINDOW, block,
cwd, ctypes.byref(info), ctypes.byref(pi))
_check(ok, f"Starting {argv[0]}")
else:
size = ctypes.c_size_t()
_k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size))
attributes = ctypes.create_string_buffer(size.value)
_check(_k32.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)),
"InitializeProcThreadAttributeList")
handles = (wt.HANDLE * 2)(out, nul)
_check(_k32.UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles,
ctypes.sizeof(handles), None, None),
"UpdateProcThreadAttribute")
info = StartupInfoEx()
info.StartupInfo.cb = ctypes.sizeof(StartupInfoEx)
info.StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
info.StartupInfo.wShowWindow = SW_HIDE
info.StartupInfo.hStdInput, info.StartupInfo.hStdOutput, info.StartupInfo.hStdError = nul, out, out
info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p)
_check(_adv.CreateProcessAsUserW(token, None, command, None, None, True,
flags | EXTENDED_STARTUPINFO_PRESENT, block, cwd,
ctypes.byref(info), ctypes.byref(pi)), f"Starting {argv[0]}")
if job and not _k32.AssignProcessToJobObject(job, pi.hProcess):
error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
_k32.TerminateProcess(pi.hProcess, 1)
_k32.CloseHandle(pi.hThread)
_k32.CloseHandle(pi.hProcess)
raise error
_k32.ResumeThread(pi.hThread)
_k32.CloseHandle(pi.hThread)
child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv)
job = None # owned by the child object now
log.info("Started %s (pid %s, %s token, %s integrity%s)", os.path.basename(argv[0]), child.pid,
"desktop" if desktop else "restricted", child.token["integrity"],
", ELEVATED" if child.token["elevated"] else "")
return child
finally:
if attributes is not None:
_k32.DeleteProcThreadAttributeList(attributes)
for handle in (out, nul, job, token):
if handle:
_k32.CloseHandle(handle)
def open_url(url: str) -> None:
"""Open a web page in the default browser as the normal user, never elevated."""
rundll = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "rundll32.exe")
child = launch([rundll, "url.dll,FileProtocolHandler", url], cwd=os.path.dirname(rundll), log_path=None,
contained=False)
child.close()
+459
View File
@@ -0,0 +1,459 @@
"""AI service: runs one LLM server at a time and swaps between them.
The selected server (settings "ai.active") is started as a normal-user child process and
restarted if it crashes (5 crashes within 5 minutes pause restarts for 5 minutes). Swapping
stops the running server completely first, so the two never share the GPU's memory.
Servers are also started on demand: a request through The Kurgan's web server
(/strata/..., /llama/...; see kurgan/web/proxy.py) selects its server and waits until it
answers. If the other server is busy (a request in flight, a reply being generated or a model
loading), the request waits for it to finish rather than cutting it off. A server nobody has
used for ai.idle_stop_minutes is stopped.
A server already listening on a port that The Kurgan didn't start (for example Strata's or
the Qwen4 service's own tray, before they are retired) is shown as "external": it is
monitored but never started, stopped or duplicated.
"""
from __future__ import annotations
import collections
import ctypes
import ctypes.wintypes as wt
import logging
import os
import socket
import threading
import time
from kurgan.ai import launcher
from kurgan.ai.backends import Backend, LlamaBackend, StrataBackend
from kurgan.ai.config import BACKENDS
from kurgan.settings import Settings
log = logging.getLogger(__name__)
_iphlp = ctypes.WinDLL("iphlpapi")
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_iphlp.GetExtendedTcpTable.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD), wt.BOOL, wt.ULONG, ctypes.c_int,
wt.ULONG]
_iphlp.GetExtendedTcpTable.restype = wt.DWORD
_k32.OpenProcess.argtypes, _k32.OpenProcess.restype = [wt.DWORD, wt.BOOL, wt.DWORD], wt.HANDLE
_k32.QueryFullProcessImageNameW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD)]
_k32.QueryFullProcessImageNameW.restype = wt.BOOL
_k32.CloseHandle.argtypes = [wt.HANDLE]
def port_in_use(port: int) -> bool:
with socket.socket() as probe:
probe.settimeout(0.3)
return probe.connect_ex(("127.0.0.1", port)) == 0
def port_owner(port: int) -> tuple[int, str] | None:
"""(pid, executable name) of the process listening on 127.0.0.1:port, if any."""
size = wt.DWORD(0)
_iphlp.GetExtendedTcpTable(None, ctypes.byref(size), False, 2, 3, 0) # AF_INET, TCP_TABLE_OWNER_PID_LISTENER
buf = ctypes.create_string_buffer(size.value)
if _iphlp.GetExtendedTcpTable(buf, ctypes.byref(size), False, 2, 3, 0) != 0:
return None
count = ctypes.c_uint32.from_buffer(buf).value
row = ctypes.c_uint32 * 6 # state, local addr, local port, remote addr, remote port, pid
for i in range(count):
state, _addr, lport, _raddr, _rport, pid = row.from_buffer(buf, 4 + i * ctypes.sizeof(row))
if ((lport & 0xFF) << 8 | (lport >> 8) & 0xFF) == port:
name = "?"
handle = _k32.OpenProcess(launcher.PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
if handle:
try:
text, length = ctypes.create_unicode_buffer(1024), wt.DWORD(1024)
if _k32.QueryFullProcessImageNameW(handle, 0, text, ctypes.byref(length)):
name = os.path.basename(text.value)
finally:
_k32.CloseHandle(handle)
return pid, name
return None
class Slot:
"""One backend and the process The Kurgan runs for it."""
def __init__(self, backend: Backend):
self.backend = backend
self.child: launcher.ChildProcess | None = None
self.variant: str | None = None
self.started_at: float | None = None
self.stopping = False
self.external: tuple[int, str] | None = None
self.crashes: collections.deque[float] = collections.deque(maxlen=5)
self.hold_until = 0.0
self.restarts = 0
self.error: str | None = None
self.reachable = False
class RouteError(Exception):
"""A request for a server that can't be served now; status is the HTTP status to answer with."""
def __init__(self, message: str, status: int = 503):
super().__init__(message)
self.status = status
BUSY_STATES = ("loading", "reading", "generating")
CLIENT_GONE = 499 # RouteError status: the client hung up while waiting (nginx's "client closed request")
class AiService:
BUSY_WAIT = 600.0 # how long a request waits for the other server to finish before giving up
READY_WAIT = 120.0 # how long it waits for its own server to start answering
def __init__(self, settings: Settings, backends: list[Backend] | None = None):
self.settings = settings
backends = backends or [StrataBackend(settings), LlamaBackend(settings)]
self.slots = {b.key: Slot(b) for b in backends}
self._wake = threading.Event()
self._lock = threading.Lock()
self._cv = threading.Condition() # guards inflight/last_used; notified when a request ends
self.inflight = {key: 0 for key in self.slots}
self.last_used = {key: time.monotonic() for key in self.slots}
self.transition: str | None = None
self.action: str | None = None # "Loading model..." while a load/unload request runs
self.message: str | None = None
self._stop: threading.Event | None = None
self._born = time.monotonic()
def set_public_url(self, url: str) -> None:
"""The Kurgan's web server, which the links in the UI point to."""
for slot in self.slots.values():
slot.backend.public = url.rstrip("/")
# -- requests from the web UI (any thread)
def set_active(self, key: str | None, variant: str | None = None) -> None:
if key is not None and key not in self.slots:
raise ValueError(f"Unknown AI backend {key!r}")
changes: dict = {"active": key}
if variant is not None:
changes["strata_model"] = variant
self.settings.update("ai", **changes) # validates the variant
log.info("AI backend selected: %s%s", key or "none", f" ({variant})" if variant else "")
if key is not None:
with self._cv:
self.last_used[key] = time.monotonic() # a full idle period before it can stop
self._wake.set()
# -- requests through the web server (any thread)
def _busy(self, key: str) -> bool:
"""Serving or about to serve: a request in flight here, or a reply/model load in progress."""
if self.inflight[key]:
return True
status = self.slots[key].backend.status
return bool(status.get("live")) or status["model"]["state"] in BUSY_STATES
def claim(self, key: str, gone=None) -> Backend:
"""Reserve key's server for one request: select it (stopping the other once that is idle)
and wait until it answers. Always pair with release(key). gone(), if given, says whether
the client has hung up; then the wait ends without switching anything."""
if key not in self.slots:
raise RouteError(f"Unknown AI server {key!r}", 404)
slot = self.slots[key]
deadline = time.monotonic() + self.BUSY_WAIT
with self._cv:
while True:
active = self.settings.get("ai", "active")
if active == key or slot.external is not None:
break
other = self.slots[active] if active else None
if gone is not None and gone():
raise RouteError(f"while waiting for {other.backend.label} to finish" if other is not None
else f"before {slot.backend.label} was started", CLIENT_GONE)
if other is None or other.external is not None or not self._busy(active):
try:
self.settings.update("ai", active=key)
except OSError as e:
raise RouteError(f"Couldn't save the AI selection: {e}", 500) from None
log.info("%s requested by a client%s", slot.backend.label,
f"; stopping {other.backend.label}" if other is not None and other.child else "")
self._wake.set()
break
if time.monotonic() >= deadline:
raise RouteError(f"{other.backend.label} is still busy with another request; try again later.")
self._cv.wait(1.0)
self.inflight[key] += 1
self.last_used[key] = time.monotonic()
try:
self._wait_ready(key, slot, gone)
except BaseException:
self.release(key)
raise
return slot.backend
def _wait_ready(self, key: str, slot: Slot, gone=None) -> None:
start = time.monotonic()
while True:
running = slot.external is not None or (slot.child is not None and not slot.stopping)
if running and port_in_use(slot.backend.port):
return
if self._stop is not None and self._stop.is_set():
raise RouteError("The Kurgan is shutting down")
if gone is not None and gone():
raise RouteError(f"while waiting for {slot.backend.label} to start", CLIENT_GONE)
waited = time.monotonic() - start
if slot.external is None and self.settings.get("ai", "active") != key and waited > 3:
raise RouteError(f"{slot.backend.label} was switched off in The Kurgan")
if slot.child is None and slot.error and waited > 3:
raise RouteError(slot.error)
if waited >= self.READY_WAIT:
raise RouteError(f"{slot.backend.label} didn't start within {self.READY_WAIT:.0f} s")
time.sleep(0.25)
def release(self, key: str) -> None:
with self._cv:
self.inflight[key] = max(0, self.inflight[key] - 1)
self.last_used[key] = time.monotonic()
self._cv.notify_all()
def running(self, key: str) -> bool:
"""The server answers now (started by The Kurgan or not)."""
slot = self.slots[key]
return slot.reachable and (slot.external is not None or (slot.child is not None and not slot.stopping))
def model_action(self, action: str) -> None:
"""Load or unload the model of the running server (in the background)."""
key = self.settings.get("ai", "active")
if key is None or action not in ("load", "unload"):
raise ValueError("No AI backend is selected" if key is None else f"Unknown action {action!r}")
slot = self.slots[key]
if not slot.reachable:
raise ValueError(f"{slot.backend.label} isn't running yet")
if self.action:
raise ValueError(f"Busy: {self.action}")
self.action = f"{'Loading' if action == 'load' else 'Unloading'} {slot.backend.label} model"
def run():
try:
getattr(slot.backend, action)()
self.message = None
except Exception as e:
log.warning("%s failed: %s", self.action, e)
self.message = f"{self.action} failed: {e}"
finally:
self.action = None
threading.Thread(target=run, name=f"ai-{action}", daemon=True).start()
# -- worker threads
def start(self, stop: threading.Event) -> list[threading.Thread]:
self._stop = stop
threads = [threading.Thread(target=self.run, args=(stop,), name="ai-supervisor", daemon=True),
threading.Thread(target=self.monitor, args=(stop,), name="ai-monitor", daemon=True)]
llama = self.slots.get("llama")
if llama is not None and isinstance(llama.backend, LlamaBackend):
threads.append(threading.Thread(target=llama.backend.logparser.follow,
args=(llama.backend.current_log, stop), name="llama-log", daemon=True))
for thread in threads:
thread.start()
return threads
def monitor(self, stop: threading.Event) -> None:
while not stop.is_set():
for slot in self.slots.values():
running = slot.child is not None or slot.external is not None
if not running:
slot.reachable = False
slot.backend.mark_offline()
continue
try:
slot.backend.poll()
slot.reachable = True
except (OSError, ValueError, KeyError, StopIteration) as e:
slot.reachable = False
slot.backend.mark_offline()
log.debug("%s poll failed: %s", slot.backend.label, e)
stop.wait(1.5)
def run(self, stop: threading.Event) -> None:
try:
while not stop.is_set():
try:
self._reconcile(stop)
except Exception:
log.exception("AI supervisor error")
self._wake.wait(1.0)
self._wake.clear()
finally:
for slot in self.slots.values():
if slot.child is not None:
self._stop_slot(slot, "The Kurgan is exiting")
def _idle_check(self, active: str | None) -> str | None:
"""Stop the selected server once nobody has used it for ai.idle_stop_minutes."""
minutes = self.settings.get("ai", "idle_stop_minutes")
if not active or not minutes:
return active
slot = self.slots[active]
if slot.child is None or slot.stopping:
return active
with self._cv:
if self._busy(active):
self.last_used[active] = time.monotonic()
return active
if time.monotonic() - self.last_used[active] < minutes * 60:
return active
try:
self.settings.update("ai", active=None)
except OSError as e:
log.warning("Couldn't save the AI selection: %s", e)
return active
log.info("%s unused for %d minutes; stopping it until the next request", slot.backend.label, minutes)
return None
def _reconcile(self, stop: threading.Event) -> None:
active = self._idle_check(self.settings.get("ai", "active"))
for slot in self.slots.values():
self._check_exit(slot)
# Stop whatever isn't selected first, so the selected server gets the GPU to itself.
for key, slot in self.slots.items():
if slot.child is not None and key != active:
self._stop_slot(slot, "switching" if active else "none selected")
for key, slot in self.slots.items():
slot.external = None
if slot.child is None and port_in_use(slot.backend.port):
slot.external = port_owner(slot.backend.port) or (0, "unknown program")
if active is None or stop.is_set():
self.transition = None
return
slot = self.slots[active]
if slot.child is not None and slot.variant != slot.backend.variant():
self._stop_slot(slot, "changing model")
if slot.child is not None or slot.external is not None:
self.transition = None
return
if time.monotonic() < slot.hold_until:
return
# At logon The Kurgan can be up before Explorer; give the desktop up to 2 minutes so the
# server gets the desktop's own token (see launcher.py) rather than the fallback.
if time.monotonic() - self._born < 120 and not launcher.desktop_ready():
self.transition = f"Waiting for the desktop to start {slot.backend.label}"
return
problem = slot.backend.check_files()
if problem:
slot.error = problem
return
self._start_slot(slot)
def _check_exit(self, slot: Slot) -> None:
if slot.child is None or slot.stopping:
return
code = slot.child.poll()
if code is None:
return
slot.child.close()
slot.child = None
slot.restarts += 1
slot.crashes.append(time.monotonic())
if len(slot.crashes) == slot.crashes.maxlen and slot.crashes[-1] - slot.crashes[0] < 300:
slot.error = f"{slot.backend.label} keeps exiting (code {code}); retrying in 5 minutes. See its log."
slot.hold_until = time.monotonic() + 300
slot.crashes.clear()
else:
slot.error = f"{slot.backend.label} exited (code {code}); restarting."
slot.hold_until = time.monotonic() + 5
log.error(slot.error)
def _start_slot(self, slot: Slot) -> None:
backend = slot.backend
self.transition = f"Starting {backend.label}"
backend.before_start()
argv, cwd, log_path = backend.command()
try:
slot.child = launcher.launch(argv, cwd, log_path)
except OSError as e:
slot.error = f"Could not start {backend.label}: {e}"
slot.hold_until = time.monotonic() + 30
log.error(slot.error)
self.transition = None
return
if isinstance(backend, LlamaBackend):
backend.owned = True
with self._cv:
self.last_used[backend.key] = time.monotonic()
slot.variant = backend.variant()
slot.started_at = time.time()
slot.error = None
self.transition = None
def _stop_slot(self, slot: Slot, why: str) -> None:
child, backend = slot.child, slot.backend
if child is None:
return
self.transition = f"Stopping {backend.label} ({why})"
log.info("Stopping %s (%s)", backend.label, why)
slot.stopping = True
try:
backend.request_stop(child)
if child.wait(backend.stop_timeout) is None:
log.warning("%s didn't stop within %.0f s; ending it", backend.label, backend.stop_timeout)
child.kill()
child.wait(10)
deadline = time.monotonic() + 10 # the port and VRAM are free once every process in the job is gone
while port_in_use(backend.port) and time.monotonic() < deadline:
time.sleep(0.25)
finally:
child.kill()
child.close()
slot.child = None
slot.stopping = False
slot.started_at = None
slot.reachable = False
if isinstance(backend, LlamaBackend):
backend.owned = False
backend.mark_offline()
self.transition = None
# -- state for the UI
def snapshot(self) -> dict:
active = self.settings.get("ai", "active")
minutes = self.settings.get("ai", "idle_stop_minutes")
now = time.monotonic()
with self._cv:
inflight = dict(self.inflight)
idle_in = {key: max(0, round(minutes * 60 - (now - self.last_used[key])))
for key, slot in self.slots.items()
if minutes and key == active and slot.child is not None and not self._busy(key)}
backends = []
for key, slot in self.slots.items():
b = slot.backend
if slot.child is not None:
process = "stopping" if slot.stopping else ("running" if slot.reachable else "starting")
elif slot.external is not None:
process = "external"
else:
process = "stopped"
backends.append({
"key": key, "label": b.label, "model_label": b.model_label(), "port": b.port,
"variants": b.variants(), "variant": b.variant(), "links": b.links(),
"process": process, "pid": slot.child.pid if slot.child else (slot.external[0] if slot.external else None),
"external_program": slot.external[1] if slot.external else None,
"token": slot.child.token if slot.child else None,
"uptime": round(time.time() - slot.started_at) if slot.started_at else None,
"restarts": slot.restarts, "error": slot.error,
"route": f"/{key}/", "inflight": inflight[key], "idle_stop_in": idle_in.get(key),
**b.snapshot(),
})
others = [s.backend.label for k, s in self.slots.items() if k != active and s.external is not None]
warning = None
if others:
names, one = " and ".join(others), len(others) == 1
warning = (f"{names} {'is' if one else 'are'} also running outside The Kurgan, so they may share "
"the GPU's memory." if active else
f"{names} {'is' if one else 'are'} running outside The Kurgan, from "
f"{'its own startup task' if one else 'their own startup tasks'}. Run setup.ps1 -RetireAIServices "
f"to let The Kurgan manage {'it' if one else 'them'}.")
return {"active": active, "backends_order": list(BACKENDS), "transition": self.transition,
"action": self.action, "message": self.message, "warning": warning,
"idle_stop_minutes": minutes, "backends": backends}
+104
View File
@@ -0,0 +1,104 @@
"""Runs Strata's OpenAI-compatible server for The Kurgan.
Started by The Kurgan with Strata's own venv (terminal\\.venv\\Scripts\\pythonw.exe), not
imported by it. Does what Strata's local-service-tray.py did, without the tray icon:
the same environment, arguments, logs and single-instance mutex. The Kurgan asks it to stop
by setting the named event given in --stop-event; Strata then shuts down cleanly (finishing
or cancelling the current request within --shutdown-timeout) and ends its engine processes.
"""
from __future__ import annotations
import _thread
import argparse
import contextlib
import ctypes
from ctypes import wintypes as wt
from datetime import datetime, timezone
import json
import logging
import os
from pathlib import Path
import sys
import threading
LOG = logging.getLogger("kurgan-strata")
K32 = ctypes.WinDLL("kernel32", use_last_error=True)
K32.CreateEventW.argtypes, K32.CreateEventW.restype = [wt.LPVOID, wt.BOOL, wt.BOOL, wt.LPCWSTR], wt.HANDLE
K32.CreateMutexW.argtypes, K32.CreateMutexW.restype = [wt.LPVOID, wt.BOOL, wt.LPCWSTR], wt.HANDLE
K32.WaitForSingleObject.argtypes, K32.WaitForSingleObject.restype = [wt.HANDLE, wt.DWORD], wt.DWORD
K32.CloseHandle.argtypes = [wt.HANDLE]
def watch_stop(event: int, stopping: threading.Event) -> None:
while K32.WaitForSingleObject(event, 1000) != 0:
pass
LOG.info("The Kurgan asked Strata to stop")
stopping.set()
_thread.interrupt_main()
def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: str) -> int:
home = root / "terminal"
sys.path.insert(0, str(home))
os.chdir(home)
from serve import lifeline, server
config = home / config_name
with config.open(encoding="utf-8-sig") as source:
model_id = json.load(source)["model_name"]
# Same name as Strata's own tray uses, so the two can never serve one port at once.
mutex = K32.CreateMutexW(None, False, f"Local\\StrataLocalService-{port}")
if not mutex:
raise ctypes.WinError(ctypes.get_last_error())
if ctypes.get_last_error() == 183:
K32.CloseHandle(mutex)
raise RuntimeError(f"Strata is already running for port {port}.")
stop_event = K32.CreateEventW(None, True, False, stop_name)
if not stop_event:
K32.CloseHandle(mutex)
raise ctypes.WinError(ctypes.get_last_error())
stopping = threading.Event()
threading.Thread(target=watch_stop, args=(stop_event, stopping), name="kurgan-stop", daemon=True).start()
try:
LOG.info("Starting Strata API for %s at 127.0.0.1:%s (The Kurgan, pid %s)", model_id, port, os.getpid())
os.environ["GGML_CUDA_DISABLE_GRAPHS"] = "1"
os.environ["STRATA_NO_CONSOLE"] = "1"
return server.main([
"--engine", "strata", "--config", str(config), "--host", "127.0.0.1",
"--port", str(port), "--lazy", "--idle-unload", str(idle_unload), "--shutdown-timeout", "30",
])
except KeyboardInterrupt:
return 0
finally:
lifeline.end_children()
K32.CloseHandle(stop_event)
K32.CloseHandle(mutex)
LOG.info("Strata stopped")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--config", required=True, help="run config file name in terminal\\")
parser.add_argument("--port", type=int, required=True)
parser.add_argument("--idle-unload", type=int, default=2000)
parser.add_argument("--stop-event", required=True)
args = parser.parse_args()
logs = args.root / "logs"
logs.mkdir(exist_ok=True)
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
logging.basicConfig(filename=logs / "local-service-task.log", level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
with (logs / f"local-service-stdout-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stdout, \
(logs / f"local-service-stderr-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stderr, \
contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
try:
return run(args.root, args.config, args.port, args.idle_unload, args.stop_event)
except (OSError, ValueError, KeyError, RuntimeError):
LOG.exception("Strata startup failed")
return 1
if __name__ == "__main__":
raise SystemExit(main())