okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
28.6 KiB561 linesraw
1"""The model catalog, the computer's figures and the fit words for `strata launch`.
2
3There is ONE catalog: setup.py's MODELS / FAMILIES / CONTEXTS, which the desktop app reads through tools/strata_mcp.py
4(`Strata.model_table`, `Strata.hardware`, `Strata.recommend`; the app page's own fit arithmetic is
5apps/host/src/lib/native-fit.ts `fitOn`). This module loads that same file from the installer folder and ports `fitOn` line by
6line; it holds no table of its own. Without the installer files (a Terminal bundle made before launch existed) it says so in
7words instead of guessing.
8"""
9
10from __future__ import annotations
11
12import importlib.util
13import json
14import os
15import sys
16from dataclasses import dataclass, field
17from pathlib import Path
18from typing import Any
19
20from strata_cli.launch import settings as S
21
22
23class CatalogUnavailable(RuntimeError):
24    """The installer files (setup.py, tools/strata_mcp.py) are not there; the message is for the user."""
25
26
27# --- apps/host/src/lib/native-fit.ts, ported (same constants, same rules) ------------------------------------------------
28DENSE_GB = 5.0
29SYSTEM_ROOM_GB = 10.0
30DENSE_EXTRA_GB = 1.0
31
32
33def _round1(n: float) -> float:
34    return round(n * 10) / 10
35
36
37def memory_needed(v: dict) -> float:
38    if isinstance(v.get("memory_gb"), (int, float)):
39        return float(v["memory_gb"])
40    if v.get("mem_total") and isinstance(v.get("ram_needed_gb"), (int, float)):
41        return float(v["ram_needed_gb"])
42    return _round1(float(v.get("experts_gb") or v.get("ram_needed_gb") or 0) + DENSE_EXTRA_GB)
43
44
45def fit_on(v: dict, ram_gb: float | None, vram_gb: float | None) -> dict[str, Any]:
46    """native-fit.ts `fitOn`: where the weights go on this computer. Returns memoryGb, vramUseGb, ramUseGb, spillGb, known."""
47    memory = memory_needed(v)
48    vram = float(vram_gb or 0)
49    if not ram_gb or ram_gb <= 0:
50        return {"memoryGb": memory, "vramUseGb": 0.0, "ramUseGb": 0.0, "spillGb": 0.0, "known": False}
51    experts = max(0.0, memory - DENSE_EXTRA_GB)
52    on_gpu = max(0.0, min(experts, vram - DENSE_GB))
53    ram_room = max(0.0, float(ram_gb) - SYSTEM_ROOM_GB)
54    spill = max(0.0, experts - on_gpu - ram_room)
55    in_ram = max(0.0, experts - on_gpu - spill)
56    vram_use = min(vram, DENSE_GB + on_gpu) if vram > 0 else 0.0
57    return {"memoryGb": memory, "vramUseGb": _round1(vram_use),
58            "ramUseGb": _round1(in_ram + (DENSE_EXTRA_GB if vram <= 0 else 0)), "spillGb": _round1(spill), "known": True}
59
60
61# --- the verdict words ---------------------------------------------------------------------------------------------------
62FITS, SLOWER, TIGHT, NO = "fits", "slower", "tight", "no"
63
64
65def verdict(on_this_pc: str | None) -> tuple[str, str]:
66    """(category, plain words) from the catalog's own `on_this_pc` text (strata_control/fit_label.py through strata_mcp: "fits" or "may run slower").
67
68    No card and a Mac with little memory get "may run slower" too (owner 11-08); an older Control's "does not fit..." is read the same way.  Never a block: the person can always try, and the screen says so."""
69    text = (on_this_pc or "").strip()
70    low = text.lower()
71    if not text:
72        return TIGHT, "not checked (this computer's memory could not be read)"
73    if low.startswith("does not fit"):
74        return SLOWER, "may run slower"
75    if low == "may run slower":
76        return SLOWER, "may run slower"
77    if low == "fits":
78        return FITS, "fits"
79    if low.startswith("tight"):
80        return TIGHT, "tight: close other programs"
81    return TIGHT, text
82
83
84@dataclass
85class ModelRow:
86    family: str
87    family_title: str
88    model: str
89    id: str                       # the run config's tag (strata-<id>.json)
90    about: str
91    download_gb: float
92    need_vram_gb: float
93    need_ram_gb: float
94    spill_gb: float
95    verdict: str
96    words: str
97    experimental: bool
98    images: bool
99    installed: bool
100    recommended: bool = False
101    mem_total: bool = False
102    memory_gb: float = 0.0        # the placement estimate (experts + dense), for the cards
103    fit_gb: float = 0.0           # the files without the lookup table: the "Needs" column and the fit label
104
105    @property
106    def title(self) -> str:
107        return f"{self.family_title} {self.model}"
108
109
110@dataclass
111class Computer:
112    ram_gb: float | None = None
113    gpus: list[dict] = field(default_factory=list)
114    disk_free_gb: float | None = None
115    os: str = ""
116    avx2: bool | None = None
117    raw: dict = field(default_factory=dict)
118    engine_vendor: str | None = None           # the make of card the engine drives (nvidia, amd, intel, apple); None: the cards name none
119
120    @property
121    def usable_gpus(self) -> list[dict]:
122        """The cards that count and the engine can drive (strata_control/gpu_fit.py: an integrated chip, a tiny card or a card of another
123        make is left out), the largest first. One engine drives one make, so a model is never split across makes."""
124        from strata_control import gpu_fit
125        return gpu_fit.usable_cards(gpu_fit.for_vendor(self.gpus, self.engine_vendor)[0])[0]
126
127    @property
128    def ignored_gpus(self) -> list[dict]:
129        from strata_control import gpu_fit
130        mine, others = gpu_fit.for_vendor(self.gpus, self.engine_vendor)
131        return gpu_fit.usable_cards(mine)[1] + [{**c, "why_ignored": "another make of card than this engine drives"} for c in others]
132
133    @property
134    def other_vendor_note(self) -> str | None:
135        """One plain line when a card of another make is the bigger one (None otherwise)."""
136        from strata_control import gpu_fit
137        return gpu_fit.other_vendor_note(self.gpus, self.engine_vendor)
138
139    @property
140    def new_card_note(self) -> tuple[str, str] | None:
141        """(what, what to do) when a usable card is an Intel Arc B-series (Battlemage): allowed, but new to Strata and untested by the maintainers."""
142        import re
143        from strata_control import gpu_fit
144        for c in gpu_fit.usable_cards(gpu_fit.for_vendor(self.gpus, self.engine_vendor)[0])[0]:
145            if c.get("vendor") == "intel" and re.search(r"Arc (?:Pro )?B\d", str(c.get("name", ""))):
146                return (f"The {str(c['name']).replace('Intel ', '')} is a B-series Arc card. It is new to Strata and we have not tested it ourselves, so pictures or long answers may fail on it.",
147                        "If something fails, start again with --vision off to turn pictures off, and tell us at https://github.com/Niko1221/Strata/issues (say it is a B-series card and attach the engine log).")
148        return None
149
150    @property
151    def main_vram_gb(self) -> float:
152        return max((float(g.get("vram_gb") or 0) for g in self.usable_gpus), default=0.0)
153
154    def line(self, data_dir: str | None = None) -> str:
155        g = self.usable_gpus
156        if g and g[0].get("unified_gb"):                       # a Mac: one pool of memory, the chip is the graphics
157            disk = f"{self.disk_free_gb:,.0f} GB free" if self.disk_free_gb is not None else ""
158            return " · ".join(x for x in (g[0].get("name", "Apple silicon"), f"{self.ram_gb:.0f} GB unified memory" if self.ram_gb else "memory unknown", disk) if x)
159        card = (f"{g[0].get('name', 'GPU').replace('NVIDIA GeForce ', '').replace('AMD Radeon ', '')} {g[0].get('vram_gb', 0):.0f} GB"
160                + (f" x{len(g)}" if len(g) > 1 else "")) if g else "no usable graphics card found"
161        ram = f"{self.ram_gb:.0f} GB RAM" if self.ram_gb else "RAM unknown"
162        disk = f"{self.disk_free_gb:,.0f} GB free" if self.disk_free_gb is not None else ""
163        return " · ".join(x for x in (card, ram, disk) if x)
164
165
166def installer_folder(explicit: str | os.PathLike | None = None) -> Path:
167    """Where setup.py and tools/ are: this Terminal's own folder (the bundle, or a source checkout)."""
168    if explicit:
169        return Path(explicit)
170    return Path(__file__).resolve().parents[2]
171
172
173def install_places(explicit: str | os.PathLike | None = None, src: str | os.PathLike | None = None) -> list:
174    """Every folder with run configs, main one first: the SAME discovery `strata models list` and the own-files import use
175    (strata_control/discovery.py). An explicit folder (the argument, or STRATA_INSTALL_DIR) is the only one."""
176    from strata_control import discovery
177    return discovery.places(here=installer_folder(src), explicit=explicit)
178
179
180def install_root(explicit: str | os.PathLike | None = None, src: str | os.PathLike | None = None) -> Path:
181    """Where run configs of installed models live: the main place found by the shared discovery, else the folder a new model is
182    installed into (beside the components folder, what the app uses)."""
183    from strata_control import discovery
184    if explicit:
185        return Path(explicit)
186    env = os.environ.get("STRATA_INSTALL_DIR")
187    if env:
188        return Path(env)
189    return discovery.find_install(here=installer_folder(src))[0]
190
191
192# Intel Arc cards by PCI id: (name, memory in GB).  The kernel does not tell an ordinary user how much memory the card has, so the discrete
193# cards are listed (the same ids as sycl/setup_intel.py; tests/terminal/test_intel_cards_029.py keeps the two in step).  An id that is not
194# here is NOT counted: it is skipped, because an Intel chip built into the processor shares this vendor id and must never be named as a card.
195# (A770: the 8 GB model shares the id of the 16 GB one, so the smaller figure is used.)
196INTEL_ARC = {"0x56a1": ("Arc A750", 8.0), "0x56a2": ("Arc A580", 8.0), "0x56a0": ("Arc A770", 8.0), "0x56a5": ("Arc A380", 6.0),
197             "0x56a6": ("Arc A310", 4.0), "0x5690": ("Arc A770M", 16.0), "0xe20b": ("Arc B580", 12.0), "0xe20c": ("Arc B570", 10.0),
198             "0xe223": ("Arc Pro B70", 32.0), "0xe222": ("Arc Pro B65", 32.0), "0xe221": ("Arc Pro B60", 24.0), "0xe211": ("Arc Pro B60", 24.0),
199             "0xe212": ("Arc B50", 16.0)}
200
201
202#: PCI id ranges of Intel's discrete cards, for a model that is not in the table above (a new Battlemage or Alchemist part): such a card is counted as an
203#: Arc of the family's smallest memory, never named by model. The processors' own graphics (0x46xx, 0x7dxx, 0xa7xx, ...) are outside these ranges.
204INTEL_ARC_FAMILIES = ((0x5690, 0x56c1, 8.0), (0xe200, 0xe2ff, 10.0))
205
206
207def _arc_entry(did: str) -> tuple[str, float] | None:
208    if did in INTEL_ARC:
209        return INTEL_ARC[did]
210    try:
211        value = int(did, 16)
212    except ValueError:
213        return None
214    for low, high, gb in INTEL_ARC_FAMILIES:
215        if low <= value <= high:
216            return "Arc", gb
217    return None
218
219
220def intel_arc_cards(root: str = "/sys/class/drm") -> list[dict]:
221    """The Intel Arc cards on this Linux computer, read from the kernel's device list (empty elsewhere). One unreadable entry or a card number
222    above 9 never hides the others, and the cards of other makes beside them (an AMD APU's graphics) do not matter here (#4971, #5111)."""
223    cards: list[dict] = []
224    try:
225        entries = sorted(Path(root).glob("card[0-9]*"), key=lambda p: (len(p.name), p.name))
226    except OSError:
227        return cards
228    for card in entries:
229        if "-" in card.name:                                 # a connector (card0-DP-1), not a card
230            continue
231        dev = card / "device"
232        try:
233            if (dev / "vendor").read_text().strip().lower() != "0x8086":
234                continue
235            did = (dev / "device").read_text().strip().lower()
236        except OSError:
237            continue
238        entry = _arc_entry(did)
239        if entry is None:
240            continue
241        name, gb = entry
242        cards.append({"vendor": "intel", "name": "Intel " + name, "vram_gb": gb, "usable": True, "index": len(cards)})
243    return cards
244
245
246class Catalog:
247    """setup.py's tables through strata_mcp's `Strata` object (the app's own catalog code)."""
248
249    def __init__(self, src: str | os.PathLike | None = None, root: str | os.PathLike | None = None,
250                 hardware: dict | None = None):
251        self.src = installer_folder(src)
252        self.places = install_places(root, self.src)
253        self.root = Path(root) if root else (self.places[0].path if self.places else install_root(None, self.src))
254        mcp = self.src / "tools" / "strata_mcp.py"
255        if not mcp.is_file() or not (self.src / "setup.py").is_file():
256            raise CatalogUnavailable(
257                "This Terminal does not carry the model list. Install it again with the one-line installer, "
258                "or run `strata launch` from a full Strata folder (the folder with setup.py).")
259        self.root.mkdir(parents=True, exist_ok=True)
260        name = "strata_mcp_for_launch"
261        mod = sys.modules.get(name)
262        if mod is None:
263            if str(self.src) not in sys.path:
264                sys.path.insert(0, str(self.src))
265            spec = importlib.util.spec_from_file_location(name, mcp)
266            mod = importlib.util.module_from_spec(spec)
267            sys.modules[name] = mod
268            real = sys.stdout
269            sys.stdout = sys.stderr           # the module must not print into a screen
270            try:
271                spec.loader.exec_module(mod)
272            finally:
273                sys.stdout = real
274        self.mcp = mod
275        self.strata = mod.Strata(self.root, self.src)
276        self._mcp_data_dir = self.strata.data_dir
277        self.strata.data_dir = self.data_dir          # one answer to "where is the data folder" for every caller, the app's included
278        self._hardware_override = hardware
279
280    # ---- the computer
281    def hardware(self, fresh: bool = False) -> dict:
282        if self._hardware_override is not None:
283            hw = dict(self._hardware_override)
284            hw.setdefault("disk_free_gb", self.strata.disk_free(self.strata.data_dir()))
285            return hw
286        hw = dict(self.strata.hardware(fresh=fresh))
287        hw["gpus"] = self._admit_old_nvidia(list(hw.get("gpus") or []))
288        if not str(hw.get("os", "")).startswith("Windows"):
289            arc = intel_arc_cards()
290            if arc:
291                # the shared hardware reader knows NVIDIA and AMD only; an Arc is added here, also beside other makes (the plan then says the
292                # Intel cards exist and how to use them: --backend intel); their numbers are the Intel engine's own (0, 1, ...)
293                have = list(hw.get("gpus") or [])
294                hw["gpus"] = have + arc
295        return hw
296
297    @staticmethod
298    def _admit_old_nvidia(gpus: list[dict]) -> list[dict]:
299        """Pascal / Volta cards (P100, P40, V100: compute capability 6.0-7.0) run on the experimental CUDA 12 engine. setup.py admits them when they
300        are the only kind of graphics card in the computer (`old_gpus_opt_in`: "it is the only kind of NVIDIA GPU in this PC"); the shared hardware
301        reader does not, so the screens said "no usable graphics card found" and left out the Cards step on a computer with several V100s.
302        A newer NVIDIA card or a usable AMD card keeps the old cards out of the way, exactly as in setup."""
303        def arch(g: dict) -> int:
304            try:
305                return int(g.get("arch"))
306            except (TypeError, ValueError):
307                return 0
308        old = [g for g in gpus if g.get("vendor") == "nvidia" and 60 <= arch(g) <= 70 and not g.get("usable", True)]
309        if not old:
310            return gpus
311        if any(g.get("usable", True) for g in gpus):
312            return gpus
313        return [({**g, "usable": True, "problem": None,
314                  "note": "experimental: the CUDA 12 engine (docs/OLDER_GPUS.md)"} if g in old else g) for g in gpus]
315
316    def computer(self, fresh: bool = False) -> Computer:
317        hw = self.hardware(fresh)
318        return Computer(ram_gb=hw.get("ram_gb"), gpus=list(hw.get("gpus") or []), disk_free_gb=hw.get("disk_free_gb"),
319                        os=str(hw.get("os") or ""), avx2=(hw.get("cpu") or {}).get("avx2"), raw=hw,
320                        engine_vendor=self.engine_vendor(hw))
321
322    def installed_backend(self) -> str | None:
323        """The installed engine's backend (cuda, hip, sycl, cpu, metal), None when there is no usable engine yet."""
324        try:
325            from strata_control import engine_component as ec
326            rep = ec.status()
327            if rep.get("usable"):
328                return (rep.get("engine") or {}).get("backend")
329        except Exception:                                    # noqa: BLE001
330            pass
331        return None
332
333    def engine_vendor(self, hw: dict | None = None) -> str | None:
334        """The make of card the engine drives: the installed engine's; with none installed, the engine setup would fetch (NVIDIA first when the
335        computer has several makes)."""
336        from strata_control import engine_component as ec, gpu_fit
337        hw = hw if hw is not None else self.hardware()
338        chosen = None
339        try:
340            backend, how = ec.detect_backend()
341            if how in ("environment", "saved choice"):          # the person's own choice (--backend, STRATA_ENGINE_BACKEND) beats the installed engine
342                chosen = backend
343        except Exception:                                      # noqa: BLE001
344            pass
345        return gpu_fit.pick_vendor(list(hw.get("gpus") or []), chosen or self.installed_backend())
346
347    # ---- the tables
348    def tables(self):
349        models, families, contexts, source = self.strata.tables()
350        return models, families, list(contexts), source
351
352    def contexts(self) -> list[int]:
353        return [int(c) for c in self.tables()[2]]
354
355    def contexts_for(self, family: str | None, model: str | None = None) -> list[int]:
356        """The context sizes to offer for this model: the shared list."""
357        return self.contexts()
358
359    def recommendation(self, hw: dict | None = None) -> dict:
360        return self.strata.recommend(hw or self.hardware())
361
362    def rows(self, hw: dict | None = None) -> list[ModelRow]:
363        hw = hw or self.hardware()
364        comp = Computer(ram_gb=hw.get("ram_gb"), gpus=list(hw.get("gpus") or []), engine_vendor=self.engine_vendor(hw))
365        vram = comp.main_vram_gb
366        rec = self.recommendation(hw)
367        out: list[ModelRow] = []
368        own = self.strata.own_families()                # Qwen3.6 is listed for the app; the Terminal's launch list is Flash-Next's
369        for fam in self.strata.model_table(hw):
370            if fam["family"] in own:
371                continue
372            for size in fam["sizes"]:
373                f = fit_on(size, hw.get("ram_gb"), vram)
374                cat, words = verdict(size.get("on_this_pc"))
375                out.append(ModelRow(
376                    family=fam["family"], family_title=fam["title"], model=size["model"], id=size["id"],
377                    about=size["about"], download_gb=float(size["download_gb"]), need_vram_gb=f["vramUseGb"],
378                    need_ram_gb=f["ramUseGb"], spill_gb=f["spillGb"], verdict=cat, words=words,
379                    experimental=bool(size.get("experimental") or fam.get("experimental")), images=bool(size.get("images")),
380                    installed=bool(size.get("installed")) or self.installed_config(str(size["id"])) is not None, mem_total=bool(size.get("mem_total")),
381                    memory_gb=float(size.get("memory_gb") or 0), fit_gb=float(size.get("fit_gb") or size.get("memory_gb") or 0),
382                    recommended=(rec.get("family") == fam["family"] and rec.get("model") == size["model"])))
383        return out
384
385    def unavailable(self, hw: dict | None = None) -> list[tuple[str, str]]:
386        """(title, the plain reason) of each model of the signed feed that this engine does not run: nothing for a feed without such a model. The model list
387        shows them under the list (same sentence as setup and the app: strata_control/feed_models.py)."""
388        try:
389            return [(f["title"], f["unavailable_reason"]) for f in self.strata.model_table(hw or self.hardware()) if f.get("available") is False]
390        except Exception:                                  # noqa: BLE001 - a line for information
391            return []
392
393    def resolve(self, model: str, family: str | None = None) -> tuple[str, str]:
394        """`iq3_xxs` or `IQ3_XXS` (and an optional family) -> (family, model); raises ValueError with the closest match."""
395        models, families, _ctx, _src = self.tables()
396        names = list(models)
397        match = next((n for n in names if n.lower() == model.lower()), None)
398        if match is None:
399            near = S.closest(model, names)
400            raise ValueError(f"There is no model called '{model}'." + (f" Did you mean '{near}'?" if near else "")
401                             + " Models: " + ", ".join(names) + ".")
402        if family is not None and family not in families:
403            near = S.closest(family, list(families))
404            raise ValueError(f"There is no model family called '{family}'." + (f" Did you mean '{near}'?" if near else "")
405                             + " Families: " + ", ".join(families) + ".")
406        offered = [f for f in families if match in self.strata.sizes_of(models, f)]
407        if family is not None:
408            if family not in offered:
409                raise ValueError(f"{families[family]['title']} has no size {match}. It offers: "
410                                 + ", ".join(self.strata.sizes_of(models, family)) + ".")
411            return family, match
412        if not offered:
413            raise ValueError(f"{match} is not offered by any model family here.")
414        return ("qwen" if "qwen" in offered else offered[0]), match
415
416    def model_name_of(self, family: str | None, model: str | None) -> str | None:
417        """The ``model_name`` setup writes into this model's run config (``qwen3.8-flash-next-iq3_s``), known before the model is installed: what the drafter table is keyed by."""
418        if not family or not model:
419            return None
420        fam = self.tables()[1].get(family) or {}
421        return f"{fam.get('name', family)}-{model.lower()}"
422
423    def tag_of(self, family: str, model: str) -> str:
424        _m, families, _c, _s = self.tables()
425        return (families[family].get("tag", "") + model).lower()
426
427    def model_folder(self, base: Path, family: str, model: str) -> Path:
428        """The folder a model's files are in under `base/models`. setup.py names it with the case kept (`models/IQ3_S`), the run-config tag is
429        lower case (`iq3_s`): on a case-sensitive disk the two are different folders, so the one that exists wins, and a folder that differs
430        only in case is found (#3996). When none exists yet it is setup's own name, because that is where the download will go."""
431        _m, families, _c, _s = self.tables()
432        models = Path(base) / "models"
433        own = models / (families[family].get("tag", "") + model)
434        lower = models / self.tag_of(family, model)
435        for candidate in (own, lower):
436            if candidate.is_dir():
437                return candidate
438        try:
439            for entry in models.iterdir():
440                if entry.name.lower() == lower.name and entry.is_dir():
441                    return entry
442        except OSError:
443            pass
444        return own
445
446    def kv_gb(self, tokens: int, kv: str = "int8") -> float:
447        """The conversation memory for this many tokens, in GB (setup.py's UD_FIT_KV_BYTES: 13 attention layers)."""
448        mod = self.strata.setup_module()
449        table = getattr(mod, "UD_FIT_KV_BYTES", None) or {"fp16": 2112, "int8": 1056, "q4_0": 576, "k8v4": 816}
450        return tokens * 13 * table.get(kv, 1056) / 1e9
451
452    def max_context(self, family: str, model: str, hw: dict | None = None) -> int | None:
453        """The context a model starts with: 128K on every card, or the largest size the model offers under it (strata_control/default_context.py,
454        the one rule of the app, the Terminal and setup). A Mac keeps its unified-memory rule."""
455        from strata_control import default_context
456        hw = hw or self.hardware()
457        if hw.get("mac") and hw.get("ram_gb"):
458            mac = self.strata.mac()                           # a Mac: the context by unified memory (strata_control/mac_fit.py)
459            if mac is not None:
460                return int(mac.recommend_context(float(hw["ram_gb"])))
461        return default_context.pick(self.contexts_for(family, model))
462
463    # ---- pictures
464    def engine_backend(self) -> str | None:
465        """The installed engine's backend (cuda, hip, sycl, cpu, metal), else the one this computer's graphics card needs, else None."""
466        installed = self.installed_backend()
467        if installed:
468            return installed
469        for g in self.computer().usable_gpus:
470            v = str(g.get("vendor") or "").lower()
471            if g.get("unified_gb") or v == "apple":
472                return "metal"
473            return {"nvidia": "cuda", "amd": "hip", "intel": "sycl"}.get(v)
474        return None
475
476    def reader_state(self) -> str:
477        """"present" when the installed engine carries the picture reader (strata-vision), "missing" when an engine is installed without it,
478        "unknown" before any engine is installed (the first launch fetches one that has it)."""
479        try:
480            from strata_control import engine_component as ec
481            rep = ec.status()
482            exe = (rep.get("engine") or {}).get("exe") if rep.get("usable") else None
483        except Exception:                                    # noqa: BLE001
484            exe = None
485        if not exe:
486            return "unknown"
487        from strata_control import vision_reader as VR
488        found = VR.find(Path(str(exe)).parent, os.name == "nt")
489        return "present" if (found["cpu"] or found["gpu"]) else "missing"
490
491    def picture_default(self, images: bool) -> str:
492        """The picture setting nobody chose: off for a model that cannot read pictures or an engine without the reader; else on, with the
493        reader the one rule of strata_control/vision_reader.py gives: the CPU reader under 24 GB of graphics memory, the GPU reader from 24 GB,
494        on every make of card (owner decision 2026-10-18); on a Mac the Metal reader (unified memory). Without a usable graphics card there is nothing to read on: the CPU reader."""
495        from strata_control import vision_reader as VR
496        if not images or self.reader_state() == "missing":
497            return "off"
498        if self.is_mac():
499            return VR.default_mode(None, unified=True)           # a Mac (unified memory): the Metal reader, nothing to keep free for a card
500        comp = self.computer()
501        vram = comp.main_vram_gb
502        return VR.default_mode(vram, "intel" if comp.engine_vendor == "intel" else "") if vram > 0 else "cpu"      # no usable card: nothing to read on, the CPU reader
503
504    def is_mac(self) -> bool:
505        """An Apple Silicon Mac: the chip's memory is the system's (the Metal engine; strata_control/vision_reader.py)."""
506        return self.engine_backend() == "metal"
507
508    # ---- installed models
509    def installed_configs(self) -> list[dict]:
510        out, seen = [], set()
511        for path in self.strata.configs():
512            seen.add(path.name)
513            d = self.strata.describe_config(path)
514            d["path"] = str(path)
515            out.append(d)
516        for place in self.places:
517            if place.path == self.root:
518                continue
519            from strata_control import discovery
520            for path in discovery.config_files(place.path):
521                if path.name in seen:
522                    continue
523                seen.add(path.name)
524                d = self.strata.describe_config(path)
525                d["path"] = str(path)
526                out.append(d)
527        return out
528
529    def installed_config(self, tag: str) -> Path | None:
530        name = f"strata-{tag.lower()}.json"
531        for folder in [self.root, *[p.path for p in self.places if p.path != self.root]]:
532            p = folder / name
533            if p.is_file():
534                return p
535        return None
536
537    def data_dir_choice(self) -> tuple[Path, str]:
538        """(the data folder, where it came from): the person's own setting, the desktop app's folder, a Documents/Strata that holds models,
539        else the default beside the install. The same rule for every command."""
540        from strata_control import discovery
541        return discovery.data_dir(Path(self._mcp_data_dir()))
542
543    def data_dir(self) -> Path:
544        return self.data_dir_choice()[0]
545
546    def data_dir_for(self, family: str | None, model: str | None) -> Path:
547        """Where this model's files are: the folder its installed run config names, else the data folder."""
548        if family and model:
549            path = self.installed_config(self.tag_of(family, model))
550            if path is not None:
551                try:
552                    from strata_control import discovery
553                    found = discovery.footprint(json.loads(path.read_text(encoding="utf-8-sig")), path).data_dir
554                    if found is not None:
555                        return found
556                except (OSError, ValueError):
557                    pass
558        return self.data_dir()
559
560    def disk_free(self, path: str | os.PathLike) -> float | None:
561        return self.strata.disk_free(Path(path))