From e61e90e5551a67f6562109312aeb85d83706480d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 23:25:34 +0200 Subject: [PATCH] launch: settings, catalog (setup.py tables via strata_mcp, fitOn port), presets store, access, runner, flags, connect, harness drafts --- strata_cli/cli.py | 13 +- strata_cli/launch/__init__.py | 1 + strata_cli/launch/access.py | 301 ++++++++++++++++ strata_cli/launch/catalog.py | 301 ++++++++++++++++ strata_cli/launch/cmd.py | 551 +++++++++++++++++++++++++++++ strata_cli/launch/harness.py | 207 +++++++++++ strata_cli/launch/params.py | 183 ++++++++++ strata_cli/launch/runner.py | 631 ++++++++++++++++++++++++++++++++++ strata_cli/launch/settings.py | 282 +++++++++++++++ strata_cli/launch/store.py | 141 ++++++++ strata_cli/launch/widgets.py | 202 +++++++++++ 11 files changed, 2812 insertions(+), 1 deletion(-) create mode 100644 strata_cli/launch/__init__.py create mode 100644 strata_cli/launch/access.py create mode 100644 strata_cli/launch/catalog.py create mode 100644 strata_cli/launch/cmd.py create mode 100644 strata_cli/launch/harness.py create mode 100644 strata_cli/launch/params.py create mode 100644 strata_cli/launch/runner.py create mode 100644 strata_cli/launch/settings.py create mode 100644 strata_cli/launch/store.py create mode 100644 strata_cli/launch/widgets.py diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 0ab1c107..12c543a2 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -449,6 +449,8 @@ def parser() -> argparse.ArgumentParser: tune_commands.add_tune_auto(tune_sp) tune_commands.add_presets(sp) + from strata_cli.launch import cmd as launch_cmd + launch_cmd.add_parsers(sp) monitor_commands.add_status(sp) monitor_commands.add_monitor(sp) monitor_commands.add_logs(sp) @@ -1847,6 +1849,9 @@ def _run(a: argparse.Namespace) -> int: return _timeskip(a) if a.command == "presets": return tune_commands.presets_command(a) + if a.command in ("launch", "connect"): + from strata_cli.launch import cmd as launch_cmd + return launch_cmd.run_launch(a) if a.command == "launch" else launch_cmd.run_connect(a) if a.command == "tune": return _tune(a) if a.command == "runtime": @@ -1915,7 +1920,13 @@ def main(argv: list[str] | None = None) -> int: except ImportError: # a thin bundle ships without strata_control pass ap = parser() - a = ap.parse_args(argv) + a, extras = ap.parse_known_args(argv) + if extras: + if getattr(a, "command", None) in ("launch", "connect"): + from strata_cli.launch import cmd as launch_cmd + print("strata: " + launch_cmd.unknown_option_message(a.command, extras, ap), file=sys.stderr) + return 2 + ap.error("unrecognized arguments: " + " ".join(extras)) if getattr(a, "json", False) and a.command not in ("status", "monitor", "logs", "connection", "config"): if a.output == "jsonl": return _serve_error(a, "--json is one-shot only; use --output jsonl for foreground events") diff --git a/strata_cli/launch/__init__.py b/strata_cli/launch/__init__.py new file mode 100644 index 00000000..75dcedf5 --- /dev/null +++ b/strata_cli/launch/__init__.py @@ -0,0 +1 @@ +"""`strata launch`: guided setup, serving and the monitor, in the terminal.""" diff --git a/strata_cli/launch/access.py b/strata_cli/launch/access.py new file mode 100644 index 00000000..2832896b --- /dev/null +++ b/strata_cli/launch/access.py @@ -0,0 +1,301 @@ +"""Who can reach the server: this computer, the local network, a Cloudflare quick tunnel, Tailscale. + +Strata starts the server; this module only works out the addresses, checks that the helper programs exist (and says in plain +words how to install them when they do not), and runs/stops the one helper Strata starts itself: the cloudflared quick tunnel. +Nothing here changes a firewall, a router or a Tailscale setting. The cloudflared output is filtered: only the public address +is ever kept or shown (a login or certificate line is dropped, never printed). +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import socket +import subprocess +import sys +import time +from dataclasses import dataclass +from pathlib import Path + +from strata_cli.launch.settings import ACCESS_KINDS, LaunchSettings + +TUNNEL_URL = re.compile(r"https://[a-z0-9-]+\.trycloudflare\.com") +WINDOWS = os.name == "nt" + + +def host_for(kind: str) -> str: + """The address the server listens on: loopback for this computer only, every address for the rest. + + Cloudflare's tunnel connects from the same computer, so it too can stay on loopback.""" + return "127.0.0.1" if kind in ("local", "cloudflare") else "0.0.0.0" + + +def lan_ips() -> list[str]: + """This computer's private IPv4 addresses, the one used for the default route first.""" + found: list[str] = [] + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.settimeout(0.2) + s.connect(("10.255.255.255", 1)) # no packet is sent; it picks the interface of the default route + found.append(s.getsockname()[0]) + s.close() + except OSError: + pass + try: + import psutil + for infos in psutil.net_if_addrs().values(): + for i in infos: + if i.family == socket.AF_INET: + found.append(i.address) + except Exception: # noqa: BLE001 + pass + private = [a for a in dict.fromkeys(found) if _is_private(a) and not a.startswith("127.") and not a.startswith("169.254.")] + return private + + +def _is_private(address: str) -> bool: + try: + a, b = (int(x) for x in address.split(".")[:2]) + except ValueError: + return False + return a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or (a == 100 and 64 <= b <= 127) + + +def find_cloudflared() -> str | None: + found = shutil.which("cloudflared") + if found: + return found + for guess in ("/usr/local/bin/cloudflared", "/opt/homebrew/bin/cloudflared", r"C:\Program Files (x86)\cloudflared\cloudflared.exe", + r"C:\Program Files\cloudflared\cloudflared.exe"): + if Path(guess).is_file(): + return guess + return None + + +def find_tailscale() -> str | None: + found = shutil.which("tailscale") + if found: + return found + for guess in ("/usr/bin/tailscale", "/usr/local/bin/tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale", + r"C:\Program Files\Tailscale\tailscale.exe"): + if Path(guess).is_file(): + return guess + return None + + +def _run(argv: list[str], timeout: float = 8.0) -> str: + try: + r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout) + return r.stdout or "" + except (OSError, subprocess.SubprocessError): + return "" + + +def tailscale_status() -> dict: + """{"installed", "running", "ip", "name"}: the tailnet address of this computer when Tailscale is up.""" + exe = find_tailscale() + out = {"installed": bool(exe), "running": False, "ip": None, "name": None} + if not exe: + return out + ip = _run([exe, "ip", "-4"]).strip().splitlines() + if ip and re.fullmatch(r"\d+\.\d+\.\d+\.\d+", ip[0].strip()): + out["running"], out["ip"] = True, ip[0].strip() + try: + data = json.loads(_run([exe, "status", "--json"]) or "{}") + name = (data.get("Self") or {}).get("DNSName") + out["name"] = name.rstrip(".") if isinstance(name, str) and name else None + except ValueError: + pass + return out + + +INSTALL_HELP = { + "cloudflared": { + "linux": "Install cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/ " + "(on Debian/Ubuntu download the .deb and run: sudo dpkg -i cloudflared-linux-amd64.deb). No account is needed for a quick tunnel.", + "windows": "Install cloudflared: winget install --id Cloudflare.cloudflared (no account is needed for a quick tunnel).", + "darwin": "Install cloudflared: brew install cloudflared (no account is needed for a quick tunnel).", + }, + "tailscale": { + "linux": "Install Tailscale: curl -fsSL https://tailscale.com/install.sh | sh, then run: sudo tailscale up", + "windows": "Install Tailscale from https://tailscale.com/download, sign in, and leave it running.", + "darwin": "Install Tailscale from https://tailscale.com/download, sign in, and leave it running.", + }, +} + + +def install_help(tool: str) -> str: + plat = "windows" if WINDOWS else "darwin" if sys.platform == "darwin" else "linux" + return INSTALL_HELP[tool][plat] + + +@dataclass +class AccessOption: + kind: str + label: str + url: str + note: str + ready: bool # the helper it needs is there (or none is needed) + warn: bool = False + + +def options(port: int, *, tunnel_url: str | None = None) -> list[AccessOption]: + """The four ways to share, with the address each would give and what is missing for it.""" + ips = lan_ips() + lan = ips[0] if ips else None + cf = find_cloudflared() + ts = tailscale_status() + out = [AccessOption("local", "This computer only", f"http://127.0.0.1:{port}", + "for apps on this computer (OpenCode, Codex, Claude Code...)", True)] + out.append(AccessOption("lan", "My local network", f"http://{lan or ''}:{port}", + "other computers at home or in the office" if lan else + "other computers on your network; no network address was found on this computer", bool(lan), warn=not lan)) + out.append(AccessOption("cloudflare", "Cloudflare tunnel", tunnel_url or "https://.trycloudflare.com", + "from anywhere, no router setup · cloudflared found" if cf else "cloudflared is not installed", + bool(cf), warn=not cf)) + if ts["running"]: + out.append(AccessOption("tailscale", "Tailscale", f"http://{ts['name'] or ts['ip']}:{port}", + f"your Tailscale devices · tailnet address {ts['ip']}", True)) + else: + out.append(AccessOption("tailscale", "Tailscale", f"http://:{port}", + "Tailscale is installed but not connected (run: tailscale up)" if ts["installed"] else + "Tailscale is not installed", False, warn=True)) + return out + + +def option_for(kind: str, port: int) -> AccessOption: + return next(o for o in options(port) if o.kind == kind) + + +def missing_helper(kind: str) -> str | None: + """Plain words about what to install before this access kind works, or None when it is ready.""" + if kind == "cloudflare" and not find_cloudflared(): + return "cloudflared is not installed on this computer. " + install_help("cloudflared") + if kind == "tailscale": + ts = tailscale_status() + if not ts["installed"]: + return "Tailscale is not installed on this computer. " + install_help("tailscale") + if not ts["running"]: + return "Tailscale is installed but not connected. Run: tailscale up" + if kind == "lan" and not lan_ips(): + return "No local network address was found on this computer. Check that it is connected to your network." + return None + + +def urls_for(s: LaunchSettings, *, tunnel_url: str | None = None) -> list[str]: + """The addresses a client can use for these choices (the first is the main one).""" + base = [f"http://127.0.0.1:{s.port}"] + if s.access == "lan": + base += [f"http://{ip}:{s.port}" for ip in lan_ips()[:1]] + elif s.access == "cloudflare" and tunnel_url: + base = [tunnel_url] + base + elif s.access == "tailscale": + ts = tailscale_status() + if ts["running"]: + base += [f"http://{ts['name'] or ts['ip']}:{s.port}"] + ([f"http://{ts['ip']}:{s.port}"] if ts["name"] else []) + return base + + +def new_key() -> str: + import secrets + return "sk-strata-" + secrets.token_urlsafe(24) + + +def mask_key(key: str | None) -> str: + if not key: + return "off" + return key[:10] + "•" * 8 if len(key) > 12 else "•" * 8 + + +# ----------------------------------------------------------------------------------------------- the quick tunnel + +def _state_dir() -> Path: + from strata_control import paths + d = paths.state_base() / "launch" + d.mkdir(parents=True, exist_ok=True) + return d + + +def _tunnel_state(name: str) -> Path: + from strata_cli.launch.settings import slug + return _state_dir() / f"{slug(name)}.tunnel.json" + + +def start_tunnel(name: str, port: int, *, wait: float = 45.0) -> tuple[str | None, str]: + """Start `cloudflared tunnel --url` for the local server; returns (public url or None, plain message). + + The process is detached (it keeps running after this terminal closes, like the server) and recorded with its start token so + `stop_tunnel` ends exactly this process and nothing else. Only the public address is read from its output.""" + exe = find_cloudflared() + if not exe: + return None, missing_helper("cloudflare") or "cloudflared is not installed." + existing = tunnel_info(name) + if existing and existing.get("url") and existing.get("port") == port: + return existing["url"], "The tunnel was already running." + stop_tunnel(name) + log = _state_dir() / f"{Path(name).name}.tunnel.log" + argv = [exe, "tunnel", "--no-autoupdate", "--url", f"http://127.0.0.1:{port}"] + with open(log, "wb") as out: + kw = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW} if WINDOWS + else {"start_new_session": True}) + proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, **kw) + from strata_control import procs + token = procs.start_token(proc.pid) + url = None + deadline = time.monotonic() + wait + while time.monotonic() < deadline and url is None and proc.poll() is None: + try: + m = TUNNEL_URL.search(log.read_text(encoding="utf-8", errors="replace")) + except OSError: + m = None + if m: + url = m.group(0) + break + time.sleep(0.4) + state = {"pid": proc.pid, "token": token, "cmd": list(procs.command_line(proc.pid) or argv), "url": url, "port": port} + _tunnel_state(name).write_text(json.dumps(state), encoding="utf-8") + try: + log.write_bytes(b"") # keep no log text: the address is all anyone needs from it + except OSError: + pass + if url is None: + stop_tunnel(name) + return None, ("The Cloudflare tunnel did not come up in time. Check your internet connection and try again; " + "the server itself is running and still works on this computer.") + return url, "The Cloudflare tunnel is up. Anyone with the address can reach the server, so keep the API key on." + + +def tunnel_info(name: str) -> dict | None: + try: + state = json.loads(_tunnel_state(name).read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + from strata_control import procs + if isinstance(state, dict) and procs.is_same(int(state.get("pid", 0)), state.get("token") or "", state.get("cmd")): + return state + return None + + +def stop_tunnel(name: str) -> bool: + """End this launch's tunnel, only if the recorded process is still exactly the one Strata started.""" + state = tunnel_info(name) + ok = False + if state: + from strata_control import procs + outcome = procs.end_one({"pid": state["pid"], "token": state["token"], "cmd": state["cmd"]}, grace=5.0) + ok = outcome in ("ended", "gone") + try: + _tunnel_state(name).unlink() + except OSError: + pass + return ok + + +def filter_line(line: str) -> str: + """For any helper output shown to a person: drop login/certificate/token lines, keep the rest.""" + low = line.lower() + if any(w in low for w in ("token", "cert", "login", "secret", "authorize", "credential")): + return "" + return line diff --git a/strata_cli/launch/catalog.py b/strata_cli/launch/catalog.py new file mode 100644 index 00000000..a911a565 --- /dev/null +++ b/strata_cli/launch/catalog.py @@ -0,0 +1,301 @@ +"""The model catalog, the computer's figures and the fit words for `strata launch`. + +There is ONE catalog: setup.py's MODELS / FAMILIES / CONTEXTS, which the desktop app reads through tools/strata_mcp.py +(`Strata.model_table`, `Strata.hardware`, `Strata.recommend`; the app page's own fit arithmetic is +apps/host/src/lib/native-fit.ts `fitOn`). This module loads that same file from the installer folder and ports `fitOn` line by +line; it holds no table of its own. Without the installer files (a Terminal bundle made before launch existed) it says so in +words instead of guessing. +""" + +from __future__ import annotations + +import importlib.util +import os +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from strata_cli.launch import settings as S + + +class CatalogUnavailable(RuntimeError): + """The installer files (setup.py, tools/strata_mcp.py) are not there; the message is for the user.""" + + +# --- apps/host/src/lib/native-fit.ts, ported (same constants, same rules) ------------------------------------------------ +DENSE_GB = 5.0 +SYSTEM_ROOM_GB = 10.0 +DENSE_EXTRA_GB = 1.0 + + +def _round1(n: float) -> float: + return round(n * 10) / 10 + + +def memory_needed(v: dict) -> float: + if isinstance(v.get("memory_gb"), (int, float)): + return float(v["memory_gb"]) + if v.get("mem_total") and isinstance(v.get("ram_needed_gb"), (int, float)): + return float(v["ram_needed_gb"]) + return _round1(float(v.get("experts_gb") or v.get("ram_needed_gb") or 0) + DENSE_EXTRA_GB) + + +def fit_on(v: dict, ram_gb: float | None, vram_gb: float | None) -> dict[str, Any]: + """native-fit.ts `fitOn`: where the weights go on this computer. Returns memoryGb, vramUseGb, ramUseGb, spillGb, known.""" + memory = memory_needed(v) + vram = float(vram_gb or 0) + if not ram_gb or ram_gb <= 0: + return {"memoryGb": memory, "vramUseGb": 0.0, "ramUseGb": 0.0, "spillGb": 0.0, "known": False} + experts = max(0.0, memory - DENSE_EXTRA_GB) + on_gpu = max(0.0, min(experts, vram - DENSE_GB)) + ram_room = max(0.0, float(ram_gb) - SYSTEM_ROOM_GB) + spill = max(0.0, experts - on_gpu - ram_room) + in_ram = max(0.0, experts - on_gpu - spill) + vram_use = min(vram, DENSE_GB + on_gpu) if vram > 0 else 0.0 + return {"memoryGb": memory, "vramUseGb": _round1(vram_use), + "ramUseGb": _round1(in_ram + (DENSE_EXTRA_GB if vram <= 0 else 0)), "spillGb": _round1(spill), "known": True} + + +# --- the verdict words --------------------------------------------------------------------------------------------------- +FITS, TIGHT, NO = "fits", "tight", "no" + + +def verdict(on_this_pc: str | None) -> tuple[str, str]: + """(category, plain words) from the catalog's own `on_this_pc` text (setup.py `--check`'s rules, through strata_mcp). + + Never a block: `no` still lets the person try, and the screen says so.""" + text = (on_this_pc or "").strip() + low = text.lower() + if not text: + return TIGHT, "not checked (this computer's memory could not be read)" + if low.startswith("does not fit"): + return NO, "does not fit (you can still try)" + if "low-ram mode" in low: + return FITS, "fits (slower: part of it stays in RAM or on the SSD)" + if "part of its experts" in low or "read from the ssd" in low: + base = "slow here" in low + return TIGHT, ("tight: part is read from the SSD, noticeably slower" if base else "fits, with part read from the SSD") + if low.startswith("tight"): + return TIGHT, "tight: close other programs" + if "fits" in low: + return FITS, "fits" + return TIGHT, text + + +@dataclass +class ModelRow: + family: str + family_title: str + model: str + id: str # the run config's tag (strata-.json) + about: str + download_gb: float + need_vram_gb: float + need_ram_gb: float + spill_gb: float + verdict: str + words: str + experimental: bool + images: bool + installed: bool + recommended: bool = False + mem_total: bool = False + memory_gb: float = 0.0 + + @property + def title(self) -> str: + return f"{self.family_title} {self.model}" + + +@dataclass +class Computer: + ram_gb: float | None = None + gpus: list[dict] = field(default_factory=list) + disk_free_gb: float | None = None + os: str = "" + avx2: bool | None = None + raw: dict = field(default_factory=dict) + + @property + def usable_gpus(self) -> list[dict]: + return [g for g in self.gpus if g.get("usable", True)] + + @property + def main_vram_gb(self) -> float: + return max((float(g.get("vram_gb") or 0) for g in self.usable_gpus), default=0.0) + + def line(self, data_dir: str | None = None) -> str: + g = self.usable_gpus + card = (f"{g[0].get('name', 'GPU').replace('NVIDIA GeForce ', '').replace('AMD Radeon ', '')} {g[0].get('vram_gb', 0):.0f} GB" + + (f" x{len(g)}" if len(g) > 1 else "")) if g else "no usable graphics card found" + ram = f"{self.ram_gb:.0f} GB RAM" if self.ram_gb else "RAM unknown" + disk = f"{self.disk_free_gb:,.0f} GB free" if self.disk_free_gb is not None else "" + return " · ".join(x for x in (card, ram, disk) if x) + + +def installer_folder(explicit: str | os.PathLike | None = None) -> Path: + """Where setup.py and tools/ are: this Terminal's own folder (the bundle, or a source checkout).""" + if explicit: + return Path(explicit) + return Path(__file__).resolve().parents[2] + + +def install_root(explicit: str | os.PathLike | None = None) -> Path: + """Where run configs of installed models live: STRATA_INSTALL_DIR, else beside the components folder (what the app uses).""" + if explicit: + return Path(explicit) + env = os.environ.get("STRATA_INSTALL_DIR") + if env: + return Path(env) + from strata_control import engine_component + return engine_component.components_dir().parent / "install" + + +class Catalog: + """setup.py's tables through strata_mcp's `Strata` object (the app's own catalog code).""" + + def __init__(self, src: str | os.PathLike | None = None, root: str | os.PathLike | None = None, + hardware: dict | None = None): + self.src = installer_folder(src) + self.root = install_root(root) + mcp = self.src / "tools" / "strata_mcp.py" + if not mcp.is_file() or not (self.src / "setup.py").is_file(): + raise CatalogUnavailable( + "This Terminal does not carry the model list. Install it again with the one-line installer, " + "or run `strata launch` from a full Strata folder (the folder with setup.py).") + self.root.mkdir(parents=True, exist_ok=True) + name = "strata_mcp_for_launch" + mod = sys.modules.get(name) + if mod is None: + if str(self.src) not in sys.path: + sys.path.insert(0, str(self.src)) + spec = importlib.util.spec_from_file_location(name, mcp) + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + real = sys.stdout + sys.stdout = sys.stderr # the module must not print into a screen + try: + spec.loader.exec_module(mod) + finally: + sys.stdout = real + self.mcp = mod + self.strata = mod.Strata(self.root, self.src) + self._hardware_override = hardware + + # ---- the computer + def hardware(self, fresh: bool = False) -> dict: + if self._hardware_override is not None: + hw = dict(self._hardware_override) + hw.setdefault("disk_free_gb", self.strata.disk_free(self.strata.data_dir())) + return hw + return self.strata.hardware(fresh=fresh) + + def computer(self, fresh: bool = False) -> Computer: + hw = self.hardware(fresh) + return Computer(ram_gb=hw.get("ram_gb"), gpus=list(hw.get("gpus") or []), disk_free_gb=hw.get("disk_free_gb"), + os=str(hw.get("os") or ""), avx2=(hw.get("cpu") or {}).get("avx2"), raw=hw) + + # ---- the tables + def tables(self): + models, families, contexts, source = self.strata.tables() + return models, families, list(contexts), source + + def contexts(self) -> list[int]: + return [int(c) for c in self.tables()[2]] + + def recommendation(self, hw: dict | None = None) -> dict: + return self.strata.recommend(hw or self.hardware()) + + def rows(self, hw: dict | None = None) -> list[ModelRow]: + hw = hw or self.hardware() + comp = Computer(ram_gb=hw.get("ram_gb"), gpus=list(hw.get("gpus") or [])) + vram = comp.main_vram_gb + rec = self.recommendation(hw) + out: list[ModelRow] = [] + for fam in self.strata.model_table(hw): + for size in fam["sizes"]: + f = fit_on(size, hw.get("ram_gb"), vram) + cat, words = verdict(size.get("on_this_pc")) + out.append(ModelRow( + family=fam["family"], family_title=fam["title"], model=size["model"], id=size["id"], + about=size["about"], download_gb=float(size["download_gb"]), need_vram_gb=f["vramUseGb"], + need_ram_gb=f["ramUseGb"], spill_gb=f["spillGb"], verdict=cat, words=words, + experimental=bool(size.get("experimental") or fam.get("experimental")), images=bool(size.get("images")), + installed=bool(size.get("installed")), mem_total=bool(size.get("mem_total")), + memory_gb=float(size.get("memory_gb") or 0), + recommended=(rec.get("family") == fam["family"] and rec.get("model") == size["model"]))) + return out + + def resolve(self, model: str, family: str | None = None) -> tuple[str, str]: + """`iq3_xxs` or `IQ3_XXS` (and an optional family) -> (family, model); raises ValueError with the closest match.""" + models, families, _ctx, _src = self.tables() + names = list(models) + match = next((n for n in names if n.lower() == model.lower()), None) + if match is None: + near = S.closest(model, names) + raise ValueError(f"There is no model called '{model}'." + (f" Did you mean '{near}'?" if near else "") + + " Models: " + ", ".join(names) + ".") + if family is not None and family not in families: + near = S.closest(family, list(families)) + raise ValueError(f"There is no model family called '{family}'." + (f" Did you mean '{near}'?" if near else "") + + " Families: " + ", ".join(families) + ".") + offered = [f for f in families if match in self.strata.sizes_of(models, f)] + if family is not None: + if family not in offered: + raise ValueError(f"{families[family]['title']} has no size {match}. It offers: " + + ", ".join(self.strata.sizes_of(models, family)) + ".") + return family, match + if not offered: + raise ValueError(f"{match} is not offered by any model family here.") + return ("qwen" if "qwen" in offered else offered[0]), match + + def tag_of(self, family: str, model: str) -> str: + _m, families, _c, _s = self.tables() + return (families[family].get("tag", "") + model).lower() + + def kv_gb(self, tokens: int, kv: str = "int8") -> float: + """The conversation memory for this many tokens, in GB (setup.py's UD_FIT_KV_BYTES: 13 attention layers).""" + mod = self.strata.setup_module() + table = getattr(mod, "UD_FIT_KV_BYTES", None) or {"fp16": 2112, "int8": 1056, "q4_0": 576, "k8v4": 816} + return tokens * 13 * table.get(kv, 1056) / 1e9 + + def max_context(self, family: str, model: str, hw: dict | None = None) -> int | None: + """The recommended context for this computer and model (setup.py: VRAM rule, then the RAM rule).""" + hw = hw or self.hardware() + usable = [g for g in hw.get("gpus") or [] if g.get("usable", True)] + vram = max((float(g.get("vram_gb") or 0) for g in usable), default=12.0) + rec = 32768 if vram < 14 else 65536 if vram < 20 else 131072 + mod = self.strata.setup_module() + models = self.tables()[0] + if mod is not None and models[model].get("budget"): + try: + if mod.unsloth_budget(model, hw.get("ram_gb") or 0.0): + rec = 8192 if vram < 14 else 32768 + except Exception: # noqa: BLE001 + pass + if mod is not None and hasattr(mod, "ram_ctx") and hw.get("ram_gb"): + try: + rec = min(rec, int(mod.ram_ctx(model, hw["ram_gb"], False))) + except Exception: # noqa: BLE001 + pass + return rec + + # ---- installed models + def installed_configs(self) -> list[dict]: + out = [] + for path in self.strata.configs(): + d = self.strata.describe_config(path) + d["path"] = str(path) + out.append(d) + return out + + def installed_config(self, tag: str) -> Path | None: + p = self.root / f"strata-{tag.lower()}.json" + return p if p.is_file() else None + + def data_dir(self) -> Path: + return self.strata.data_dir() + + def disk_free(self, path: str | os.PathLike) -> float | None: + return self.strata.disk_free(Path(path)) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py new file mode 100644 index 00000000..f6b70158 --- /dev/null +++ b/strata_cli/launch/cmd.py @@ -0,0 +1,551 @@ +"""The `strata launch` and `strata connect` commands: the flags, the plain-text (no TUI) run, and the hand-over to the TUI.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import threading +from pathlib import Path +from typing import Any + +from strata_cli.launch import settings as S + +EXAMPLES = """\ +examples: + strata launch open the guided screens (saved presets, then set up from the beginning) + strata launch --preset "IQ3_XXS 128K" start a saved preset (opens the monitor) + strata launch --model iq3_xxs --context 128k --parallel 4 --vision off --tune quick \\ + --access lan --port 8080 --save-preset "Office" --no-tui + set everything on the command line, serve, print the address + strata launch --model-path /data/models/IQ3_XXS --no-tui + use model files you already have (a folder or one .gguf) + strata launch --preset Office --set prefill=65536 --set STRATA_PIN_BY_NEED=1 --no-tui + change one advanced setting for this start + strata launch --plan --model q2_0 show what would happen, change nothing + strata launch --list-presets | --delete-preset NAME | --status | --stop [--preset NAME] + strata connect list the apps Strata can be connected to + strata connect opencode --write write OpenCode's config for the running server (keeps a backup) +""" + + +def _choice(label: str, options: tuple[str, ...]): + def convert(value: str) -> str: + v = str(value).strip().lower() + if v in options: + return v + near = S.closest(v, list(options)) + raise argparse.ArgumentTypeError( + f"'{value}' is not {label}." + (f" Did you mean '{near}'?" if near else "") + f" Choose one of: {', '.join(options)}.") + return convert + + +def _context(value: str) -> int: + try: + return S.parse_context(value) + except ValueError as e: + raise argparse.ArgumentTypeError(str(e)) from None + + +def _port(value: str) -> int: + try: + p = int(value) + except ValueError: + raise argparse.ArgumentTypeError(f"'{value}' is not a port number. Use a number from 1 to 65535, for example 8080.") from None + if not 1 <= p <= 65535: + raise argparse.ArgumentTypeError(f"port {p} does not exist. Use a number from 1 to 65535, for example 8080.") + return p + + +def _parallel(value: str) -> int: + try: + p = int(value) + except ValueError: + raise argparse.ArgumentTypeError(f"'{value}' is not a number of requests. Use 1 to 8, or leave it out to fit your card.") from None + if not 1 <= p <= 8: + raise argparse.ArgumentTypeError(f"{p} requests at once is outside what the engine can do. Use 1 to 8.") + return p + + +def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser]: + p = sp.add_parser( + "launch", help="guided setup, serve and monitor (the screens), or the same with flags", epilog=EXAMPLES, + formatter_class=argparse.RawDescriptionHelpFormatter, + description="Set up a model, tune it, start serving and watch it, in one place. With no flags it opens the guided screens: " + "start from a saved preset or set up from the beginning, one decision per screen. With flags it does the same " + "without asking, and opens the monitor (or, with --no-tui, prints the address and returns). " + "Presets are shared with the Strata app's profiles and tuning presets.") + g = p.add_argument_group("what to run") + g.add_argument("--preset", metavar="NAME", help="start a saved preset (other flags change it for this start)") + g.add_argument("--model", metavar="NAME", help="the model size, e.g. iq3_xxs, q2_0, ud-q4_k_xl (any case)") + g.add_argument("--family", metavar="NAME", help="the model family when a size is offered by several (qwen, swift, coder, ...)") + g.add_argument("--model-path", metavar="PATH", help="use model files you already have: a folder of shards or one .gguf file") + g.add_argument("--data-dir", metavar="DIR", help="where downloaded model files are stored (default: Strata's data folder)") + g.add_argument("--context", type=_context, metavar="SIZE", help="how much text it remembers at once: 32k, 64k, 128k, 256k or a number of tokens") + g.add_argument("--kv", type=_choice("a memory format", S.KV_MODES), metavar="FORMAT", help="conversation memory format: int8 (default), q4_0 (half the memory), k8v4, fp16") + g.add_argument("--vision", type=_choice("a picture setting", S.VISION_MODES), metavar="off|on|gpu|cpu", + help="let the model read pictures (default off)") + g.add_argument("--parallel", type=_parallel, metavar="N", help="requests answered at the same time, 1 to 8 (default: fit to your graphics card)") + g.add_argument("--gpu", metavar="LIST", help="graphics card numbers to use, e.g. 0 or 0,1 (default: the engine's choice)") + g.add_argument("--tune", type=_choice("a tuning mode", S.TUNE_MODES), metavar="quick|thorough|skip", help="find the fastest settings first (default: skip)") + g.add_argument("--tune-allow-small", action="store_true", help="let the tuner also try settings that can change answers very slightly") + g.add_argument("--set", action="append", default=[], metavar="KEY=VALUE", + help="an advanced engine setting or STRATA_* variable, e.g. prefill=65536 (repeat); unknown names get a warning, not a refusal") + a = p.add_argument_group("who can use it") + a.add_argument("--access", type=_choice("a way to share Strata", S.ACCESS_KINDS), metavar="local|lan|cloudflare|tailscale", + help="local: this computer only; lan: your network; cloudflare: a quick tunnel; tailscale: your tailnet") + a.add_argument("--port", type=_port, metavar="N", help=f"port (default {S.DEFAULT_PORT})") + a.add_argument("--api-key", metavar="KEY", help="the key clients must send (made for you when you share beyond this computer)") + a.add_argument("--api-key-env", metavar="NAME", help="read the key from this environment variable") + a.add_argument("--new-key", action="store_true", help="make a new API key") + o = p.add_argument_group("running") + o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name") + o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return") + o.add_argument("--plan", action="store_true", help="show what would happen and exit; nothing is changed") + o.add_argument("--feed", metavar="URL|DIR", help="where the signed update feed (engine downloads) is; default: STRATA_UPDATE_FEED or the project's") + o.add_argument("--output", choices=("human", "json"), default="human") + m = p.add_argument_group("manage") + m.add_argument("--list-presets", action="store_true", help="list saved presets") + m.add_argument("--delete-preset", metavar="NAME", help="delete a saved preset") + m.add_argument("--status", action="store_true", help="show what this command is serving now") + m.add_argument("--stop", action="store_true", help="stop what this command started (with --preset NAME: that one)") + m.add_argument("--show-key", action="store_true", help="print the API key of --preset NAME (or of the running launch)") + + c = sp.add_parser( + "connect", help="print (or write) the setup for an app that uses the running server", epilog=EXAMPLES, + formatter_class=argparse.RawDescriptionHelpFormatter, + description="Shows the settings file and environment an app needs to talk to the Strata server that `strata launch` started. " + "Without a name it lists the apps. With --write it writes the file after asking, keeping a backup of any file it replaces.") + c.add_argument("harness", nargs="?", help="opencode, codex, claude-code, omp, pi, hermes, openclaw, deepseek-harness") + c.add_argument("--url", metavar="URL", help="the server address (default: the running launch, else http://127.0.0.1:8080)") + c.add_argument("--key", metavar="KEY", help="the API key (default: the running launch's)") + c.add_argument("--key-env", metavar="NAME", help="read the key from this environment variable") + c.add_argument("--model", metavar="NAME", help="the model name the server reports (default: the running launch's)") + c.add_argument("--preset", metavar="NAME", help="take the address, key and model from this saved preset") + c.add_argument("--write", action="store_true", help="write the file(s), after asking; a replaced file is backed up first") + c.add_argument("--yes", action="store_true", help="do not ask before --write") + c.add_argument("--show-key", action="store_true", help="print the real key instead of a masked one") + c.add_argument("--output", choices=("human", "json"), default="human") + return [p, c] + + +def unknown_option_message(command: str, extras: list[str], parser: argparse.ArgumentParser) -> str: + """A plain sentence for flags the parser did not know, with the closest real one.""" + sub = None + for action in parser._actions: # noqa: SLF001 + if isinstance(action, argparse._SubParsersAction): # noqa: SLF001 + sub = action.choices.get(command) + known = sorted({o for act in (sub._actions if sub else []) for o in act.option_strings if o.startswith("--")}) # noqa: SLF001 + lines = [] + for bad in extras: + if not bad.startswith("-"): + lines.append(f"'{bad}' was not expected here.") + continue + name = bad.split("=", 1)[0] + near = S.closest(name, known) + lines.append(f"'{name}' is not a strata {command} option." + (f" Did you mean '{near}'?" if near else "")) + return " ".join(lines) + f" See: strata {command} --help" + + +# ------------------------------------------------------------------------------------------------ settings from flags + +def _gpus(text: str | None) -> list[int] | None: + if not text: + return None + try: + return [int(x) for x in str(text).replace(" ", "").split(",") if x != ""] + except ValueError: + raise ValueError(f"'{text}' is not a list of graphics card numbers. Use 0 or 0,1.") from None + + +def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSettings, list[str]]: + """The preset (if named) with the flags on top; model names resolved against the catalog. Returns (settings, warnings).""" + from strata_cli.launch import store + notices: list[str] = [] + s = store.load(a.preset) if a.preset else S.LaunchSettings() + if a.preset: + s.name = s.name or a.preset + if a.model_path: + s.model_path = str(Path(a.model_path).expanduser()) + if not a.model: + s.family = s.model = None + if a.model: + if catalog is None: + raise ValueError("The model list is not available in this Terminal; run it from the full Terminal install.") + s.family, s.model = catalog.resolve(a.model, a.family) + if not a.model_path: + s.model_path = None + elif a.family and s.model: + s.family = a.family + if a.data_dir: + s.data_dir = a.data_dir + if a.context: + s.context = a.context + if a.kv: + s.kv = a.kv + if a.vision: + s.vision = a.vision + if a.parallel: + s.parallel = a.parallel + if a.gpu: + s.gpus = _gpus(a.gpu) + if a.tune: + s.tune = a.tune + if a.tune_allow_small: + s.tune_allow_small = True + if a.access: + s.access = a.access + if a.port: + s.port = a.port + if a.api_key: + s.api_key = a.api_key + if a.api_key_env: + val = os.environ.get(a.api_key_env) + if not val: + raise ValueError(f"The environment variable {a.api_key_env} is empty or not set.") + s.api_key = val + if a.set: + s.extra = {**s.extra, **S.settings_from_pairs(a.set)} + if a.save_preset: + s.name = a.save_preset + return s, notices + + +def apply_defaults(s: S.LaunchSettings, catalog) -> tuple[S.LaunchSettings, list[S.Notice]]: + """Fill what was left open with the recommendation for this computer, and collect warnings (never errors for a bad fit).""" + notices: list[S.Notice] = [] + comp = catalog.computer() + hw = comp.raw + if not (s.family and s.model) and not s.model_path: + rec = catalog.recommendation(hw) + if rec.get("model"): + s.family, s.model = rec["family"], rec["model"] + notices.append(S.Notice("warn", f"No model was named, so Strata picked {rec['title']} for this computer ({rec['why']}).", "")) + else: + notices.append(S.Notice("error", "No model fits this computer by Strata's rules, and none was chosen.", + "Name one with --model (strata launch --help lists them); a bigger one will run slowly.")) + if s.family and s.model: + if s.context is None: + s.context = catalog.max_context(s.family, s.model, hw) + rows = [r for r in catalog.rows(hw) if r.family == s.family and r.model == s.model] + if rows: + r = rows[0] + if r.verdict == "no": + notices.append(S.Notice("warn", f"{r.title} does not fit this computer ({r.words}).", "It can still start; expect it to be slow or to run out of memory.")) + elif r.verdict == "tight": + notices.append(S.Notice("warn", f"{r.title} is a tight fit: {r.words}.", "Close other programs before you start.")) + if s.vision != "off" and not r.images: + notices.append(S.Notice("warn", f"{r.title} cannot read pictures yet, so pictures are off.", "")) + s.vision = "off" + notices += S.check_context(s, max_fit_tokens=None) + if s.access != "local" and not s.api_key: + from strata_cli.launch import access + s.api_key = access.new_key() + notices.append(S.Notice("warn", "A new API key was made, because the server is shared beyond this computer.", + "It is saved with the preset; show it with: strata launch --show-key")) + notices += S.check_access(s) + vram = comp.main_vram_gb or None + notices += S.check_parallel(s, vram_gb=vram) + return s, notices + + +# ------------------------------------------------------------------------------------------------ plain-text run + +def _say(line: str = "") -> None: + sys.stdout.write(line + "\n") + sys.stdout.flush() + + +def _printer(quiet: bool = False): + """An emit callback that prints readable lines: new text once, progress in steps of 10% when not on a terminal.""" + state = {"last": None, "pct": -10, "stage": None} + isatty = sys.stdout.isatty() + + def emit(ev) -> None: + if quiet: + return + text = ev.text + if ev.pct is not None and ev.stage in ("model", "engine", "tune"): + if isatty: + sys.stdout.write(f"\r {text} {ev.pct:.0f}% " + ("\n" if ev.pct >= 100 else "")) + sys.stdout.flush() + return + if ev.pct < 100 and ev.pct < state["pct"] + 10 and state["stage"] == ev.stage: + return + state["pct"] = ev.pct + if ev.stage != state["stage"] or text != state["last"]: + marker = {"warn": "[!] ", "error": "[X] "}.get(ev.level, " ") + _say(f"{marker}{text}") + state["last"], state["stage"] = text, ev.stage + return emit + + +def _stop_all(name: str | None) -> int: + from strata_cli.launch import access, store + from strata_control import profiles, runtime + targets = [name] if name else [p["id"] for p in profiles.list_profiles() if p["id"].startswith("launch-")] + stopped = 0 + for prof in targets: + prof = prof if prof.startswith("launch-") else "launch-" + S.slug(prof) + st = runtime.status(prof) + if st.get("state") in ("ready", "starting", "failed", "stale"): + r = runtime.stop(prof, timeout=180) + _say(f"Stopped {prof[7:]}." if r.get("ok") else f"Could not stop {prof[7:]}: {r.get('error') or r.get('state')}.") + stopped += 1 if r.get("ok") else 0 + access.stop_tunnel(prof) + if not stopped and not targets: + _say("Nothing from `strata launch` is running.") + elif not stopped: + _say("Nothing from `strata launch` is running.") + return 0 + + +def running_launches() -> list[dict]: + """Launch profiles whose server is up now: [{name, profile, url, state}].""" + from strata_control import profiles, runtime + out = [] + try: + listing = profiles.list_profiles() + except Exception: # noqa: BLE001 + return out + for p in listing: + if not p["id"].startswith("launch-"): + continue + try: + st = runtime.status(p["id"]) + except Exception: # noqa: BLE001 + continue + if st.get("state") not in ("ready", "starting"): + continue + try: + prof, _rev = profiles.load(p["id"]) + ov = prof.get("overrides") or {} + except Exception: # noqa: BLE001 + ov = {} + port = ov.get("port", S.DEFAULT_PORT) + out.append({"name": p["id"][7:], "profile": p["id"], "state": st.get("state"), "port": port, + "url": f"http://127.0.0.1:{port}", "host": ov.get("host", "127.0.0.1"), "config": prof.get("source_config")}) + return out + + +def launch_info(name: str | None = None) -> dict | None: + """Address, key and model name of a launch that is running (or the named preset), for `connect` and the monitor's Connect view.""" + from strata_cli.launch import store + running = running_launches() + pick = None + if name: + pick = next((r for r in running if r["name"] == S.slug(name)), None) + elif running: + pick = running[0] + cfg = {} + cfg_path = (pick or {}).get("config") + if cfg_path: + try: + cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + cfg = {} + preset = store.load(name, missing_ok=True) if name else None + if pick is None and preset is None: + return None + port = (pick or {}).get("port") or (preset.port if preset else S.DEFAULT_PORT) + return {"url": (pick or {}).get("url") or f"http://127.0.0.1:{port}", "key": cfg.get("api_key") or (preset.api_key if preset else None), + "model": cfg.get("model_name") or "strata", "running": bool(pick), "name": (pick or {}).get("name") or (preset.name if preset else None), + "port": port, "access": preset.access if preset else None} + + +def run_launch(a: argparse.Namespace) -> int: + from strata_cli.launch import store + from strata_cli.launch.catalog import Catalog, CatalogUnavailable + from strata_cli.launch.runner import LaunchError, Runner + machine = a.output == "json" + + def fail(text: str, code: int = 2) -> int: + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": text}})) + else: + print(f"strata: {text}", file=sys.stderr) + return code + + try: + if a.list_presets: + items = store.list_presets() + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "presets": [i.to_dict(with_key=False) for i in items]})) + elif not items: + _say("No saved presets yet. Save one with: strata launch --model ... --save-preset NAME") + else: + for i in items: + sm = store.summary(i) + _say(f"{i.name:<28} {sm['model']:<14} {S.context_label(i.context):<6} " + f"{(str(i.parallel) + ' request' + ('s' if i.parallel != 1 else '')) if i.parallel else 'fit to card':<14} " + f"{('tuned ' + (i.tuned_at or '')) if i.tuned_preset else 'not tuned':<16} {i.last_used or ''}") + return 0 + if a.delete_preset: + store.delete(a.delete_preset) + _say(f"Deleted the preset '{a.delete_preset}'. Models and tuning results were not touched.") + return 0 + if a.stop: + return _stop_all("launch-" + S.slug(a.preset) if a.preset else None) + if a.status: + rows = running_launches() + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "running": rows})) + elif not rows: + _say("Nothing from `strata launch` is running.") + for r in rows: + _say(f"{r['name']}: {r['state']} at {r['url']}") + return 0 + if a.show_key: + info = launch_info(a.preset) + if not info or not info.get("key"): + return fail("There is no API key for that launch." + ("" if a.preset else " Name a preset with --preset NAME."), 5) + _say(info["key"]) + return 0 + + try: + catalog = Catalog() + except CatalogUnavailable as e: + catalog = None + if a.model or a.model_path: + return fail(str(e), 5) + s, notices = settings_from_args(a, catalog) + have_choices = bool(a.preset or a.model or a.model_path or a.context or a.vision or a.parallel or a.access or a.tune) + interactive = sys.stdin.isatty() and sys.stdout.isatty() and not a.no_tui and not machine and not a.plan + if interactive and not have_choices: + from strata_cli.launch import app + return app.run_tui(None, catalog=catalog, feed=a.feed) + if catalog is None: + return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) + s, notes = apply_defaults(s, catalog) + errors = [n for n in notes if n.level == "error"] + if errors: + return fail(errors[0].line(), 2) + if a.new_key: + from strata_cli.launch import access + s.api_key = access.new_key() + if not s.name: + s.name = f"{s.model or 'model'} {S.context_label(s.context)}" + runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed) + if a.plan: + plan = runner.plan() + plan["warnings"] = [n.line() for n in notes] + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "plan": plan})) + else: + _say(f"Plan for '{s.name}':") + _say(f" model {s.family} {s.model}" if s.model else f" model your files at {s.model_path}") + _say(f" context {S.context_label(s.context)} pictures {s.vision} parallel {s.parallel or 'fit to your card'}") + _say(f" tuning {s.tune} access {S.ACCESS_WORDS[s.access]}, port {s.port}" + + (" API key on" if s.api_key else "")) + for n in notes: + _say(f" [!] {n.line()}") + _say(f" same as {S.flags_text(s)}") + _say("Nothing was changed.") + return 0 + for n in notes: + if not machine: + _say(f"[!] {n.line()}") + if interactive and have_choices: + from strata_cli.launch import app + return app.run_tui(s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset)) + try: + result = runner.run() + except LaunchError as e: + return fail(f"{e.text}" + (f" {e.next}" if e.next else ""), e.code) + if a.save_preset or a.preset: + saved = store.save(s, s.name) + store.touch_used(saved.name) + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "name": s.name, "profile": result.profile, "urls": result.urls, + "api_key": "set" if result.key else None, "tuned": result.tune_word, + "notices": result.notices + [n.line() for n in notes]})) + return 0 + _say("") + _say("Strata is serving.") + for i, u in enumerate(result.urls): + _say(f" {'This computer' if i == 0 and '127.0.0.1' in u else 'Address':<14} {u}/v1") + if result.key: + from strata_cli.launch import access + _say(f" {'API key':<14} {access.mask_key(result.key)} (show it: strata launch --show-key --preset \"{s.name}\")") + for n in result.notices: + _say(f"[!] {n}") + _say(f" Watch it: strata monitor --url {result.urls[0] if result.urls else ''}") + _say(f" Connect an app: strata connect opencode Stop: strata launch --stop --preset \"{s.name}\"") + return 0 + except store.PresetError as e: + return fail(str(e), 2) + except ValueError as e: + return fail(str(e), 2) + except KeyboardInterrupt: + return fail("Stopped.", 130) + + +# ------------------------------------------------------------------------------------------------ connect + +def run_connect(a: argparse.Namespace) -> int: + from strata_cli.launch import access, harness + machine = a.output == "json" + if not a.harness: + rows = [{"id": h.id, "title": h.title, "speaks": h.speaks, "status": h.status} for h in harness.HARNESSES] + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "harnesses": rows})) + else: + _say(f"{'App':<20}{'Works with':<22}Status") + for r in rows: + _say(f"{r['id']:<20}{r['speaks']:<22}{r['status']}") + _say("") + _say("Show one: strata connect opencode Write it for you: strata connect opencode --write") + return 0 + h = harness.find(a.harness) + if h is None: + near = harness.closest_name(a.harness) + msg = f"There is no app called '{a.harness}'." + (f" Did you mean '{near}'?" if near else "") + \ + " Apps: " + ", ".join(x.id for x in harness.HARNESSES) + "." + print(f"strata: {msg}", file=sys.stderr) + return 2 + info = launch_info(a.preset) or {} + url = a.url or info.get("url") or f"http://127.0.0.1:{S.DEFAULT_PORT}" + key = a.key or (os.environ.get(a.key_env) if a.key_env else None) or info.get("key") or "" + model = a.model or info.get("model") or "strata" + out = harness.render(h, url=url, key=key or "", model=model) + shown_key = key if a.show_key else None + if machine: + print(json.dumps({"schema_version": 1, "ok": True, **{k: (harness.mask(json.dumps(v), key) if False else v) for k, v in out.items()}})) + return 0 + _say(f"{h.title} ({h.speaks}; {h.status})") + if not info.get("running") and not a.url: + _say("[!] No running Strata server was found, so this uses the default address. Start one with: strata launch") + if not h.built_in and not h.tested: + _say("[!] This setup has not been tested with this app yet; treat it as a starting point.") + for n in h.notes: + _say(f" {n}") + for f in out["files"]: + _say("") + _say(f"File: {f['path']}" + (" (merged into an existing file)" if f["merge"] else "")) + for line in (f["text"] if shown_key else harness.mask(f["text"], key)).splitlines(): + _say(" " + line) + if out["env"]: + _say("") + _say("Environment:" if True else "") + for k, v in out["env"].items(): + _say(f" {k}={v if shown_key else harness.mask(v, key)}" if os.name != "nt" else f" set {k}={v if shown_key else harness.mask(v, key)}") + if h.install: + _say("") + _say(f"Install the app (if you have not): {h.install}") + if a.write: + if not out["files"]: + _say("Nothing to write for this app.") + return 0 + if not a.yes: + if not sys.stdin.isatty(): + print("strata: --write asks first; run it in a terminal or add --yes.", file=sys.stderr) + return 2 + ans = input("\nWrite these files now? A file that exists is copied to a backup first. [y/N] ").strip().lower() + if ans not in ("y", "yes"): + _say("Nothing was written.") + return 0 + for f in out["files"]: + r = harness.write_file(f) + _say(f"{r['action'].capitalize()} {r['path']}" + (f" (backup: {r['backup']})" if r["backup"] else "")) + return 0 diff --git a/strata_cli/launch/harness.py b/strata_cli/launch/harness.py new file mode 100644 index 00000000..2966b7d6 --- /dev/null +++ b/strata_cli/launch/harness.py @@ -0,0 +1,207 @@ +"""`strata connect `: the setup text for an app that talks to a running Strata server. + +Each harness is one entry of `HARNESSES` below: what it speaks, where its config file lives, the text to put there, the +environment variables, and whether that config has been **tested** (phaseA-tests/split/harness-configs/.md, section 4 of +TUI-LAUNCH-SPEC.md: one prompt with the answer checked and one tool call with its arguments checked, at 32K). + +TODO table (an entry says `tested=False` until its tested config replaces the draft below; the draft comes from the app's public +documentation and is labelled "not tested yet" on screen): + + opencode codex claude-code omp pi hermes openclaw -> tested configs from the section-4 worker + deepseek-harness -> built into the Strata app, nothing to write + +Placeholders in the templates: {url} (server root, no /v1), {key}, {model}, {port}. +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import time +from dataclasses import dataclass, field +from pathlib import Path + + +@dataclass +class FileSpec: + path: str # may start with ~ ; {home} {appdata} are not needed, ~ is expanded + kind: str # json | toml | yaml | text | env + content: str # template + merge: bool = False # json only: merge into an existing file instead of replacing it + + +@dataclass +class Harness: + id: str + title: str + speaks: str # "chat + tools", "responses + tools", ... + files: list[FileSpec] = field(default_factory=list) + env: dict[str, str] = field(default_factory=dict) + notes: list[str] = field(default_factory=list) + tested: bool = False + built_in: bool = False + aliases: tuple[str, ...] = () + install: str = "" + + @property + def status(self) -> str: + return "built into the Strata app" if self.built_in else ("tested" if self.tested else "not tested yet") + + +def _j(obj) -> str: + return json.dumps(obj, indent=2) + + +# --- drafts: replaced by the tested files of harness-configs/ (see the TODO table above) -------------------------------------- +HARNESSES: list[Harness] = [ + Harness("opencode", "OpenCode", "chat + tools", + files=[FileSpec("~/.config/opencode/opencode.json", "json", _j({ + "$schema": "https://opencode.ai/config.json", + "provider": {"strata": {"npm": "@ai-sdk/openai-compatible", "name": "Strata", + "options": {"baseURL": "{url}/v1", "apiKey": "{key}"}, + "models": {"{model}": {"name": "Strata ({model})"}}}}, + "model": "strata/{model}"}), merge=True)], + install="npm i -g opencode-ai"), + Harness("codex", "Codex CLI", "responses + tools", + files=[FileSpec("~/.codex/config.toml", "toml", + 'model = "{model}"\nmodel_provider = "strata"\n\n[model_providers.strata]\nname = "Strata"\n' + 'base_url = "{url}/v1"\nenv_key = "STRATA_API_KEY"\nwire_api = "responses"\n')], + env={"STRATA_API_KEY": "{key}"}, install="npm i -g @openai/codex"), + Harness("claude-code", "Claude Code", "messages + tools", + files=[FileSpec("~/.claude/settings.json", "json", _j({"env": { + "ANTHROPIC_BASE_URL": "{url}", "ANTHROPIC_AUTH_TOKEN": "{key}", "ANTHROPIC_MODEL": "{model}", + "ANTHROPIC_SMALL_FAST_MODEL": "{model}", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"}}), merge=True)], + env={"ANTHROPIC_BASE_URL": "{url}", "ANTHROPIC_AUTH_TOKEN": "{key}", "ANTHROPIC_MODEL": "{model}"}, + notes=["No Anthropic login is needed: the server answers with your local model."], + aliases=("claude",), install="npm i -g @anthropic-ai/claude-code"), + Harness("omp", "oh-my-pi (omp)", "chat + tools", + files=[FileSpec("~/.omp/agent/models.yml", "yaml", + "providers:\n strata:\n baseUrl: {url}/v1\n apiKey: {key}\n api: openai-completions\n" + " models:\n - id: {model}\n name: Strata ({model})\n")], + aliases=("oh-my-pi",)), + Harness("pi", "pi (pi.dev)", "chat + tools", + files=[FileSpec("~/.pi/agent/models.json", "json", _j({"providers": {"strata": { + "baseUrl": "{url}/v1", "api": "openai-completions", "apiKey": "{key}", + "models": [{"id": "{model}"}]}}}), merge=True)]), + Harness("hermes", "Hermes Agent", "chat + tools", + files=[FileSpec("~/.hermes/config.yaml", "yaml", + "model:\n provider: custom\n base_url: {url}/v1\n api_key: {key}\n default: {model}\n")], + aliases=("hermes-agent",)), + Harness("openclaw", "OpenClaw", "chat + tools", + files=[FileSpec("~/.openclaw/openclaw.json", "json", _j({"models": {"mode": "merge", "providers": {"strata": { + "baseUrl": "{url}/v1", "apiKey": "{key}", "api": "openai-completions", + "models": [{"id": "{model}", "name": "Strata ({model})"}]}}}, + "agents": {"defaults": {"model": {"primary": "strata/{model}"}}}}), merge=True)]), + Harness("deepseek-harness", "DeepSeek Harness", "the Strata app", built_in=True, + notes=["Strata's own coding harness lives in the Strata app: open the app, choose Code, and it uses this server."], + aliases=("deepseek",)), +] + +# The tested configs, when they exist, override the drafts: harness-configs/.json beside this file (made from the .md files). +OVERRIDE_DIR = Path(__file__).with_name("harness_configs") + + +def load_overrides() -> None: + if not OVERRIDE_DIR.is_dir(): + return + by_id = {h.id: h for h in HARNESSES} + for path in sorted(OVERRIDE_DIR.glob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + h = by_id.get(data["id"]) or Harness(data["id"], data.get("title", data["id"]), data.get("speaks", "")) + h.title = data.get("title", h.title) + h.speaks = data.get("speaks", h.speaks) + h.files = [FileSpec(**f) for f in data.get("files", [])] + h.env = dict(data.get("env", {})) + h.notes = list(data.get("notes", [])) + h.tested = bool(data.get("tested", True)) + h.install = data.get("install", h.install) + if h.id not in by_id: + HARNESSES.append(h) + except (OSError, ValueError, KeyError, TypeError): + continue + + +load_overrides() + + +def find(name: str) -> Harness | None: + key = name.strip().lower() + for h in HARNESSES: + if key == h.id or key in h.aliases or key == h.title.lower(): + return h + return None + + +def closest_name(name: str) -> str | None: + from strata_cli.launch.settings import closest + return closest(name, [h.id for h in HARNESSES]) + + +# ------------------------------------------------------------------------------------------------ rendering + +def fill(text: str, *, url: str, key: str, model: str, port: int) -> str: + """Replace the placeholders; the key goes in only where the caller passed a real one.""" + out = text + for k, v in (("{url}", url.rstrip("/")), ("{key}", key), ("{model}", model), ("{port}", str(port))): + out = out.replace(k, v) + return out + + +def render(h: Harness, *, url: str, key: str, model: str) -> dict: + """What to show or write for this harness: files with their text, and environment lines.""" + m = re.search(r":(\d+)(?:/|$)", url) + port = int(m.group(1)) if m else (443 if url.startswith("https") else 80) + files = [] + for f in h.files: + files.append({"path": f.path, "kind": f.kind, "merge": f.merge, + "text": fill(f.content, url=url, key=key, model=model, port=port)}) + env = {k: fill(v, url=url, key=key, model=model, port=port) for k, v in h.env.items()} + return {"harness": h.id, "title": h.title, "speaks": h.speaks, "status": h.status, "files": files, "env": env, + "notes": list(h.notes), "install": h.install} + + +def expand(path: str) -> Path: + return Path(os.path.expanduser(path)) + + +def write_file(spec: dict, *, backup: bool = True) -> dict: + """Write one rendered file. An existing file is copied to `.strata-bak-