okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2d08647c
main
1#!/usr/bin/env python3 2"""tools/strata_mcp.py - an MCP server that lets an AI assistant install, start, check and stop Strata. 3 4claude mcp add strata -- python /path/to/Strata/tools/strata_mcp.py 5 6Add it to Claude Code, Claude Desktop, Cursor, VS Code, Codex ... (docs/MCP_SERVER.md has every client's snippet) and 7ask your AI "install Strata for this PC", "start Strata", "is Strata running?". It speaks MCP (JSON-RPC 2.0, one 8message per line) over stdin/stdout, uses the Python standard library only (it runs before setup made .venv; Python 93.10 or newer), and offers a fixed set of tools: strata_status, strata_models, strata_install, strata_start, 10strata_stop, strata_logs, strata_benchmark, strata_connect_info. 11 12Safety: no tool takes a shell command or a free path. Every argument is checked against setup.py's own choices 13(models, families, contexts ...); the only path argument (install's data_dir) must be the Strata data folder, a folder 14inside the Strata folder, or a new folder named Strata* outside the system folders. Setup and the model run as 15background processes this server starts itself; it keeps their process id and start time in .strata-mcp/ and only 16ever stops a process it started (a Strata started elsewhere, e.g. from its own window, is only asked over its API to 17unload the model). 18 19Not to be confused with serve/mcp.py: that is Strata's MCP *client* (the model calling your tools from the chat page). 20This file is an MCP *server* for the AI assistant you already use. 21""" 22from __future__import annotations 23 24import argparse 25import importlib .util 26import json 27import os 28import platform 29import re 30import shutil 31import signal 32import subprocess 33import sys 34import threading 35import time 36import traceback 37import urllib .error 38import urllib .request 39from pathlib import Path 40 41PROTOCOL = "2025-06-18" 42PROTOCOLS = ("2025-06-18" ,"2025-03-26" ,"2024-11-05" )# the revisions this server answers in 43VERSION = "0.1.0" 44WIN = os .name == "nt" 45DEFAULT_ROOT = Path (__file__ ).resolve ().parent .parent 46# The desktop app runs this under Strata Control's Python (STRATA_CONTROL_INSTALL=1): the install runs on that Python, makes no 47# .venv and installs no package (setup.py's own CONTROL mode). 48CONTROL = os .environ .get ("STRATA_CONTROL_INSTALL" )== "1" 49DEFAULT_PORT = 8080 50STATE_DIR = ".strata-mcp" # in the Strata folder (git-ignored) 51 52# What setup.py offers, used only when setup.py cannot be imported (the numbers are setup's MODELS / FAMILIES / 53# CONTEXTS; tools/test_strata_mcp.py checks they still match). 54FALLBACK_MODELS = { 55"Q2_0" : {"about" :"2-bit, the fastest" ,"download_gb" :66.4 ,"ram_gb" :48 ,"arena_gb" :34.0 ,"families" : ("qwen" ,)}, 56"IQ2_XS" : {"about" :"2-bit i-quant, a little better quality, close in speed" ,"download_gb" :68.0 ,"ram_gb" :48 , 57"arena_gb" :35.5 }, 58"IQ3_XXS" : {"about" :"3-bit i-quant, better quality, slower (more CPU work per token)" ,"download_gb" :75.8 , 59"ram_gb" :60 ,"arena_gb" :42.9 }, 60"IQ3_S" : {"about" :"3.5-bit i-quant, the best quality (matches the full model), the slowest; needs a 64 GB PC " 61"with little else running" ,"download_gb" :83.6 ,"ram_gb" :62 ,"arena_gb" :50.3 }, 62"IQ1_M" : {"about" :"the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)" ,"download_gb" :58.4 , 63"ram_gb" :32 ,"arena_gb" :23.4 ,"families" : ("coder" ,)}, 64"UD-IQ4_XS" : {"about" :"~4-bit i-quant (Unsloth Dynamic), between IQ3_S and UD-Q4_K_XL in quality; on a PC with " 65"less than ~80 GB of RAM part of its experts are read from the SSD" , 66"download_gb" :93.7 ,"ram_gb" :48 ,"arena_gb" :59.5 ,"families" : ("unsloth" ,),"budget" :True , 67"vision" :True }, 68"UD-Q4_K_XL" : {"about" :"4-bit (Unsloth Dynamic): K-quant experts, between UD-IQ4_XS and UD-Q5_K_XL in quality" , 69"download_gb" :111.3 ,"ram_gb" :48 ,"arena_gb" :77.0 ,"families" : ("unsloth" ,),"budget" :True , 70"vision" :True },# #967: images allowed (setup warns: untested with this file) 71"UD-Q5_K_XL" : {"about" :"5-bit (Unsloth Dynamic): Q5_K experts with Q8_0 downs, close to Q8_0 in quality" , 72"download_gb" :158.3 ,"ram_gb" :108 ,"arena_gb" :98.4 ,"families" : ("unsloth" ,),"budget" :True , 73"vision" :True }, 74"UD-Q6_K_XL" : {"about" :"6-bit (Unsloth Dynamic): Q6_K experts with Q8_0 downs" , 75"download_gb" :169.2 ,"ram_gb" :118 ,"arena_gb" :109.2 ,"families" : ("unsloth" ,),"budget" :True , 76"vision" :True }, 77"Q8_0" : {"about" :"8-bit, the reference quality (every expert Q8_0); for a 192 GB PC" , 78"download_gb" :188.2 ,"ram_gb" :136 ,"arena_gb" :128.3 ,"families" : ("unsloth" ,),"budget" :True , 79"vision" :True }, 80# round 0214: Unsloth's v3.1 sets (setup.py MODELS; the about lines come with the wording commit) 81"UD-IQ1_M" : {"about" :"~1-bit (Unsloth Dynamic v3.1), the smallest download" ,"download_gb" :68.0 ,"ram_gb" :48 ,"arena_gb" :34.8 ,"families" : ("unsloth" ,),"budget" :True , 82"vision" :True }, 83"UD-Q2_0" : {"about" :"2-bit (Unsloth Dynamic v3.1)" ,"download_gb" :70.5 ,"ram_gb" :48 ,"arena_gb" :37.4 ,"families" : ("unsloth" ,),"budget" :True , 84"vision" :True }, 85"UD-IQ2_XS" : {"about" :"2-bit i-quant (Unsloth Dynamic v3.1)" ,"download_gb" :75.8 ,"ram_gb" :48 ,"arena_gb" :42.3 ,"families" : ("unsloth" ,),"budget" :True , 86"vision" :True }, 87"UD-Q2_K_XL" : {"about" :"2-bit (Unsloth Dynamic v3.1) with some 3-bit experts" ,"download_gb" :79.6 ,"ram_gb" :48 ,"arena_gb" :46.0 ,"families" : ("unsloth" ,),"budget" :True , 88"vision" :True }, 89"UD-IQ3_XXS" : {"about" :"3-bit i-quant (Unsloth Dynamic v3.1)" ,"download_gb" :83.6 ,"ram_gb" :48 ,"arena_gb" :50.3 ,"families" : ("unsloth" ,),"budget" :True , 90"vision" :True }, 91"UD-Q3_K_XL" : {"about" :"3-bit (Unsloth Dynamic v3.1) with some 4-bit experts" ,"download_gb" :89.5 ,"ram_gb" :48 ,"arena_gb" :56.2 ,"families" : ("unsloth" ,),"budget" :True , 92"vision" :True }, 93"UD-IQ4_XS-v31" : {"about" :"~4-bit i-quant (Unsloth Dynamic v3.1), a newer file than UD-IQ4_XS with other tensor types" ,"download_gb" :93.7 ,"ram_gb" :48 ,"arena_gb" :60.4 ,"families" : ("unsloth" ,),"budget" :True , 94"vision" :True }, 95"Gyro-S" : {"about" :"the smallest option, for PCs with little memory (27.6 GB of VRAM + RAM together); lower quality " 96"than the 2-3-bit sizes, and the 2-bit Q2_0 decodes faster" , 97"engine" : (0 ,1 ,45 ,1 ), 98"download_gb" :58.5 ,"ram_gb" :27.6 ,"arena_gb" :25.8 ,"families" : ("gyro" ,),"mem_total" :True , 99"vision" :True }, 100"Gyro-M" : {"about" :"about IQ3_XXS quality with about 20% less GPU memory (35 GB of VRAM + RAM together); decodes " 101"about 16-21% slower than Q2_0 on 12 GB cards" , 102"engine" : (0 ,1 ,45 ,1 ), 103"download_gb" :92.0 ,"ram_gb" :35.0 ,"arena_gb" :32.1 ,"families" : ("gyro" ,),"mem_total" :True , 104"vision" :True }, 105"NVFP4" : {"about" :"4-bit NVFP4 experts, GPTQ (sergqwer's strata-nvfp4 pack); RTX 50 has FP4 tensor cores, other " 106"NVIDIA cards run it at 8-bit precision" ,"download_gb" :128.0 ,"ram_gb" :80 ,"arena_gb" :68.0 , 107"families" : ("nvfp4" ,),"vision" :True }, 108"NVFP4-NVIDIA" : {"about" :"NVIDIA's own NVFP4 checkpoint (plain rounding), converted by sergqwer; the same size " 109"and speed as NVFP4" ,"download_gb" :128.0 ,"ram_gb" :80 ,"arena_gb" :68.0 , 110"families" : ("nvfp4" ,),"vision" :True }, 111"NVFP4-QAD" : {"about" :"NVIDIA's FP4, trained for FP4 - slightly faster on short prompts; a 102 GB download " 112"that this PC turns into a Strata pack once; it reads pictures" , 113"download_gb" :102.2 ,"ram_gb" :80 ,"arena_gb" :68.0 ,"families" : ("nvfp4" ,),"vision" :True }, 114} 115FALLBACK_FAMILIES = { 116"qwen" : {"title" :"Qwen3.8-Flash-Next" ,"about" :"the original model" ,"tag" :"" }, 117"swift" : {"title" :"Swift 1.5" ,"about" :"thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its " 118"authors' numbers)" ,"tag" :"swift-" }, 119"coder" : {"title" :"Qwen3.8-Flash-Next Coder" ,"about" :"half the experts (code, tools, images kept): needs ~32 GB " 120"of RAM, faster; weaker outside coding" ,"tag" :"coder-" }, 121"unsloth" : {"title" :"Qwen3.8-Flash-Next (Unsloth)" ,"about" :"UD-IQ1_M, UD-Q2_0, UD-IQ2_XS, UD-Q2_K_XL, UD-IQ3_XXS, UD-Q3_K_XL, UD-IQ4_XS, UD-IQ4_XS-v31, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL or Q8_0 " 122"(68 to 188 GB downloads): every expert in RAM from " 123"~50 GB (UD-IQ1_M) to ~136 GB (Q8_0) of RAM, else " 124"part of them read from the SSD" , 125"tag" :"unsloth-" ,"vision" :True }, 126"gyro" : {"title" :"Qwen3.8-Flash-Next (Gyro)" ,"about" :"Gyro-S (27.6 GB of memory) and Gyro-M (35 GB): the smallest " 127"sizes, for PCs with little memory; 58 and 92 GB " 128"downloads (the files include the n-gram table)" , 129"tag" :"gyro-" }, 130"nvfp4" : {"title" :"Qwen3.8-Flash-Next (NVFP4)" ,"about" :"4-bit NVFP4 experts, NVIDIA cards; a 128 GB download, " 131"~80 GB of RAM to keep every expert in RAM" , 132"tag" :"nvfp4-" }, 133} 134OWN_PATH_ENGINE = (0 ,1 ,45 )# the first engine that runs Qwen3.6-35B-A3B with pictures and parallel requests (setup.py MIN_ENGINE note) 135MEMORY_TIERS = ((62.0 ,"qwen" ,"IQ3_S" ), (46.0 ,"qwen" ,"IQ3_XXS" ), (38.0 ,"swift" ,"IQ2_XS" ))# as setup.py's: RAM + VRAM floors of the owner's 64 / 48 / 40 GB tiers 136# #3425 (owner's rule, same as setup.py's TIER_SYSTEM_RESERVE_GB): the floors count RAM + VRAM less the 5 GB Windows and the system keep 137TIER_SYSTEM_RESERVE_GB = 5.0 138GYRO_ROOM_GB = 4.0 # recommend() suggests a Gyro size only when VRAM + RAM exceed its memory figure by this much 139FALLBACK_CONTEXTS = [8192 ,32768 ,65536 ,131072 ,204800 ,262144 ,393216 ,524288 ] 140BENCH_PROMPT = ("Write a short story (about 300 words) about a lighthouse keeper who finds a message in a bottle. " 141"Plain prose, no title." ) 142 143if WIN : 144import ctypes 145from ctypes import wintypes 146 147_k32 = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 148_k32 .OpenProcess .restype = wintypes .HANDLE 149_k32 .OpenProcess .argtypes = (wintypes .DWORD ,wintypes .BOOL ,wintypes .DWORD ) 150_k32 .GetProcessTimes .argtypes = (wintypes .HANDLE ,* (ctypes .POINTER (wintypes .FILETIME ),)* 4 ) 151_k32 .GetExitCodeProcess .argtypes = (wintypes .HANDLE ,ctypes .POINTER (wintypes .DWORD )) 152_k32 .TerminateProcess .argtypes = (wintypes .HANDLE ,wintypes .UINT ) 153_k32 .WaitForSingleObject .argtypes = (wintypes .HANDLE ,wintypes .DWORD ) 154_k32 .CloseHandle .argtypes = (wintypes .HANDLE ,) 155_QUERY ,_TERMINATE ,_SYNCHRONIZE ,_STILL_ACTIVE = 0x1000 ,0x0001 ,0x00100000 ,259 156 157class _PROCESSENTRY32W (ctypes .Structure ): 158_fields_ = [("dwSize" ,wintypes .DWORD ), ("cntUsage" ,wintypes .DWORD ), ("th32ProcessID" ,wintypes .DWORD ), 159 ("th32DefaultHeapID" ,ctypes .c_size_t ), ("th32ModuleID" ,wintypes .DWORD ), 160 ("cntThreads" ,wintypes .DWORD ), ("th32ParentProcessID" ,wintypes .DWORD ), 161 ("pcPriClassBase" ,ctypes .c_long ), ("dwFlags" ,wintypes .DWORD ), ("szExeFile" ,ctypes .c_wchar * 260 )] 162_k32 .CreateToolhelp32Snapshot .restype = wintypes .HANDLE 163_k32 .CreateToolhelp32Snapshot .argtypes = (wintypes .DWORD ,wintypes .DWORD ) 164_k32 .Process32FirstW .argtypes = (wintypes .HANDLE ,ctypes .POINTER (_PROCESSENTRY32W )) 165_k32 .Process32NextW .argtypes = (wintypes .HANDLE ,ctypes .POINTER (_PROCESSENTRY32W )) 166CREATE_NEW_PROCESS_GROUP ,CREATE_NO_WINDOW ,CREATE_BREAKAWAY_FROM_JOB = 0x200 ,0x08000000 ,0x01000000 167 168 169def log (msg :str )-> None : 170"""Diagnostics go to stderr: stdout carries only the protocol.""" 171try : 172sys .stderr .write (f"[strata-mcp] { msg } \n" ) 173sys .stderr .flush () 174except (OSError ,ValueError ): 175pass 176 177 178# ------------------------------------------------------------------------------------------------ processes 179def proc_identity (pid )-> str | None : 180"""A token for a RUNNING process: its start time (so a reused process id is never mistaken for ours), or None 181when no such process runs.""" 182try : 183pid = int (pid ) 184except (TypeError ,ValueError ): 185return None 186if pid <= 0 : 187return None 188if WIN : 189h = _k32 .OpenProcess (_QUERY ,False ,pid ) 190if not h : 191return None 192try : 193code = wintypes .DWORD () 194if not _k32 .GetExitCodeProcess (h ,ctypes .byref (code ))or code .value != _STILL_ACTIVE : 195return None 196c ,e ,k ,u = (wintypes .FILETIME ()for _ in range (4 )) 197if not _k32 .GetProcessTimes (h ,ctypes .byref (c ),ctypes .byref (e ),ctypes .byref (k ),ctypes .byref (u )): 198return None 199return f"win: { ( c . dwHighDateTime << 32 ) | c . dwLowDateTime } " 200finally : 201_k32 .CloseHandle (h ) 202stat = Path (f"/proc/ { pid } /stat" ) 203if _has_proc (): 204try : 205fields = stat .read_text ().rsplit (")" ,1 )[1 ].split () 206except (OSError ,IndexError ): 207return None 208if fields [0 ]in ("Z" ,"X" ):# a zombie has ended 209return None 210return f"linux: { fields [ 19 ] } " # field 22 of stat: the start time in clock ticks 211state = _ps_state (pid )# elsewhere (macOS: no /proc): ps says whether it runs; a zombie (an ended child 212if state is not None :# not reaped yet) answers kill(pid, 0) but has ended (lane 8, a Mac install that "ran" for ever) 213return "pid" if state and not state .startswith ("Z" )else None 214try :# no ps either: alive, without a start time 215os .kill (pid ,0 ) 216return "pid" 217except OSError : 218return None 219 220 221def _has_proc ()-> bool : 222return Path ("/proc/self/stat" ).exists () 223 224 225def _ps_state (pid :int )-> str | None : 226"""The process state letter(s) ps reports for the process ("S", "R+", "Z" ...), "" when no such process runs, None when ps cannot be asked.""" 227try : 228done = subprocess .run (["ps" ,"-o" ,"stat=" ,"-p" ,str (pid )],capture_output = True ,text = True ,timeout = 5 ) 229except (OSError ,subprocess .SubprocessError ): 230return None 231out = done .stdout .strip () 232if done .returncode != 0 and not out : 233return "" # ps: no such process 234return out 235 236 237def proc_alive (pid ,ident )-> bool : 238return bool (ident )and proc_identity (pid )== ident 239 240 241def proc_terminate (pid ,ident )-> bool : 242"""Ask a process WE started to end (POSIX: SIGTERM, the server's clean path; Windows: TerminateProcess). Never 243touches a process whose start time differs from the one recorded.""" 244if not proc_alive (pid ,ident ): 245return False 246if WIN : 247h = _k32 .OpenProcess (_TERMINATE | _QUERY ,False ,int (pid )) 248if not h : 249return False 250try : 251return bool (_k32 .TerminateProcess (h ,1 )) 252finally : 253_k32 .CloseHandle (h ) 254try : 255os .kill (int (pid ),signal .SIGTERM ) 256return True 257except OSError : 258return False 259 260 261def _rmtree_ignore_missing (func ,path ,exc_info ): 262"""shutil.rmtree error hook: a file that vanished while its folder was being removed is already gone.""" 263exc = exc_info [1 ]if isinstance (exc_info ,tuple )else exc_info 264if isinstance (exc ,FileNotFoundError ): 265return 266raise exc 267 268 269def proc_children_map ()-> dict : 270"""Windows: {parent pid: [child pids]} of every running process (a Toolhelp snapshot); {} elsewhere or when it fails.""" 271if not WIN : 272return {} 273snap = _k32 .CreateToolhelp32Snapshot (0x2 ,0 )# TH32CS_SNAPPROCESS 274if not snap or snap == wintypes .HANDLE (- 1 ).value : 275return {} 276kids :dict = {} 277try : 278entry = _PROCESSENTRY32W () 279entry .dwSize = ctypes .sizeof (_PROCESSENTRY32W ) 280ok = _k32 .Process32FirstW (snap ,ctypes .byref (entry )) 281while ok : 282kids .setdefault (entry .th32ParentProcessID , []).append (entry .th32ProcessID ) 283ok = _k32 .Process32NextW (snap ,ctypes .byref (entry )) 284finally : 285_k32 .CloseHandle (snap ) 286return kids 287 288 289def proc_tree_snapshot (pid )-> list : 290"""Every process below `pid` as [(pid, identity)], taken NOW: once a middle process of the tree ends, taskkill /T can no longer reach 291what it started (#3257: a cancelled install left tools/mtp_fetch.py writing). Windows only; [] elsewhere (a process group does that).""" 292kids = proc_children_map () 293out ,seen ,todo = [], {int (pid )}, [int (pid )] 294while todo : 295for child in kids .get (todo .pop (), []): 296if child in seen : 297continue 298seen .add (child ) 299ident = proc_identity (child ) 300if ident : 301out .append ((child ,ident )) 302todo .append (child ) 303return out 304 305 306def kill_snapshot (procs )-> None : 307"""End what a proc_tree_snapshot() listed and still runs (the same process: its start time still matches).""" 308for pid ,ident in reversed (list (procs )): 309if proc_alive (pid ,ident ): 310proc_terminate (pid ,ident ) 311 312 313def proc_kill_tree (pid ,ident )-> bool : 314"""End a process WE started together with the processes it started (setup's pip / cmake, the engine).""" 315if not proc_alive (pid ,ident ): 316return False 317if WIN : 318tree = proc_tree_snapshot (pid )# before taskkill: it walks parent ids, and a break in the chain hides the rest 319r = subprocess .run (["taskkill" ,"/PID" ,str (int (pid )),"/T" ,"/F" ],capture_output = True , 320creationflags = CREATE_NO_WINDOW ) 321kill_snapshot (tree ) 322return r .returncode == 0 or not proc_alive (pid ,ident ) 323try : 324os .killpg (int (pid ),signal .SIGKILL )# started as a session leader: its group is its own 325return True 326except OSError : 327try : 328os .kill (int (pid ),signal .SIGKILL ) 329return True 330except OSError : 331return False 332 333 334def end_group_leftovers (pgid )-> None : 335"""POSIX: after the server WE started (a session leader) is gone, end what is left of its process group - an 336engine it started but could not close (e.g. stopped while loading, before its own SIGTERM handler existed). 337While any member lives, the group id cannot belong to anybody else.""" 338if WIN or not pgid : 339return 340for sig ,wait in ((signal .SIGTERM ,20.0 ), (signal .SIGKILL ,5.0 )): 341try : 342os .killpg (int (pgid ),sig ) 343except OSError : 344return # no such group left 345end = time .time ()+ wait 346while time .time ()< end : 347try : 348os .killpg (int (pgid ),0 ) 349except OSError : 350return 351time .sleep (0.25 ) 352 353 354def wait_gone (pid ,ident ,seconds :float )-> bool : 355end = time .time ()+ seconds 356while time .time ()< end : 357if not proc_alive (pid ,ident ): 358return True 359time .sleep (0.25 ) 360return not proc_alive (pid ,ident ) 361 362 363def spawn_detached (cmd :list ,cwd :Path ,log_path :Path ,env :dict | None = None )-> subprocess .Popen : 364"""Start a background process whose output goes to log_path. It keeps running when the AI client (and this 365server) ends: its own process group / session, no console window on Windows.""" 366log_path .parent .mkdir (parents = True ,exist_ok = True ) 367with open (log_path ,"ab" )as logf : 368kw = dict (cwd = str (cwd ),stdin = subprocess .DEVNULL ,stdout = logf ,stderr = subprocess .STDOUT , 369env = env ,close_fds = True ) 370if WIN : 371flags = CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW 372try :# out of the AI client's job, if it lets us 373return subprocess .Popen (cmd ,creationflags = flags | CREATE_BREAKAWAY_FROM_JOB ,** kw ) 374except OSError : 375return subprocess .Popen (cmd ,creationflags = flags ,** kw ) 376return subprocess .Popen (cmd ,start_new_session = True ,** kw ) 377 378 379def run_quiet (cmd ,timeout = 30 )-> str : 380"""A command's stdout ('' when it is missing or fails), without a console window flashing up on Windows.""" 381try : 382return subprocess .run (cmd ,capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ,stdin = subprocess .DEVNULL , 383creationflags = CREATE_NO_WINDOW if WIN else 0 ).stdout or "" 384except (OSError ,subprocess .SubprocessError ,ValueError ): 385return "" 386 387 388def read_tail (path :Path ,lines :int ,max_bytes :int = 512 * 1024 )-> list [str ]: 389"""The last lines of a log; a progress line rewritten with \\r counts as its last version.""" 390try : 391with open (path ,"rb" )as f : 392f .seek (0 ,os .SEEK_END ) 393size = f .tell () 394f .seek (max (0 ,size - max_bytes )) 395data = f .read ().decode ("utf-8" ,"replace" ) 396except OSError : 397return [] 398out = [] 399for raw in data .split ("\n" ): 400part = [p for p in raw .split ("\r" )if p .strip ()] 401if part : 402out .append (part [- 1 ].rstrip ()) 403return out [- lines :] 404 405 406def dir_size_gb (path :Path ,limit_files :int = 20000 )-> float : 407total ,n = 0 ,0 408for base ,_dirs ,files in os .walk (path ): 409for f in files : 410try : 411total += os .stat (os .path .join (base ,f )).st_size 412except OSError : 413pass 414n += 1 415if n >= limit_files : 416return round (total / 1e9 ,1 ) 417return round (total / 1e9 ,1 ) 418 419 420# ------------------------------------------------------------------------------------------------ HTTP 421_OPENER = urllib .request .build_opener (urllib .request .ProxyHandler ({}))# localhost: never through a proxy 422 423 424def http_json (url :str ,method = "GET" ,body = None ,api_key = None ,timeout = 3.0 ): 425"""(status, JSON or None); status 0 when nothing answers.""" 426data = json .dumps (body ).encode ()if body is not None else (b"" if method == "POST" else None ) 427req = urllib .request .Request (url ,data = data ,method = method ,headers = {"Content-Type" :"application/json" }) 428if api_key : 429req .add_header ("Authorization" ,f"Bearer { api_key } " ) 430try : 431with _OPENER .open (req ,timeout = timeout )as r : 432raw = r .read () 433status = r .status 434except urllib .error .HTTPError as e : 435raw ,status = e .read (),e .code 436except (OSError ,ValueError ): 437return 0 ,None 438try : 439return status ,json .loads (raw or b"null" ) 440except ValueError : 441return status ,None 442 443 444def port_free (port :int ,host = "127.0.0.1" )-> bool : 445import socket 446s = socket .socket (socket .AF_INET ,socket .SOCK_STREAM ) 447try : 448s .bind ((host ,port )) 449return True 450except OSError : 451return False 452finally : 453s .close () 454 455 456# ------------------------------------------------------------------------------------------------ validation 457class ToolError (Exception ): 458"""A clear message for the AI (and its user): the tool result is an error, the server goes on.""" 459 460 461def check_schema (schema :dict ,args )-> dict : 462"""The tools' JSON schemas, enforced: object, known properties only, types, enums, ranges, patterns.""" 463if args is None : 464args = {} 465if not isinstance (args ,dict ): 466raise ToolError ("arguments must be a JSON object" ) 467props = schema .get ("properties" , {}) 468for k in args : 469if k not in props : 470raise ToolError (f"unknown argument { k !r } ; this tool takes: { ', ' . join ( props ) or 'no arguments' } " ) 471for k in schema .get ("required" , []): 472if k not in args : 473raise ToolError (f"missing argument { k !r } " ) 474for k ,v in args .items (): 475p = props [k ] 476t = p .get ("type" ) 477if t == "integer" and (isinstance (v ,bool )or not isinstance (v ,int )): 478if isinstance (v ,float )and v .is_integer (): 479v = args [k ]= int (v ) 480elif isinstance (v ,str )and re .fullmatch (r"\d{1,7}" ,v .strip ()): 481v = args [k ]= int (v .strip ())# some clients send numbers as strings 482else : 483raise ToolError (f" { k } must be a whole number" ) 484if t == "boolean" and not isinstance (v ,bool ): 485if v in ("true" ,"false" ): 486v = args [k ]= v == "true" 487else : 488raise ToolError (f" { k } must be true or false" ) 489if t == "string" : 490if not isinstance (v ,str ): 491raise ToolError (f" { k } must be a string" ) 492if len (v )> p .get ("maxLength" ,300 )or "\x00" in v or "\n" in v or "\r" in v : 493raise ToolError (f" { k } is too long or contains control characters" ) 494if "pattern" in p and not re .fullmatch (p ["pattern" ],v ): 495raise ToolError (f" { k } = { v !r } is not valid ( { p . get ( 'description' , p [ 'pattern' ]) } )" ) 496if "enum" in p and v not in p ["enum" ]: 497raise ToolError (f" { k } must be one of: { ', ' . join ( map ( str , p [ 'enum' ])) } (got { v !r } )" ) 498if t == "integer" : 499if "minimum" in p and v < p ["minimum" ]or "maximum" in p and v > p ["maximum" ]: 500raise ToolError (f" { k } must be between { p . get ( 'minimum' ) } and { p . get ( 'maximum' ) } (got { v } )" ) 501return args 502 503 504def is_inside (path :Path ,root :Path )-> bool : 505try : 506path .relative_to (root ) 507return True 508except ValueError : 509return False 510 511 512def norm (p )-> Path : 513"""A path to compare: absolute, links and Windows' short names (AI-SER~1) resolved, case folded on Windows.""" 514return Path (os .path .normcase (os .path .realpath (os .path .abspath (str (p ))))) 515 516 517def mounted_drive (n :Path )-> bool : 518"""A drive the desktop mounted for the person: /run/media/<user>/<drive>/..., inside /run but not system state.""" 519return not WIN and is_inside (n ,norm ("/run/media" ))and n != norm ("/run/media" ) 520 521 522def system_folders ()-> list [Path ]: 523if WIN : 524env = [os .environ .get (k )for k in ("SystemRoot" ,"windir" ,"ProgramFiles" ,"ProgramFiles(x86)" ,"ProgramData" , 525"ProgramW6432" )] 526return [norm (p )for p in env if p ] 527return [norm (p )for p in ("/bin" ,"/boot" ,"/dev" ,"/etc" ,"/lib" ,"/lib32" ,"/lib64" ,"/proc" ,"/run" ,"/sbin" , 528"/sys" ,"/usr" ,"/var" ,"/snap" )] 529 530 531# ------------------------------------------------------------------------------------------------ Strata 532class Strata : 533"""One Strata folder: what is installed there, the PC, and the processes this server started.""" 534 535def __init__ (self ,root :Path | str = DEFAULT_ROOT ,src :Path | str | None = None ): 536self .root = Path (root ).resolve () 537# where setup.py, tools/ and serve/ are (the app: inside Strata Control); `root` is where the installs live 538self .src = Path (src ).resolve ()if src else self .root 539self .state_dir = self .root / STATE_DIR 540self .lock = threading .Lock ()# install / start / stop one at a time 541self .children :list [subprocess .Popen ]= []# reaped now and then (no zombies on POSIX) 542self ._setup = None 543self ._setup_tried = False 544self ._hw_cache = None 545# tests: the interpreter that runs setup / the server. The app's Control runs the installer on its own Python. 546self .python_override :str | None = sys .executable if CONTROL else None 547self .health_timeout = 2.0 548 549# ---- setup.py's own tables and logic 550def setup_module (self ): 551"""setup.py imported as a module (its tables and its pure checks), or None. Its command runner is replaced 552by one without console windows; nothing of its install path runs.""" 553if not self ._setup_tried : 554self ._setup_tried = True 555try : 556if str (self .src )not in sys .path : 557sys .path .insert (0 ,str (self .src ))# setup.py imports strata_control 558spec = importlib .util .spec_from_file_location ("strata_setup_for_mcp" ,self .src / "setup.py" ) 559mod = importlib .util .module_from_spec (spec ) 560real = sys .stdout 561sys .stdout = sys .stderr # nothing it prints may reach the protocol stream 562try : 563spec .loader .exec_module (mod ) 564finally : 565sys .stdout = real 566if all (hasattr (mod ,a )for a in ("MODELS" ,"FAMILIES" ,"CONTEXTS" )): 567mod .out = lambda cmd :run_quiet (cmd ,60 ) 568self ._setup = mod 569if hasattr (mod ,"feed_models_setup" ): 570try :# the signed feed's models (the last verified list; nothing is fetched here), after the built-in ones 571mod .feed_models_setup (fetch = False ) 572except Exception as e :# noqa: BLE001 573log (f"the feed's model list was not added: { e } " ) 574except (Exception ,SystemExit )as e :# noqa: BLE001 - any failure: the built-in tables 575log (f"setup.py could not be imported ( { e } ); using the built-in model table" ) 576return self ._setup 577 578def tables (self ): 579s = self .setup_module () 580if s is not None : 581return s .MODELS , {** s .FAMILIES ,** self .own_families ()},list (s .CONTEXTS ),"setup.py" 582return FALLBACK_MODELS ,FALLBACK_FAMILIES ,FALLBACK_CONTEXTS ,"built-in table (setup.py not importable)" 583 584def own_families (self )-> dict : 585"""setup.py's OWN_PATH_FAMILIES (Qwen3.6-35B-A3B): families with an engine path of their own. They are not in FAMILIES 586(whose entries are Flash-Next files with packs), so the model list used to leave them out and the app's Qwen3.6 page 587showed no versions at all. Each is returned as a family entry (title, about, tag, license) of this server's table.""" 588s = self .setup_module () 589out = {} 590for f ,d in (getattr (s ,"OWN_PATH_FAMILIES" ,None )or {}).items (): 591out [f ]= {"title" :d ["title" ],"about" :d .get ("about" ),"tag" :d ["tag" ],"license" :d .get ("license" ), 592"vision" :bool (d .get ("vision" ,True )),"own_path" :True ,** ({"feed" :True }if d .get ("feed" )else {})} 593return out 594 595def own_size_names (self )-> list : 596"""The size names of the families that have an engine path of their own (Qwen3.6): the install tool accepts them as `model`.""" 597s = self .setup_module () 598names = [] 599for table in ("OWN_PATH_FAMILIES" ,): 600for fam in (getattr (s ,table ,None )or {}).values (): 601names .extend (n for n in fam .get ("models" , {})if n not in names ) 602return names 603 604def own_size (self ,family ,model )-> dict | None : 605"""One size of an own-path family as a model-table row for install_plan / model_table (None: not an own-path size). 606The download is the GGUF; the picture reader (mmproj, ~0.9 GB) is counted by the plan when pictures are on.""" 607d = (getattr (self .setup_module (),"OWN_PATH_FAMILIES" ,None )or {}).get (family ) 608if not d or model not in d ["models" ]: 609return None 610size_gb = d ["sha256" ][d ["file" ].format (q = model )][0 ]/ 1e9 611return {"about" :d ["models" ][model ]["about" ],"download_gb" :round (size_gb ,1 ),"ram_gb" :d ["models" ][model ]["ram_gb" ], 612# the routed experts are ~93% of the file (setup.own_path_parallel_fits_all); the dense part and buffers ~1 GB more 613"arena_gb" :round (size_gb * 0.93 ,1 ),"vision" :bool (d .get ("vision" ,True )), 614"engine" :OWN_PATH_ENGINE ,"families" : (family ,),"context_fit" :self .own_context_fit (d ,model )} 615 616@staticmethod 617def own_context_fit (fam :dict ,model )-> dict | None : 618"""Which context fits a card for this own-path size (#5715): strata_control/own_path_fit.py's inputs, the figures the app's estimate uses.""" 619try : 620from strata_control import own_path_fit 621return own_path_fit .inputs (fam .get ("name" ),model ) 622except ImportError : 623return None 624 625def sizes_of (self ,models ,family )-> list : 626"""The family's sizes as setup lists them: an experimental one last (never the default).""" 627own = (getattr (self .setup_module (),"OWN_PATH_FAMILIES" ,None )or {}).get (family ) 628if own : 629return list (own ["models" ]) 630return sorted ((m for m in models if family in models [m ].get ("families" , ("qwen" ,"swift" ))), 631key = lambda m :bool (models [m ].get ("experimental" ))) 632 633# ---- paths 634def settings_path (self )-> Path : 635if os .environ .get ("STRATA_SETTINGS_FILE" ): 636return Path (os .environ ["STRATA_SETTINGS_FILE" ]) 637if WIN : 638return Path (os .environ .get ("APPDATA" )or Path .home ()/ "AppData" / "Roaming" )/ "Strata" / "settings.json" 639return Path (os .environ .get ("XDG_CONFIG_HOME" )or Path .home ()/ ".config" )/ "strata" / "settings.json" 640 641def data_dir (self )-> Path : 642try : 643s = json .loads (self .settings_path ().read_text (encoding = "utf-8" )) 644except (OSError ,ValueError ): 645s = {} 646d = s .get ("data_dir" )if isinstance (s ,dict )else None 647return Path (d )if d else self .root .parent / "Strata-data" 648 649def allowed_roots (self )-> list [Path ]: 650return [norm (self .root ),norm (self .data_dir ())] 651 652def allowed (self ,p )-> bool : 653p = norm (p ) 654return any (is_inside (p ,r )for r in self .allowed_roots ()) 655 656def venv_python (self )-> Path : 657return self .root / ".venv" / ("Scripts/python.exe" if WIN else "bin/python" ) 658 659def run_python (self )-> str : 660return self .python_override or str (self .venv_python ()) 661 662def state (self ,name :str )-> dict : 663try : 664d = json .loads ((self .state_dir / f" { name } .json" ).read_text (encoding = "utf-8" )) 665return d if isinstance (d ,dict )else {} 666except (OSError ,ValueError ): 667return {} 668 669def save_state (self ,name :str ,d :dict | None )-> None : 670self .state_dir .mkdir (parents = True ,exist_ok = True ) 671f = self .state_dir / f" { name } .json" 672if d is None : 673f .unlink (missing_ok = True ) 674else : 675tmp = f .with_suffix (".tmp" ) 676tmp .write_text (json .dumps (d ,indent = 1 ),encoding = "utf-8" ) 677os .replace (tmp ,f ) 678 679def reap (self ): 680self .children = [p for p in self .children if p .poll ()is None ] 681 682# ---- what is installed 683def configs (self )-> list [Path ]: 684return sorted ((p for p in self .root .glob ("strata-*.json" )if not p .name .endswith (".shared-settings.json" )), 685key = lambda p :p .stat ().st_mtime ,reverse = True )# #346: the Chat settings file is no config 686 687@staticmethod 688def read_config (path :Path )-> dict : 689try : 690cfg = json .loads (path .read_text (encoding = "utf-8-sig" )) 691return cfg if isinstance (cfg ,dict )else {} 692except (OSError ,ValueError ): 693return {} 694 695def describe_config (self ,path :Path ,usage :dict | None = None )-> dict : 696cfg = self .read_config (path ) 697a = cfg .get ("args" )if isinstance (cfg .get ("args" ),list )else [] 698 699def val (k ): 700return a [a .index (k )+ 1 ]if k in a and a .index (k )+ 1 < len (a )else None 701tag = path .stem [len ("strata-" ):] 702missing = [p for p in [cfg .get ("exe" ),* [x for x in a if isinstance (x ,str )and x .endswith (".gguf" )]] 703if not p or not Path (p ).exists ()] 704gaps = shard_gaps ([x for x in a if isinstance (x ,str )and x .endswith (".gguf" )])# a model in parts is whole only with every part 705missing += gaps 706script = self .root / f"run- { tag } . { 'bat' if WIN else 'sh' } " 707vis = cfg .get ("vision" ) 708own_usage = (usage or self .disk_usage ())["models" ].get (tag )or {"gb" :0.0 ,"bytes" :0 ,"shared_bytes" :0 } 709plan = self .removal_plan (path ) 710return {"model" :tag ,"config" :path .name ,"model_name" :cfg .get ("model_name" ), 711"context" :int (val ("--max-context" ))if str (val ("--max-context" )or "" ).isdigit ()else None , 712"kv" :val ("--kv" ),"images" : ("gpu" if vis .get ("gpu" )else "cpu" )if isinstance (vis ,dict ) 713else "off" , 714"port" :cfg .get ("port" ,DEFAULT_PORT ),"host" :cfg .get ("host" ,"127.0.0.1" ), 715"gpu" :cfg .get ("gpu" ),"gpu_roles" :cfg .get ("gpu_roles" ),"api_key_set" :bool (cfg .get ("api_key" )), 716"low_ram" :"--resident-experts" in a or "--mmap-experts" in a , 717"start_script" :script .name if script .exists ()else None , 718"ready" :not missing and bool (cfg ),"missing_files" :missing [:3 ],"parts_missing" :len (gaps ), 719"disk_gb" :own_usage ["gb" ],"disk_bytes" :own_usage ["bytes" ], 720"shared_bytes" :own_usage ["shared_bytes" ], 721# what Delete would remove (files in Strata's own folders that no other model uses); the person's own GGUF folders stay 722"removable_gb" :plan ["gb" ],"kept_files" :len (plan ["keep" ]), 723"last_used" :time .strftime ("%Y-%m-%d %H:%M" ,time .localtime (path .stat ().st_mtime ))} 724 725# ---- what a model owns on disk (Delete, and the per-model disk usage in Storage) 726FILE_FLAGS = ("--native" ,"--ple-gguf" ,"--embd-gguf" ,"--native-dense-gguf" ) 727DIR_FLAGS = ("--pack" ,"--mtp" ) 728 729def model_paths (self ,cfg :dict )-> tuple [list ,list ]: 730"""(the GGUF files, the folders) a run config names: --native/--ple-gguf/... and --pack/--mtp, plus any other .gguf.""" 731a = [x for x in (cfg .get ("args" )or [])if isinstance (x ,str )] 732files = [Path (a [i + 1 ])for i ,x in enumerate (a [:- 1 ])if x in self .FILE_FLAGS ] 733files += [Path (x )for x in a if x .lower ().endswith (".gguf" )] 734dirs = [Path (a [i + 1 ])for i ,x in enumerate (a [:- 1 ])if x in self .DIR_FLAGS ] 735seen ,once = set (), [] 736for f in files :# one file named by several flags is still one file 737if norm (f )not in seen : 738seen .add (norm (f )) 739once .append (f ) 740seen_d ,once_d = set (), [] 741for d in dirs : 742if norm (d )not in seen_d : 743seen_d .add (norm (d )) 744once_d .append (d ) 745return once ,once_d 746 747@staticmethod 748def with_shards (files :list )-> list : 749"""The files plus the other parts of every multi-part GGUF among them (name-00001-of-00004.gguf: the config names only the 750first), so deleting a model takes all its parts and never leaves 100 GB behind (#3716).""" 751out ,seen = [],set () 752for f in files : 753names = [Path (f )] 754m = SHARD_NAME .match (str (f )) 755if m : 756names += [Path (f" { m . group ( 1 ) } - { i :05d } -of- { m . group ( 3 ) } .gguf" )for i in range (1 ,int (m .group (3 ))+ 1 )] 757for n in names : 758key = norm (n ) 759if key not in seen : 760seen .add (key ) 761out .append (n ) 762return out 763 764@staticmethod 765def tree_bytes (path :Path )-> int : 766if path .is_file (): 767try : 768return path .stat ().st_size 769except OSError : 770return 0 771total = 0 772for base ,_d ,names in os .walk (path ): 773for n in names : 774try : 775total += os .stat (os .path .join (base ,n )).st_size 776except OSError : 777pass 778return total 779 780@staticmethod 781def file_key (path :Path ): 782"""What makes two names the same file on disk: device + inode (hard links), else the resolved path.""" 783try : 784st = os .stat (path ) 785if st .st_ino : 786return ("ino" ,st .st_dev ,st .st_ino ),st .st_size 787return ("path" ,str (norm (path ))),st .st_size 788except OSError : 789return None ,0 790 791def used_files (self ,cfg :dict )-> dict : 792"""Every file a model really uses, from its run config: all parts of a multi-part GGUF (the config names the first), the 793picture reader, the packs and the draft layer folders. {file identity: bytes}, wherever they live (the Strata folders or the 794person's own).""" 795files ,dirs = self .model_paths (cfg ) 796paths = list (files ) 797vis = cfg .get ("vision" ) 798if isinstance (vis ,dict )and isinstance (vis .get ("mmproj" ),str ): 799paths .append (Path (vis ["mmproj" ])) 800for f in list (paths ):# the other parts of a multi-part file 801m = SHARD_NAME .match (str (f )) 802if m : 803paths += [Path (f" { m . group ( 1 ) } - { i :05d } -of- { m . group ( 3 ) } .gguf" )for i in range (1 ,int (m .group (3 ))+ 1 )] 804for d in dirs : 805for base ,_sub ,names in os .walk (d ): 806paths += [Path (base )/ n for n in names ] 807out = {} 808for p in paths : 809if p .is_file (): 810key ,size = self .file_key (p ) 811if key is not None : 812out [key ]= size 813return out 814 815def disk_usage (self )-> dict : 816"""What the installed models take on disk, from the real files: each model's own files, the files shared between models 817(the picture reader, the draft layer) counted ONCE, and the total. A model's own figure leaves out the shared files and 818every other model's; rows plus 'shared' add up to the total.""" 819per = {c .stem [len ("strata-" ):]:self .used_files (self .read_config (c ))for c in self .configs ()} 820owners :dict = {} 821for files in per .values (): 822for k in files : 823owners [k ]= owners .get (k ,0 )+ 1 824models ,shared = {}, {} 825for tag ,files in per .items (): 826own = sum (b for k ,b in files .items ()if owners [k ]== 1 ) 827models [tag ]= {"bytes" :own ,"gb" :round (own / 1e9 ,2 ),"files" :len (files ), 828"shared_bytes" :sum (b for k ,b in files .items ()if owners [k ]> 1 )} 829shared .update ({k :b for k ,b in files .items ()if owners [k ]> 1 }) 830shared_bytes = sum (shared .values ()) 831total = sum (m ["bytes" ]for m in models .values ())+ shared_bytes 832return {"models" :models ,"shared_bytes" :shared_bytes ,"shared_gb" :round (shared_bytes / 1e9 ,2 ), 833"total_bytes" :total ,"total_gb" :round (total / 1e9 ,2 )} 834 835@staticmethod 836def made_by_strata (p :Path ,is_dir :bool )-> bool : 837"""A download or pack Strata wrote itself, even in a models folder the person picked or the app chose: a finished GGUF has its 838.done mark beside it, a prepared pack has its conversion record. The person's own GGUF files have neither (#3716).""" 839try : 840if is_dir : 841return any ((p / n ).is_file ()for n in ("conversions.json" ,"experts.bin.src.json" )) 842return p .with_name (p .name + ".done" ).is_file () 843except OSError : 844return False 845 846def removal_plan (self ,config :Path )-> dict : 847"""What deleting this model removes and what it keeps. A file or folder another installed model's config still names 848(the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders.""" 849cfg = self .read_config (config ) 850files ,dirs = self .model_paths (cfg ) 851files = self .with_shards (files ) 852used_files ,used_dirs = set (),set () 853for other in self .configs (): 854if norm (other )== norm (config ): 855continue 856f ,d = self .model_paths (self .read_config (other )) 857f = self .with_shards (f ) 858used_files |= {norm (x )for x in f } 859used_dirs |= {norm (x )for x in d } 860remove ,keep = [], [] 861 862def shared (p :Path ,is_dir :bool )-> bool : 863n = norm (p ) 864if n in used_files or n in used_dirs or any (is_inside (u ,n )for u in used_files | used_dirs )and is_dir : 865return True 866return any (is_inside (n ,u )for u in used_dirs ) 867 868for p ,is_dir in [(x ,False )for x in files ]+ [(x ,True )for x in dirs ]: 869if not p .exists (): 870continue 871if not self .allowed (p )and not self .made_by_strata (p ,is_dir ): 872keep .append ({"path" :str (p ),"reason" :"outside Strata's folders" }) 873elif shared (p ,is_dir ): 874keep .append ({"path" :str (p ),"reason" :"another installed model still uses it" }) 875else : 876remove .append ({"path" :str (p ),"kind" :"folder" if is_dir else "file" ,"bytes" :self .tree_bytes (p )}) 877if not is_dir : 878for extra in (p .with_name (p .name + ".done" ),p .with_name (p .name + ".part" ), 879p .with_name (p .name + ".part.chunks" )): 880if extra .exists (): 881remove .append ({"path" :str (extra ),"kind" :"file" ,"bytes" :self .tree_bytes (extra )}) 882tag = config .stem [len ("strata-" ):] 883for extra in (config ,config .with_name (config .name + ".bak" ),config .with_name (f"strata- { tag } .log" ), 884self .root / f"run- { tag } .bat" ,self .root / f"run- { tag } .sh" ): 885if extra .exists (): 886remove .append ({"path" :str (extra ),"kind" :"file" ,"bytes" :self .tree_bytes (extra )}) 887total = sum (x ["bytes" ]for x in remove ) 888return {"model" :tag ,"remove" :remove ,"keep" :keep ,"bytes" :total ,"gb" :round (total / 1e9 ,2 )} 889 890def find_config (self ,model :str | None )-> Path : 891have = self .configs () 892if not have : 893raise ToolError ("no model is installed in " + str (self .root )+ " yet: install one first (strata_install)" ) 894if not model : 895return have [0 ]# the most recently used, as setup starts it 896m = model .strip ().lower () 897exact = [c for c in have if c .stem [len ("strata-" ):]== m ] 898if exact : 899return exact [0 ] 900by_name = [c for c in have if str (self .read_config (c ).get ("model_name" ,"" )).lower ()== m ] 901if by_name : 902return by_name [0 ] 903ends = [c for c in have if c .stem .endswith ("-" + m )] 904if len (ends )== 1 : 905return ends [0 ] 906raise ToolError (f"no installed model { model !r } ; installed: " + 907", " .join (c .stem [len ("strata-" ):]for c in have )) 908 909def engine_info (self )-> dict : 910for d in ("engine" ,): 911try : 912meta = json .loads ((self .root / d / "BUILD.json" ).read_text ()) 913return {"folder" :d ,"version" :meta .get ("version" ),"source" :meta .get ("source" ), 914"backend" :meta .get ("backend" )} 915except (OSError ,ValueError ): 916continue 917return {"folder" :None ,"version" :None } 918 919def installed (self )-> dict : 920data = self .data_dir () 921items = {} 922for sub in ("models" ,"packs" ): 923for base in dict .fromkeys ([data ,self .root ]): 924d = base / sub 925if d .is_dir (): 926for c in sorted (d .iterdir ()): 927if c .is_dir (): 928ggufs = list (c .glob ("*.gguf" )) 929entry = {"folder" :str (c ),"size_gb" :dir_size_gb (c )} 930if sub == "models" : 931entry ["complete" ]= bool (ggufs )and all ( 932g .with_name (g .name + ".done" ).exists ()for g in ggufs ) 933entry ["downloading" ]= bool (list (c .glob ("*.part" ))) 934items .setdefault (sub , []).append (entry ) 935mtp = data / "mtp" / "rt" / "experts.bin" 936usage = self .disk_usage () 937return {"strata_folder" :str (self .root ),"data_folder" :str (data ),"data_folder_exists" :data .is_dir (), 938"python_env" :self .venv_python ().exists (),"engine" :self .engine_info (), 939"models" : [self .describe_config (c ,usage )for c in self .configs ()], 940"usage" :usage , 941"downloads" :items .get ("models" , []),"prepared" :items .get ("packs" , []), 942"draft_layer" :mtp .exists ()} 943 944# ---- the PC 945def hardware (self ,fresh = False )-> dict : 946if self ._hw_cache and not fresh and time .time ()- self ._hw_cache [0 ]< 600 : 947hw = dict (self ._hw_cache [1 ]) 948else : 949hw = self ._hardware () 950self ._hw_cache = (time .time (),hw ) 951hw = dict (hw ) 952hw ["disk_free_gb" ]= self .disk_free (self .data_dir ()) 953return hw 954 955@staticmethod 956def disk_free (p :Path )-> float | None : 957p = Path (p ) 958while not p .exists ()and p .parent != p : 959p = p .parent 960try : 961return round (shutil .disk_usage (p ).free / 1e9 ,1 ) 962except OSError : 963return None 964 965def _hardware (self )-> dict : 966S = self .setup_module () 967hw = {"os" :f" { platform . system () } { platform . release () } " ,"os_version" :platform .version (), 968"machine" :platform .machine (),"python" :platform .python_version ()} 969if not WIN and Path ("/proc/version" ).exists (): 970try : 971hw ["wsl" ]= "microsoft" in Path ("/proc/version" ).read_text ().lower () 972except OSError : 973pass 974try : 975hw ["ram_gb" ]= round (S .ram_gb (),1 )if S else round (own_ram_gb (),1 ) 976except Exception :# noqa: BLE001 977hw ["ram_gb" ]= round (own_ram_gb (),1 ) 978if S and WIN : 979try : 980hw ["page_file_gb" ]= round (S .page_file_gb (),1 ) 981except Exception :# noqa: BLE001 982pass 983try : 984if S : 985name ,avx2 ,avx512 = S .cpu_info () 986else : 987name ,avx2 ,avx512 = platform .processor ()or "unknown CPU" ,None ,None 988hw ["cpu" ]= {"name" :name ,"cores" :physical_cores (),"threads" :os .cpu_count (),"avx2" :avx2 ,"avx512" :avx512 } 989except Exception :# noqa: BLE001 990hw ["cpu" ]= {"name" :platform .processor (),"cores" :physical_cores (),"threads" :os .cpu_count ()} 991if sys .platform == "darwin" :# a Mac: one pool of unified memory, the Metal engine (strata_control/mac_fit.py) 992return self ._mac_hardware (hw ) 993nv = [] 994try : 995nv = S .gpus ()if S else own_nvidia_gpus () 996except Exception :# noqa: BLE001 997nv = own_nvidia_gpus () 998for g in nv : 999g ["vendor" ]= "nvidia" 1000g ["vram_gb" ]= round (g ["vram_gb" ],1 ) 1001try : 1002g ["problem" ]= S .gpu_problem (g )if S else (None if int (g ["arch" ])>= 75 else "older than RTX 20" ) 1003except Exception :# noqa: BLE001 1004g ["problem" ]= None 1005g ["usable" ]= g ["problem" ]is None 1006amd = [] 1007try :# Linux: the kernel's KFD topology; Windows: the display adapters' PCI ids + registry (setup.amd_gpus_win) 1008amd = S .amd_gpus ()if S else [] 1009for g in amd : 1010g ["vendor" ]= "amd" 1011g ["vram_gb" ]= round (g ["vram_gb" ],1 ) 1012g ["problem" ]= S .amd_problem (g ) 1013g ["usable" ]= g ["problem" ]is None 1014except Exception :# noqa: BLE001 1015amd = [] 1016if not WIN and not amd and shutil .which ("rocm-smi" ): 1017amd = rocm_smi_gpus () 1018if not WIN and not amd :# no setup module, no rocm-smi (ROCm from a Python venv): the kernel's own list 1019amd = kfd_gpus () 1020# A PC whose only NVIDIA cards are Pascal / Volta (two GTX 1080s) and that has no AMD card Strata can use: setup runs them with the 1021# CUDA 12 engine (old_gpus_opt_in), so the app must not call it "no supported graphics card" and start both cards Off (#3655). 1022# A PC with a newer card keeps recommending that one; naming an old card is still the opt-in. 1023try : 1024if S and nv and S .old_gpus_opt_in (nv , (),None ,any (g .get ("usable" )for g in amd )): 1025for g in nv : 1026if S .sm60_card (g ["arch" ])and g .get ("problem" )and "older than the RTX 20" in str (g ["problem" ]): 1027g ["problem" ],g ["usable" ],g ["engine_variant" ]= None ,True ,"cuda12" 1028except Exception :# noqa: BLE001 - the hardware page never breaks over this 1029pass 1030if any (g .get ("usable" )for g in nv ): 1031for g in amd :# a Ryzen's integrated graphics beside an NVIDIA card: the engine runs on the NVIDIA card 1032if g .get ("uma" )and g .get ("usable" ): 1033g ["usable" ],g ["problem" ]= False ,"integrated graphics: Strata uses the NVIDIA card in this computer" 1034try :# does the card drive a display? (the app keeps less VRAM free on one that does not, #3215) 1035mark_display (nv + amd ,nvidia_display_active ()if nv else {},windows_desktop_adapters ()if WIN and amd else []) 1036except Exception :# noqa: BLE001 - unknown stays unknown: the app then keeps its safety default 1037pass 1038try :# the reserve setup writes for this chip when a run config names none (strata_control/setup_config.py UMA_WIN_RESERVE_MIB, G16): 1039# the app's Load uses it on a one-card run whose config has no reserve of setup's, so the app and `strata launch` start the same engine line (QAGUI-STRIX 11-09). 1040# The same condition as setup_config.config_for: Windows, the HIP engine (an AMD card), unified memory, gfx1151 exactly (gfx_arch_is: "gfx1151" or "gfx1151:..."). 1041if WIN and amd : 1042if str (self .src )not in sys .path : 1043sys .path .insert (0 ,str (self .src )) 1044from strata_control import setup_config 1045for g in amd : 1046arch = str (g .get ("arch" )or "" ) 1047if g .get ("uma" )and (arch == "gfx1151" or arch .startswith ("gfx1151:" )): 1048g ["setup_reserve_mib" ]= setup_config .UMA_WIN_RESERVE_MIB 1049except Exception :# noqa: BLE001 - an older Control folder: no field, the app keeps its own floor 1050pass 1051arc = [] 1052if not WIN :# an Intel Arc (Linux, the SYCL engine): only a PC with no usable NVIDIA or AMD card gets one (strata_control/intel_app.py) 1053try : 1054if str (self .src )not in sys .path : 1055sys .path .insert (0 ,str (self .src )) 1056from strata_control import intel_app 1057arc = intel_app .cards_to_add (nv ,amd ) 1058except Exception :# noqa: BLE001 - an older Control folder without it: the report is what it was 1059arc = [] 1060hw ["gpus" ]= nv + amd + arc 1061for g in hw ["gpus" ]:# each make numbers its cards from 0 (the engine drives one make): a stable id tells two cards apart 1062g .setdefault ("id" ,f" { g . get ( 'vendor' ) or 'gpu' } : { g . get ( 'index' ) } " ) 1063try :# how fast each card is (SMs x clock): the app and the Terminal pick the Main card by it 1064from strata_control import gpu_roles 1065gpu_roles .add_speeds (hw ["gpus" ]) 1066except Exception :# noqa: BLE001 - unknown speed: the card with the most memory is Main 1067pass 1068self ._engine_code (hw ) 1069self ._engine_vendor (hw ) 1070if WIN : 1071hw ["display_adapters" ]= windows_video_controllers () 1072hw ["nvidia_smi" ]= bool (shutil .which ("nvidia-smi" )) 1073return hw 1074 1075@staticmethod 1076def _engine_code (hw :dict )-> None : 1077"""An AMD card the installed engine package has no code for is not one Strata can run on (the engine would stop on it, #3203): flag it 1078unusable with the plain reason, so the card lists and "Automatic" leave it out. Only a package that lists its archs speaks here.""" 1079amd = [g for g in hw .get ("gpus" , [])if g .get ("vendor" )== "amd" and g .get ("arch" )] 1080if not amd : 1081return 1082try : 1083from strata_control import engine_component as ec 1084rep = ec .status () 1085eng = rep .get ("engine" )or {} 1086built = [a for a in eng .get ("archs" )or []if str (a ).startswith ("gfx" )] 1087if not rep .get ("usable" )or eng .get ("backend" )!= "hip" or not built : 1088return 1089except Exception :# noqa: BLE001 - never break the hardware page over this 1090return 1091for g in amd : 1092if g ["arch" ]not in built and g .get ("usable" )is not False : 1093g ["usable" ]= False 1094g ["problem" ]= (ec .no_package_note ([g ["arch" ]])or f"this Strata engine has no code for { g [ 'arch' ] } (it is built for { ', ' . join ( built ) } )" ) 1095 1096@staticmethod 1097def _engine_vendor (hw :dict )-> None : 1098"""One engine drives the cards of ONE make (CUDA: NVIDIA, HIP: AMD, ...): note which one for this PC (the installed engine's, else the one 1099setup fetches first) and, when the other make has the bigger card, the one plain line that says so. The model list below only counts 1100the cards this engine can drive; a model is never split across makes (strata_control/gpu_fit.py).""" 1101try : 1102from strata_control import gpu_fit 1103backend = None 1104try : 1105from strata_control import engine_component as ec 1106rep = ec .status () 1107backend = (rep .get ("engine" )or {}).get ("backend" )if rep .get ("usable" )else None 1108except Exception :# noqa: BLE001 1109backend = None 1110vendor = gpu_fit .pick_vendor (hw .get ("gpus" , []),backend ) 1111hw ["engine_vendor" ]= vendor 1112note = gpu_fit .other_vendor_note (hw .get ("gpus" , []),vendor ) 1113if note : 1114hw ["gpu_note" ]= note 1115except Exception :# noqa: BLE001 - never break the hardware page over this 1116pass 1117 1118@staticmethod 1119def engine_gpus (hw :dict | None )-> list : 1120"""The usable cards the engine of this PC drives (all usable cards when the make is not known).""" 1121hw = hw or {} 1122vendor = hw .get ("engine_vendor" ) 1123return [g for g in hw .get ("gpus" , [])if g .get ("usable" )and (not vendor or not g .get ("vendor" )or g .get ("vendor" )== vendor )] 1124 1125# ---- a Mac (Apple Silicon): unified memory, the Metal engine. The rules are strata_control/mac_fit.py's (the same module 1126# metal/setup_mac.py uses), so the app, the Terminal and a Mac that builds the engine itself judge a model the same way. 1127def mac (self ): 1128"""strata_control/mac_fit.py, or None when this Strata folder does not carry it.""" 1129try : 1130if str (self .src )not in sys .path : 1131sys .path .insert (0 ,str (self .src )) 1132from strata_control import mac_fit 1133return mac_fit 1134except Exception as e :# noqa: BLE001 1135log (f"strata_control/mac_fit.py could not be imported ( { e } )" ) 1136return None 1137 1138def _mac_hardware (self ,hw :dict )-> dict : 1139mf = self .mac () 1140info = mf .mac_info ()if mf else {"chip" :platform .processor ()or "Apple silicon" ,"ram_gb" :hw .get ("ram_gb" )or 0.0 , 1141"macos" :platform .mac_ver ()[0 ],"arm64" :platform .machine ()== "arm64" ,"clt" :"x" } 1142problems = mf .mac_problems (info ,need_compiler = False )if mf else [] 1143ram = round (float (info .get ("ram_gb" )or hw .get ("ram_gb" )or 0.0 ),1 ) 1144hw ["ram_gb" ]= ram 1145hw ["cpu" ]= {"name" :info ["chip" ],"cores" :os .cpu_count (),"avx2" :None ,"avx512" :None } 1146# The graphics memory IS the RAM here: vram_gb stays 0 so nothing is counted twice (the pages that fit RAM + VRAM add them up). 1147hw ["gpus" ]= [{"index" :0 ,"name" :info ["chip" ],"vendor" :"apple" ,"vram_gb" :0.0 ,"unified_gb" :ram ,"arch" :"apple-gpu" , 1148"problem" :problems [0 ]if problems else None ,"usable" :not problems }] 1149hw ["mac" ]= {"chip" :info ["chip" ],"macos" :info .get ("macos" ),"unified_gb" :ram } 1150hw ["nvidia_smi" ]= False 1151return hw 1152 1153def _mac_sizes (self ,models :dict ,family :str = "qwen" )-> list : 1154"""The sizes the app offers on a Mac: the GSQ-RCO files of the Qwen family (two shards, no repack), agentionai's Gyro files (one 1155file, no repack) and, since round 0214, Unsloth's sets (many shards: setup.py's Mac install repacks them with 1156metal/tools/metal_repack.py, as the Terminal's setup does); a set the Metal engine cannot run yet is left out (mac_fit.MAC_MODELS "missing").""" 1157mf = self .mac () 1158return [m for m in mf .app_sizes (family )if m in models ]if mf else [] 1159 1160def _mac_verdict (self ,model :str ,ram :float )-> str : 1161mf = self .mac () 1162from strata_control import fit_label 1163if ram < mf .MIN_STREAM_RAM_GB : 1164return fit_label .SLOWER # too little memory for the Metal engine's streaming: the same two words, said not refused 1165return fit_label .SLOWER if mf .streams (model ,ram )else fit_label .FITS # the Mac's own count of what stays in memory (strata_control/mac_fit.py) 1166 1167def _mac_recommend (self ,hw :dict ,models :dict ,families :dict )-> dict : 1168mf = self .mac () 1169ram = float (hw .get ("ram_gb" )or 0 ) 1170usable = [g for g in hw .get ("gpus" , [])if g .get ("usable" )] 1171if not mf or not usable : 1172why = (hw .get ("gpus" )or [{}])[0 ].get ("problem" )or "this Mac cannot run the Metal engine" 1173return {"family" :None ,"model" :None ,"why" :why } 1174if ram < mf .MIN_STREAM_RAM_GB : 1175return {"family" :None ,"model" :None , 1176"why" :f" { ram :.0f } GB of unified memory: Strata needs { mf . MIN_STREAM_RAM_GB :.0f } GB or more on a Mac (32 GB or more is what it was tested on)" } 1177model ,notes = mf .recommend_model (ram ) 1178notes = [n for n in notes if "UD-Q4_K_XL" not in n ]# the app does not offer the Unsloth files yet 1179if model not in self ._mac_sizes (models ): 1180model = "Q2_0" 1181if mf .streams (model ,ram ): 1182speed = mf .STREAM_MEASURED .get (model ) 1183why = (f" { ram :.0f } GB of unified memory: no size fits whole, so { model } 's experts are read from the SSD as it answers" 1184+ (f" ( { speed } measured on a 32 GB Mac mini)" if speed else "" )) 1185else : 1186why = f" { ram :.0f } GB of unified memory: { model } stays in memory (the best size that does)" 1187ctx = mf .recommend_context (ram ) 1188return {"family" :"qwen" ,"model" :model ,"title" :families ["qwen" ]["title" ]+ " " + model ,"context" :ctx , 1189"backend" :"metal" ,"gpu" : {k :usable [0 ].get (k )for k in ("index" ,"name" ,"vram_gb" )}, 1190"download_gb" :models [model ]["download_gb" ],"why" :why ,"notes" :notes , 1191"setup_command" :f"./setup.sh --setup --yes --family qwen --model { model } --context { ctx } " } 1192 1193def _mac_model_table (self ,hw :dict )-> list : 1194models ,families ,_ctx ,_src = self .tables () 1195from strata_control import fit_label 1196ram = float (hw .get ("ram_gb" )or 0 ) 1197have = {c .stem [len ("strata-" ):]for c in self .configs ()} 1198out = [] 1199for family in (self .mac ().all_families ()if self .mac ()else ("qwen" ,"gyro" )):# Qwen, Unsloth's sets, then Gyro: never the default 1200fd = families .get (family ) 1201if fd is None : 1202continue 1203sizes = [] 1204for m in self ._mac_sizes (models ,family ): 1205d = models [m ] 1206tag = (fd .get ("tag" ,"" )+ m ).lower () 1207sizes .append ({"model" :m ,"about" :d ["about" ],"download_gb" :d ["download_gb" ],"experimental" :False , 1208"images" :d .get ("vision" ,fd .get ("vision" ,True ))is not False ,# the Mac engine carries the picture reader (Metal) 1209"ram_needed_gb" :d ["ram_gb" ],"experts_gb" :d .get ("arena_gb" ),"mem_total" :False , 1210"memory_gb" :round (float (d .get ("arena_gb" )or d ["ram_gb" ])+ 1.0 ,1 ), 1211"fit_gb" :fit_label .files_gb (family ,m ,d ), 1212"on_this_pc" :self ._mac_verdict (m ,ram )if ram else None ,"installed" :tag in have ,"id" :tag }) 1213if sizes : 1214out .append ({"family" :family ,"title" :fd ["title" ],"about" :fd .get ("about" ),"experimental" :False , 1215"images" :any (x ["images" ]for x in sizes ),"sizes" :sizes }) 1216return self ._feed_rows (out ,self .setup_module ()) 1217 1218def recommend (self ,hw :dict )-> dict : 1219"""setup.py's own rules: the size it preselects (IQ3_XXS from 60 GB of RAM, else the first, Q2_0), the 1220Coder below the full model's RAM (setup's RAM table), the low-RAM mode when the GPU makes up for the RAM, and 1221the context it preselects for the card's VRAM (32K under 14 GB, 64K under 20 GB, else 128K).""" 1222models ,families ,_ctx ,_src = self .tables () 1223if hw .get ("mac" ): 1224return self ._mac_recommend (hw ,models ,families ) 1225S = self .setup_module () 1226usable = self .engine_gpus (hw ) 1227ram = hw .get ("ram_gb" )or 0 1228if not usable : 1229why = ("no NVIDIA RTX 20-series-or-newer GPU found (nvidia-smi did not list one)" 1230+ ("; the AMD graphics in this PC is not a card Strata supports (an RX 7000 or 9000 series card, or a Ryzen AI Max, is needed)" if WIN and any ( 1231"amd" in str (a .get ("name" ,"" )).lower ()or "radeon" in str (a .get ("name" ,"" )).lower () 1232for a in hw .get ("display_adapters" , []))else "" )) 1233return {"family" :None ,"model" :None ,"why" :why } 1234best = max (usable ,key = lambda g : (round (g ["vram_gb" ]),- g .get ("index" ,0 ))) 1235vram = best ["vram_gb" ] 1236backend = "hip" if best .get ("vendor" )== "amd" else "sycl" if best .get ("vendor" )== "intel" else "cuda" 1237 1238def low_fits (m ): 1239try : 1240return S .low_ram_fits (m ,ram ,vram )if S else ram - 6 + max (0.0 ,vram - 5 - 1.0 )>= models [m ]["arena_gb" ] 1241except Exception :# noqa: BLE001 1242return False 1243notes = [] 1244# 0.2.0, the owner's memory tiers (README "The other sizes"; setup.py MEMORY_TIERS holds the same floors): RAM + VRAM 1245# together. An APU's shared memory is the RAM itself, so only its BIOS carve-out counts as VRAM. 1246tvram = float (best .get ("dedicated_gb" ,0.0 ))if best .get ("uma" )else float (vram ) 1247tier = next (((f ,n )for lo ,f ,n in MEMORY_TIERS if ram + tvram - TIER_SYSTEM_RESERVE_GB >= lo ),None ) 1248if tier and tier [1 ]in models and tier [0 ]in families : 1249fam ,model = tier 1250total = f" { ram :.0f } GB of RAM + { tvram :.0f } GB of VRAM = { ram + tvram :.0f } GB, { TIER_SYSTEM_RESERVE_GB :.0f } GB of it kept for Windows and the system" 1251if model == "IQ2_XS" : 1252why = (f" { total } , the 40 GB tier: Swift 1.5's IQ2_XS (thinks for a shorter time)" 1253+ ("; Gyro-M (35 GB) is the other choice there, close to IQ3_XXS in quality but 16-21% slower at " 1254"writing answers than Q2_0" if "Gyro-M" in models and best .get ("vendor" )in ("nvidia" ,"amd" ,"intel" )else "" )) 1255elif model == "IQ3_XXS" : 1256why = f" { total } , the 48 GB tier: IQ3_XXS (better quality, slower)" 1257else : 1258why = (f" { total } , the 64 GB tier: IQ3_S (matches the full model, the slowest); Swift 1.5's IQ3_S is an " 1259"equal choice" ) 1260elif ram >= 60 : 1261fam ,model ,why = "qwen" ,"IQ3_XXS" ,f" { ram :.0f } GB of RAM: setup's own pick from 60 GB (better quality)" 1262elif ram >= models ["Q2_0" ]["ram_gb" ]- 4 : 1263fam ,model ,why = "qwen" ,"Q2_0" ,f" { ram :.0f } GB of RAM: the full model's fastest size fits" 1264elif ram >= models ["IQ1_M" ]["ram_gb" ]- 4 : 1265fam ,model ,why = "coder" ,"IQ1_M" , (f" { ram :.0f } GB of RAM: the full model needs ~48 GB; the Coder " 1266"(half the experts, best for code) needs ~32 GB" ) 1267elif low_fits ("IQ1_M" ): 1268fam ,model ,why = "coder" ,"IQ1_M" , (f" { ram :.0f } GB of RAM is below the Coder's 32 GB, but the GPU's " 1269f" { vram :.0f } GB make up for it (setup's low-RAM mode: slower)" ) 1270elif "Gyro-S" in models and ram + vram >= models ["Gyro-S" ]["ram_gb" ]+ GYRO_ROOM_GB : 1271# Gyro (agentionai): only where the sizes above do not fit. Their memory figure (Gyro-S 27.6 GB, Gyro-M 35 GB) 1272# is VRAM + RAM together and the system needs room beside it, so GYRO_ROOM_GB more is asked for here. 1273# Gyro-M when this PC has that much, else Gyro-S. 1274model = "Gyro-M" if ram + vram >= models ["Gyro-M" ]["ram_gb" ]+ GYRO_ROOM_GB else "Gyro-S" 1275fam ,why = "gyro" , (f" { ram :.0f } GB of RAM is below the Coder's 32 GB, but RAM + VRAM = { ram + vram :.0f } GB " 1276f"holds { model } ( { models [ model ][ 'ram_gb' ] } GB of memory in total; the quality is lower " 1277"than the 2-3-bit sizes, and it needs the whole download on a fast SSD)" ) 1278else : 1279return {"family" :None ,"model" :None ,"why" :f" { ram :.0f } GB of RAM: Strata needs 32 GB or more " 1280"(the smallest model, the Coder, keeps ~23 GB of experts in " 1281"RAM)" } 1282ctx = 131072 # 128K on every card (owner, 2026-11-01) 1283# #3425: the tiers count RAM + VRAM together, but the desktop keeps about 10 GB of the RAM and the card keeps ~6 GB for 1284# its dense weights, so a PC at the floor of its tier reads part of the experts from the SSD at every answer. Said 1285# plainly beside the pick (the same arithmetic as the app's "This computer" card); the pick itself stays the owner's tier. 1286arena = float (models [model ].get ("arena_gb" )or 0 ) 1287spill = arena - max (0.0 ,tvram - 6.0 )- max (0.0 ,ram - 10.0 ) 1288if arena and spill >= 4.0 : 1289notes .append (f"about { spill :.0f } GB of { model } would be read from the SSD while answering (this PC's RAM leaves about 10 GB " 1290"for the system and the card holds the rest): expect a few tokens per second on a SATA or USB drive, more " 1291"on a fast NVMe. A smaller size fits better; it is a recommendation, every size stays a choice" ) 1292if vram < 11 : 1293notes .append ("less than 12 GB of VRAM: it runs, but slowly (most experts stay on the CPU)" ) 1294if hw .get ("cpu" , {}).get ("avx2" )is False :# #623: a warning, not a stop (setup compiles for it) 1295notes .append ("this CPU has no AVX2: EXPERIMENTAL and slow - setup compiles the engine on this PC for the " 1296"older CPU (10-20 minutes), and the CPU's share of the experts runs a few times slower" ) 1297if backend == "hip" : 1298notes .append ("AMD (experimental): pictures are on; the reader runs on the CPU under 24 GB of VRAM and on the GPU from 24 GB" ) 1299if backend == "sycl" : 1300from strata_control import intel_app 1301notes .append (intel_app .NO_DOWNLOAD ) 1302cmd = (("START-HERE.bat --setup" if WIN else "./setup.sh --setup" )+ 1303f" --yes --family { fam } --model { model } --context { ctx } " + (f" --backend { backend } " if backend in ("hip" ,"sycl" )else "" )) 1304return {"family" :fam ,"model" :model ,"title" :families [fam ]["title" ]+ " " + model ,"context" :ctx , 1305"backend" :backend ,"gpu" : {k :best .get (k )for k in ("index" ,"name" ,"vram_gb" )}, 1306"download_gb" :models [model ]["download_gb" ],"why" :why ,"notes" :notes ,"setup_command" :cmd } 1307 1308def model_table (self ,hw :dict | None )-> list : 1309if (hw or {}).get ("mac" ): 1310return self ._mac_model_table (hw ) 1311models ,families ,_ctx ,_src = self .tables () 1312S = self .setup_module () 1313ram = (hw or {}).get ("ram_gb" ) 1314usable = self .engine_gpus (hw ) 1315vram = max ((g ["vram_gb" ]for g in usable ),default = 0.0 ) 1316from strata_control import fit_label 1317card_room = fit_label .card_room_gb (usable ) 1318have = {c .stem [len ("strata-" ):]for c in self .configs ()} 1319out = [] 1320for f ,fd in sorted (families .items (),key = lambda kv :bool (kv [1 ].get ("feed" ))):# the signed feed's models after the built-in ones (False sorts first, the order is kept) 1321sizes = [] 1322for m in self .sizes_of (models ,f ): 1323own = self .own_size (f ,m ) 1324d = own or models [m ] 1325tag = (fd .get ("tag" ,"" )+ m ).lower () 1326# the model's files without the lookup table's file (download size minus the table) against the card's memory plus the RAM: "fits" or "may run slower" 1327# (strata_control/fit_label.py, the owner's one rule) 1328memory_gb = round (float (d ["ram_gb" ])if d .get ("mem_total" )else float (d .get ("arena_gb" )or d ["ram_gb" ])+ 1.0 ,1 )# the placement estimate (experts + dense) 1329fit_gb = fit_label .files_gb (f ,m ,d )# what the label and the Terminal's "Needs" column use 1330verdict = None 1331if ram is not None : 1332verdict = fit_label .label (fit_gb ,ram ,card_room ) 1333sizes .append ({"model" :m ,"about" :d ["about" ],"download_gb" :d ["download_gb" ], 1334"experimental" :bool (d .get ("experimental" )), 1335"images" :d .get ("vision" ,fd .get ("vision" ,True ))is not False , 1336# which picture reader "pictures on" gets on this PC (strata_control/vision_reader.py, the one rule: the CPU reader 1337# under 24 GB of graphics memory, the GPU reader from 24 GB; the person can switch it per model) 1338"images_reader" :self .images_reader (vram ), 1339"ram_needed_gb" :d ["ram_gb" ],"experts_gb" :d .get ("arena_gb" ), 1340# RAM + VRAM the weights need together, WITHOUT the n-gram table (that stays on the SSD): Gyro states it 1341# (mem_total), for the rest the experts plus ~1 GB for the dense part (Swift IQ2_XS: 35.5 + 1 = 36.5) 1342"mem_total" :bool (d .get ("mem_total" )),"multi_file" :False , 1343"disk_gb" :None , 1344# the first engine that reads this size's files (setup.py "engine"); the app says "needs a newer engine" 1345# with the update step when the installed one is older. None: any engine that setup accepts. 1346"engine_min" :"." .join (map (str ,d ["engine" ]))if d .get ("engine" )else None , 1347"memory_gb" :memory_gb ,"fit_gb" :fit_gb , 1348# Qwen3.6: the conversation memory per token and what the card holds before it (strata_control/own_path_fit.py, 1349# #5715): the app's context estimate and its warning use these; absent for every other model 1350** ({"context_fit" :d ["context_fit" ]}if d .get ("context_fit" )else {}), 1351"on_this_pc" :verdict ,"installed" :tag in have ,"id" :tag , 1352"rdna4_faster" :None , 1353# which graphics cards to use for it (strata_control/gpu_fit.py, the one rule app / Terminal / setup share): 1354# only with two or more cards that count; "recommended" names the pre-selected option 1355"gpu_options" :None if own else self .gpu_options (d ,ram ,hw )})# Qwen3.6 runs on one card so far 1356out .append ({"family" :f ,"title" :fd ["title" ],"about" :fd .get ("about" ), 1357"experimental" :bool (fd .get ("experimental" )), 1358"images" :any (x ["images" ]for x in sizes )if sizes else fd .get ("vision" ,True )is not False , 1359"sizes" :sizes }) 1360return self ._feed_rows (out ,S ) 1361 1362def _feed_rows (self ,out :list ,S )-> list : 1363"""The signed feed's models in a model table: their family rows carry `feed: true`; a model this engine does not run has `available: false` and the reason 1364(`sizes` empty when it is not offered, kept when the owner's rule allows the install: feed_models.UNAVAILABLE_POLICY).""" 1365unavailable = (getattr (S ,"FEED_UNAVAILABLE" ,None )or {})if S else {} 1366for row in out : 1367if (getattr (S ,"FEED_MODELS" ,None )or {}).get (row ["family" ]): 1368row ["feed" ]= True 1369if row ["family" ]in unavailable : 1370row ["available" ],row ["unavailable_reason" ]= False ,unavailable [row ["family" ]]["reason" ] 1371for fid ,u in unavailable .items (): 1372if not any (r ["family" ]== fid for r in out ): 1373out .append ({"family" :fid ,"title" :u ["title" ],"about" :u ["reason" ],"experimental" :False ,"images" :False ,"sizes" : [],"feed" :True , 1374"available" :False ,"unavailable_reason" :u ["reason" ]}) 1375return out 1376 1377@staticmethod 1378def images_reader (vram )-> str : 1379try : 1380from strata_control import vision_reader 1381return vision_reader .default_mode (vram )if vram else "cpu" 1382except Exception :# noqa: BLE001 1383return "cpu" 1384 1385@staticmethod 1386def gpu_options (d :dict ,ram ,hw )-> dict | None : 1387try : 1388from strata_control import gpu_fit 1389mem = float (d ["ram_gb" ])if d .get ("mem_total" )else float (d .get ("arena_gb" )or d ["ram_gb" ])+ 1.0 1390res = gpu_fit .options (round (mem ,1 ),ram , (hw or {}).get ("gpus" , []), (hw or {}).get ("engine_vendor" )) 1391if len (res ["options" ])>= 2 : 1392return res 1393# one card the engine can drive: no choice to offer, but a bigger card of the other make is still worth one plain line 1394return {"options" : [],"recommended" :None ,"other_vendor_note" :res .get ("other_vendor_note" )}if res .get ("other_vendor_note" )else None 1395except Exception :# noqa: BLE001 - the choice is a convenience: never break the model list 1396return None 1397 1398# ---- the running server 1399def ports (self ,port :int | None )-> list [int ]: 1400if port : 1401return [port ] 1402ps = [self .state ("server" ).get ("port" )]+ [self .describe_config (c )["port" ]for c in self .configs ()] 1403return list (dict .fromkeys (int (p )for p in [* ps ,DEFAULT_PORT ]if isinstance (p ,int ))) 1404 1405def api_key_for (self ,port :int )-> str | None : 1406"""The key a config of this folder set for that port (used for our own requests; never shown).""" 1407def real (cfg ):# "api_key": "none" = served without a key on purpose 1408k = cfg .get ("api_key" ) 1409return k if k and str (k ).strip ().lower ()!= "none" else None 1410for c in self .configs (): 1411cfg = self .read_config (c ) 1412if real (cfg )and int (cfg .get ("port" ,DEFAULT_PORT ))== port : 1413return cfg ["api_key" ] 1414for c in self .configs (): 1415if real (self .read_config (c )): 1416return self .read_config (c )["api_key" ] 1417return None 1418 1419def probe (self ,port :int ,deep = True )-> dict | None : 1420"""What answers on 127.0.0.1:port: a Strata server's facts, {"other": True} for something else, None for 1421nothing.""" 1422base = f"http://127.0.0.1: { port } " 1423st ,health = http_json (base + "/health" ,timeout = self .health_timeout ) 1424if st == 0 : 1425return None 1426if st != 200 or not isinstance (health ,dict )or health .get ("service" )!= "strata" : 1427return {"port" :port ,"other" :True ,"note" :"something else answers on this port (not a Strata server)" } 1428info = {"port" :port ,"url" :base ,"model" :health .get ("model" ),"context" :health .get ("max_context" ), 1429"images" :health .get ("images" ),"loaded" :health .get ("loaded" ), 1430"api_key_required" :bool (health .get ("api_key" ))} 1431if not deep : 1432return info 1433key = self .api_key_for (port ) 1434st ,v1 = http_json (base + "/v1/status" ,api_key = key ,timeout = self .health_timeout ) 1435if st == 200 and isinstance (v1 ,dict ): 1436info ["engine_version" ]= v1 .get ("engine" ) 1437info ["uptime_s" ]= v1 .get ("uptime_s" ) 1438info ["requests_served" ]= (v1 .get ("activity" )or {}).get ("requests" ) 1439m = v1 .get ("machine" )or {} 1440if m .get ("gpu" ): 1441info ["gpu" ]= m ["gpu" ] 1442if m .get ("ram" ): 1443info ["ram" ]= m ["ram" ] 1444if v1 .get ("last_timings" ): 1445lt = v1 ["last_timings" ] 1446info ["last_request" ]= {k :lt .get (k )for k in ("prompt_n" ,"prompt_per_second" ,"predicted_n" , 1447"predicted_per_second" )if k in lt } 1448elif st == 401 : 1449info ["note" ]= "the server wants an API key this folder's configs do not have" 1450st ,s = http_json (base + "/status" ,api_key = key ,timeout = self .health_timeout ) 1451if st == 200 and isinstance (s ,dict ): 1452info ["busy" ]= bool (s .get ("busy" )) 1453info ["activity" ]= {k :s .get (k )for k in ("phase" ,"generated" ,"tokens_per_s" ,"queued" ,"elapsed_s" ) 1454if s .get (k )is not None } 1455if "gpu" not in info :# older servers: the Monitor's numbers 1456st ,met = http_json (base + "/metrics" ,api_key = key ,timeout = self .health_timeout ) 1457if st == 200 and isinstance (met ,dict ): 1458hwn = met .get ("hardware" )or {} 1459if hwn .get ("gpu_mem_total" ): 1460info ["gpu" ]= {"used_mib" :round (hwn .get ("gpu_mem_used" ,0 )/ 2 ** 20 ), 1461"total_mib" :round (hwn ["gpu_mem_total" ]/ 2 ** 20 )} 1462if hwn .get ("ram_total" ): 1463info ["ram" ]= {"used_gib" :round (hwn .get ("ram_used" ,0 )/ 2 ** 30 ,1 ), 1464"total_gib" :round (hwn ["ram_total" ]/ 2 ** 30 ,1 )} 1465info ["engine_version" ]= (met .get ("engine" )or {}).get ("version" ) 1466return info 1467 1468def tracked_server (self )-> dict | None : 1469"""The server this MCP server started, while it still runs (else its record is cleared).""" 1470s = self .state ("server" ) 1471if not s : 1472return None 1473if proc_alive (s .get ("pid" ),s .get ("ident" )): 1474return s 1475return {** s ,"ended" :True } 1476 1477# ---- install job 1478def install_job (self )-> dict | None : 1479j = self .state ("install" ) 1480if not j : 1481return None 1482res = self .state ("install-result" ) 1483running = proc_alive (j .get ("pid" ),j .get ("ident" )) 1484log_path = Path (j .get ("log" ,"" )) 1485tail = read_tail (log_path ,1500 )if log_path .name else []# a step's heading must stay inside it: the pack tools print hundreds of lines 1486prog = install_progress (tail ) 1487prog = combined_progress (prog ,j ) 1488out = {"running" :running ,"started" :j .get ("started" ),"model" :j .get ("model" ),"family" :j .get ("family" ), 1489"log" :str (log_path ),** prog } 1490if not running : 1491if res .get ("job" )== j .get ("job" )and "exit_code" in res : 1492out ["exit_code" ]= res ["exit_code" ] 1493out ["finished" ]= res .get ("ended" ) 1494out ["result" ]= "installed" if res ["exit_code" ]== 0 else "failed" 1495else : 1496out ["result" ]= "ended unexpectedly (no exit code recorded)" 1497else : 1498out ["result" ]= "running" 1499out ["last_lines" ]= tail [- 12 :] 1500return out 1501 1502 1503SHARD_NAME = re .compile (r"^(.*)-(\d{5})-of-(\d{5})\.gguf$" ) 1504DEFAULT_MMPROJ_BYTES = 907_543_008 # the Flash-Next picture reader (mmproj BF16), when a family does not pin its size 1505 1506 1507def shard_gaps (ggufs )-> list : 1508"""The parts of a multi-part GGUF (name-00001-of-00004.gguf) that are not there whole: a missing part, or one still being 1509downloaded (<part>.part). A config that names only the first part used to look finished with one part of four on disk.""" 1510gaps = [] 1511for g in ggufs : 1512m = SHARD_NAME .match (str (g )) 1513if not m : 1514continue 1515for i in range (1 ,int (m .group (3 ))+ 1 ): 1516sib = Path (f" { m . group ( 1 ) } - { i :05d } -of- { m . group ( 3 ) } .gguf" ) 1517if not sib .is_file ()or sib .with_name (sib .name + ".part" ).exists (): 1518gaps .append (str (sib )) 1519return gaps 1520 1521 1522def expected_files (S ,family :str ,model :str ,models_dir :Path ,vision :bool )-> list : 1523"""The files setup fetches for one install, with the sizes it can know before the download starts: 1524[{path, bytes|None, role}] where role is "model" (the shards or the pack's files) or "vision" (the picture reader). 1525Empty when the setup module cannot say (the caller then falls back to the folder scan).""" 1526out = [] 1527try : 1528own = (getattr (S ,"OWN_PATH_FAMILIES" ,None )or {}).get (family ) 1529if own :# Qwen3.6: the GGUF and the picture reader in the model's folder 1530folder = Path (models_dir )/ (own ["tag" ]+ model ) 1531name = own ["file" ].format (q = model ) 1532out .append ({"path" :str (folder / name ),"bytes" :own ["sha256" ][name ][0 ],"role" :"model" }) 1533if vision : 1534out .append ({"path" :str (folder / own ["mmproj" ]),"bytes" :own ["sha256" ][own ["mmproj" ]][0 ],"role" :"vision" }) 1535return out 1536fam ,d = S .FAMILIES [family ],S .MODELS [model ] 1537if d .get ("repo" ):# NVFP4: a ready-made pack, many files with pinned sizes 1538for f in S .ready_needed (model ,Path (models_dir )): 1539out .append ({"path" :str (S .ready_where (Path (models_dir ),f )),"bytes" :f [4 ],"role" :"model" }) 1540else : 1541folder = Path (models_dir )/ (fam .get ("tag" ,"" )+ model ) 1542for i in range (1 ,S .model_shards (fam ,model )+ 1 ): 1543out .append ({"path" :str (folder / S .model_file (fam ,model ,i )),"bytes" :None ,"role" :"model" }) 1544if vision :# beside the model folders, not inside them (setup step 5) 1545size = (fam .get ("mmproj_sha256" )or (None ,))[0 ]or DEFAULT_MMPROJ_BYTES 1546out .append ({"path" :str (Path (models_dir )/ fam .get ("mmproj" ,S .MMPROJ )),"bytes" :size ,"role" :"vision" }) 1547except Exception :# noqa: BLE001 - progress is a convenience: never break the install 1548return [] 1549return out 1550 1551 1552def files_progress (prog :dict ,job :dict ,files :list )-> dict : 1553"""One honest download figure for a model in parts: every part counted (finished, partial, waiting), the picture reader as a part 1554of its own, and a part list the screen can name ("part 2 of 4"). The finished state needs EVERY part: a first shard that is whole 1555does not make the model downloaded.""" 1556log = prog .get ("download" )or {} 1557cur_gb = float (log .get ("total_gb" )or 0 ) 1558rows = [] 1559for f in files : 1560p = Path (f ["path" ]) 1561part = p .with_name (p .name + ".part" ) 1562try : 1563if part .is_file (): 1564state ,have = "downloading" ,part .stat ().st_size 1565elif p .is_file (): 1566state ,have = "done" ,p .stat ().st_size 1567else : 1568state ,have = "waiting" ,0 1569except OSError : 1570state ,have = "waiting" ,0 1571total = f .get ("bytes" )or (have if state == "done" else 0 ) 1572named = p .name in str (log .get ("file" ,"" ))or (f .get ("role" )== "vision" and str (log .get ("file" ,"" )).startswith ("vision encoder" )) 1573if state == "downloading" and cur_gb and named :# the log line names this file (setup calls the picture reader "vision encoder") 1574# The .part file is as long as the furthest byte written, which the parallel pieces push to the full size well before the 1575# download is done: the pieces setup counts are the truth. 1576have = min (have ,int (float (log .get ("done_gb" )or 0 )* 1e9 ))if have else have 1577if not total : 1578total = int (cur_gb * 1e9 ) 1579rows .append ({"role" :f .get ("role" ,"model" ),"state" :state ,"have" :have ,"total" :max (total ,have )}) 1580plan_total = float (job .get ("total_gb" )or 0 )* 1e9 1581parts = [] 1582for role ,name in (("model" ,"Model files" ), ("vision" ,"Picture reader" )): 1583mine = [r for r in rows if r ["role" ]== role ] 1584if not mine : 1585continue 1586have = sum (r ["have" ]for r in mine ) 1587known = sum (r ["total" ]for r in mine ) 1588total = known if all (r ["total" ]for r in mine )else max (plan_total if role == "model" else 0 ,known ,have ) 1589k = sum (1 for r in mine if r ["state" ]== "done" ) 1590state = "done" if k == len (mine )else "downloading" if any (r ["state" ]== "downloading" for r in mine )or k else "waiting" 1591parts .append ({"kind" :role ,"name" :name ,"state" :state ,"done_gb" :round (min (have ,total )/ 1e9 ,3 ), 1592"total_gb" :round (total / 1e9 ,3 ),"files_done" :k ,"files_total" :len (mine )}) 1593total_gb = sum (x ["total_gb" ]for x in parts ) 1594done_gb = min (sum (x ["done_gb" ]for x in parts ),total_gb ) 1595active = next ((x for x in parts if x ["state" ]!= "done" ),parts [- 1 ]if parts else None ) 1596if active and active ["state" ]== "waiting" and any (x ["state" ]== "done" for x in parts ): 1597active = dict (active ,state = "downloading" ) 1598prog ["download" ]= {"file" :"picture reader" if active and active ["kind" ]== "vision" else "model files" , 1599"done_gb" :round (done_gb ,3 ),"total_gb" :round (total_gb ,3 ), 1600"remaining_gb" :round (max (0.0 ,total_gb - done_gb ),3 ), 1601# 100 only when every file is whole (DL99: the bar stopped at 99% with everything in) 1602"percent" : (100 if all (x ["state" ]== "done" for x in parts )else min (99 ,int (100 * done_gb / total_gb )))if total_gb else 0 } 1603prog ["parts" ]= parts 1604return prog 1605 1606 1607def draft_progress (prog :dict ,job :dict ,dl :dict )-> dict : 1608"""Setup step 6 downloads the ~5 GB of MTP tensors (tools/mtp_fetch.py prints `MTP draft layer: 1.2 / 5.0 GB (24%)`). The figure 1609the app shows is the whole job's: the model files (done by now) plus this part, so the bar does not fall back to 0 (#3257).""" 1610done_gb ,total_gb = float (dl .get ("done_gb" )or 0 ),float (dl .get ("total_gb" )or 0 ) 1611parts = [] 1612if job .get ("files" ): 1613base = files_progress ({},job ,job ["files" ]) 1614parts = [dict (p ,state = "done" ,done_gb = p ["total_gb" ])for p in base .get ("parts" , [])if p .get ("state" )== "done" ] 1615parts .append ({"kind" :"draft" ,"name" :"Draft layer" ,"state" :"done" if int (dl .get ("percent" )or 0 )>= 100 else "downloading" , 1616"done_gb" :round (done_gb ,3 ),"total_gb" :round (total_gb ,3 )}) 1617total = sum (p ["total_gb" ]for p in parts ) 1618done = min (sum (p ["done_gb" ]for p in parts ),total ) 1619prog ["parts" ]= parts 1620prog ["download" ]= {"file" :"Draft layer" ,"done_gb" :round (done ,3 ),"total_gb" :round (total ,3 ), 1621"remaining_gb" :round (max (0.0 ,total - done ),3 ), 1622"percent" :min (99 ,int (100 * done / total ))if total else 0 } 1623return prog 1624 1625 1626def combined_progress (prog :dict ,job :dict )-> dict : 1627"""One total for the whole model: the bytes of all its files (finished, partial and the one in flight, read from the 1628model's folder) over the download size, instead of each file's own 0-100% (a two-file model went 70 GB -> 0 -> up 1629again). Only while the download step runs; later steps are not a download.""" 1630folder ,total = job .get ("folder" ),job .get ("total_gb" ) 1631step = str (prog .get ("step" )or "" ) 1632dl = prog .get ("download" )or {} 1633if step .startswith ("6/" )and str (dl .get ("file" ,"" )).startswith ("MTP draft layer" ): 1634return draft_progress (prog ,job ,dl ) 1635if step .startswith ("5/" )and str (dl .get ("file" ,"" )).startswith ("checking " ): 1636# setup is hashing files that are all on disk: the figure is the check's own (not a download at "99%") 1637if job .get ("files" ): 1638prog = files_progress (prog ,job ,job ["files" ]) 1639prog ["download" ]= {"file" :"checking files" ,"done_gb" :dl ["done_gb" ],"total_gb" :dl ["total_gb" ], 1640"remaining_gb" :round (max (0.0 ,dl ["total_gb" ]- dl ["done_gb" ]),3 ),"percent" :int (dl ["percent" ])} 1641return prog 1642if job .get ("files" )and step .startswith ("5/" ):# the install knows its files: count each of them 1643return files_progress (prog ,job ,job ["files" ]) 1644if job .get ("files" )and step .startswith (("6/" ,"7/" )): 1645# after the download: no download figure (setup prepares the files), but the parts stay, all whole, so the app's one bar is complete 1646# (DL99: they were dropped and the app counted the engine's part alone, "99% · 0.7 / 0.7 GB") 1647prog = files_progress (prog ,job ,job ["files" ]) 1648prog .pop ("download" ,None ) 1649return prog 1650if not folder or not total or not step .startswith ("5/" ): 1651prog .pop ("download" ,None ) 1652return prog 1653done = 0 1654try : 1655for entry in os .scandir (folder ): 1656if entry .is_file ()and (entry .name .endswith (".gguf" )or entry .name .endswith (".part" )): 1657done += entry .stat ().st_size 1658except OSError : 1659pass 1660if not done :# nothing on disk yet: the log's own line is all there is 1661return prog 1662done_gb = min (done / 1e9 ,float (total )) 1663prog ["download" ]= {"file" :"model files" ,"done_gb" :round (done_gb ,3 ),"total_gb" :float (total ), 1664"remaining_gb" :round (max (0.0 ,float (total )- done_gb ),3 ), 1665"percent" :min (99 ,int (100 * done_gb / float (total )))if total else 0 } 1666# The parts of the whole job, for a progress bar that sums them (the job that fetches the engine adds its own part): 1667# {kind, name, done_gb, total_gb, state} 1668prog ["parts" ]= [{"kind" :"model" ,"name" :"Model files" ,"done_gb" :prog ["download" ]["done_gb" ], 1669"total_gb" :float (total ),"state" :"downloading" }] 1670return prog 1671 1672 1673def install_progress (lines :list [str ])-> dict : 1674"""setup's progress from its output: the step, a download's percentage, a failure.""" 1675step ,title ,dl ,err = None ,None ,None ,None 1676for i ,line in enumerate (lines ): 1677m = re .search (r"=== Step (\d+): (.+?) ===" ,line ) 1678if m : 1679step ,title ,err ,dl = int (m .group (1 )),m .group (2 ),None ,None # a download figure belongs to its own step 1680m = re .match (r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)" ,line ) 1681if m : 1682dl = {"file" :m .group (1 ),"done_gb" :float (m .group (2 )),"total_gb" :float (m .group (3 )), 1683"percent" :int (m .group (4 ))} 1684if line .strip ().startswith ("[X]" ): 1685err = line .strip ()[3 :].strip () 1686if i + 1 < len (lines )and lines [i + 1 ].startswith (" " ): 1687err += " - " + lines [i + 1 ].strip () 1688out = {"step" :f" { step } /7: { title } " if step else None } 1689if dl : 1690out ["download" ]= dl 1691if err : 1692out ["error" ]= err 1693words = progress_words_for (step ,lines ,dl ) 1694if words : 1695out ["label" ],out ["phase" ]= words 1696return out 1697 1698 1699def physical_cores ()-> int | None : 1700"""The CPU's physical cores (os.cpu_count() counts logical threads: 16 on an 8-core SMT chip, and the app's Work profile took 170180% of that for --pool-workers, more than the cores, #3417). Falls back to the thread count when the machine cannot say.""" 1702try : 1703from strata_control import tune_machine 1704n = tune_machine .cpu ().get ("physical" ) 1705if isinstance (n ,int )and n > 0 : 1706return n 1707except Exception :# noqa: BLE001 - a hardware report must never fail on this 1708pass 1709return os .cpu_count () 1710 1711 1712def progress_words_for (step ,lines ,download ): 1713"""(the plain sentence, its phase) for what setup is doing now (strata_control/progress_words.py, the words the Terminal uses too); 1714None when this Strata folder does not carry the module.""" 1715try : 1716from strata_control import progress_words 1717except ImportError : 1718return None 1719w = progress_words .describe (step ,lines ,download ) 1720return w .label ,w .phase 1721 1722 1723def own_ram_gb ()-> float : 1724if WIN : 1725class MS (ctypes .Structure ): 1726_fields_ = [("dwLength" ,ctypes .c_ulong ), ("dwMemoryLoad" ,ctypes .c_ulong ), 1727* ((n ,ctypes .c_ulonglong )for n in ("tp" ,"ap" ,"tpf" ,"apf" ,"tv" ,"av" ,"aev" ))] 1728m = MS () 1729m .dwLength = ctypes .sizeof (MS ) 1730ctypes .windll .kernel32 .GlobalMemoryStatusEx (ctypes .byref (m )) 1731return m .tp / 2 ** 30 1732try : 1733for line in open ("/proc/meminfo" ): 1734if line .startswith ("MemTotal" ): 1735return int (line .split ()[1 ])* 1024 / 2 ** 30 1736except OSError : 1737pass 1738return 0.0 1739 1740 1741def own_nvidia_gpus ()-> list : 1742s = run_quiet (["nvidia-smi" ,"--query-gpu=index,name,memory.total,compute_cap,driver_version" , 1743"--format=csv,noheader,nounits" ]) 1744found = [] 1745for line in s .strip ().splitlines (): 1746try : 1747idx ,name ,mem ,cc ,drv = [x .strip ()for x in line .split ("," )] 1748try : 1749mem_gb = float (mem )/ 1024.0 1750except ValueError : 1751if platform .machine ().lower ()not in ("aarch64" ,"arm64" ): 1752raise # as before on x86: a card whose memory nvidia-smi does not report is not listed 1753# a DGX Spark (GB10): one memory for the CPU and the GPU, memory.total is [N/A]; counted as setup.py's gpus() counts it 1754# (the RAM less the OS's 6 GB, none of it room beside the RAM) 1755shared = max (0.0 ,own_ram_gb ()- 6 ) 1756found .append ({"index" :int (idx ),"name" :name ,"vram_gb" :shared ,"arch" :cc .replace ("." ,"" ),"driver" :drv , 1757"uma" :True ,"dedicated_gb" :0.0 ,"shared_gb" :shared }) 1758continue 1759found .append ({"index" :int (idx ),"name" :name ,"vram_gb" :mem_gb , 1760"arch" :cc .replace ("." ,"" ),"driver" :drv }) 1761except ValueError : 1762continue 1763return found 1764 1765 1766def nvidia_display_active ()-> dict : 1767"""{GPU index: True when a display is attached to the card} from nvidia-smi (display_active Enabled); {} when it says nothing.""" 1768found = {} 1769for line in run_quiet (["nvidia-smi" ,"--query-gpu=index,display_active" ,"--format=csv,noheader" ]).strip ().splitlines (): 1770idx ,_ ,state = line .partition ("," ) 1771if idx .strip ().isdigit ()and state .strip ().lower ()in ("enabled" ,"disabled" ): 1772found [int (idx )]= state .strip ().lower ()== "enabled" 1773return found 1774 1775 1776def windows_desktop_adapters ()-> list : 1777"""The PNPDeviceIDs of the Windows display adapters that have a desktop resolution (a monitor is attached to them).""" 1778out = [] 1779for line in run_quiet (["powershell" ,"-NoProfile" ,"-NonInteractive" ,"-Command" , 1780"Get-CimInstance Win32_VideoController | ForEach-Object { $_.PNPDeviceID + '|' + $_.CurrentHorizontalResolution }" ] 1781 ).splitlines (): 1782pnp ,_ ,res = line .strip ().rpartition ("|" ) 1783if pnp and res .strip ().isdigit ()and int (res )> 0 : 1784out .append (pnp ) 1785return out 1786 1787 1788def mark_display (gpus :list ,nvidia_active :dict ,desktop_pnp :list )-> None : 1789"""Sets g["drives_display"] (True / False) on the cards that can be told, from nvidia-smi (NVIDIA) and the Windows adapters that have a desktop 1790resolution (AMD and Intel, matched by PCI device id; two cards of one model are not told apart: left unknown). A card left without the key is 1791unknown, and the app treats an unknown card as one that drives a display.""" 1792desk = [str (p ).upper ()for p in desktop_pnp ] 1793for g in gpus : 1794if g .get ("vendor" )== "nvidia" and g .get ("index" )in nvidia_active : 1795g ["drives_display" ]= nvidia_active [g ["index" ]] 1796elif g .get ("vendor" )== "amd" and isinstance (g .get ("pci_id" ),int )and desktop_pnp is not None and desktop_pnp : 1797tag = f"DEV_ { g [ 'pci_id' ]:04X } " 1798twins = [x for x in gpus if x .get ("vendor" )== "amd" and x .get ("pci_id" )== g ["pci_id" ]] 1799if len (twins )== 1 : 1800g ["drives_display" ]= any (tag in p and "VEN_1002" in p for p in desk ) 1801 1802 1803def windows_video_controllers ()-> list : 1804s = run_quiet (["powershell" ,"-NoProfile" ,"-NonInteractive" ,"-Command" , 1805"Get-CimInstance Win32_VideoController | Select-Object Name,DriverVersion | ConvertTo-Json -Compress" ]) 1806try : 1807d = json .loads (s )if s .strip ()else [] 1808except ValueError : 1809return [] 1810d = [d ]if isinstance (d ,dict )else d 1811return [{"name" :x .get ("Name" ),"driver" :x .get ("DriverVersion" )}for x in d if isinstance (x ,dict )] 1812 1813 1814KFD_SUPPORTED = ("gfx1100" ,"gfx1101" ,"gfx1102" ,"gfx1200" ,"gfx1201" ,"gfx1030" ,"gfx1031" ,"gfx1151" ) 1815 1816 1817def kfd_gpus (sysfs :str = "/sys" )-> list : 1818"""AMD cards from the kernel's KFD topology and the amdgpu driver's files, with no ROCm tool and no setup module: a PC that has only the 1819driver plus the engine's own runtime has no rocm-smi, amd-smi or rocminfo, and the cards were then not counted at all (a 4-card PC ran on one). 1820Numbered as HIP numbers them (the GPU nodes in order, CPU nodes skipped).""" 1821base = Path (sysfs )/ "class/kfd/kfd/topology/nodes" 1822out = [] 1823try : 1824nodes = sorted ((p for p in base .iterdir ()if p .name .isdigit ()),key = lambda p :int (p .name )) 1825except OSError : 1826return out 1827for node in nodes : 1828try : 1829props = dict (line .partition (" " )[::2 ]for line in (node / "properties" ).read_text ().splitlines ()) 1830ver ,simd = int (props .get ("gfx_target_version" )or 0 ),int (props .get ("simd_count" )or 0 ) 1831except (OSError ,ValueError ): 1832continue 1833if ver == 0 or simd == 0 : 1834continue 1835arch = f"gfx { ver // 10000 } {( ver // 100 ) % 100 :x } { ver % 100 :x } " 1836dev = Path (sysfs )/ f"class/drm/renderD { props . get ( 'drm_render_minor' , '' ). strip () } /device" 1837try : 1838vram = int ((dev / "mem_info_vram_total" ).read_text ())/ 2 ** 30 1839except (OSError ,ValueError ): 1840vram = 0.0 1841try : 1842name = (dev / "product_name" ).read_text ().strip ()or f"AMD Radeon ( { arch } )" 1843except OSError : 1844name = f"AMD Radeon ( { arch } )" 1845ok = arch in KFD_SUPPORTED 1846out .append ({"index" :len (out ),"name" :name ,"vram_gb" :round (vram ,1 ),"arch" :arch ,"driver" :"amdgpu" ,"vendor" :"amd" , 1847"usable" :ok ,"problem" :None if ok else f"not supported - Strata's AMD backend does not list { arch } " }) 1848return out 1849 1850 1851def rocm_smi_gpus ()-> list : 1852s = run_quiet (["rocm-smi" ,"--showproductname" ,"--showmeminfo" ,"vram" ,"--json" ]) 1853try : 1854d = json .loads (s ) 1855except ValueError : 1856return [] 1857out = [] 1858for i , (card ,v )in enumerate (sorted (d .items ())): 1859if not isinstance (v ,dict )or not card .lower ().startswith ("card" ): 1860continue 1861total = next ((v [k ]for k in v if "total" in k .lower ()and "vram" in k .lower ()),0 ) 1862try : 1863vram = int (total )/ 2 ** 30 1864except (TypeError ,ValueError ): 1865vram = 0.0 1866out .append ({"index" :i ,"name" :v .get ("Card Series" )or v .get ("Card SKU" )or card ,"vram_gb" :round (vram ,1 ), 1867"vendor" :"amd" ,"usable" :None ,"problem" :"listed by rocm-smi (setup checks the card itself)" }) 1868return out 1869 1870 1871# ------------------------------------------------------------------------------------------------ the tools 1872GPUS_PATTERN = r"all|\d{1,2}(,\d{1,2}){1,7}" 1873MODEL_ID_PATTERN = r"[A-Za-z0-9][A-Za-z0-9_.-]{0,48}" 1874 1875 1876def tool_defs (models :dict ,families :dict ,contexts :list )-> list : 1877port = {"type" :"integer" ,"minimum" :1024 ,"maximum" :65535 , 1878"description" :"the server's port (default: the installed model's port, usually 8080)" } 1879installed_model = {"type" :"string" ,"pattern" :MODEL_ID_PATTERN ,"maxLength" :49 , 1880"description" :"an installed model's id as strata_status lists it (e.g. 'q2_0', " 1881"'coder-iq1_m', 'swift-iq3_xxs'); default: the most recently used one" } 1882ro = {"readOnlyHint" :True ,"destructiveHint" :False ,"openWorldHint" :False } 1883return [ 1884 {"name" :"strata_status" ,"title" :"Strata status" , 1885"description" :"Is Strata (the local AI model server) running, and what is installed? Reports the running " 1886"server (model, engine version, context, busy or idle, VRAM/RAM in use), the installed models " 1887"and data folder, an install in progress, this PC's hardware (OS, CPU, RAM, GPUs, free disk) " 1888"and the model size setup recommends for this PC. Read-only; call it first." , 1889"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : { 1890"port" :port , 1891"hardware" : {"type" :"boolean" ,"description" :"include the hardware check and the recommendation " 1892"(default true; takes a second or two)" }}}, 1893"annotations" :ro }, 1894 {"name" :"strata_models" ,"title" :"Strata models" , 1895"description" :"The models and sizes Strata's setup offers (families: qwen = Qwen3.8-Flash-Next, swift = " 1896"Swift 1.5, coder = the Coder, unsloth = Unsloth's ~4-bit), with download size, RAM needed, " 1897"whether each fits this PC, which are installed, the context lengths, and the recommendation. " 1898"Read-only." , 1899"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : {}}, 1900"annotations" :ro }, 1901 {"name" :"strata_remove" ,"title" :"Delete an installed model" , 1902"description" :"Delete an installed model's own files (its model GGUFs, its pack folder, its run config) and nothing " 1903"another installed model still uses (a shared MTP draft or PLE file). Without confirm=true it only " 1904"returns the plan (what would be removed and how big, what is kept). Stop the model first." , 1905"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"required" : ["model" ], 1906"properties" : {"model" :installed_model ,"confirm" : {"type" :"boolean" }}}, 1907"annotations" : {"readOnlyHint" :False ,"destructiveHint" :True }}, 1908 {"name" :"strata_install" ,"title" :"Install Strata" , 1909"description" :"Install a Strata model on this PC by running Strata's setup non-interactively in the " 1910"background (Python packages, the engine, a 58-111 GB model download, preparation, start " 1911"script). Without confirm=true it only returns the plan (what would be downloaded, disk " 1912"space): show it to the user and call again with confirm=true once they agree. Returns at " 1913"once; call it again (no arguments needed) to see the progress, or with cancel=true to stop " 1914"it (it resumes later). Defaults: the recommended model and context for this PC, pictures on where the model can read them. " 1915"After it finishes, start the model with strata_start." , 1916"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : { 1917"family" : {"type" :"string" ,"enum" :list (families ), 1918"description" :"qwen = Qwen3.8-Flash-Next (the original), swift = Swift 1.5 (thinks " 1919"shorter), coder = the Coder (half the experts, ~32 GB RAM, for code), " 1920"unsloth = Unsloth's 1- to 8-bit files (UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, " 1921"UD-Q6_K_XL, Q8_0): every expert in RAM where they fit, else part of them read " 1922"from the SSD" }, 1923"model" : {"type" :"string" ,"enum" :list (models ), 1924"description" :"the size (quantization): see strata_models" }, 1925"context" : {"type" :"integer" ,"minimum" :1024 ,"maximum" :2097152 ,"examples" :contexts , 1926"description" :"context length in tokens (more needs more VRAM). Any whole number works, " 1927"for example one typed into a model's run config by hand; the usual sizes are " 1928f" { ', ' . join ( str ( c ) for c in contexts ) } " }, 1929"vision" : {"type" :"string" ,"enum" : ["no" ,"yes" ,"gpu" ,"cpu" ], 1930"description" :"let the model read images (~0.9 GB more download). Default yes where the model can " 1931"read them (not on a Mac): yes = the best reader for this card (the CPU " 1932"under 24 GB of VRAM, the GPU from 24 GB, any make), gpu / cpu = that " 1933"reader, no = text only" }, 1934"kv" : {"type" :"string" ,"enum" : ["int8" ,"q4_0" ,"k8v4" ], 1935"description" :"KV cache precision above 8K context (default int8)" }, 1936"gpu" : {"type" :"integer" ,"minimum" :0 ,"maximum" :63 , 1937"description" :"one GPU, as nvidia-smi numbers them (default: the one with the most VRAM)" }, 1938"gpus" : {"type" :"string" ,"pattern" :GPUS_PATTERN ,"maxLength" :40 , 1939"description" :"several GPUs sharing the model: '0,2' or 'all' (experimental)" }, 1940"backend" : {"type" :"string" ,"enum" : ["auto" ,"cuda" ,"hip" ,"sycl" ], 1941"description" :"auto (default), cuda = NVIDIA, hip = AMD on Linux (experimental), sycl = Intel Arc on Linux " 1942"(experimental; the model's files must already be on this computer: gguf_dir)" }, 1943"low_ram" : {"type" :"string" ,"enum" : ["auto" ,"on" ,"off" ,"resident" ,"mmap" ], 1944"description" :"setup's low-RAM mode (default auto)" }, 1945"port" : {** port ,"description" :"the port the model will listen on (default 8080)" }, 1946"data_dir" : {"type" :"string" ,"maxLength" :260 , 1947"description" :"where the model files go (default: the Strata-data folder next to the " 1948"Strata folder). Only the current data folder, a folder inside the Strata " 1949"folder, or a new absolute path whose last folder is named Strata... " 1950"(e.g. D:\\Strata-data) outside system folders" }, 1951"drafter" : {"type" :"string" ,"enum" : ["mtp" ,"dflash2" ], 1952"description" :"which drafter this model will use: dflash2 downloads only DFlash2's drafter (a separate step), not the MTP draft layer's ~5 GB; " 1953"mtp (the default) downloads the draft layer" }, 1954"mtp" : {"type" :"string" ,"enum" : ["on" ,"off" ], 1955"description" :"off = Drafting Off: the MTP draft layer (~5 GB) is not downloaded and the model starts without it (setup --mtp off)" }, 1956"gguf_dir" : {"type" :"string" ,"maxLength" :260 , 1957"description" :"a folder that already holds this model's GGUF files under their original names: setup " 1958"checks them (size and SHA-256) and does not download them again" }, 1959"confirm" : {"type" :"boolean" ,"description" :"true = really start the install (after the user agreed " 1960"to the plan and the download size)" }, 1961"cancel" : {"type" :"boolean" ,"description" :"true = stop the install in progress" }}}, 1962"annotations" : {"readOnlyHint" :False ,"destructiveHint" :False ,"idempotentHint" :True , 1963"openWorldHint" :True }}, 1964 {"name" :"strata_start" ,"title" :"Start Strata" , 1965"description" :"Start an installed Strata model in the background (as its start script does, without " 1966"opening a browser) and wait until it answers. Loading takes 1-3 minutes and the PC can be " 1967"slow meanwhile; if it is not ready within wait_seconds this returns 'loading' - check again " 1968"with strata_status. The model keeps running until strata_stop." , 1969"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : { 1970"model" :installed_model ,"port" :port , 1971"gpu" : {"type" :"integer" ,"minimum" :0 ,"maximum" :63 , 1972"description" :"run on this GPU for this start (as nvidia-smi numbers them)" }, 1973"wait_seconds" : {"type" :"integer" ,"minimum" :0 ,"maximum" :600 , 1974"description" :"how long to wait for it to be ready (default 50: some AI apps end " 1975"a tool call after 60 s)" }}}, 1976"annotations" : {"readOnlyHint" :False ,"destructiveHint" :False ,"idempotentHint" :True , 1977"openWorldHint" :False }}, 1978 {"name" :"strata_stop" ,"title" :"Stop Strata" , 1979"description" :"Stop the Strata model: the engine is unloaded through the server's own API (it frees its " 1980"VRAM and RAM itself), then the server this tool started is ended. A Strata started " 1981"elsewhere (e.g. its own window) is only unloaded - close its window to end it. Refuses while " 1982"a request is running unless force=true." , 1983"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : { 1984"port" :port , 1985"force" : {"type" :"boolean" ,"description" :"stop even while a request is running" }}}, 1986"annotations" : {"readOnlyHint" :False ,"destructiveHint" :True ,"idempotentHint" :True , 1987"openWorldHint" :False }}, 1988 {"name" :"strata_logs" ,"title" :"Strata logs" , 1989"description" :"The last lines of a Strata log: 'server' (the model server this tool started: loading, " 1990"requests, errors), 'engine' (the engine's own log for a model), 'setup' (the install). " 1991"Default: the setup log while an install runs, else the server log. Read-only." , 1992"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : { 1993"source" : {"type" :"string" ,"enum" : ["server" ,"engine" ,"setup" ]}, 1994"model" :installed_model , 1995"lines" : {"type" :"integer" ,"minimum" :1 ,"maximum" :500 ,"description" :"default 80" }}}, 1996"annotations" :ro }, 1997 {"name" :"strata_benchmark" ,"title" :"Strata speed test" , 1998"description" :"A short fixed request (greedy, thinking off) through the running Strata server; reports " 1999"the output speed (tokens/s) and prompt speed. Takes 10-60 s. Refuses while the model is " 2000"busy." , 2001"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : { 2002"port" :port , 2003"max_tokens" : {"type" :"integer" ,"minimum" :16 ,"maximum" :512 ,"description" :"default 200" }}}, 2004"annotations" : {"readOnlyHint" :True ,"destructiveHint" :False ,"openWorldHint" :False }}, 2005 {"name" :"strata_connect_info" ,"title" :"Connect to Strata" , 2006"description" :"How to point other apps at the local Strata server: the OpenAI and Anthropic base URLs, " 2007"the model id, whether an API key is needed, and ready-to-paste settings for Claude Code, " 2008"Codex CLI, the OpenAI SDK, curl, Cursor/Continue/Open WebUI. Read-only." , 2009"inputSchema" : {"type" :"object" ,"additionalProperties" :False ,"properties" : {"port" :port }}, 2010"annotations" :ro }, 2011 ] 2012 2013 2014class Tools : 2015def __init__ (self ,strata :Strata ): 2016self .s = strata 2017 2018def defs (self )-> list : 2019models ,families ,contexts = self .s .tables ()[:3 ] 2020return tool_defs ({** {name : {}for name in self .s .own_size_names ()if name not in models },** models },families ,contexts ) 2021 2022def call (self ,name :str ,args )-> dict : 2023defs = {d ["name" ]:d for d in self .defs ()} 2024if name not in defs : 2025raise KeyError (name ) 2026args = check_schema (defs [name ]["inputSchema" ],args ) 2027return getattr (self ,name )(** args ) 2028 2029# ---- strata_status 2030def strata_status (self ,port = None ,hardware = True )-> dict : 2031s = self .s 2032s .reap () 2033servers = [] 2034for p in s .ports (port ): 2035info = s .probe (p ) 2036if info is not None : 2037servers .append (info ) 2038tracked = s .tracked_server () 2039out = {} 2040running = [x for x in servers if not x .get ("other" )] 2041if tracked and not tracked .get ("ended" ): 2042mine = next ((x for x in running if x ["port" ]== tracked ["port" ]),None ) 2043if mine : 2044mine ["started_by" ]= f"this MCP server (pid { tracked [ 'pid' ] } )" 2045else : 2046out ["loading" ]= {"model" :tracked .get ("model" ),"port" :tracked ["port" ],"pid" :tracked ["pid" ], 2047"since" :tracked .get ("started" ), 2048"last_log_line" : (read_tail (Path (tracked .get ("log" ,"" )),1 )or [None ])[- 1 ]} 2049elif tracked and tracked .get ("ended" ): 2050out ["last_start" ]= {"model" :tracked .get ("model" ),"ended" :True , 2051"last_log_lines" :read_tail (Path (tracked .get ("log" ,"" )),6 )} 2052for x in running : 2053x .setdefault ("started_by" ,"outside this MCP server (its own window, a start script or a service)" ) 2054out ["running" ]= running 2055others = [x for x in servers if x .get ("other" )] 2056if others : 2057out ["ports_used_by_other_programs" ]= others 2058if running : 2059r = running [0 ] 2060summary = (f"Strata is running on port { r [ 'port' ] } : { r . get ( 'model' ) } " 2061+ (", busy" if r .get ("busy" )else ", idle" ) 2062+ ("" if r .get ("loaded" ,True )else " (model unloaded; the next request loads it)" )) 2063elif "loading" in out : 2064summary = f"Strata is loading { out [ 'loading' ][ 'model' ] } (port { out [ 'loading' ][ 'port' ] } )" 2065else : 2066summary = "Strata is not running" 2067inst = s .installed () 2068job = s .install_job () 2069if job : 2070out ["install" ]= job 2071if job ["running" ]: 2072summary += f"; an install is running ( { job . get ( 'step' ) or 'starting' } )" 2073if not inst ["models" ]: 2074summary += "; no model is installed yet" 2075else : 2076summary += "; installed: " + ", " .join (m ["model" ]for m in inst ["models" ]) 2077out ["installed" ]= inst 2078if hardware : 2079hw = s .hardware () 2080out ["hardware" ]= hw 2081out ["recommendation" ]= s .recommend (hw ) 2082return {"summary" :summary ,** out } 2083 2084# ---- strata_models 2085def strata_models (self )-> dict : 2086s = self .s 2087hw = s .hardware () 2088_m ,_f ,contexts ,src = s .tables () 2089rec = s .recommend (hw ) 2090return {"summary" :"Model families and sizes setup offers" + ( 2091f"; recommended for this PC: { rec [ 'title' ] } , { rec [ 'context' ] // 1024 } K context" 2092if rec .get ("model" )else f"; no model fits this PC: { rec [ 'why' ] } " ), 2093"families" :s .model_table (hw ),"contexts" :contexts , 2094"context_note" :"longer contexts need more VRAM (fewer experts fit on the GPU); past 262144 setup adds " 2095"rope scaling (experimental)" , 2096"recommendation" :rec ,"source" :src , 2097"this_pc" : {"ram_gb" :hw .get ("ram_gb" ), 2098"gpus" : [{k :g .get (k )for k in ("index" ,"name" ,"vram_gb" ,"usable" ,"vendor" )} 2099for g in hw .get ("gpus" , [])], 2100** ({"engine_vendor" :hw ["engine_vendor" ]}if hw .get ("engine_vendor" )else {}), 2101** ({"gpu_note" :hw ["gpu_note" ]}if hw .get ("gpu_note" )else {})}} 2102 2103# ---- strata_remove 2104def strata_remove (self ,model = None ,confirm = False )-> dict : 2105s = self .s 2106config = s .find_config (model ) 2107plan = s .removal_plan (config ) 2108if not confirm : 2109return {"summary" :f"Plan: delete { plan [ 'model' ] } ( { plan [ 'gb' ]:.1f } GB). Nothing was done yet." ,"plan" :plan } 2110with s .lock : 2111job = s .install_job () 2112if job and job ["running" ]: 2113raise ToolError ("an install is running: wait for it to finish or stop it first" ) 2114tracked = s .tracked_server () 2115if tracked and not tracked .get ("ended" )and tracked .get ("model" )== plan ["model" ]: 2116raise ToolError ("this model is running: stop it first" ) 2117failed = [] 2118# The plan can list a folder and files inside it, or a file that is already gone (an earlier delete, a file moved by hand): 2119# a path that is not there is already removed, not an error. Only what is still there afterwards counts as a failure. 2120for item in sorted (plan ["remove" ],key = lambda x : (x ["path" ]== str (config ),x ["path" ])): 2121p = Path (item ["path" ]) 2122try : 2123if p .is_dir ()and not p .is_symlink (): 2124shutil .rmtree (p ,onerror = _rmtree_ignore_missing ) 2125else : 2126p .unlink (missing_ok = True ) 2127except FileNotFoundError : 2128pass 2129except OSError as e : 2130if p .exists ()or p .is_symlink (): 2131failed .append (f" { p . name } : { e } " ) 2132files ,dirs = s .model_paths (s .read_config (config ))if config .exists ()else ([], []) 2133for p in {x .parent for x in [Path (i ["path" ])for i in plan ["remove" ]]if x .suffix == ".gguf" }: 2134try : 2135p .rmdir ()# the model's own folder, when nothing else is in it 2136except OSError : 2137pass 2138return {"summary" :f"Deleted { plan [ 'model' ] } ( { plan [ 'gb' ]:.1f } GB)" + (f"; could not remove { len ( failed ) } item(s)" if failed else "" ), 2139"plan" :plan ,"failed" :failed } 2140 2141# ---- strata_install 2142def check_data_dir (self ,raw :str )-> Path : 2143s = self .s 2144if raw .startswith ("\\\\" )or raw .startswith ("//" ): 2145raise ToolError ("data_dir: network (UNC) paths are not allowed; use a local drive" ) 2146p = Path (os .path .expandvars (raw )).expanduser () 2147if not p .is_absolute (): 2148raise ToolError ("data_dir must be an absolute path (e.g. D:\\Strata-data or /mnt/big/Strata-data)" ) 2149if ".." in p .parts : 2150raise ToolError ("data_dir must not contain '..'" ) 2151n = norm (p ) 2152current = norm (s .data_dir ()) 2153if n == current or is_inside (n ,norm (s .root ))or n == norm (s .root .parent / "Strata-data" ): 2154pass 2155else : 2156if not p .name .lower ().startswith ("strata" ): 2157raise ToolError (f"data_dir { raw !r } : a new data folder must be named Strata... (e.g. " 2158f" { Path ( p . anchor or '/' ) / 'Strata-data' } ), so that no other folder is filled with " 2159"model files" ) 2160if not p .parent .is_dir (): 2161raise ToolError (f"data_dir { raw !r } : its parent folder { p . parent } does not exist" ) 2162if not mounted_drive (n )and any (n == f or is_inside (n ,f )for f in system_folders ()): 2163raise ToolError (f"data_dir { raw !r } is inside a system folder" ) 2164if p .exists ()and not p .is_dir (): 2165raise ToolError (f"data_dir { raw !r } is a file" ) 2166return p 2167 2168def strata_install (self ,family = None ,model = None ,context = None ,vision = None ,kv = None ,gpu = None ,gpus = None , 2169backend = None ,low_ram = None ,port = None ,data_dir = None ,confirm = False ,cancel = False , 2170gguf_dir = None ,drafter = None ,mtp = None )-> dict : 2171s = self .s 2172with s .lock : 2173job = s .install_job () 2174if cancel : 2175if not job or not job ["running" ]: 2176return {"summary" :"no install is running" ,"install" :job } 2177j = s .state ("install" ) 2178res = s .state ("install-result" ) 2179child = res .get ("child_pid" )if res .get ("job" )== j .get ("job" )else None 2180tree = proc_tree_snapshot (j ["pid" ])if proc_alive (j ["pid" ],j ["ident" ])else []# setup.py and what it runs (#3257) 2181if child : 2182proc_kill_tree (child ,res .get ("child_ident" )) 2183proc_kill_tree (j ["pid" ],j ["ident" ]) 2184kill_snapshot (tree ) 2185wait_gone (j ["pid" ],j ["ident" ],15 ) 2186return {"summary" :"the install was stopped; calling strata_install again resumes it (downloads " 2187"continue where they stopped)" ,"install" :s .install_job ()} 2188if job and job ["running" ]: 2189return {"summary" :f"an install is running: { job . get ( 'step' ) or 'starting' } " 2190+ (f", downloading { job [ 'download' ][ 'file' ] } { job [ 'download' ][ 'percent' ] } %" 2191if job .get ("download" )else "" ), 2192"install" :job ,"follow" :"call strata_install again for progress, or strata_logs " 2193"source=setup for the full output" } 2194given = [x for x in (family ,model ,context ,vision ,kv ,gpu ,gpus ,backend ,low_ram ,port ,data_dir ) 2195if x is not None ] 2196if job and not given and not confirm : 2197return {"summary" :f"the last install { job [ 'result' ] } " + (f": { job [ 'error' ] } " if job .get ("error" )else "" ), 2198"install" :job , 2199"next" :"strata_start" if job .get ("exit_code" )== 0 else 2200"fix the problem above and call strata_install again with confirm=true (finished " 2201"steps are skipped)" } 2202plan ,args = self .install_plan (family ,model ,context ,vision ,kv ,gpu ,gpus ,backend ,low_ram ,port , 2203data_dir ,gguf_dir ,drafter ,mtp ) 2204tracked = s .tracked_server () 2205if tracked and not tracked .get ("ended" ): 2206raise ToolError ("Strata is running (started by strata_start): stop it first with strata_stop - setup " 2207"may update the engine files it uses" ) 2208if not confirm : 2209return {"summary" :f"Plan: install { plan [ 'title' ] } ( { plan [ 'download_gb' ]:.0f } GB download" 2210f" { ' at most; part of it is already here' if plan [ 'partly_downloaded' ] else '' } ). " 2211"Nothing was done yet: ask the user, then call strata_install again with the " 2212"same arguments and confirm=true." ,"plan" :plan } 2213if plan ["disk_short" ]: 2214raise ToolError (plan ["disk_short" ]) 2215return self .launch_install (plan ,args ) 2216 2217def install_plan (self ,family ,model ,context ,vision ,kv ,gpu ,gpus ,backend ,low_ram ,port ,data_dir ,gguf_dir = None ,drafter = None ,mtp = None ): 2218s = self .s 2219models ,families ,contexts ,_src = s .tables () 2220if gpu is not None and gpus is not None : 2221raise ToolError ("give gpu (one card) or gpus (several), not both" ) 2222if sys .version_info < (3 ,10 )or (WIN and sys .maxsize <= 2 ** 32 ): 2223raise ToolError ("this Python is too old or 32-bit: Strata's setup needs 64-bit Python 3.10+; run " 2224+ ("START-HERE.bat" if WIN else "./setup.sh" )+ " once instead (it installs Python)" ) 2225hw = s .hardware () 2226rec = s .recommend (hw ) 2227if model is None and family is None : 2228if not rec .get ("model" ): 2229raise ToolError ("no model was given and none fits this PC: " + rec ["why" ]) 2230family ,model = rec ["family" ],rec ["model" ] 2231context = context or rec ["context" ] 2232elif model is None : 2233sizes = s .sizes_of (models ,family ) 2234model = rec ["model" ]if rec .get ("family" )== family else ("IQ3_XXS" if "IQ3_XXS" in sizes and 2235hw .get ("ram_gb" ,0 )>= 60 else sizes [0 ]) 2236elif family is None : 2237fams = [f for f in families if model in s .sizes_of (models ,f )] 2238family = "qwen" if "qwen" in fams else fams [0 ] 2239if family not in families : 2240raise ToolError (f"unknown family { family } ; the families: { ', ' . join ( families ) } " ) 2241sizes = s .sizes_of (models ,family ) 2242if model not in sizes : 2243raise ToolError (f" { families [ family ][ 'title' ] } has no { model } ; its sizes: { ', ' . join ( sizes ) } " ) 2244md = s .own_size (family ,model )or models [model ]# Qwen3.6-35B-A3B: its sizes are not in setup's MODELS 2245mac = bool (hw .get ("mac" )) 2246if mac :# a Mac: no card to pick, no KV choice, no RAM mode: unified memory decides 2247if rec .get ("model" )is None and model is not None and s .mac ()and hw .get ("ram_gb" ,0 )< s .mac ().MIN_STREAM_RAM_GB : 2248raise ToolError (f" { model } does not fit this Mac: { rec [ 'why' ] } " ) 2249gpu = gpus = kv = low_ram = None 2250context = context or (s .mac ().recommend_context (hw .get ("ram_gb" )or 0 )if s .mac ()else 32768 ) 2251if context is None : 2252usable = s .engine_gpus (hw ) 2253vram = max ((g ["vram_gb" ]for g in usable ),default = 12 ) 2254context = 131072 # 128K on every card (owner, 2026-11-01; strata_control/default_context.py) 2255own = (getattr (s .setup_module (),"OWN_PATH_FAMILIES" ,None )or {}).get (family ) 2256if own :# Qwen3.6: the largest size that fits the card when 128K does not (#5715, setup's own rule) 2257context = s .setup_module ().own_path_context (own ,max ((g ["vram_gb" ]for g in usable ),default = 0.0 ),model ) 2258if vision in ("yes" ,"gpu" ,"cpu" )and md .get ("vision" ,families [family ].get ("vision" ))is False : 2259raise ToolError (f"images are not available with { families [ family ][ 'title' ] } { model } yet: use vision=no" ) 2260if vision is None : 2261# owner rule (2026-10-18): pictures are on by default wherever the model can read them and the engine has a reader; setup picks 2262# the reader (strata_control/vision_reader.py: the CPU under 24 GB, the GPU from 24 GB, every make of card; a Mac reads on its GPU). 2263can_read = md .get ("vision" ,families [family ].get ("vision" ))is not False 2264vision = "yes" if can_read else "no" 2265target = self .check_data_dir (data_dir )if data_dir else s .data_dir () 2266tag = (families [family ].get ("tag" ,"" )+ model ) 2267have_dir = target / "models" / tag 2268# An Intel Arc (Linux, the SYCL engine): setup.py's `--backend sycl` in its CONTROL mode prepares the model's files and writes the run config, as the 2269# Terminal does (strata_control/intel_app.py); it downloads nothing. NVIDIA and AMD never come here. 2270arc = backend == "sycl" or (backend in (None ,"auto" )and any (g .get ("vendor" )== "intel" for g in hw .get ("gpus" , []))) 2271if arc : 2272from strata_control import intel_app 2273if mac or not intel_app .supported_here ()or not any (g .get ("vendor" )== "intel" for g in hw .get ("gpus" , [])): 2274raise ToolError ("no Intel Arc card Strata can use was found in this computer (the Intel Arc engine runs on Linux)" ) 2275if not intel_app .can_set_up (family ,families [family ]): 2276raise ToolError (f" { families [ family ][ 'title' ] } { model } can't be set up for an Intel Arc card yet; " 2277"the Qwen3.8-Flash-Next, Swift, Coder, Gyro and Unsloth sizes can" ) 2278backend ,vision = "sycl" ,"no" # pictures stay off on an Arc (strata_cli/launch/adopt.py) 2279if not gguf_dir and not intel_app .model_files_in (have_dir ,family ,families [family ]): 2280raise ToolError (intel_app .NO_DOWNLOAD ) 2281partly = (have_dir .is_dir ()and any (have_dir .glob ("*.gguf*" )))or bool (gguf_dir )# a local folder: nothing to download 2282need = (8 if partly else md ["download_gb" ]+ 8 )+ (1 if vision in ("yes" ,"gpu" ,"cpu" )else 0 )+ (s .mac ().repacked_gb (model )if mac and s .mac ()else 0 )# a Mac repacks Unsloth's shards into one file for the GPU (mac_fit.repacked_gb) 2283free = s .disk_free (target ) 2284short = None 2285if free is not None and free < need : 2286short = (f"not enough free disk space for { model } : about { need :.0f } GB needed at { target } , " 2287f" { free :.0f } GB free; free some space or choose data_dir on a bigger drive (e.g. D:\\Strata-data)" ) 2288args = ["--yes" ,"--no-start" ,"--family" ,family ,"--model" ,model ,"--context" ,str (context ), 2289"--vision" ,vision or "no" ] 2290if family in ("qwen" ,"coder" ): 2291args += ["--experimental-speed-projection" ,"off" ] 2292own = bool (s .own_families ().get (family )) 2293for flag ,v in (("--kv" ,kv ), ("--gpu" ,gpu ), ("--gpus" ,gpus ), ("--low-ram" ,low_ram ), ("--port" ,port ), 2294 ("--data-dir" ,str (target )if data_dir else None )): 2295if own and flag in ("--kv" ,"--low-ram" ):# Flash-Next settings: Qwen3.6's engine path does not use them (setup would warn) 2296continue 2297if v is not None : 2298args += [flag ,str (v )] 2299if gguf_dir : 2300local = Path (os .path .expandvars (gguf_dir )).expanduser () 2301if not local .is_absolute ()or not local .is_dir ()or ".." in local .parts : 2302raise ToolError ("gguf_dir must be an existing absolute folder" ) 2303args += ["--gguf-dir" ,str (local )] 2304if backend in ("cuda" ,"hip" ,"sycl" ): 2305args += ["--backend" ,backend ] 2306if drafter in ("mtp" ,"dflash2" )and backend != "sycl" :# an Arc runs with no drafter the installer sets up (the Terminal's adopted config has none either) 2307args += ["--drafter" ,drafter ] 2308if mtp in ("on" ,"off" ):# the app's Drafting Off: no draft layer is fetched, on a Mac too (setup.py takes --mtp everywhere) 2309args += ["--mtp" ,mtp ] 2310fit = None 2311ram = hw .get ("ram_gb" ) 2312if ram is not None : 2313from strata_control import fit_label 2314fit = fit_label .label (fit_label .files_gb (family ,model ,md ),ram ,fit_label .card_room_gb (s .engine_gpus (hw ))) 2315installed = (s .root / f"strata- { tag . lower () } .json" ).exists () 2316plan = {"title" :f" { families [ family ][ 'title' ] } { model } " ,"family" :family ,"model" :model , 2317"context" :context ,"images" :vision or "no" ,"download_gb" :md ["download_gb" ], 2318"partly_downloaded" :partly ,"ram" :fit ,"data_folder" :str (target ),"model_folder" :str (have_dir ), 2319"disk_free_gb" :free , 2320"disk_needed_gb" :round (need ),"disk_short" :short ,"already_installed" :installed , 2321"setup_command" : ("START-HERE.bat " if WIN else "./setup.sh " )+ " " .join (args ), 2322"takes" :"about 20-90 minutes, mostly the download; the PC stays usable" , 2323"recommended_for_this_pc" :rec if rec .get ("model" )else None } 2324if installed : 2325plan ["note" ]= ("this model is already installed: running setup again updates the engine and applies " 2326"the options (finished steps are skipped)" ) 2327if families [family ].get ("license" ): 2328plan ["license" ]= families [family ]["license" ] 2329if families [family ].get ("experimental" )or md .get ("experimental" ): 2330plan ["experimental" ]= True 2331return plan ,args 2332 2333def launch_install (self ,plan :dict ,args :list )-> dict : 2334s = self .s 2335s .state_dir .mkdir (parents = True ,exist_ok = True ) 2336job_id = f" { int ( time . time ()) } - { os . getpid () } " 2337log_path = s .state_dir / "setup.log" 2338with open (log_path ,"a" ,encoding = "utf-8" )as f : 2339f .write (f"\n===== strata-mcp: install { plan [ 'title' ] } at { time . strftime ( '%Y-%m-%d %H:%M:%S' ) } =====\n" ) 2340spec = {"job" :job_id ,"root" :str (s .root ),"src" :str (s .src ),"control" :CONTROL , 2341"python" :s .run_python (),"base_python" :sys .executable , 2342"create_venv" :s .python_override is None and not s .venv_python ().exists (), 2343"args" :args ,"result" :str (s .state_dir / "install-result.json" )} 2344spec_path = s .state_dir / "install-job.json" 2345spec_path .write_text (json .dumps (spec ,indent = 1 ),encoding = "utf-8" ) 2346s .save_state ("install-result" ,None ) 2347env = dict (os .environ ,PYTHONUNBUFFERED = "1" ,PYTHONIOENCODING = "utf-8" ) 2348p = spawn_detached ([sys .executable ,str (Path (__file__ ).resolve ()),"--install-job" ,str (spec_path )], 2349s .root ,log_path ,env ) 2350s .children .append (p ) 2351time .sleep (0.2 ) 2352ident = proc_identity (p .pid ) 2353if ident is None and p .poll ()and s .state ("install-result" ).get ("job" )!= job_id : 2354raise ToolError ("setup did not start: " + " | " .join (read_tail (log_path ,5 ))) 2355folder = plan .get ("model_folder" ) 2356files = [] 2357if s .setup_module ()is not None and folder :# every file of this install, for a progress that counts all the parts 2358files = expected_files (s .setup_module (),plan ["family" ],plan ["model" ],Path (folder ).parent , 2359plan .get ("images" )in ("yes" ,"gpu" ,"cpu" )) 2360s .save_state ("install" , {"job" :job_id ,"pid" :p .pid ,"ident" :ident ,"log" :str (log_path ), 2361"model" :plan ["model" ],"family" :plan ["family" ],"folder" :folder ,"files" :files , 2362"total_gb" :plan .get ("download_gb" ), 2363"started" :time .strftime ("%Y-%m-%d %H:%M:%S" ),"args" :args }) 2364return {"summary" :f"Install of { plan [ 'title' ] } started in the background (about 20-90 minutes, mostly the " 2365f" { plan [ 'download_gb' ]:.0f } GB download). Call strata_install again to see the progress; " 2366"when it is done, start it with strata_start." , 2367"plan" :plan ,"log" :str (log_path ),"pid" :p .pid } 2368 2369# ---- strata_start 2370def strata_start (self ,model = None ,port = None ,gpu = None ,wait_seconds = 50 )-> dict : 2371s = self .s 2372with s .lock : 2373job = s .install_job () 2374if job and job ["running" ]: 2375raise ToolError ("an install is still running (strata_install shows its progress); start the model " 2376"when it is done" ) 2377cfg_path = s .find_config (model ) 2378desc = s .describe_config (cfg_path ) 2379if not desc ["ready" ]: 2380raise ToolError (f" { cfg_path . name } refers to missing files ( { ', ' . join ( desc [ 'missing_files' ]) } ): run " 2381"the install again (strata_install with confirm=true) to repair it" ) 2382port = port or desc ["port" ]or DEFAULT_PORT 2383tracked = s .tracked_server () 2384if tracked and not tracked .get ("ended" ): 2385info = s .probe (tracked ["port" ]) 2386return {"summary" :f"Strata is already { 'running' if info else 'loading' } ( { tracked . get ( 'model' ) } , " 2387f"port { tracked [ 'port' ] } , started by this MCP server)" 2388+ ("" if tracked .get ("model" )== desc ["model" ]else 2389": stop it first (strata_stop) to start another model" ), 2390"server" :info } 2391info = s .probe (port ,deep = False ) 2392if info and not info .get ("other" ): 2393return {"summary" :f"a Strata server already runs on port { port } ( { info . get ( 'model' ) } ), started " 2394"outside this MCP server; stop it (close its window) or use another port" , 2395"server" :info } 2396if info or not port_free (port ): 2397raise ToolError (f"port { port } is used by another program; choose another port (port=...)" ) 2398py = s .run_python () 2399if not Path (py ).exists (): 2400raise ToolError ("Strata's Python environment (.venv) is missing: run the install again" ) 2401cmd = [py ,str (s .root / "serve" / "server.py" ),"--engine" ,"strata" ,"--config" ,str (cfg_path ), 2402"--port" ,str (port )] 2403if gpu is not None : 2404cmd += ["--gpu" ,str (gpu )] 2405log_path = s .state_dir / "server.log" 2406s .state_dir .mkdir (parents = True ,exist_ok = True ) 2407with open (log_path ,"a" ,encoding = "utf-8" )as f : 2408f .write (f"\n===== strata-mcp: start { desc [ 'model' ] } on port { port } at " 2409f" { time . strftime ( '%Y-%m-%d %H:%M:%S' ) } =====\n" ) 2410env = dict (os .environ ,PYTHONUNBUFFERED = "1" ,PYTHONIOENCODING = "utf-8" ) 2411try : 2412os .utime (cfg_path )# the most recently used model, as setup's start marks it 2413except OSError : 2414pass 2415p = spawn_detached (cmd ,s .root ,log_path ,env ) 2416s .children .append (p ) 2417time .sleep (0.1 ) 2418ident = proc_identity (p .pid ) 2419s .save_state ("server" , {"pid" :p .pid ,"ident" :ident ,"port" :port ,"model" :desc ["model" ], 2420"config" :cfg_path .name ,"log" :str (log_path ), 2421"started" :time .strftime ("%Y-%m-%d %H:%M:%S" )}) 2422return self .wait_ready (p ,ident ,port ,desc ,wait_seconds ,log_path ) 2423 2424def wait_ready (self ,p ,ident ,port ,desc ,wait_seconds ,log_path )-> dict : 2425s = self .s 2426end = time .time ()+ wait_seconds 2427while True : 2428if p .poll ()is not None or not proc_alive (p .pid ,ident ): 2429tail = read_tail (log_path ,15 ) 2430end_group_leftovers (p .pid ) 2431s .save_state ("server" ,None ) 2432raise ToolError (f"Strata stopped while starting (exit code { p . poll () } ). Its last output:\n" 2433+ "\n" .join (tail )) 2434info = s .probe (port ) 2435if info and not info .get ("other" ): 2436return {"summary" :f"Strata is running: { info . get ( 'model' ) } on http://127.0.0.1: { port } /v1 " 2437"(OpenAI and Anthropic APIs; chat page at http://127.0.0.1:" + str (port )+ "/)" , 2438"server" : {** info ,"pid" :p .pid }} 2439if time .time ()>= end : 2440return {"summary" :f"Strata is loading { desc [ 'model' ] } (this takes 1-3 minutes; the PC may be slow " 2441"meanwhile). Check with strata_status in a minute." , 2442"loading" : {"pid" :p .pid ,"port" :port , 2443"last_log_line" : (read_tail (log_path ,1 )or [None ])[- 1 ]}} 2444time .sleep (1.0 ) 2445 2446# ---- strata_stop 2447def strata_stop (self ,port = None ,force = False )-> dict : 2448s = self .s 2449with s .lock : 2450tracked = s .tracked_server () 2451if tracked and tracked .get ("ended" ): 2452s .save_state ("server" ,None ) 2453tracked = None 2454if tracked : 2455port = tracked ["port" ] 2456key = s .api_key_for (port ) 2457st ,body = http_json (f"http://127.0.0.1: { port } /status" ,api_key = key ,timeout = 3 ) 2458if st == 200 and isinstance (body ,dict )and body .get ("busy" )and not force : 2459raise ToolError ("a request is running on Strata right now; wait for it, or call strata_stop " 2460"with force=true to stop anyway" ) 2461st ,body = http_json (f"http://127.0.0.1: { port } /unload" ,"POST" ,api_key = key ,timeout = 120 ) 2462unloaded = (body or {}).get ("status" )if isinstance (body ,dict )else None 2463if st == 409 and not force : 2464raise ToolError ("Strata is busy (a request is running or queued); call again with force=true " 2465"to stop anyway" ) 2466proc_terminate (tracked ["pid" ],tracked ["ident" ])# POSIX: SIGTERM = the server's own Ctrl+C path 2467clean = wait_gone (tracked ["pid" ],tracked ["ident" ],30 ) 2468if not clean : 2469proc_kill_tree (tracked ["pid" ],tracked ["ident" ]) 2470wait_gone (tracked ["pid" ],tracked ["ident" ],15 ) 2471s .reap () 2472gone = not proc_alive (tracked ["pid" ],tracked ["ident" ]) 2473if gone : 2474end_group_leftovers (tracked ["pid" ]) 2475s .save_state ("server" ,None ) 2476return {"summary" :"Strata stopped" + ("" if gone else " - but its process still runs; see strata_logs" ) 2477+ (" (the engine unloaded itself first)" if unloaded == "unloaded" else "" ), 2478"model" :tracked .get ("model" ),"port" :port ,"engine_unloaded" :unloaded , 2479"ended_cleanly" :clean } 2480for p in s .ports (port ): 2481info = s .probe (p ,deep = False ) 2482if info and not info .get ("other" ): 2483key = s .api_key_for (p ) 2484st ,body = http_json (f"http://127.0.0.1: { p } /unload" ,"POST" ,api_key = key ,timeout = 120 ) 2485r = body .get ("status" )if isinstance (body ,dict )else None 2486if st == 409 : 2487raise ToolError ("Strata is busy (a request is running); try again when it is done" ) 2488if st == 401 : 2489raise ToolError ("Strata (started outside this MCP server) wants an API key this folder's " 2490"configs do not have; close its window to stop it" ) 2491return {"summary" :f"Strata on port { p } was started outside this MCP server (its own window or a " 2492f"service), so only its model was unloaded ( { r } ): its VRAM and RAM are free, " 2493"but the server still listens and loads the model again on the next request. " 2494"Close its window to end it completely." , 2495"port" :p ,"engine_unloaded" :r } 2496return {"summary" :"Strata is not running" } 2497 2498# ---- strata_logs 2499def strata_logs (self ,source = None ,model = None ,lines = 80 )-> dict : 2500s = self .s 2501if source is None : 2502job = s .install_job () 2503source = "setup" if job and job ["running" ]else "server" 2504if source == "setup" : 2505path = s .state_dir / "setup.log" 2506elif source == "server" : 2507path = s .state_dir / "server.log" 2508else : 2509cfg = s .find_config (model or (s .state ("server" ).get ("model" ))) 2510raw = s .read_config (cfg ).get ("log" ) 2511if not raw : 2512raise ToolError (f" { cfg . name } names no engine log" ) 2513path = Path (raw ) 2514if not s .allowed (path ): 2515raise ToolError (f" { cfg . name } 's log { raw } is outside the Strata folder and its data folder: not shown" ) 2516if not path .exists (): 2517return {"summary" :f"no { source } log yet ( { path } )" ,"log" :str (path ),"lines" : []} 2518tail = read_tail (path ,lines ) 2519return {"summary" :f"last { len ( tail ) } lines of the { source } log" ,"log" :str (path ),"lines" :tail } 2520 2521# ---- strata_benchmark 2522def strata_benchmark (self ,port = None ,max_tokens = 200 )-> dict : 2523s = self .s 2524target = None 2525for p in s .ports (port ): 2526info = s .probe (p ,deep = False ) 2527if info and not info .get ("other" ): 2528target = info 2529break 2530if target is None : 2531raise ToolError ("Strata is not running: start it first (strata_start)" ) 2532p = target ["port" ] 2533key = s .api_key_for (p ) 2534st ,stat = http_json (f"http://127.0.0.1: { p } /status" ,api_key = key ,timeout = 3 ) 2535if st == 200 and isinstance (stat ,dict )and (stat .get ("busy" )or stat .get ("queued" )): 2536raise ToolError ("Strata is busy with a request; run the speed test when it is idle" ) 2537body = {"model" :target .get ("model" )or "strata" ,"max_tokens" :max_tokens ,"temperature" :0 , 2538"reasoning_effort" :"none" ,"stream" :False , 2539"messages" : [{"role" :"user" ,"content" :BENCH_PROMPT }]} 2540t0 = time .time () 2541st ,r = http_json (f"http://127.0.0.1: { p } /v1/chat/completions" ,"POST" ,body ,api_key = key ,timeout = 600 ) 2542wall = time .time ()- t0 2543if st != 200 or not isinstance (r ,dict ): 2544msg = (r or {}).get ("error" , {}).get ("message" )if isinstance (r ,dict )else None 2545raise ToolError (f"the request failed (HTTP { st } ): { msg or 'no answer' } " ) 2546usage ,tm = r .get ("usage" )or {},r .get ("timings" )or {} 2547n = usage .get ("completion_tokens" )or tm .get ("predicted_n" )or 0 2548out = {"model" :r .get ("model" ),"port" :p ,"prompt_tokens" :usage .get ("prompt_tokens" ), 2549"output_tokens" :n ,"wall_s" :round (wall ,2 ), 2550"output_tok_s" :round (tm ["predicted_per_second" ],1 )if tm .get ("predicted_per_second" )else None , 2551"prompt_tok_s" :round (tm ["prompt_per_second" ],1 )if tm .get ("prompt_per_second" )else None , 2552"wall_tok_s" :round (n / wall ,1 )if wall > 0 and n else None , 2553"finish_reason" : ((r .get ("choices" )or [{}])[0 ]).get ("finish_reason" ), 2554"settings" :f"greedy (temperature 0), thinking off, max_tokens { max_tokens } , a fixed story prompt" } 2555speed = out ["output_tok_s" ]or out ["wall_tok_s" ] 2556out ["summary" ]= (f" { n } tokens at { speed } tokens/s" + (f" (prompt { out [ 'prompt_tok_s' ] } tokens/s)" 2557if out ["prompt_tok_s" ]else "" ) 2558+ f", { wall :.1f } s in total" ) 2559out ["note" ]= ("output speed depends on the context length, the GPU's free VRAM and what else the PC does; " 2560"the first request after a start is slower" ) 2561return out 2562 2563# ---- strata_connect_info 2564def strata_connect_info (self ,port = None )-> dict : 2565s = self .s 2566target = None 2567for p in s .ports (port ): 2568info = s .probe (p ,deep = False ) 2569if info and not info .get ("other" ): 2570target = info 2571break 2572if port is None : 2573cfgs = s .configs () 2574port = target ["port" ]if target else (s .describe_config (cfgs [0 ])["port" ]if cfgs else DEFAULT_PORT ) 2575model = (target or {}).get ("model" )or "strata" 2576key_needed = (target or {}).get ("api_key_required" ) 2577if key_needed is None : 2578key_needed = any (s .describe_config (c )["api_key_set" ]for c in s .configs ()) 2579key = "<your api_key from strata-<model>.json>" if key_needed else "none" 2580base = f"http://127.0.0.1: { port } " 2581return { 2582"summary" : (f"Strata { 'runs' if target else 'will run' } at { base } : OpenAI base URL { base } /v1, Anthropic " 2583f"base URL { base } " + (" (an API key is required)" if key_needed else " (any API key works)" )), 2584"running" :bool (target ),"openai_base_url" :f" { base } /v1" ,"anthropic_base_url" :base , 2585"anthropic_messages_endpoint" :f" { base } /v1/messages" ,"chat_page" :base + "/" ,"model" :model , 2586"api_key" : ("required: the \"api_key\" value in the Strata folder's strata-<model>.json" 2587if key_needed else "not required (send any value)" ), 2588"examples" : { 2589"claude_code" : {"env" : {"ANTHROPIC_BASE_URL" :base ,"ANTHROPIC_AUTH_TOKEN" :key , 2590"ANTHROPIC_MODEL" :"claude-sonnet-4-5" }, 2591"note" :"Claude Code needs a Claude model name it knows; Strata ignores the name" }, 2592"codex_cli" : {"file" :"~/.codex/config.toml" , 2593"toml" :f'model = " { model } "\nmodel_provider = "strata"\n\n[model_providers.strata]\n' 2594f'name = "Strata"\nbase_url = " { base } /v1"\nwire_api = "chat"' }, 2595"openai_python" : (f'from openai import OpenAI\nclient = OpenAI(base_url=" { base } /v1", api_key=" { key } ")\n' 2596f'r = client.chat.completions.create(model=" { model } ", messages=[{{"role": "user", ' 2597f'"content": "Hello!"}}])\nprint(r.choices[0].message.content)' ), 2598"curl" : (f"curl { base } /v1/chat/completions -H \"Content-Type: application/json\" " 2599+ (f"-H \"Authorization: Bearer { key } \" " if key_needed else "" ) 2600+ f"-d '{{\"model\": \" { model } \", \"messages\": [{{\"role\": \"user\", \"content\": " 2601"\"Hello!\"}]}'" ), 2602"openai_compatible_apps" : {"base_url" :f" { base } /v1" ,"api_key" :key ,"model" :model , 2603"apps" :"Cursor (Settings > Models > OpenAI base URL override), " 2604"Continue, Open WebUI, LM Studio clients, aider " 2605f"(--openai-api-base { base } /v1)" }}, 2606"other_devices" :"the server listens on this PC only; to reach it from your network, run setup with " 2607"--host 0.0.0.0 --api-key <secret> (docs/DETAILS.md, 'Using it')" } 2608 2609 2610# ------------------------------------------------------------------------------------------------ MCP over stdio 2611INSTRUCTIONS = ("Strata runs a large AI model (Qwen3.8-Flash-Next, a mixture of experts) locally on this PC's GPU and " 2612"RAM, with an OpenAI- and Anthropic-compatible server on http://127.0.0.1:8080. Call strata_status " 2613"first. To install: strata_install (it returns a plan; get the user's OK for the 58-111 GB download, " 2614"then call it with confirm=true; it runs in the background - call it again for progress). Then " 2615"strata_start, strata_stop, strata_logs for problems, strata_connect_info to point other apps at it." ) 2616 2617 2618class McpServer : 2619def __init__ (self ,strata :Strata ,out = None ): 2620self .strata = strata 2621self .tools = Tools (strata ) 2622self .out = out 2623self .write_lock = threading .Lock () 2624self .protocol = PROTOCOL 2625 2626def send (self ,msg :dict )-> None : 2627data = (json .dumps (msg ,ensure_ascii = False )+ "\n" ).encode ("utf-8" ) 2628with self .write_lock : 2629self .out .write (data ) 2630self .out .flush () 2631 2632@staticmethod 2633def result (rid ,result ): 2634return {"jsonrpc" :"2.0" ,"id" :rid ,"result" :result } 2635 2636@staticmethod 2637def error (rid ,code ,message ): 2638return {"jsonrpc" :"2.0" ,"id" :rid ,"error" : {"code" :code ,"message" :message }} 2639 2640def handle (self ,msg )-> dict | None : 2641"""One JSON-RPC message -> its response (None for a notification or a response).""" 2642if not isinstance (msg ,dict )or msg .get ("jsonrpc" )!= "2.0" : 2643return self .error (msg .get ("id" )if isinstance (msg ,dict )else None ,- 32600 ,"invalid request" ) 2644if "method" not in msg : 2645return None # a response to something we never ask: ignored 2646method ,rid ,params = msg ["method" ],msg .get ("id" ),msg .get ("params" )or {} 2647if "id" not in msg : 2648return None # notifications (initialized, cancelled ...): nothing to say 2649if not isinstance (params ,dict ): 2650return self .error (rid ,- 32602 ,"params must be an object" ) 2651if method == "initialize" : 2652asked = str (params .get ("protocolVersion" )or PROTOCOL ) 2653self .protocol = asked if asked in PROTOCOLS else PROTOCOL 2654return self .result (rid , {"protocolVersion" :self .protocol , 2655"capabilities" : {"tools" : {"listChanged" :False }}, 2656"serverInfo" : {"name" :"strata" ,"title" :"Strata" ,"version" :VERSION }, 2657"instructions" :INSTRUCTIONS }) 2658if method == "ping" : 2659return self .result (rid , {}) 2660if method == "tools/list" : 2661return self .result (rid , {"tools" :self .tools .defs ()}) 2662if method == "tools/call" : 2663name = params .get ("name" ) 2664try : 2665res = self .tools .call (name ,params .get ("arguments" )) 2666return self .result (rid ,self .content (res ,error = False )) 2667except KeyError : 2668return self .error (rid ,- 32602 ,f"unknown tool: { name } " ) 2669except ToolError as e : 2670return self .result (rid ,self .content ({"error" :str (e )},error = True )) 2671except Exception as e :# noqa: BLE001 - a bug must not end the server 2672log ("tool failed:\n" + traceback .format_exc ()) 2673return self .result (rid ,self .content ({"error" :f"internal error in { name } : { e } " },error = True )) 2674if method in ("resources/list" ,"prompts/list" ): 2675return self .result (rid , {method .split ("/" )[0 ]: []}) 2676return self .error (rid ,- 32601 ,f"method not found: { method } " ) 2677 2678def content (self ,res :dict ,error :bool )-> dict : 2679text = json .dumps (res ,indent = 1 ,ensure_ascii = False ) 2680out = {"content" : [{"type" :"text" ,"text" :text }],"isError" :error } 2681if self .protocol >= "2025-06-18" : 2682out ["structuredContent" ]= res 2683return out 2684 2685def serve (self ,inp )-> None : 2686"""Read JSON-RPC lines until stdin closes; tool calls run in their own threads (a start waits for the model 2687while pings and status calls are still answered).""" 2688threads = [] 2689for raw in inp : 2690line = raw .decode ("utf-8" ,"replace" ).strip ()if isinstance (raw ,bytes )else raw .strip () 2691if not line : 2692continue 2693try : 2694msg = json .loads (line ) 2695except ValueError : 2696self .send (self .error (None ,- 32700 ,"parse error" )) 2697continue 2698batch = isinstance (msg ,list ) 2699if batch or (isinstance (msg ,dict )and msg .get ("method" )== "tools/call" ): 2700t = threading .Thread (target = self ._run ,args = (msg ,),daemon = True ) 2701t .start () 2702threads .append (t ) 2703threads = [x for x in threads if x .is_alive ()] 2704else : 2705self ._run (msg ) 2706for t in threads : 2707t .join (timeout = 5 ) 2708 2709def _run (self ,msg )-> None : 2710if isinstance (msg ,list ): 2711out = [r for r in (self .handle (m )for m in msg )if r is not None ] 2712if out : 2713data = (json .dumps (out ,ensure_ascii = False )+ "\n" ).encode ("utf-8" ) 2714with self .write_lock : 2715self .out .write (data ) 2716self .out .flush () 2717return 2718r = self .handle (msg ) 2719if r is not None : 2720self .send (r ) 2721 2722 2723# ------------------------------------------------------------------------------------------------ the install job 2724def install_job (spec_path :str )-> int : 2725"""The background half of strata_install (this file started again with --install-job): make .venv like 2726START-HERE.bat / setup.sh do when it is missing, run setup, record its exit code.""" 2727spec = json .loads (Path (spec_path ).read_text (encoding = "utf-8" )) 2728root = Path (spec ["root" ]) 2729result = Path (spec ["result" ]) 2730 2731def record (** kw ): 2732try : 2733old = json .loads (result .read_text (encoding = "utf-8" ))if result .exists ()else {} 2734except (OSError ,ValueError ): 2735old = {} 2736tmp = result .with_suffix (".tmp" ) 2737tmp .write_text (json .dumps ({** old ,"job" :spec ["job" ],** kw },indent = 1 ),encoding = "utf-8" ) 2738os .replace (tmp ,result ) 2739 2740py = Path (spec ["python" ]) 2741src = Path (spec .get ("src" )or root ) 2742try : 2743if spec .get ("create_venv" ): 2744venv = root / ".venv" 2745if py .exists ()and subprocess .run ([str (py ),"-m" ,"pip" ,"--version" ],capture_output = True ).returncode : 2746"strata-mcp: .venv has no pip (an earlier run stopped half-way): making it again" ,flush = True ) 2747shutil .rmtree (venv ,ignore_errors = True ) 2748if not py .exists (): 2749f"strata-mcp: creating Strata's Python environment in { venv } ..." ,flush = True ) 2750r = subprocess .run ([spec ["base_python" ],"-m" ,"venv" ,str (venv )]) 2751if r .returncode or not py .exists (): 2752"\n [X] could not create the Python environment (.venv)" ,flush = True ) 2753" Linux: install python3-venv (sudo apt install python3-venv) or run ./setup.sh " 2754"once in a terminal" ,flush = True ) 2755record (exit_code = 1 ,ended = time .strftime ("%Y-%m-%d %H:%M:%S" )) 2756return 1 2757cmd = [str (py ),str (src / "setup.py" ),* spec ["args" ]] 2758"strata-mcp: running " + " " .join (cmd ),flush = True ) 2759env = dict (os .environ ,PYTHONUNBUFFERED = "1" ,PYTHONIOENCODING = "utf-8" ) 2760if spec .get ("control" ):# the app: the installer's own mode, writing to `root` 2761env .update (STRATA_CONTROL_INSTALL = "1" ,STRATA_INSTALL_DIR = str (root ),PYTHONNOUSERSITE = "1" ) 2762for key in ("PYTHONHOME" ,"PYTHONPATH" ,"VIRTUAL_ENV" ): 2763env .pop (key ,None ) 2764# This job is the explicit install the user asked for (it downloads model files and the preparation sources). The 2765# server that started it, and every start or serve, keep STRATA_NO_ACQUIRE; setup.py's CONTROL mode still runs 2766# no pip, git, compiler or engine fetch. 2767env .pop ("STRATA_NO_ACQUIRE" ,None ) 2768p = subprocess .Popen (cmd ,cwd = str (src if spec .get ("control" )else root ),stdin = subprocess .DEVNULL ,env = env ) 2769record (child_pid = p .pid ,child_ident = proc_identity (p .pid )) 2770rc = p .wait () 2771except Exception as e :# noqa: BLE001 2772f"\n [X] strata-mcp could not run setup: { e } " ,flush = True ) 2773rc = 1 2774f"strata-mcp: setup ended with exit code { rc } " ,flush = True ) 2775record (exit_code = rc ,ended = time .strftime ("%Y-%m-%d %H:%M:%S" )) 2776return rc 2777 2778 2779def main (argv = None )-> int : 2780ap = argparse .ArgumentParser (description = "Strata's MCP server (stdio): install, start, check and stop Strata " 2781"from an AI assistant. See docs/MCP_SERVER.md." ) 2782ap .add_argument ("--root" ,help = "the Strata folder (default: the one this file is in)" ) 2783ap .add_argument ("--src" ,help = "where setup.py, tools/ and serve/ are, when that is not the Strata folder (the app)" ) 2784ap .add_argument ("--install-job" ,help = argparse .SUPPRESS ) 2785a = ap .parse_args (argv ) 2786if a .install_job : 2787return install_job (a .install_job ) 2788if sys .version_info < (3 ,10 ): 2789log ("Python 3.10 or newer is needed" ) 2790return 2 2791root = Path (a .root ).expanduser ().resolve ()if a .root else DEFAULT_ROOT 2792src = Path (a .src ).expanduser ().resolve ()if a .src else root 2793if not (src / "setup.py" ).is_file ()or not (src / "serve" / "server.py" ).is_file (): 2794log (f" { src } is not a Strata folder (no setup.py / serve/server.py)" ) 2795return 2 2796out = sys .stdout .buffer 2797sys .stdout = sys .stderr # stray prints must never corrupt the protocol stream 2798server = McpServer (Strata (root ,src ),out ) 2799log (f"ready (Strata folder { root } )" ) 2800try : 2801server .serve (sys .stdin .buffer ) 2802except KeyboardInterrupt : 2803pass 2804return 0 2805 2806 2807if __name__ == "__main__" : 2808sys .exit (main ())