okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221app: Drafting Off fetches no draft layer; the offline note only when no drafter runsb2d08647c

main
162.4 KiB2808 linesraw
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
4    claude 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:
144    import ctypes
145    from 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
157    class _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))
166    CREATE_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."""
171    try:
172        sys.stderr.write(f"[strata-mcp] {msg}\n")
173        sys.stderr.flush()
174    except (OSError, ValueError):
175        pass
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
181    when no such process runs."""
182    try:
183        pid = int(pid)
184    except (TypeError, ValueError):
185        return None
186    if pid <= 0:
187        return None
188    if WIN:
189        h = _k32.OpenProcess(_QUERY, False, pid)
190        if not h:
191            return None
192        try:
193            code = wintypes.DWORD()
194            if not _k32.GetExitCodeProcess(h, ctypes.byref(code)) or code.value != _STILL_ACTIVE:
195                return None
196            c, e, k, u = (wintypes.FILETIME() for _ in range(4))
197            if not _k32.GetProcessTimes(h, ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u)):
198                return None
199            return f"win:{(c.dwHighDateTime << 32) | c.dwLowDateTime}"
200        finally:
201            _k32.CloseHandle(h)
202    stat = Path(f"/proc/{pid}/stat")
203    if _has_proc():
204        try:
205            fields = stat.read_text().rsplit(")", 1)[1].split()
206        except (OSError, IndexError):
207            return None
208        if fields[0] in ("Z", "X"):                     # a zombie has ended
209            return None
210        return f"linux:{fields[19]}"                    # field 22 of stat: the start time in clock ticks
211    state = _ps_state(pid)                              # elsewhere (macOS: no /proc): ps says whether it runs; a zombie (an ended child
212    if state is not None:                               # not reaped yet) answers kill(pid, 0) but has ended (lane 8, a Mac install that "ran" for ever)
213        return "pid" if state and not state.startswith("Z") else None
214    try:                                                # no ps either: alive, without a start time
215        os.kill(pid, 0)
216        return "pid"
217    except OSError:
218        return None
219
220
221def _has_proc() -> bool:
222    return 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."""
227    try:
228        done = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True, timeout=5)
229    except (OSError, subprocess.SubprocessError):
230        return None
231    out = done.stdout.strip()
232    if done.returncode != 0 and not out:
233        return ""                                       # ps: no such process
234    return out
235
236
237def proc_alive(pid, ident) -> bool:
238    return 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
243    touches a process whose start time differs from the one recorded."""
244    if not proc_alive(pid, ident):
245        return False
246    if WIN:
247        h = _k32.OpenProcess(_TERMINATE | _QUERY, False, int(pid))
248        if not h:
249            return False
250        try:
251            return bool(_k32.TerminateProcess(h, 1))
252        finally:
253            _k32.CloseHandle(h)
254    try:
255        os.kill(int(pid), signal.SIGTERM)
256        return True
257    except OSError:
258        return 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."""
263    exc = exc_info[1] if isinstance(exc_info, tuple) else exc_info
264    if isinstance(exc, FileNotFoundError):
265        return
266    raise 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."""
271    if not WIN:
272        return {}
273    snap = _k32.CreateToolhelp32Snapshot(0x2, 0)                  # TH32CS_SNAPPROCESS
274    if not snap or snap == wintypes.HANDLE(-1).value:
275        return {}
276    kids: dict = {}
277    try:
278        entry = _PROCESSENTRY32W()
279        entry.dwSize = ctypes.sizeof(_PROCESSENTRY32W)
280        ok = _k32.Process32FirstW(snap, ctypes.byref(entry))
281        while ok:
282            kids.setdefault(entry.th32ParentProcessID, []).append(entry.th32ProcessID)
283            ok = _k32.Process32NextW(snap, ctypes.byref(entry))
284    finally:
285        _k32.CloseHandle(snap)
286    return 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
291    what it started (#3257: a cancelled install left tools/mtp_fetch.py writing).  Windows only; [] elsewhere (a process group does that)."""
292    kids = proc_children_map()
293    out, seen, todo = [], {int(pid)}, [int(pid)]
294    while todo:
295        for child in kids.get(todo.pop(), []):
296            if child in seen:
297                continue
298            seen.add(child)
299            ident = proc_identity(child)
300            if ident:
301                out.append((child, ident))
302                todo.append(child)
303    return 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)."""
308    for pid, ident in reversed(list(procs)):
309        if proc_alive(pid, ident):
310            proc_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)."""
315    if not proc_alive(pid, ident):
316        return False
317    if WIN:
318        tree = proc_tree_snapshot(pid)                  # before taskkill: it walks parent ids, and a break in the chain hides the rest
319        r = subprocess.run(["taskkill", "/PID", str(int(pid)), "/T", "/F"], capture_output=True,
320                           creationflags=CREATE_NO_WINDOW)
321        kill_snapshot(tree)
322        return r.returncode == 0 or not proc_alive(pid, ident)
323    try:
324        os.killpg(int(pid), signal.SIGKILL)             # started as a session leader: its group is its own
325        return True
326    except OSError:
327        try:
328            os.kill(int(pid), signal.SIGKILL)
329            return True
330        except OSError:
331            return 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
336    engine it started but could not close (e.g. stopped while loading, before its own SIGTERM handler existed).
337    While any member lives, the group id cannot belong to anybody else."""
338    if WIN or not pgid:
339        return
340    for sig, wait in ((signal.SIGTERM, 20.0), (signal.SIGKILL, 5.0)):
341        try:
342            os.killpg(int(pgid), sig)
343        except OSError:
344            return                                      # no such group left
345        end = time.time() + wait
346        while time.time() < end:
347            try:
348                os.killpg(int(pgid), 0)
349            except OSError:
350                return
351            time.sleep(0.25)
352
353
354def wait_gone(pid, ident, seconds: float) -> bool:
355    end = time.time() + seconds
356    while time.time() < end:
357        if not proc_alive(pid, ident):
358            return True
359        time.sleep(0.25)
360    return 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
365    server) ends: its own process group / session, no console window on Windows."""
366    log_path.parent.mkdir(parents=True, exist_ok=True)
367    with open(log_path, "ab") as logf:
368        kw = dict(cwd=str(cwd), stdin=subprocess.DEVNULL, stdout=logf, stderr=subprocess.STDOUT,
369                  env=env, close_fds=True)
370        if WIN:
371            flags = CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW
372            try:                                        # out of the AI client's job, if it lets us
373                return subprocess.Popen(cmd, creationflags=flags | CREATE_BREAKAWAY_FROM_JOB, **kw)
374            except OSError:
375                return subprocess.Popen(cmd, creationflags=flags, **kw)
376        return 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."""
381    try:
382        return subprocess.run(cmd, capture_output=True, text=True, errors="replace", timeout=timeout, stdin=subprocess.DEVNULL,
383                              creationflags=CREATE_NO_WINDOW if WIN else 0).stdout or ""
384    except (OSError, subprocess.SubprocessError, ValueError):
385        return ""
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."""
390    try:
391        with open(path, "rb") as f:
392            f.seek(0, os.SEEK_END)
393            size = f.tell()
394            f.seek(max(0, size - max_bytes))
395            data = f.read().decode("utf-8", "replace")
396    except OSError:
397        return []
398    out = []
399    for raw in data.split("\n"):
400        part = [p for p in raw.split("\r") if p.strip()]
401        if part:
402            out.append(part[-1].rstrip())
403    return out[-lines:]
404
405
406def dir_size_gb(path: Path, limit_files: int = 20000) -> float:
407    total, n = 0, 0
408    for base, _dirs, files in os.walk(path):
409        for f in files:
410            try:
411                total += os.stat(os.path.join(base, f)).st_size
412            except OSError:
413                pass
414            n += 1
415            if n >= limit_files:
416                return round(total / 1e9, 1)
417    return 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."""
426    data = json.dumps(body).encode() if body is not None else (b"" if method == "POST" else None)
427    req = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"})
428    if api_key:
429        req.add_header("Authorization", f"Bearer {api_key}")
430    try:
431        with _OPENER.open(req, timeout=timeout) as r:
432            raw = r.read()
433            status = r.status
434    except urllib.error.HTTPError as e:
435        raw, status = e.read(), e.code
436    except (OSError, ValueError):
437        return 0, None
438    try:
439        return status, json.loads(raw or b"null")
440    except ValueError:
441        return status, None
442
443
444def port_free(port: int, host="127.0.0.1") -> bool:
445    import socket
446    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
447    try:
448        s.bind((host, port))
449        return True
450    except OSError:
451        return False
452    finally:
453        s.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."""
463    if args is None:
464        args = {}
465    if not isinstance(args, dict):
466        raise ToolError("arguments must be a JSON object")
467    props = schema.get("properties", {})
468    for k in args:
469        if k not in props:
470            raise ToolError(f"unknown argument {k!r}; this tool takes: {', '.join(props) or 'no arguments'}")
471    for k in schema.get("required", []):
472        if k not in args:
473            raise ToolError(f"missing argument {k!r}")
474    for k, v in args.items():
475        p = props[k]
476        t = p.get("type")
477        if t == "integer" and (isinstance(v, bool) or not isinstance(v, int)):
478            if isinstance(v, float) and v.is_integer():
479                v = args[k] = int(v)
480            elif isinstance(v, str) and re.fullmatch(r"\d{1,7}", v.strip()):
481                v = args[k] = int(v.strip())              # some clients send numbers as strings
482            else:
483                raise ToolError(f"{k} must be a whole number")
484        if t == "boolean" and not isinstance(v, bool):
485            if v in ("true", "false"):
486                v = args[k] = v == "true"
487            else:
488                raise ToolError(f"{k} must be true or false")
489        if t == "string":
490            if not isinstance(v, str):
491                raise ToolError(f"{k} must be a string")
492            if len(v) > p.get("maxLength", 300) or "\x00" in v or "\n" in v or "\r" in v:
493                raise ToolError(f"{k} is too long or contains control characters")
494            if "pattern" in p and not re.fullmatch(p["pattern"], v):
495                raise ToolError(f"{k}={v!r} is not valid ({p.get('description', p['pattern'])})")
496        if "enum" in p and v not in p["enum"]:
497            raise ToolError(f"{k} must be one of: {', '.join(map(str, p['enum']))} (got {v!r})")
498        if t == "integer":
499            if "minimum" in p and v < p["minimum"] or "maximum" in p and v > p["maximum"]:
500                raise ToolError(f"{k} must be between {p.get('minimum')} and {p.get('maximum')} (got {v})")
501    return args
502
503
504def is_inside(path: Path, root: Path) -> bool:
505    try:
506        path.relative_to(root)
507        return True
508    except ValueError:
509        return 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."""
514    return 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."""
519    return not WIN and is_inside(n, norm("/run/media")) and n != norm("/run/media")
520
521
522def system_folders() -> list[Path]:
523    if WIN:
524        env = [os.environ.get(k) for k in ("SystemRoot", "windir", "ProgramFiles", "ProgramFiles(x86)", "ProgramData",
525                                            "ProgramW6432")]
526        return [norm(p) for p in env if p]
527    return [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
535    def __init__(self, root: Path | str = DEFAULT_ROOT, src: Path | str | None = None):
536        self.root = Path(root).resolve()
537        # where setup.py, tools/ and serve/ are (the app: inside Strata Control); `root` is where the installs live
538        self.src = Path(src).resolve() if src else self.root
539        self.state_dir = self.root / STATE_DIR
540        self.lock = threading.Lock()                    # install / start / stop one at a time
541        self.children: list[subprocess.Popen] = []      # reaped now and then (no zombies on POSIX)
542        self._setup = None
543        self._setup_tried = False
544        self._hw_cache = None
545        # tests: the interpreter that runs setup / the server. The app's Control runs the installer on its own Python.
546        self.python_override: str | None = sys.executable if CONTROL else None
547        self.health_timeout = 2.0
548
549    # ---- setup.py's own tables and logic
550    def setup_module(self):
551        """setup.py imported as a module (its tables and its pure checks), or None.  Its command runner is replaced
552        by one without console windows; nothing of its install path runs."""
553        if not self._setup_tried:
554            self._setup_tried = True
555            try:
556                if str(self.src) not in sys.path:
557                    sys.path.insert(0, str(self.src))   # setup.py imports strata_control
558                spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.src / "setup.py")
559                mod = importlib.util.module_from_spec(spec)
560                real = sys.stdout
561                sys.stdout = sys.stderr                 # nothing it prints may reach the protocol stream
562                try:
563                    spec.loader.exec_module(mod)
564                finally:
565                    sys.stdout = real
566                if all(hasattr(mod, a) for a in ("MODELS", "FAMILIES", "CONTEXTS")):
567                    mod.out = lambda cmd: run_quiet(cmd, 60)
568                    self._setup = mod
569                    if hasattr(mod, "feed_models_setup"):
570                        try:                            # the signed feed's models (the last verified list; nothing is fetched here), after the built-in ones
571                            mod.feed_models_setup(fetch=False)
572                        except Exception as e:          # noqa: BLE001
573                            log(f"the feed's model list was not added: {e}")
574            except (Exception, SystemExit) as e:        # noqa: BLE001 - any failure: the built-in tables
575                log(f"setup.py could not be imported ({e}); using the built-in model table")
576        return self._setup
577
578    def tables(self):
579        s = self.setup_module()
580        if s is not None:
581            return s.MODELS, {**s.FAMILIES, **self.own_families()}, list(s.CONTEXTS), "setup.py"
582        return FALLBACK_MODELS, FALLBACK_FAMILIES, FALLBACK_CONTEXTS, "built-in table (setup.py not importable)"
583
584    def 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
587        showed no versions at all.  Each is returned as a family entry (title, about, tag, license) of this server's table."""
588        s = self.setup_module()
589        out = {}
590        for f, d in (getattr(s, "OWN_PATH_FAMILIES", None) or {}).items():
591            out[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 {})}
593        return out
594
595    def 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`."""
597        s = self.setup_module()
598        names = []
599        for table in ("OWN_PATH_FAMILIES",):
600            for fam in (getattr(s, table, None) or {}).values():
601                names.extend(n for n in fam.get("models", {}) if n not in names)
602        return names
603
604    def 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).
606        The download is the GGUF; the picture reader (mmproj, ~0.9 GB) is counted by the plan when pictures are on."""
607        d = (getattr(self.setup_module(), "OWN_PATH_FAMILIES", None) or {}).get(family)
608        if not d or model not in d["models"]:
609            return None
610        size_gb = d["sha256"][d["file"].format(q=model)][0] / 1e9
611        return {"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
617    def 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."""
619        try:
620            from strata_control import own_path_fit
621            return own_path_fit.inputs(fam.get("name"), model)
622        except ImportError:
623            return None
624
625    def sizes_of(self, models, family) -> list:
626        """The family's sizes as setup lists them: an experimental one last (never the default)."""
627        own = (getattr(self.setup_module(), "OWN_PATH_FAMILIES", None) or {}).get(family)
628        if own:
629            return list(own["models"])
630        return sorted((m for m in models if family in models[m].get("families", ("qwen", "swift"))),
631                      key=lambda m: bool(models[m].get("experimental")))
632
633    # ---- paths
634    def settings_path(self) -> Path:
635        if os.environ.get("STRATA_SETTINGS_FILE"):
636            return Path(os.environ["STRATA_SETTINGS_FILE"])
637        if WIN:
638            return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json"
639        return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json"
640
641    def data_dir(self) -> Path:
642        try:
643            s = json.loads(self.settings_path().read_text(encoding="utf-8"))
644        except (OSError, ValueError):
645            s = {}
646        d = s.get("data_dir") if isinstance(s, dict) else None
647        return Path(d) if d else self.root.parent / "Strata-data"
648
649    def allowed_roots(self) -> list[Path]:
650        return [norm(self.root), norm(self.data_dir())]
651
652    def allowed(self, p) -> bool:
653        p = norm(p)
654        return any(is_inside(p, r) for r in self.allowed_roots())
655
656    def venv_python(self) -> Path:
657        return self.root / ".venv" / ("Scripts/python.exe" if WIN else "bin/python")
658
659    def run_python(self) -> str:
660        return self.python_override or str(self.venv_python())
661
662    def state(self, name: str) -> dict:
663        try:
664            d = json.loads((self.state_dir / f"{name}.json").read_text(encoding="utf-8"))
665            return d if isinstance(d, dict) else {}
666        except (OSError, ValueError):
667            return {}
668
669    def save_state(self, name: str, d: dict | None) -> None:
670        self.state_dir.mkdir(parents=True, exist_ok=True)
671        f = self.state_dir / f"{name}.json"
672        if d is None:
673            f.unlink(missing_ok=True)
674        else:
675            tmp = f.with_suffix(".tmp")
676            tmp.write_text(json.dumps(d, indent=1), encoding="utf-8")
677            os.replace(tmp, f)
678
679    def reap(self):
680        self.children = [p for p in self.children if p.poll() is None]
681
682    # ---- what is installed
683    def configs(self) -> list[Path]:
684        return sorted((p for p in self.root.glob("strata-*.json") if not p.name.endswith(".shared-settings.json")),
685                      key=lambda p: p.stat().st_mtime, reverse=True)   # #346: the Chat settings file is no config
686
687    @staticmethod
688    def read_config(path: Path) -> dict:
689        try:
690            cfg = json.loads(path.read_text(encoding="utf-8-sig"))
691            return cfg if isinstance(cfg, dict) else {}
692        except (OSError, ValueError):
693            return {}
694
695    def describe_config(self, path: Path, usage: dict | None = None) -> dict:
696        cfg = self.read_config(path)
697        a = cfg.get("args") if isinstance(cfg.get("args"), list) else []
698
699        def val(k):
700            return a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None
701        tag = path.stem[len("strata-"):]
702        missing = [p for p in [cfg.get("exe"), *[x for x in a if isinstance(x, str) and x.endswith(".gguf")]]
703                   if not p or not Path(p).exists()]
704        gaps = 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
705        missing += gaps
706        script = self.root / f"run-{tag}.{'bat' if WIN else 'sh'}"
707        vis = cfg.get("vision")
708        own_usage = (usage or self.disk_usage())["models"].get(tag) or {"gb": 0.0, "bytes": 0, "shared_bytes": 0}
709        plan = self.removal_plan(path)
710        return {"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)
713                else "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)
726    FILE_FLAGS = ("--native", "--ple-gguf", "--embd-gguf", "--native-dense-gguf")
727    DIR_FLAGS = ("--pack", "--mtp")
728
729    def 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."""
731        a = [x for x in (cfg.get("args") or []) if isinstance(x, str)]
732        files = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.FILE_FLAGS]
733        files += [Path(x) for x in a if x.lower().endswith(".gguf")]
734        dirs = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.DIR_FLAGS]
735        seen, once = set(), []
736        for f in files:                                 # one file named by several flags is still one file
737            if norm(f) not in seen:
738                seen.add(norm(f))
739                once.append(f)
740        seen_d, once_d = set(), []
741        for d in dirs:
742            if norm(d) not in seen_d:
743                seen_d.add(norm(d))
744                once_d.append(d)
745        return once, once_d
746
747    @staticmethod
748    def 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
750        first), so deleting a model takes all its parts and never leaves 100 GB behind (#3716)."""
751        out, seen = [], set()
752        for f in files:
753            names = [Path(f)]
754            m = SHARD_NAME.match(str(f))
755            if m:
756                names += [Path(f"{m.group(1)}-{i:05d}-of-{m.group(3)}.gguf") for i in range(1, int(m.group(3)) + 1)]
757            for n in names:
758                key = norm(n)
759                if key not in seen:
760                    seen.add(key)
761                    out.append(n)
762        return out
763
764    @staticmethod
765    def tree_bytes(path: Path) -> int:
766        if path.is_file():
767            try:
768                return path.stat().st_size
769            except OSError:
770                return 0
771        total = 0
772        for base, _d, names in os.walk(path):
773            for n in names:
774                try:
775                    total += os.stat(os.path.join(base, n)).st_size
776                except OSError:
777                    pass
778        return total
779
780    @staticmethod
781    def file_key(path: Path):
782        """What makes two names the same file on disk: device + inode (hard links), else the resolved path."""
783        try:
784            st = os.stat(path)
785            if st.st_ino:
786                return ("ino", st.st_dev, st.st_ino), st.st_size
787            return ("path", str(norm(path))), st.st_size
788        except OSError:
789            return None, 0
790
791    def 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
793        picture reader, the packs and the draft layer folders.  {file identity: bytes}, wherever they live (the Strata folders or the
794        person's own)."""
795        files, dirs = self.model_paths(cfg)
796        paths = list(files)
797        vis = cfg.get("vision")
798        if isinstance(vis, dict) and isinstance(vis.get("mmproj"), str):
799            paths.append(Path(vis["mmproj"]))
800        for f in list(paths):                           # the other parts of a multi-part file
801            m = SHARD_NAME.match(str(f))
802            if m:
803                paths += [Path(f"{m.group(1)}-{i:05d}-of-{m.group(3)}.gguf") for i in range(1, int(m.group(3)) + 1)]
804        for d in dirs:
805            for base, _sub, names in os.walk(d):
806                paths += [Path(base) / n for n in names]
807        out = {}
808        for p in paths:
809            if p.is_file():
810                key, size = self.file_key(p)
811                if key is not None:
812                    out[key] = size
813        return out
814
815    def 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
818        every other model's; rows plus 'shared' add up to the total."""
819        per = {c.stem[len("strata-"):]: self.used_files(self.read_config(c)) for c in self.configs()}
820        owners: dict = {}
821        for files in per.values():
822            for k in files:
823                owners[k] = owners.get(k, 0) + 1
824        models, shared = {}, {}
825        for tag, files in per.items():
826            own = sum(b for k, b in files.items() if owners[k] == 1)
827            models[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)}
829            shared.update({k: b for k, b in files.items() if owners[k] > 1})
830        shared_bytes = sum(shared.values())
831        total = sum(m["bytes"] for m in models.values()) + shared_bytes
832        return {"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
836    def 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)."""
839        try:
840            if is_dir:
841                return any((p / n).is_file() for n in ("conversions.json", "experts.bin.src.json"))
842            return p.with_name(p.name + ".done").is_file()
843        except OSError:
844            return False
845
846    def 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."""
849        cfg = self.read_config(config)
850        files, dirs = self.model_paths(cfg)
851        files = self.with_shards(files)
852        used_files, used_dirs = set(), set()
853        for other in self.configs():
854            if norm(other) == norm(config):
855                continue
856            f, d = self.model_paths(self.read_config(other))
857            f = self.with_shards(f)
858            used_files |= {norm(x) for x in f}
859            used_dirs |= {norm(x) for x in d}
860        remove, keep = [], []
861
862        def shared(p: Path, is_dir: bool) -> bool:
863            n = norm(p)
864            if 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:
865                return True
866            return any(is_inside(n, u) for u in used_dirs)
867
868        for p, is_dir in [(x, False) for x in files] + [(x, True) for x in dirs]:
869            if not p.exists():
870                continue
871            if not self.allowed(p) and not self.made_by_strata(p, is_dir):
872                keep.append({"path": str(p), "reason": "outside Strata's folders"})
873            elif shared(p, is_dir):
874                keep.append({"path": str(p), "reason": "another installed model still uses it"})
875            else:
876                remove.append({"path": str(p), "kind": "folder" if is_dir else "file", "bytes": self.tree_bytes(p)})
877                if not is_dir:
878                    for extra in (p.with_name(p.name + ".done"), p.with_name(p.name + ".part"),
879                                  p.with_name(p.name + ".part.chunks")):
880                        if extra.exists():
881                            remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)})
882        tag = config.stem[len("strata-"):]
883        for extra in (config, config.with_name(config.name + ".bak"), config.with_name(f"strata-{tag}.log"),
884                      self.root / f"run-{tag}.bat", self.root / f"run-{tag}.sh"):
885            if extra.exists():
886                remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)})
887        total = sum(x["bytes"] for x in remove)
888        return {"model": tag, "remove": remove, "keep": keep, "bytes": total, "gb": round(total / 1e9, 2)}
889
890    def find_config(self, model: str | None) -> Path:
891        have = self.configs()
892        if not have:
893            raise ToolError("no model is installed in " + str(self.root) + " yet: install one first (strata_install)")
894        if not model:
895            return have[0]                              # the most recently used, as setup starts it
896        m = model.strip().lower()
897        exact = [c for c in have if c.stem[len("strata-"):] == m]
898        if exact:
899            return exact[0]
900        by_name = [c for c in have if str(self.read_config(c).get("model_name", "")).lower() == m]
901        if by_name:
902            return by_name[0]
903        ends = [c for c in have if c.stem.endswith("-" + m)]
904        if len(ends) == 1:
905            return ends[0]
906        raise ToolError(f"no installed model {model!r}; installed: " +
907                        ", ".join(c.stem[len("strata-"):] for c in have))
908
909    def engine_info(self) -> dict:
910        for d in ("engine",):
911            try:
912                meta = json.loads((self.root / d / "BUILD.json").read_text())
913                return {"folder": d, "version": meta.get("version"), "source": meta.get("source"),
914                        "backend": meta.get("backend")}
915            except (OSError, ValueError):
916                continue
917        return {"folder": None, "version": None}
918
919    def installed(self) -> dict:
920        data = self.data_dir()
921        items = {}
922        for sub in ("models", "packs"):
923            for base in dict.fromkeys([data, self.root]):
924                d = base / sub
925                if d.is_dir():
926                    for c in sorted(d.iterdir()):
927                        if c.is_dir():
928                            ggufs = list(c.glob("*.gguf"))
929                            entry = {"folder": str(c), "size_gb": dir_size_gb(c)}
930                            if sub == "models":
931                                entry["complete"] = bool(ggufs) and all(
932                                    g.with_name(g.name + ".done").exists() for g in ggufs)
933                                entry["downloading"] = bool(list(c.glob("*.part")))
934                            items.setdefault(sub, []).append(entry)
935        mtp = data / "mtp" / "rt" / "experts.bin"
936        usage = self.disk_usage()
937        return {"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
945    def hardware(self, fresh=False) -> dict:
946        if self._hw_cache and not fresh and time.time() - self._hw_cache[0] < 600:
947            hw = dict(self._hw_cache[1])
948        else:
949            hw = self._hardware()
950            self._hw_cache = (time.time(), hw)
951            hw = dict(hw)
952        hw["disk_free_gb"] = self.disk_free(self.data_dir())
953        return hw
954
955    @staticmethod
956    def disk_free(p: Path) -> float | None:
957        p = Path(p)
958        while not p.exists() and p.parent != p:
959            p = p.parent
960        try:
961            return round(shutil.disk_usage(p).free / 1e9, 1)
962        except OSError:
963            return None
964
965    def _hardware(self) -> dict:
966        S = self.setup_module()
967        hw = {"os": f"{platform.system()} {platform.release()}", "os_version": platform.version(),
968              "machine": platform.machine(), "python": platform.python_version()}
969        if not WIN and Path("/proc/version").exists():
970            try:
971                hw["wsl"] = "microsoft" in Path("/proc/version").read_text().lower()
972            except OSError:
973                pass
974        try:
975            hw["ram_gb"] = round(S.ram_gb(), 1) if S else round(own_ram_gb(), 1)
976        except Exception:                               # noqa: BLE001
977            hw["ram_gb"] = round(own_ram_gb(), 1)
978        if S and WIN:
979            try:
980                hw["page_file_gb"] = round(S.page_file_gb(), 1)
981            except Exception:                           # noqa: BLE001
982                pass
983        try:
984            if S:
985                name, avx2, avx512 = S.cpu_info()
986            else:
987                name, avx2, avx512 = platform.processor() or "unknown CPU", None, None
988            hw["cpu"] = {"name": name, "cores": physical_cores(), "threads": os.cpu_count(), "avx2": avx2, "avx512": avx512}
989        except Exception:                               # noqa: BLE001
990            hw["cpu"] = {"name": platform.processor(), "cores": physical_cores(), "threads": os.cpu_count()}
991        if sys.platform == "darwin":                    # a Mac: one pool of unified memory, the Metal engine (strata_control/mac_fit.py)
992            return self._mac_hardware(hw)
993        nv = []
994        try:
995            nv = S.gpus() if S else own_nvidia_gpus()
996        except Exception:                               # noqa: BLE001
997            nv = own_nvidia_gpus()
998        for g in nv:
999            g["vendor"] = "nvidia"
1000            g["vram_gb"] = round(g["vram_gb"], 1)
1001            try:
1002                g["problem"] = S.gpu_problem(g) if S else (None if int(g["arch"]) >= 75 else "older than RTX 20")
1003            except Exception:                           # noqa: BLE001
1004                g["problem"] = None
1005            g["usable"] = g["problem"] is None
1006        amd = []
1007        try:                                            # Linux: the kernel's KFD topology; Windows: the display adapters' PCI ids + registry (setup.amd_gpus_win)
1008            amd = S.amd_gpus() if S else []
1009            for g in amd:
1010                g["vendor"] = "amd"
1011                g["vram_gb"] = round(g["vram_gb"], 1)
1012                g["problem"] = S.amd_problem(g)
1013                g["usable"] = g["problem"] is None
1014        except Exception:                               # noqa: BLE001
1015            amd = []
1016        if not WIN and not amd and shutil.which("rocm-smi"):
1017            amd = rocm_smi_gpus()
1018        if not WIN and not amd:                         # no setup module, no rocm-smi (ROCm from a Python venv): the kernel's own list
1019            amd = 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.
1023        try:
1024            if S and nv and S.old_gpus_opt_in(nv, (), None, any(g.get("usable") for g in amd)):
1025                for g in nv:
1026                    if S.sm60_card(g["arch"]) and g.get("problem") and "older than the RTX 20" in str(g["problem"]):
1027                        g["problem"], g["usable"], g["engine_variant"] = None, True, "cuda12"
1028        except Exception:                               # noqa: BLE001 - the hardware page never breaks over this
1029            pass
1030        if any(g.get("usable") for g in nv):
1031            for g in amd:                             # a Ryzen's integrated graphics beside an NVIDIA card: the engine runs on the NVIDIA card
1032                if g.get("uma") and g.get("usable"):
1033                    g["usable"], g["problem"] = False, "integrated graphics: Strata uses the NVIDIA card in this computer"
1034        try:                                            # does the card drive a display?  (the app keeps less VRAM free on one that does not, #3215)
1035            mark_display(nv + amd, nvidia_display_active() if nv else {}, windows_desktop_adapters() if WIN and amd else [])
1036        except Exception:                               # noqa: BLE001 - unknown stays unknown: the app then keeps its safety default
1037            pass
1038        try:                                            # 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:...").
1041            if WIN and amd:
1042                if str(self.src) not in sys.path:
1043                    sys.path.insert(0, str(self.src))
1044                from strata_control import setup_config
1045                for g in amd:
1046                    arch = str(g.get("arch") or "")
1047                    if g.get("uma") and (arch == "gfx1151" or arch.startswith("gfx1151:")):
1048                        g["setup_reserve_mib"] = setup_config.UMA_WIN_RESERVE_MIB
1049        except Exception:                               # noqa: BLE001 - an older Control folder: no field, the app keeps its own floor
1050            pass
1051        arc = []
1052        if 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)
1053            try:
1054                if str(self.src) not in sys.path:
1055                    sys.path.insert(0, str(self.src))
1056                from strata_control import intel_app
1057                arc = intel_app.cards_to_add(nv, amd)
1058            except Exception:                           # noqa: BLE001 - an older Control folder without it: the report is what it was
1059                arc = []
1060        hw["gpus"] = nv + amd + arc
1061        for g in hw["gpus"]:                            # each make numbers its cards from 0 (the engine drives one make): a stable id tells two cards apart
1062            g.setdefault("id", f"{g.get('vendor') or 'gpu'}:{g.get('index')}")
1063        try:                                            # how fast each card is (SMs x clock): the app and the Terminal pick the Main card by it
1064            from strata_control import gpu_roles
1065            gpu_roles.add_speeds(hw["gpus"])
1066        except Exception:                               # noqa: BLE001 - unknown speed: the card with the most memory is Main
1067            pass
1068        self._engine_code(hw)
1069        self._engine_vendor(hw)
1070        if WIN:
1071            hw["display_adapters"] = windows_video_controllers()
1072        hw["nvidia_smi"] = bool(shutil.which("nvidia-smi"))
1073        return hw
1074
1075    @staticmethod
1076    def _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
1078        unusable with the plain reason, so the card lists and "Automatic" leave it out.  Only a package that lists its archs speaks here."""
1079        amd = [g for g in hw.get("gpus", []) if g.get("vendor") == "amd" and g.get("arch")]
1080        if not amd:
1081            return
1082        try:
1083            from strata_control import engine_component as ec
1084            rep = ec.status()
1085            eng = rep.get("engine") or {}
1086            built = [a for a in eng.get("archs") or [] if str(a).startswith("gfx")]
1087            if not rep.get("usable") or eng.get("backend") != "hip" or not built:
1088                return
1089        except Exception:                               # noqa: BLE001 - never break the hardware page over this
1090            return
1091        for g in amd:
1092            if g["arch"] not in built and g.get("usable") is not False:
1093                g["usable"] = False
1094                g["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
1097    def _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
1099        setup fetches first) and, when the other make has the bigger card, the one plain line that says so. The model list below only counts
1100        the cards this engine can drive; a model is never split across makes (strata_control/gpu_fit.py)."""
1101        try:
1102            from strata_control import gpu_fit
1103            backend = None
1104            try:
1105                from strata_control import engine_component as ec
1106                rep = ec.status()
1107                backend = (rep.get("engine") or {}).get("backend") if rep.get("usable") else None
1108            except Exception:                           # noqa: BLE001
1109                backend = None
1110            vendor = gpu_fit.pick_vendor(hw.get("gpus", []), backend)
1111            hw["engine_vendor"] = vendor
1112            note = gpu_fit.other_vendor_note(hw.get("gpus", []), vendor)
1113            if note:
1114                hw["gpu_note"] = note
1115        except Exception:                               # noqa: BLE001 - never break the hardware page over this
1116            pass
1117
1118    @staticmethod
1119    def 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)."""
1121        hw = hw or {}
1122        vendor = hw.get("engine_vendor")
1123        return [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.
1127    def mac(self):
1128        """strata_control/mac_fit.py, or None when this Strata folder does not carry it."""
1129        try:
1130            if str(self.src) not in sys.path:
1131                sys.path.insert(0, str(self.src))
1132            from strata_control import mac_fit
1133            return mac_fit
1134        except Exception as e:                          # noqa: BLE001
1135            log(f"strata_control/mac_fit.py could not be imported ({e})")
1136            return None
1137
1138    def _mac_hardware(self, hw: dict) -> dict:
1139        mf = self.mac()
1140        info = 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"}
1142        problems = mf.mac_problems(info, need_compiler=False) if mf else []
1143        ram = round(float(info.get("ram_gb") or hw.get("ram_gb") or 0.0), 1)
1144        hw["ram_gb"] = ram
1145        hw["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).
1147        hw["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}]
1149        hw["mac"] = {"chip": info["chip"], "macos": info.get("macos"), "unified_gb": ram}
1150        hw["nvidia_smi"] = False
1151        return hw
1152
1153    def _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
1155        file, no repack) and, since round 0214, Unsloth's sets (many shards: setup.py's Mac install repacks them with
1156        metal/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")."""
1157        mf = self.mac()
1158        return [m for m in mf.app_sizes(family) if m in models] if mf else []
1159
1160    def _mac_verdict(self, model: str, ram: float) -> str:
1161        mf = self.mac()
1162        from strata_control import fit_label
1163        if ram < mf.MIN_STREAM_RAM_GB:
1164            return fit_label.SLOWER                          # too little memory for the Metal engine's streaming: the same two words, said not refused
1165        return 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
1167    def _mac_recommend(self, hw: dict, models: dict, families: dict) -> dict:
1168        mf = self.mac()
1169        ram = float(hw.get("ram_gb") or 0)
1170        usable = [g for g in hw.get("gpus", []) if g.get("usable")]
1171        if not mf or not usable:
1172            why = (hw.get("gpus") or [{}])[0].get("problem") or "this Mac cannot run the Metal engine"
1173            return {"family": None, "model": None, "why": why}
1174        if ram < mf.MIN_STREAM_RAM_GB:
1175            return {"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)"}
1177        model, notes = mf.recommend_model(ram)
1178        notes = [n for n in notes if "UD-Q4_K_XL" not in n]          # the app does not offer the Unsloth files yet
1179        if model not in self._mac_sizes(models):
1180            model = "Q2_0"
1181        if mf.streams(model, ram):
1182            speed = mf.STREAM_MEASURED.get(model)
1183            why = (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 ""))
1185        else:
1186            why = f"{ram:.0f} GB of unified memory: {model} stays in memory (the best size that does)"
1187        ctx = mf.recommend_context(ram)
1188        return {"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
1193    def _mac_model_table(self, hw: dict) -> list:
1194        models, families, _ctx, _src = self.tables()
1195        from strata_control import fit_label
1196        ram = float(hw.get("ram_gb") or 0)
1197        have = {c.stem[len("strata-"):] for c in self.configs()}
1198        out = []
1199        for family in (self.mac().all_families() if self.mac() else ("qwen", "gyro")):      # Qwen, Unsloth's sets, then Gyro: never the default
1200            fd = families.get(family)
1201            if fd is None:
1202                continue
1203            sizes = []
1204            for m in self._mac_sizes(models, family):
1205                d = models[m]
1206                tag = (fd.get("tag", "") + m).lower()
1207                sizes.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})
1213            if sizes:
1214                out.append({"family": family, "title": fd["title"], "about": fd.get("about"), "experimental": False,
1215                            "images": any(x["images"] for x in sizes), "sizes": sizes})
1216        return self._feed_rows(out, self.setup_module())
1217
1218    def 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
1220        Coder below the full model's RAM (setup's RAM table), the low-RAM mode when the GPU makes up for the RAM, and
1221        the context it preselects for the card's VRAM (32K under 14 GB, 64K under 20 GB, else 128K)."""
1222        models, families, _ctx, _src = self.tables()
1223        if hw.get("mac"):
1224            return self._mac_recommend(hw, models, families)
1225        S = self.setup_module()
1226        usable = self.engine_gpus(hw)
1227        ram = hw.get("ram_gb") or 0
1228        if not usable:
1229            why = ("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()
1232                       for a in hw.get("display_adapters", [])) else ""))
1233            return {"family": None, "model": None, "why": why}
1234        best = max(usable, key=lambda g: (round(g["vram_gb"]), -g.get("index", 0)))
1235        vram = best["vram_gb"]
1236        backend = "hip" if best.get("vendor") == "amd" else "sycl" if best.get("vendor") == "intel" else "cuda"
1237
1238        def low_fits(m):
1239            try:
1240                return S.low_ram_fits(m, ram, vram) if S else ram - 6 + max(0.0, vram - 5 - 1.0) >= models[m]["arena_gb"]
1241            except Exception:                           # noqa: BLE001
1242                return False
1243        notes = []
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.
1246        tvram = float(best.get("dedicated_gb", 0.0)) if best.get("uma") else float(vram)
1247        tier = next(((f, n) for lo, f, n in MEMORY_TIERS if ram + tvram - TIER_SYSTEM_RESERVE_GB >= lo), None)
1248        if tier and tier[1] in models and tier[0] in families:
1249            fam, model = tier
1250            total = 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"
1251            if model == "IQ2_XS":
1252                why = (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 ""))
1255            elif model == "IQ3_XXS":
1256                why = f"{total}, the 48 GB tier: IQ3_XXS (better quality, slower)"
1257            else:
1258                why = (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")
1260        elif ram >= 60:
1261            fam, model, why = "qwen", "IQ3_XXS", f"{ram:.0f} GB of RAM: setup's own pick from 60 GB (better quality)"
1262        elif ram >= models["Q2_0"]["ram_gb"] - 4:
1263            fam, model, why = "qwen", "Q2_0", f"{ram:.0f} GB of RAM: the full model's fastest size fits"
1264        elif ram >= models["IQ1_M"]["ram_gb"] - 4:
1265            fam, 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")
1267        elif low_fits("IQ1_M"):
1268            fam, model, why = "coder", "IQ1_M", (f"{ram:.0f} GB of RAM is below the Coder's 32 GB, but the GPU's "
1269                                                 f"{vram:.0f} GB make up for it (setup's low-RAM mode: slower)")
1270        elif "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.
1274            model = "Gyro-M" if ram + vram >= models["Gyro-M"]["ram_gb"] + GYRO_ROOM_GB else "Gyro-S"
1275            fam, why = "gyro", (f"{ram:.0f} GB of RAM is below the Coder's 32 GB, but RAM + VRAM = {ram + vram:.0f} GB "
1276                                f"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)")
1278        else:
1279            return {"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)"}
1282        ctx = 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.
1286        arena = float(models[model].get("arena_gb") or 0)
1287        spill = arena - max(0.0, tvram - 6.0) - max(0.0, ram - 10.0)
1288        if arena and spill >= 4.0:
1289            notes.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")
1292        if vram < 11:
1293            notes.append("less than 12 GB of VRAM: it runs, but slowly (most experts stay on the CPU)")
1294        if hw.get("cpu", {}).get("avx2") is False:      # #623: a warning, not a stop (setup compiles for it)
1295            notes.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")
1297        if backend == "hip":
1298            notes.append("AMD (experimental): pictures are on; the reader runs on the CPU under 24 GB of VRAM and on the GPU from 24 GB")
1299        if backend == "sycl":
1300            from strata_control import intel_app
1301            notes.append(intel_app.NO_DOWNLOAD)
1302        cmd = (("START-HERE.bat --setup" if WIN else "./setup.sh --setup") +
1303               f" --yes --family {fam} --model {model} --context {ctx}" + (f" --backend {backend}" if backend in ("hip", "sycl") else ""))
1304        return {"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
1308    def model_table(self, hw: dict | None) -> list:
1309        if (hw or {}).get("mac"):
1310            return self._mac_model_table(hw)
1311        models, families, _ctx, _src = self.tables()
1312        S = self.setup_module()
1313        ram = (hw or {}).get("ram_gb")
1314        usable = self.engine_gpus(hw)
1315        vram = max((g["vram_gb"] for g in usable), default=0.0)
1316        from strata_control import fit_label
1317        card_room = fit_label.card_room_gb(usable)
1318        have = {c.stem[len("strata-"):] for c in self.configs()}
1319        out = []
1320        for 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)
1321            sizes = []
1322            for m in self.sizes_of(models, f):
1323                own = self.own_size(f, m)
1324                d = own or models[m]
1325                tag = (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)
1328                memory_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)
1329                fit_gb = fit_label.files_gb(f, m, d)          # what the label and the Terminal's "Needs" column use
1330                verdict = None
1331                if ram is not None:
1332                    verdict = fit_label.label(fit_gb, ram, card_room)
1333                sizes.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
1356            out.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})
1360        return self._feed_rows(out, S)
1361
1362    def _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)."""
1365        unavailable = (getattr(S, "FEED_UNAVAILABLE", None) or {}) if S else {}
1366        for row in out:
1367            if (getattr(S, "FEED_MODELS", None) or {}).get(row["family"]):
1368                row["feed"] = True
1369                if row["family"] in unavailable:
1370                    row["available"], row["unavailable_reason"] = False, unavailable[row["family"]]["reason"]
1371        for fid, u in unavailable.items():
1372            if not any(r["family"] == fid for r in out):
1373                out.append({"family": fid, "title": u["title"], "about": u["reason"], "experimental": False, "images": False, "sizes": [], "feed": True,
1374                            "available": False, "unavailable_reason": u["reason"]})
1375        return out
1376
1377    @staticmethod
1378    def images_reader(vram) -> str:
1379        try:
1380            from strata_control import vision_reader
1381            return vision_reader.default_mode(vram) if vram else "cpu"
1382        except Exception:                                  # noqa: BLE001
1383            return "cpu"
1384
1385    @staticmethod
1386    def gpu_options(d: dict, ram, hw) -> dict | None:
1387        try:
1388            from strata_control import gpu_fit
1389            mem = float(d["ram_gb"]) if d.get("mem_total") else float(d.get("arena_gb") or d["ram_gb"]) + 1.0
1390            res = gpu_fit.options(round(mem, 1), ram, (hw or {}).get("gpus", []), (hw or {}).get("engine_vendor"))
1391            if len(res["options"]) >= 2:
1392                return 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
1394            return {"options": [], "recommended": None, "other_vendor_note": res.get("other_vendor_note")} if res.get("other_vendor_note") else None
1395        except Exception:                                  # noqa: BLE001 - the choice is a convenience: never break the model list
1396            return None
1397
1398    # ---- the running server
1399    def ports(self, port: int | None) -> list[int]:
1400        if port:
1401            return [port]
1402        ps = [self.state("server").get("port")] + [self.describe_config(c)["port"] for c in self.configs()]
1403        return list(dict.fromkeys(int(p) for p in [*ps, DEFAULT_PORT] if isinstance(p, int)))
1404
1405    def 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)."""
1407        def real(cfg):                                   # "api_key": "none" = served without a key on purpose
1408            k = cfg.get("api_key")
1409            return k if k and str(k).strip().lower() != "none" else None
1410        for c in self.configs():
1411            cfg = self.read_config(c)
1412            if real(cfg) and int(cfg.get("port", DEFAULT_PORT)) == port:
1413                return cfg["api_key"]
1414        for c in self.configs():
1415            if real(self.read_config(c)):
1416                return self.read_config(c)["api_key"]
1417        return None
1418
1419    def 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
1421        nothing."""
1422        base = f"http://127.0.0.1:{port}"
1423        st, health = http_json(base + "/health", timeout=self.health_timeout)
1424        if st == 0:
1425            return None
1426        if st != 200 or not isinstance(health, dict) or health.get("service") != "strata":
1427            return {"port": port, "other": True, "note": "something else answers on this port (not a Strata server)"}
1428        info = {"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"))}
1431        if not deep:
1432            return info
1433        key = self.api_key_for(port)
1434        st, v1 = http_json(base + "/v1/status", api_key=key, timeout=self.health_timeout)
1435        if st == 200 and isinstance(v1, dict):
1436            info["engine_version"] = v1.get("engine")
1437            info["uptime_s"] = v1.get("uptime_s")
1438            info["requests_served"] = (v1.get("activity") or {}).get("requests")
1439            m = v1.get("machine") or {}
1440            if m.get("gpu"):
1441                info["gpu"] = m["gpu"]
1442            if m.get("ram"):
1443                info["ram"] = m["ram"]
1444            if v1.get("last_timings"):
1445                lt = v1["last_timings"]
1446                info["last_request"] = {k: lt.get(k) for k in ("prompt_n", "prompt_per_second", "predicted_n",
1447                                                               "predicted_per_second") if k in lt}
1448        elif st == 401:
1449            info["note"] = "the server wants an API key this folder's configs do not have"
1450        st, s = http_json(base + "/status", api_key=key, timeout=self.health_timeout)
1451        if st == 200 and isinstance(s, dict):
1452            info["busy"] = bool(s.get("busy"))
1453            info["activity"] = {k: s.get(k) for k in ("phase", "generated", "tokens_per_s", "queued", "elapsed_s")
1454                                if s.get(k) is not None}
1455        if "gpu" not in info:                           # older servers: the Monitor's numbers
1456            st, met = http_json(base + "/metrics", api_key=key, timeout=self.health_timeout)
1457            if st == 200 and isinstance(met, dict):
1458                hwn = met.get("hardware") or {}
1459                if hwn.get("gpu_mem_total"):
1460                    info["gpu"] = {"used_mib": round(hwn.get("gpu_mem_used", 0) / 2**20),
1461                                   "total_mib": round(hwn["gpu_mem_total"] / 2**20)}
1462                if hwn.get("ram_total"):
1463                    info["ram"] = {"used_gib": round(hwn.get("ram_used", 0) / 2**30, 1),
1464                                   "total_gib": round(hwn["ram_total"] / 2**30, 1)}
1465                info["engine_version"] = (met.get("engine") or {}).get("version")
1466        return info
1467
1468    def tracked_server(self) -> dict | None:
1469        """The server this MCP server started, while it still runs (else its record is cleared)."""
1470        s = self.state("server")
1471        if not s:
1472            return None
1473        if proc_alive(s.get("pid"), s.get("ident")):
1474            return s
1475        return {**s, "ended": True}
1476
1477    # ---- install job
1478    def install_job(self) -> dict | None:
1479        j = self.state("install")
1480        if not j:
1481            return None
1482        res = self.state("install-result")
1483        running = proc_alive(j.get("pid"), j.get("ident"))
1484        log_path = Path(j.get("log", ""))
1485        tail = 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
1486        prog = install_progress(tail)
1487        prog = combined_progress(prog, j)
1488        out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"),
1489               "log": str(log_path), **prog}
1490        if not running:
1491            if res.get("job") == j.get("job") and "exit_code" in res:
1492                out["exit_code"] = res["exit_code"]
1493                out["finished"] = res.get("ended")
1494                out["result"] = "installed" if res["exit_code"] == 0 else "failed"
1495            else:
1496                out["result"] = "ended unexpectedly (no exit code recorded)"
1497        else:
1498            out["result"] = "running"
1499        out["last_lines"] = tail[-12:]
1500        return 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
1509    downloaded (<part>.part).  A config that names only the first part used to look finished with one part of four on disk."""
1510    gaps = []
1511    for g in ggufs:
1512        m = SHARD_NAME.match(str(g))
1513        if not m:
1514            continue
1515        for i in range(1, int(m.group(3)) + 1):
1516            sib = Path(f"{m.group(1)}-{i:05d}-of-{m.group(3)}.gguf")
1517            if not sib.is_file() or sib.with_name(sib.name + ".part").exists():
1518                gaps.append(str(sib))
1519    return 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).
1525    Empty when the setup module cannot say (the caller then falls back to the folder scan)."""
1526    out = []
1527    try:
1528        own = (getattr(S, "OWN_PATH_FAMILIES", None) or {}).get(family)
1529        if own:                                         # Qwen3.6: the GGUF and the picture reader in the model's folder
1530            folder = Path(models_dir) / (own["tag"] + model)
1531            name = own["file"].format(q=model)
1532            out.append({"path": str(folder / name), "bytes": own["sha256"][name][0], "role": "model"})
1533            if vision:
1534                out.append({"path": str(folder / own["mmproj"]), "bytes": own["sha256"][own["mmproj"]][0], "role": "vision"})
1535            return out
1536        fam, d = S.FAMILIES[family], S.MODELS[model]
1537        if d.get("repo"):                               # NVFP4: a ready-made pack, many files with pinned sizes
1538            for f in S.ready_needed(model, Path(models_dir)):
1539                out.append({"path": str(S.ready_where(Path(models_dir), f)), "bytes": f[4], "role": "model"})
1540        else:
1541            folder = Path(models_dir) / (fam.get("tag", "") + model)
1542            for i in range(1, S.model_shards(fam, model) + 1):
1543                out.append({"path": str(folder / S.model_file(fam, model, i)), "bytes": None, "role": "model"})
1544        if vision:                                      # beside the model folders, not inside them (setup step 5)
1545            size = (fam.get("mmproj_sha256") or (None,))[0] or DEFAULT_MMPROJ_BYTES
1546            out.append({"path": str(Path(models_dir) / fam.get("mmproj", S.MMPROJ)), "bytes": size, "role": "vision"})
1547    except Exception:                                   # noqa: BLE001 - progress is a convenience: never break the install
1548        return []
1549    return 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
1554    of 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
1555    does not make the model downloaded."""
1556    log = prog.get("download") or {}
1557    cur_gb = float(log.get("total_gb") or 0)
1558    rows = []
1559    for f in files:
1560        p = Path(f["path"])
1561        part = p.with_name(p.name + ".part")
1562        try:
1563            if part.is_file():
1564                state, have = "downloading", part.stat().st_size
1565            elif p.is_file():
1566                state, have = "done", p.stat().st_size
1567            else:
1568                state, have = "waiting", 0
1569        except OSError:
1570            state, have = "waiting", 0
1571        total = f.get("bytes") or (have if state == "done" else 0)
1572        named = p.name in str(log.get("file", "")) or (f.get("role") == "vision" and str(log.get("file", "")).startswith("vision encoder"))
1573        if 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.
1576            have = min(have, int(float(log.get("done_gb") or 0) * 1e9)) if have else have
1577            if not total:
1578                total = int(cur_gb * 1e9)
1579        rows.append({"role": f.get("role", "model"), "state": state, "have": have, "total": max(total, have)})
1580    plan_total = float(job.get("total_gb") or 0) * 1e9
1581    parts = []
1582    for role, name in (("model", "Model files"), ("vision", "Picture reader")):
1583        mine = [r for r in rows if r["role"] == role]
1584        if not mine:
1585            continue
1586        have = sum(r["have"] for r in mine)
1587        known = sum(r["total"] for r in mine)
1588        total = known if all(r["total"] for r in mine) else max(plan_total if role == "model" else 0, known, have)
1589        k = sum(1 for r in mine if r["state"] == "done")
1590        state = "done" if k == len(mine) else "downloading" if any(r["state"] == "downloading" for r in mine) or k else "waiting"
1591        parts.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)})
1593    total_gb = sum(x["total_gb"] for x in parts)
1594    done_gb = min(sum(x["done_gb"] for x in parts), total_gb)
1595    active = next((x for x in parts if x["state"] != "done"), parts[-1] if parts else None)
1596    if active and active["state"] == "waiting" and any(x["state"] == "done" for x in parts):
1597        active = dict(active, state="downloading")
1598    prog["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}
1603    prog["parts"] = parts
1604    return 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
1609    the 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)."""
1610    done_gb, total_gb = float(dl.get("done_gb") or 0), float(dl.get("total_gb") or 0)
1611    parts = []
1612    if job.get("files"):
1613        base = files_progress({}, job, job["files"])
1614        parts = [dict(p, state="done", done_gb=p["total_gb"]) for p in base.get("parts", []) if p.get("state") == "done"]
1615    parts.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)})
1617    total = sum(p["total_gb"] for p in parts)
1618    done = min(sum(p["done_gb"] for p in parts), total)
1619    prog["parts"] = parts
1620    prog["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}
1623    return 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
1628    model's folder) over the download size, instead of each file's own 0-100% (a two-file model went 70 GB -> 0 -> up
1629    again). Only while the download step runs; later steps are not a download."""
1630    folder, total = job.get("folder"), job.get("total_gb")
1631    step = str(prog.get("step") or "")
1632    dl = prog.get("download") or {}
1633    if step.startswith("6/") and str(dl.get("file", "")).startswith("MTP draft layer"):
1634        return draft_progress(prog, job, dl)
1635    if 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%")
1637        if job.get("files"):
1638            prog = files_progress(prog, job, job["files"])
1639        prog["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"])}
1641        return prog
1642    if job.get("files") and step.startswith("5/"):      # the install knows its files: count each of them
1643        return files_progress(prog, job, job["files"])
1644    if 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")
1647        prog = files_progress(prog, job, job["files"])
1648        prog.pop("download", None)
1649        return prog
1650    if not folder or not total or not step.startswith("5/"):
1651        prog.pop("download", None)
1652        return prog
1653    done = 0
1654    try:
1655        for entry in os.scandir(folder):
1656            if entry.is_file() and (entry.name.endswith(".gguf") or entry.name.endswith(".part")):
1657                done += entry.stat().st_size
1658    except OSError:
1659        pass
1660    if not done:                                        # nothing on disk yet: the log's own line is all there is
1661        return prog
1662    done_gb = min(done / 1e9, float(total))
1663    prog["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}
1668    prog["parts"] = [{"kind": "model", "name": "Model files", "done_gb": prog["download"]["done_gb"],
1669                      "total_gb": float(total), "state": "downloading"}]
1670    return 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."""
1675    step, title, dl, err = None, None, None, None
1676    for i, line in enumerate(lines):
1677        m = re.search(r"=== Step (\d+): (.+?) ===", line)
1678        if m:
1679            step, title, err, dl = int(m.group(1)), m.group(2), None, None      # a download figure belongs to its own step
1680        m = re.match(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)", line)
1681        if m:
1682            dl = {"file": m.group(1), "done_gb": float(m.group(2)), "total_gb": float(m.group(3)),
1683                  "percent": int(m.group(4))}
1684        if line.strip().startswith("[X]"):
1685            err = line.strip()[3:].strip()
1686            if i + 1 < len(lines) and lines[i + 1].startswith("       "):
1687                err += " - " + lines[i + 1].strip()
1688    out = {"step": f"{step}/7: {title}" if step else None}
1689    if dl:
1690        out["download"] = dl
1691    if err:
1692        out["error"] = err
1693    words = progress_words_for(step, lines, dl)
1694    if words:
1695        out["label"], out["phase"] = words
1696    return 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
1701    80% of that for --pool-workers, more than the cores, #3417).  Falls back to the thread count when the machine cannot say."""
1702    try:
1703        from strata_control import tune_machine
1704        n = tune_machine.cpu().get("physical")
1705        if isinstance(n, int) and n > 0:
1706            return n
1707    except Exception:                                   # noqa: BLE001 - a hardware report must never fail on this
1708        pass
1709    return 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);
1714    None when this Strata folder does not carry the module."""
1715    try:
1716        from strata_control import progress_words
1717    except ImportError:
1718        return None
1719    w = progress_words.describe(step, lines, download)
1720    return w.label, w.phase
1721
1722
1723def own_ram_gb() -> float:
1724    if WIN:
1725        class 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"))]
1728        m = MS()
1729        m.dwLength = ctypes.sizeof(MS)
1730        ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
1731        return m.tp / 2**30
1732    try:
1733        for line in open("/proc/meminfo"):
1734            if line.startswith("MemTotal"):
1735                return int(line.split()[1]) * 1024 / 2**30
1736    except OSError:
1737        pass
1738    return 0.0
1739
1740
1741def own_nvidia_gpus() -> list:
1742    s = run_quiet(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,driver_version",
1743                   "--format=csv,noheader,nounits"])
1744    found = []
1745    for line in s.strip().splitlines():
1746        try:
1747            idx, name, mem, cc, drv = [x.strip() for x in line.split(",")]
1748            try:
1749                mem_gb = float(mem) / 1024.0
1750            except ValueError:
1751                if platform.machine().lower() not in ("aarch64", "arm64"):
1752                    raise            # 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)
1755                shared = max(0.0, own_ram_gb() - 6)
1756                found.append({"index": int(idx), "name": name, "vram_gb": shared, "arch": cc.replace(".", ""), "driver": drv,
1757                              "uma": True, "dedicated_gb": 0.0, "shared_gb": shared})
1758                continue
1759            found.append({"index": int(idx), "name": name, "vram_gb": mem_gb,
1760                          "arch": cc.replace(".", ""), "driver": drv})
1761        except ValueError:
1762            continue
1763    return 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."""
1768    found = {}
1769    for line in run_quiet(["nvidia-smi", "--query-gpu=index,display_active", "--format=csv,noheader"]).strip().splitlines():
1770        idx, _, state = line.partition(",")
1771        if idx.strip().isdigit() and state.strip().lower() in ("enabled", "disabled"):
1772            found[int(idx)] = state.strip().lower() == "enabled"
1773    return 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)."""
1778    out = []
1779    for line in run_quiet(["powershell", "-NoProfile", "-NonInteractive", "-Command",
1780                           "Get-CimInstance Win32_VideoController | ForEach-Object { $_.PNPDeviceID + '|' + $_.CurrentHorizontalResolution }"]
1781                          ).splitlines():
1782        pnp, _, res = line.strip().rpartition("|")
1783        if pnp and res.strip().isdigit() and int(res) > 0:
1784            out.append(pnp)
1785    return 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
1790    resolution (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
1791    unknown, and the app treats an unknown card as one that drives a display."""
1792    desk = [str(p).upper() for p in desktop_pnp]
1793    for g in gpus:
1794        if g.get("vendor") == "nvidia" and g.get("index") in nvidia_active:
1795            g["drives_display"] = nvidia_active[g["index"]]
1796        elif g.get("vendor") == "amd" and isinstance(g.get("pci_id"), int) and desktop_pnp is not None and desktop_pnp:
1797            tag = f"DEV_{g['pci_id']:04X}"
1798            twins = [x for x in gpus if x.get("vendor") == "amd" and x.get("pci_id") == g["pci_id"]]
1799            if len(twins) == 1:
1800                g["drives_display"] = any(tag in p and "VEN_1002" in p for p in desk)
1801
1802
1803def windows_video_controllers() -> list:
1804    s = run_quiet(["powershell", "-NoProfile", "-NonInteractive", "-Command",
1805                   "Get-CimInstance Win32_VideoController | Select-Object Name,DriverVersion | ConvertTo-Json -Compress"])
1806    try:
1807        d = json.loads(s) if s.strip() else []
1808    except ValueError:
1809        return []
1810    d = [d] if isinstance(d, dict) else d
1811    return [{"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
1819    driver 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).
1820    Numbered as HIP numbers them (the GPU nodes in order, CPU nodes skipped)."""
1821    base = Path(sysfs) / "class/kfd/kfd/topology/nodes"
1822    out = []
1823    try:
1824        nodes = sorted((p for p in base.iterdir() if p.name.isdigit()), key=lambda p: int(p.name))
1825    except OSError:
1826        return out
1827    for node in nodes:
1828        try:
1829            props = dict(line.partition(" ")[::2] for line in (node / "properties").read_text().splitlines())
1830            ver, simd = int(props.get("gfx_target_version") or 0), int(props.get("simd_count") or 0)
1831        except (OSError, ValueError):
1832            continue
1833        if ver == 0 or simd == 0:
1834            continue
1835        arch = f"gfx{ver // 10000}{(ver // 100) % 100:x}{ver % 100:x}"
1836        dev = Path(sysfs) / f"class/drm/renderD{props.get('drm_render_minor', '').strip()}/device"
1837        try:
1838            vram = int((dev / "mem_info_vram_total").read_text()) / 2 ** 30
1839        except (OSError, ValueError):
1840            vram = 0.0
1841        try:
1842            name = (dev / "product_name").read_text().strip() or f"AMD Radeon ({arch})"
1843        except OSError:
1844            name = f"AMD Radeon ({arch})"
1845        ok = arch in KFD_SUPPORTED
1846        out.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}"})
1848    return out
1849
1850
1851def rocm_smi_gpus() -> list:
1852    s = run_quiet(["rocm-smi", "--showproductname", "--showmeminfo", "vram", "--json"])
1853    try:
1854        d = json.loads(s)
1855    except ValueError:
1856        return []
1857    out = []
1858    for i, (card, v) in enumerate(sorted(d.items())):
1859        if not isinstance(v, dict) or not card.lower().startswith("card"):
1860            continue
1861        total = next((v[k] for k in v if "total" in k.lower() and "vram" in k.lower()), 0)
1862        try:
1863            vram = int(total) / 2**30
1864        except (TypeError, ValueError):
1865            vram = 0.0
1866        out.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)"})
1868    return 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:
1877    port = {"type": "integer", "minimum": 1024, "maximum": 65535,
1878            "description": "the server's port (default: the installed model's port, usually 8080)"}
1879    installed_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"}
1882    ro = {"readOnlyHint": True, "destructiveHint": False, "openWorldHint": False}
1883    return [
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 "
1928                                        f"{', '.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:
2015    def __init__(self, strata: Strata):
2016        self.s = strata
2017
2018    def defs(self) -> list:
2019        models, families, contexts = self.s.tables()[:3]
2020        return tool_defs({**{name: {} for name in self.s.own_size_names() if name not in models}, **models}, families, contexts)
2021
2022    def call(self, name: str, args) -> dict:
2023        defs = {d["name"]: d for d in self.defs()}
2024        if name not in defs:
2025            raise KeyError(name)
2026        args = check_schema(defs[name]["inputSchema"], args)
2027        return getattr(self, name)(**args)
2028
2029    # ---- strata_status
2030    def strata_status(self, port=None, hardware=True) -> dict:
2031        s = self.s
2032        s.reap()
2033        servers = []
2034        for p in s.ports(port):
2035            info = s.probe(p)
2036            if info is not None:
2037                servers.append(info)
2038        tracked = s.tracked_server()
2039        out = {}
2040        running = [x for x in servers if not x.get("other")]
2041        if tracked and not tracked.get("ended"):
2042            mine = next((x for x in running if x["port"] == tracked["port"]), None)
2043            if mine:
2044                mine["started_by"] = f"this MCP server (pid {tracked['pid']})"
2045            else:
2046                out["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]}
2049        elif tracked and tracked.get("ended"):
2050            out["last_start"] = {"model": tracked.get("model"), "ended": True,
2051                                 "last_log_lines": read_tail(Path(tracked.get("log", "")), 6)}
2052        for x in running:
2053            x.setdefault("started_by", "outside this MCP server (its own window, a start script or a service)")
2054        out["running"] = running
2055        others = [x for x in servers if x.get("other")]
2056        if others:
2057            out["ports_used_by_other_programs"] = others
2058        if running:
2059            r = running[0]
2060            summary = (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)"))
2063        elif "loading" in out:
2064            summary = f"Strata is loading {out['loading']['model']} (port {out['loading']['port']})"
2065        else:
2066            summary = "Strata is not running"
2067        inst = s.installed()
2068        job = s.install_job()
2069        if job:
2070            out["install"] = job
2071            if job["running"]:
2072                summary += f"; an install is running ({job.get('step') or 'starting'})"
2073        if not inst["models"]:
2074            summary += "; no model is installed yet"
2075        else:
2076            summary += "; installed: " + ", ".join(m["model"] for m in inst["models"])
2077        out["installed"] = inst
2078        if hardware:
2079            hw = s.hardware()
2080            out["hardware"] = hw
2081            out["recommendation"] = s.recommend(hw)
2082        return {"summary": summary, **out}
2083
2084    # ---- strata_models
2085    def strata_models(self) -> dict:
2086        s = self.s
2087        hw = s.hardware()
2088        _m, _f, contexts, src = s.tables()
2089        rec = s.recommend(hw)
2090        return {"summary": "Model families and sizes setup offers" + (
2091                    f"; recommended for this PC: {rec['title']}, {rec['context'] // 1024}K context"
2092                    if 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")}
2099                                     for 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
2104    def strata_remove(self, model=None, confirm=False) -> dict:
2105        s = self.s
2106        config = s.find_config(model)
2107        plan = s.removal_plan(config)
2108        if not confirm:
2109            return {"summary": f"Plan: delete {plan['model']} ({plan['gb']:.1f} GB). Nothing was done yet.", "plan": plan}
2110        with s.lock:
2111            job = s.install_job()
2112            if job and job["running"]:
2113                raise ToolError("an install is running: wait for it to finish or stop it first")
2114            tracked = s.tracked_server()
2115            if tracked and not tracked.get("ended") and tracked.get("model") == plan["model"]:
2116                raise ToolError("this model is running: stop it first")
2117            failed = []
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.
2120            for item in sorted(plan["remove"], key=lambda x: (x["path"] == str(config), x["path"])):
2121                p = Path(item["path"])
2122                try:
2123                    if p.is_dir() and not p.is_symlink():
2124                        shutil.rmtree(p, onerror=_rmtree_ignore_missing)
2125                    else:
2126                        p.unlink(missing_ok=True)
2127                except FileNotFoundError:
2128                    pass
2129                except OSError as e:
2130                    if p.exists() or p.is_symlink():
2131                        failed.append(f"{p.name}: {e}")
2132            files, dirs = s.model_paths(s.read_config(config)) if config.exists() else ([], [])
2133            for p in {x.parent for x in [Path(i["path"]) for i in plan["remove"]] if x.suffix == ".gguf"}:
2134                try:
2135                    p.rmdir()                           # the model's own folder, when nothing else is in it
2136                except OSError:
2137                    pass
2138        return {"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
2142    def check_data_dir(self, raw: str) -> Path:
2143        s = self.s
2144        if raw.startswith("\\\\") or raw.startswith("//"):
2145            raise ToolError("data_dir: network (UNC) paths are not allowed; use a local drive")
2146        p = Path(os.path.expandvars(raw)).expanduser()
2147        if not p.is_absolute():
2148            raise ToolError("data_dir must be an absolute path (e.g. D:\\Strata-data or /mnt/big/Strata-data)")
2149        if ".." in p.parts:
2150            raise ToolError("data_dir must not contain '..'")
2151        n = norm(p)
2152        current = norm(s.data_dir())
2153        if n == current or is_inside(n, norm(s.root)) or n == norm(s.root.parent / "Strata-data"):
2154            pass
2155        else:
2156            if not p.name.lower().startswith("strata"):
2157                raise ToolError(f"data_dir {raw!r}: a new data folder must be named Strata... (e.g. "
2158                                f"{Path(p.anchor or '/') / 'Strata-data'}), so that no other folder is filled with "
2159                                "model files")
2160            if not p.parent.is_dir():
2161                raise ToolError(f"data_dir {raw!r}: its parent folder {p.parent} does not exist")
2162            if not mounted_drive(n) and any(n == f or is_inside(n, f) for f in system_folders()):
2163                raise ToolError(f"data_dir {raw!r} is inside a system folder")
2164            if p.exists() and not p.is_dir():
2165                raise ToolError(f"data_dir {raw!r} is a file")
2166        return p
2167
2168    def strata_install(self, family=None, model=None, context=None, vision=None, kv=None, gpu=None, gpus=None,
2169                       backend=None, low_ram=None, port=None, data_dir=None, confirm=False, cancel=False,
2170                       gguf_dir=None, drafter=None, mtp=None) -> dict:
2171        s = self.s
2172        with s.lock:
2173            job = s.install_job()
2174            if cancel:
2175                if not job or not job["running"]:
2176                    return {"summary": "no install is running", "install": job}
2177                j = s.state("install")
2178                res = s.state("install-result")
2179                child = res.get("child_pid") if res.get("job") == j.get("job") else None
2180                tree = proc_tree_snapshot(j["pid"]) if proc_alive(j["pid"], j["ident"]) else []   # setup.py and what it runs (#3257)
2181                if child:
2182                    proc_kill_tree(child, res.get("child_ident"))
2183                proc_kill_tree(j["pid"], j["ident"])
2184                kill_snapshot(tree)
2185                wait_gone(j["pid"], j["ident"], 15)
2186                return {"summary": "the install was stopped; calling strata_install again resumes it (downloads "
2187                                   "continue where they stopped)", "install": s.install_job()}
2188            if job and job["running"]:
2189                return {"summary": f"an install is running: {job.get('step') or 'starting'}"
2190                                   + (f", downloading {job['download']['file']} {job['download']['percent']}%"
2191                                      if job.get("download") else ""),
2192                        "install": job, "follow": "call strata_install again for progress, or strata_logs "
2193                                                  "source=setup for the full output"}
2194            given = [x for x in (family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir)
2195                     if x is not None]
2196            if job and not given and not confirm:
2197                return {"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)"}
2202            plan, args = self.install_plan(family, model, context, vision, kv, gpu, gpus, backend, low_ram, port,
2203                                           data_dir, gguf_dir, drafter, mtp)
2204            tracked = s.tracked_server()
2205            if tracked and not tracked.get("ended"):
2206                raise ToolError("Strata is running (started by strata_start): stop it first with strata_stop - setup "
2207                                "may update the engine files it uses")
2208            if not confirm:
2209                return {"summary": f"Plan: install {plan['title']} ({plan['download_gb']:.0f} GB download"
2210                                   f"{' 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}
2213            if plan["disk_short"]:
2214                raise ToolError(plan["disk_short"])
2215            return self.launch_install(plan, args)
2216
2217    def install_plan(self, family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir, gguf_dir=None, drafter=None, mtp=None):
2218        s = self.s
2219        models, families, contexts, _src = s.tables()
2220        if gpu is not None and gpus is not None:
2221            raise ToolError("give gpu (one card) or gpus (several), not both")
2222        if sys.version_info < (3, 10) or (WIN and sys.maxsize <= 2**32):
2223            raise 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)")
2225        hw = s.hardware()
2226        rec = s.recommend(hw)
2227        if model is None and family is None:
2228            if not rec.get("model"):
2229                raise ToolError("no model was given and none fits this PC: " + rec["why"])
2230            family, model = rec["family"], rec["model"]
2231            context = context or rec["context"]
2232        elif model is None:
2233            sizes = s.sizes_of(models, family)
2234            model = rec["model"] if rec.get("family") == family else ("IQ3_XXS" if "IQ3_XXS" in sizes and
2235                                                                     hw.get("ram_gb", 0) >= 60 else sizes[0])
2236        elif family is None:
2237            fams = [f for f in families if model in s.sizes_of(models, f)]
2238            family = "qwen" if "qwen" in fams else fams[0]
2239        if family not in families:
2240            raise ToolError(f"unknown family {family}; the families: {', '.join(families)}")
2241        sizes = s.sizes_of(models, family)
2242        if model not in sizes:
2243            raise ToolError(f"{families[family]['title']} has no {model}; its sizes: {', '.join(sizes)}")
2244        md = s.own_size(family, model) or models[model]   # Qwen3.6-35B-A3B: its sizes are not in setup's MODELS
2245        mac = bool(hw.get("mac"))
2246        if mac:                                         # a Mac: no card to pick, no KV choice, no RAM mode: unified memory decides
2247            if 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:
2248                raise ToolError(f"{model} does not fit this Mac: {rec['why']}")
2249            gpu = gpus = kv = low_ram = None
2250            context = context or (s.mac().recommend_context(hw.get("ram_gb") or 0) if s.mac() else 32768)
2251        if context is None:
2252            usable = s.engine_gpus(hw)
2253            vram = max((g["vram_gb"] for g in usable), default=12)
2254            context = 131072                          # 128K on every card (owner, 2026-11-01; strata_control/default_context.py)
2255            own = (getattr(s.setup_module(), "OWN_PATH_FAMILIES", None) or {}).get(family)
2256            if own:                                   # Qwen3.6: the largest size that fits the card when 128K does not (#5715, setup's own rule)
2257                context = s.setup_module().own_path_context(own, max((g["vram_gb"] for g in usable), default=0.0), model)
2258        if vision in ("yes", "gpu", "cpu") and md.get("vision", families[family].get("vision")) is False:
2259            raise ToolError(f"images are not available with {families[family]['title']} {model} yet: use vision=no")
2260        if 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).
2263            can_read = md.get("vision", families[family].get("vision")) is not False
2264            vision = "yes" if can_read else "no"
2265        target = self.check_data_dir(data_dir) if data_dir else s.data_dir()
2266        tag = (families[family].get("tag", "") + model)
2267        have_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.
2270        arc = backend == "sycl" or (backend in (None, "auto") and any(g.get("vendor") == "intel" for g in hw.get("gpus", [])))
2271        if arc:
2272            from strata_control import intel_app
2273            if mac or not intel_app.supported_here() or not any(g.get("vendor") == "intel" for g in hw.get("gpus", [])):
2274                raise ToolError("no Intel Arc card Strata can use was found in this computer (the Intel Arc engine runs on Linux)")
2275            if not intel_app.can_set_up(family, families[family]):
2276                raise 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")
2278            backend, vision = "sycl", "no"                  # pictures stay off on an Arc (strata_cli/launch/adopt.py)
2279            if not gguf_dir and not intel_app.model_files_in(have_dir, family, families[family]):
2280                raise ToolError(intel_app.NO_DOWNLOAD)
2281        partly = (have_dir.is_dir() and any(have_dir.glob("*.gguf*"))) or bool(gguf_dir)   # a local folder: nothing to download
2282        need = (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)
2283        free = s.disk_free(target)
2284        short = None
2285        if free is not None and free < need:
2286            short = (f"not enough free disk space for {model}: about {need:.0f} GB needed at {target}, "
2287                     f"{free:.0f} GB free; free some space or choose data_dir on a bigger drive (e.g. D:\\Strata-data)")
2288        args = ["--yes", "--no-start", "--family", family, "--model", model, "--context", str(context),
2289                "--vision", vision or "no"]
2290        if family in ("qwen", "coder"):
2291            args += ["--experimental-speed-projection", "off"]
2292        own = bool(s.own_families().get(family))
2293        for 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)):
2295            if own and flag in ("--kv", "--low-ram"):      # Flash-Next settings: Qwen3.6's engine path does not use them (setup would warn)
2296                continue
2297            if v is not None:
2298                args += [flag, str(v)]
2299        if gguf_dir:
2300            local = Path(os.path.expandvars(gguf_dir)).expanduser()
2301            if not local.is_absolute() or not local.is_dir() or ".." in local.parts:
2302                raise ToolError("gguf_dir must be an existing absolute folder")
2303            args += ["--gguf-dir", str(local)]
2304        if backend in ("cuda", "hip", "sycl"):
2305            args += ["--backend", backend]
2306        if 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)
2307            args += ["--drafter", drafter]
2308        if mtp in ("on", "off"):                                      # the app's Drafting Off: no draft layer is fetched, on a Mac too (setup.py takes --mtp everywhere)
2309            args += ["--mtp", mtp]
2310        fit = None
2311        ram = hw.get("ram_gb")
2312        if ram is not None:
2313            from strata_control import fit_label
2314            fit = fit_label.label(fit_label.files_gb(family, model, md), ram, fit_label.card_room_gb(s.engine_gpus(hw)))
2315        installed = (s.root / f"strata-{tag.lower()}.json").exists()
2316        plan = {"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}
2324        if installed:
2325            plan["note"] = ("this model is already installed: running setup again updates the engine and applies "
2326                            "the options (finished steps are skipped)")
2327        if families[family].get("license"):
2328            plan["license"] = families[family]["license"]
2329        if families[family].get("experimental") or md.get("experimental"):
2330            plan["experimental"] = True
2331        return plan, args
2332
2333    def launch_install(self, plan: dict, args: list) -> dict:
2334        s = self.s
2335        s.state_dir.mkdir(parents=True, exist_ok=True)
2336        job_id = f"{int(time.time())}-{os.getpid()}"
2337        log_path = s.state_dir / "setup.log"
2338        with open(log_path, "a", encoding="utf-8") as f:
2339            f.write(f"\n===== strata-mcp: install {plan['title']} at {time.strftime('%Y-%m-%d %H:%M:%S')} =====\n")
2340        spec = {"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")}
2344        spec_path = s.state_dir / "install-job.json"
2345        spec_path.write_text(json.dumps(spec, indent=1), encoding="utf-8")
2346        s.save_state("install-result", None)
2347        env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8")
2348        p = spawn_detached([sys.executable, str(Path(__file__).resolve()), "--install-job", str(spec_path)],
2349                           s.root, log_path, env)
2350        s.children.append(p)
2351        time.sleep(0.2)
2352        ident = proc_identity(p.pid)
2353        if ident is None and p.poll() and s.state("install-result").get("job") != job_id:
2354            raise ToolError("setup did not start: " + " | ".join(read_tail(log_path, 5)))
2355        folder = plan.get("model_folder")
2356        files = []
2357        if s.setup_module() is not None and folder:     # every file of this install, for a progress that counts all the parts
2358            files = expected_files(s.setup_module(), plan["family"], plan["model"], Path(folder).parent,
2359                                   plan.get("images") in ("yes", "gpu", "cpu"))
2360        s.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})
2364        return {"summary": f"Install of {plan['title']} started in the background (about 20-90 minutes, mostly the "
2365                           f"{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
2370    def strata_start(self, model=None, port=None, gpu=None, wait_seconds=50) -> dict:
2371        s = self.s
2372        with s.lock:
2373            job = s.install_job()
2374            if job and job["running"]:
2375                raise ToolError("an install is still running (strata_install shows its progress); start the model "
2376                                "when it is done")
2377            cfg_path = s.find_config(model)
2378            desc = s.describe_config(cfg_path)
2379            if not desc["ready"]:
2380                raise 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")
2382            port = port or desc["port"] or DEFAULT_PORT
2383            tracked = s.tracked_server()
2384            if tracked and not tracked.get("ended"):
2385                info = s.probe(tracked["port"])
2386                return {"summary": f"Strata is already {'running' if info else 'loading'} ({tracked.get('model')}, "
2387                                   f"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}
2391            info = s.probe(port, deep=False)
2392            if info and not info.get("other"):
2393                return {"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}
2396            if info or not port_free(port):
2397                raise ToolError(f"port {port} is used by another program; choose another port (port=...)")
2398            py = s.run_python()
2399            if not Path(py).exists():
2400                raise ToolError("Strata's Python environment (.venv) is missing: run the install again")
2401            cmd = [py, str(s.root / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
2402                   "--port", str(port)]
2403            if gpu is not None:
2404                cmd += ["--gpu", str(gpu)]
2405            log_path = s.state_dir / "server.log"
2406            s.state_dir.mkdir(parents=True, exist_ok=True)
2407            with open(log_path, "a", encoding="utf-8") as f:
2408                f.write(f"\n===== strata-mcp: start {desc['model']} on port {port} at "
2409                        f"{time.strftime('%Y-%m-%d %H:%M:%S')} =====\n")
2410            env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8")
2411            try:
2412                os.utime(cfg_path)                      # the most recently used model, as setup's start marks it
2413            except OSError:
2414                pass
2415            p = spawn_detached(cmd, s.root, log_path, env)
2416            s.children.append(p)
2417            time.sleep(0.1)
2418            ident = proc_identity(p.pid)
2419            s.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")})
2422        return self.wait_ready(p, ident, port, desc, wait_seconds, log_path)
2423
2424    def wait_ready(self, p, ident, port, desc, wait_seconds, log_path) -> dict:
2425        s = self.s
2426        end = time.time() + wait_seconds
2427        while True:
2428            if p.poll() is not None or not proc_alive(p.pid, ident):
2429                tail = read_tail(log_path, 15)
2430                end_group_leftovers(p.pid)
2431                s.save_state("server", None)
2432                raise ToolError(f"Strata stopped while starting (exit code {p.poll()}). Its last output:\n"
2433                                + "\n".join(tail))
2434            info = s.probe(port)
2435            if info and not info.get("other"):
2436                return {"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}}
2439            if time.time() >= end:
2440                return {"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]}}
2444            time.sleep(1.0)
2445
2446    # ---- strata_stop
2447    def strata_stop(self, port=None, force=False) -> dict:
2448        s = self.s
2449        with s.lock:
2450            tracked = s.tracked_server()
2451            if tracked and tracked.get("ended"):
2452                s.save_state("server", None)
2453                tracked = None
2454            if tracked:
2455                port = tracked["port"]
2456                key = s.api_key_for(port)
2457                st, body = http_json(f"http://127.0.0.1:{port}/status", api_key=key, timeout=3)
2458                if st == 200 and isinstance(body, dict) and body.get("busy") and not force:
2459                    raise ToolError("a request is running on Strata right now; wait for it, or call strata_stop "
2460                                    "with force=true to stop anyway")
2461                st, body = http_json(f"http://127.0.0.1:{port}/unload", "POST", api_key=key, timeout=120)
2462                unloaded = (body or {}).get("status") if isinstance(body, dict) else None
2463                if st == 409 and not force:
2464                    raise ToolError("Strata is busy (a request is running or queued); call again with force=true "
2465                                    "to stop anyway")
2466                proc_terminate(tracked["pid"], tracked["ident"])   # POSIX: SIGTERM = the server's own Ctrl+C path
2467                clean = wait_gone(tracked["pid"], tracked["ident"], 30)
2468                if not clean:
2469                    proc_kill_tree(tracked["pid"], tracked["ident"])
2470                    wait_gone(tracked["pid"], tracked["ident"], 15)
2471                s.reap()
2472                gone = not proc_alive(tracked["pid"], tracked["ident"])
2473                if gone:
2474                    end_group_leftovers(tracked["pid"])
2475                    s.save_state("server", None)
2476                return {"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}
2480            for p in s.ports(port):
2481                info = s.probe(p, deep=False)
2482                if info and not info.get("other"):
2483                    key = s.api_key_for(p)
2484                    st, body = http_json(f"http://127.0.0.1:{p}/unload", "POST", api_key=key, timeout=120)
2485                    r = body.get("status") if isinstance(body, dict) else None
2486                    if st == 409:
2487                        raise ToolError("Strata is busy (a request is running); try again when it is done")
2488                    if st == 401:
2489                        raise 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")
2491                    return {"summary": f"Strata on port {p} was started outside this MCP server (its own window or a "
2492                                       f"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}
2496            return {"summary": "Strata is not running"}
2497
2498    # ---- strata_logs
2499    def strata_logs(self, source=None, model=None, lines=80) -> dict:
2500        s = self.s
2501        if source is None:
2502            job = s.install_job()
2503            source = "setup" if job and job["running"] else "server"
2504        if source == "setup":
2505            path = s.state_dir / "setup.log"
2506        elif source == "server":
2507            path = s.state_dir / "server.log"
2508        else:
2509            cfg = s.find_config(model or (s.state("server").get("model")))
2510            raw = s.read_config(cfg).get("log")
2511            if not raw:
2512                raise ToolError(f"{cfg.name} names no engine log")
2513            path = Path(raw)
2514            if not s.allowed(path):
2515                raise ToolError(f"{cfg.name}'s log {raw} is outside the Strata folder and its data folder: not shown")
2516        if not path.exists():
2517            return {"summary": f"no {source} log yet ({path})", "log": str(path), "lines": []}
2518        tail = read_tail(path, lines)
2519        return {"summary": f"last {len(tail)} lines of the {source} log", "log": str(path), "lines": tail}
2520
2521    # ---- strata_benchmark
2522    def strata_benchmark(self, port=None, max_tokens=200) -> dict:
2523        s = self.s
2524        target = None
2525        for p in s.ports(port):
2526            info = s.probe(p, deep=False)
2527            if info and not info.get("other"):
2528                target = info
2529                break
2530        if target is None:
2531            raise ToolError("Strata is not running: start it first (strata_start)")
2532        p = target["port"]
2533        key = s.api_key_for(p)
2534        st, stat = http_json(f"http://127.0.0.1:{p}/status", api_key=key, timeout=3)
2535        if st == 200 and isinstance(stat, dict) and (stat.get("busy") or stat.get("queued")):
2536            raise ToolError("Strata is busy with a request; run the speed test when it is idle")
2537        body = {"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}]}
2540        t0 = time.time()
2541        st, r = http_json(f"http://127.0.0.1:{p}/v1/chat/completions", "POST", body, api_key=key, timeout=600)
2542        wall = time.time() - t0
2543        if st != 200 or not isinstance(r, dict):
2544            msg = (r or {}).get("error", {}).get("message") if isinstance(r, dict) else None
2545            raise ToolError(f"the request failed (HTTP {st}): {msg or 'no answer'}")
2546        usage, tm = r.get("usage") or {}, r.get("timings") or {}
2547        n = usage.get("completion_tokens") or tm.get("predicted_n") or 0
2548        out = {"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"}
2555        speed = out["output_tok_s"] or out["wall_tok_s"]
2556        out["summary"] = (f"{n} tokens at {speed} tokens/s" + (f" (prompt {out['prompt_tok_s']} tokens/s)"
2557                                                              if out["prompt_tok_s"] else "")
2558                          + f", {wall:.1f} s in total")
2559        out["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")
2561        return out
2562
2563    # ---- strata_connect_info
2564    def strata_connect_info(self, port=None) -> dict:
2565        s = self.s
2566        target = None
2567        for p in s.ports(port):
2568            info = s.probe(p, deep=False)
2569            if info and not info.get("other"):
2570                target = info
2571                break
2572        if port is None:
2573            cfgs = s.configs()
2574            port = target["port"] if target else (s.describe_config(cfgs[0])["port"] if cfgs else DEFAULT_PORT)
2575        model = (target or {}).get("model") or "strata"
2576        key_needed = (target or {}).get("api_key_required")
2577        if key_needed is None:
2578            key_needed = any(s.describe_config(c)["api_key_set"] for c in s.configs())
2579        key = "<your api_key from strata-<model>.json>" if key_needed else "none"
2580        base = f"http://127.0.0.1:{port}"
2581        return {
2582            "summary": (f"Strata {'runs' if target else 'will run'} at {base}: OpenAI base URL {base}/v1, Anthropic "
2583                        f"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"
2587                        if 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'
2594                                      f'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'
2596                                  f'r = client.chat.completions.create(model="{model}", messages=[{{"role": "user", '
2597                                  f'"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 "
2605                                                   f"(--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:
2619    def __init__(self, strata: Strata, out=None):
2620        self.strata = strata
2621        self.tools = Tools(strata)
2622        self.out = out
2623        self.write_lock = threading.Lock()
2624        self.protocol = PROTOCOL
2625
2626    def send(self, msg: dict) -> None:
2627        data = (json.dumps(msg, ensure_ascii=False) + "\n").encode("utf-8")
2628        with self.write_lock:
2629            self.out.write(data)
2630            self.out.flush()
2631
2632    @staticmethod
2633    def result(rid, result):
2634        return {"jsonrpc": "2.0", "id": rid, "result": result}
2635
2636    @staticmethod
2637    def error(rid, code, message):
2638        return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
2639
2640    def handle(self, msg) -> dict | None:
2641        """One JSON-RPC message -> its response (None for a notification or a response)."""
2642        if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
2643            return self.error(msg.get("id") if isinstance(msg, dict) else None, -32600, "invalid request")
2644        if "method" not in msg:
2645            return None                                 # a response to something we never ask: ignored
2646        method, rid, params = msg["method"], msg.get("id"), msg.get("params") or {}
2647        if "id" not in msg:
2648            return None                                 # notifications (initialized, cancelled ...): nothing to say
2649        if not isinstance(params, dict):
2650            return self.error(rid, -32602, "params must be an object")
2651        if method == "initialize":
2652            asked = str(params.get("protocolVersion") or PROTOCOL)
2653            self.protocol = asked if asked in PROTOCOLS else PROTOCOL
2654            return self.result(rid, {"protocolVersion": self.protocol,
2655                                     "capabilities": {"tools": {"listChanged": False}},
2656                                     "serverInfo": {"name": "strata", "title": "Strata", "version": VERSION},
2657                                     "instructions": INSTRUCTIONS})
2658        if method == "ping":
2659            return self.result(rid, {})
2660        if method == "tools/list":
2661            return self.result(rid, {"tools": self.tools.defs()})
2662        if method == "tools/call":
2663            name = params.get("name")
2664            try:
2665                res = self.tools.call(name, params.get("arguments"))
2666                return self.result(rid, self.content(res, error=False))
2667            except KeyError:
2668                return self.error(rid, -32602, f"unknown tool: {name}")
2669            except ToolError as e:
2670                return self.result(rid, self.content({"error": str(e)}, error=True))
2671            except Exception as e:                      # noqa: BLE001 - a bug must not end the server
2672                log("tool failed:\n" + traceback.format_exc())
2673                return self.result(rid, self.content({"error": f"internal error in {name}: {e}"}, error=True))
2674        if method in ("resources/list", "prompts/list"):
2675            return self.result(rid, {method.split("/")[0]: []})
2676        return self.error(rid, -32601, f"method not found: {method}")
2677
2678    def content(self, res: dict, error: bool) -> dict:
2679        text = json.dumps(res, indent=1, ensure_ascii=False)
2680        out = {"content": [{"type": "text", "text": text}], "isError": error}
2681        if self.protocol >= "2025-06-18":
2682            out["structuredContent"] = res
2683        return out
2684
2685    def 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
2687        while pings and status calls are still answered)."""
2688        threads = []
2689        for raw in inp:
2690            line = raw.decode("utf-8", "replace").strip() if isinstance(raw, bytes) else raw.strip()
2691            if not line:
2692                continue
2693            try:
2694                msg = json.loads(line)
2695            except ValueError:
2696                self.send(self.error(None, -32700, "parse error"))
2697                continue
2698            batch = isinstance(msg, list)
2699            if batch or (isinstance(msg, dict) and msg.get("method") == "tools/call"):
2700                t = threading.Thread(target=self._run, args=(msg,), daemon=True)
2701                t.start()
2702                threads.append(t)
2703                threads = [x for x in threads if x.is_alive()]
2704            else:
2705                self._run(msg)
2706        for t in threads:
2707            t.join(timeout=5)
2708
2709    def _run(self, msg) -> None:
2710        if isinstance(msg, list):
2711            out = [r for r in (self.handle(m) for m in msg) if r is not None]
2712            if out:
2713                data = (json.dumps(out, ensure_ascii=False) + "\n").encode("utf-8")
2714                with self.write_lock:
2715                    self.out.write(data)
2716                    self.out.flush()
2717            return
2718        r = self.handle(msg)
2719        if r is not None:
2720            self.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
2726    START-HERE.bat / setup.sh do when it is missing, run setup, record its exit code."""
2727    spec = json.loads(Path(spec_path).read_text(encoding="utf-8"))
2728    root = Path(spec["root"])
2729    result = Path(spec["result"])
2730
2731    def record(**kw):
2732        try:
2733            old = json.loads(result.read_text(encoding="utf-8")) if result.exists() else {}
2734        except (OSError, ValueError):
2735            old = {}
2736        tmp = result.with_suffix(".tmp")
2737        tmp.write_text(json.dumps({**old, "job": spec["job"], **kw}, indent=1), encoding="utf-8")
2738        os.replace(tmp, result)
2739
2740    py = Path(spec["python"])
2741    src = Path(spec.get("src") or root)
2742    try:
2743        if spec.get("create_venv"):
2744            venv = root / ".venv"
2745            if py.exists() and subprocess.run([str(py), "-m", "pip", "--version"], capture_output=True).returncode:
2746                print("strata-mcp: .venv has no pip (an earlier run stopped half-way): making it again", flush=True)
2747                shutil.rmtree(venv, ignore_errors=True)
2748            if not py.exists():
2749                print(f"strata-mcp: creating Strata's Python environment in {venv} ...", flush=True)
2750                r = subprocess.run([spec["base_python"], "-m", "venv", str(venv)])
2751                if r.returncode or not py.exists():
2752                    print("\n  [X]  could not create the Python environment (.venv)", flush=True)
2753                    print("       Linux: install python3-venv (sudo apt install python3-venv) or run ./setup.sh "
2754                          "once in a terminal", flush=True)
2755                    record(exit_code=1, ended=time.strftime("%Y-%m-%d %H:%M:%S"))
2756                    return 1
2757        cmd = [str(py), str(src / "setup.py"), *spec["args"]]
2758        print("strata-mcp: running " + " ".join(cmd), flush=True)
2759        env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8")
2760        if spec.get("control"):                         # the app: the installer's own mode, writing to `root`
2761            env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(root), PYTHONNOUSERSITE="1")
2762            for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"):
2763                env.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.
2767            env.pop("STRATA_NO_ACQUIRE", None)
2768        p = subprocess.Popen(cmd, cwd=str(src if spec.get("control") else root), stdin=subprocess.DEVNULL, env=env)
2769        record(child_pid=p.pid, child_ident=proc_identity(p.pid))
2770        rc = p.wait()
2771    except Exception as e:                              # noqa: BLE001
2772        print(f"\n  [X]  strata-mcp could not run setup: {e}", flush=True)
2773        rc = 1
2774    print(f"strata-mcp: setup ended with exit code {rc}", flush=True)
2775    record(exit_code=rc, ended=time.strftime("%Y-%m-%d %H:%M:%S"))
2776    return rc
2777
2778
2779def main(argv=None) -> int:
2780    ap = argparse.ArgumentParser(description="Strata's MCP server (stdio): install, start, check and stop Strata "
2781                                             "from an AI assistant. See docs/MCP_SERVER.md.")
2782    ap.add_argument("--root", help="the Strata folder (default: the one this file is in)")
2783    ap.add_argument("--src", help="where setup.py, tools/ and serve/ are, when that is not the Strata folder (the app)")
2784    ap.add_argument("--install-job", help=argparse.SUPPRESS)
2785    a = ap.parse_args(argv)
2786    if a.install_job:
2787        return install_job(a.install_job)
2788    if sys.version_info < (3, 10):
2789        log("Python 3.10 or newer is needed")
2790        return 2
2791    root = Path(a.root).expanduser().resolve() if a.root else DEFAULT_ROOT
2792    src = Path(a.src).expanduser().resolve() if a.src else root
2793    if not (src / "setup.py").is_file() or not (src / "serve" / "server.py").is_file():
2794        log(f"{src} is not a Strata folder (no setup.py / serve/server.py)")
2795        return 2
2796    out = sys.stdout.buffer
2797    sys.stdout = sys.stderr                             # stray prints must never corrupt the protocol stream
2798    server = McpServer(Strata(root, src), out)
2799    log(f"ready (Strata folder {root})")
2800    try:
2801        server.serve(sys.stdin.buffer)
2802    except KeyboardInterrupt:
2803        pass
2804    return 0
2805
2806
2807if __name__ == "__main__":
2808    sys.exit(main())