llmctl-cli 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,350 @@
1
+ """Official ggml-org/llama.cpp binary installer and updater (`llmctl server install/update`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import os
8
+ import platform
9
+ import shutil
10
+ import stat
11
+ import tarfile
12
+ import zipfile
13
+ from dataclasses import asdict, dataclass
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from llmctl.cache import format_bytes
18
+ from llmctl.config import AppConfig, set_config_server_binary
19
+ from llmctl.hardware import HardwareInfo, detect_hardware
20
+ from llmctl.http_client import HttpError, download_bytes, request_json
21
+ from llmctl.ui import Console
22
+
23
+ LLAMA_CPP_RELEASES_API = "https://api.github.com/repos/ggml-org/llama.cpp/releases"
24
+
25
+
26
+ @dataclass
27
+ class ReleaseAssetChoice:
28
+ """Selected official llama.cpp release archive."""
29
+
30
+ tag: str
31
+ asset_name: str
32
+ download_url: str
33
+ size_bytes: int
34
+ backend: str
35
+
36
+ def to_dict(self) -> dict[str, object]:
37
+ return asdict(self)
38
+
39
+
40
+ def infer_accel_backend(hw: HardwareInfo, requested: str = "auto") -> str:
41
+ """Choose best llama.cpp binary flavor: metal | cuda | vulkan | cpu."""
42
+ clean = requested.strip().lower()
43
+ if clean in {"metal", "cuda", "vulkan", "cpu"}:
44
+ return clean
45
+ if hw.os_name == "darwin":
46
+ return "metal" if hw.arch.lower() in {"arm64", "aarch64"} else "cpu"
47
+ vendors = {g.vendor for g in hw.gpus}
48
+ if "nvidia" in vendors:
49
+ return "cuda"
50
+ if "vulkan" in vendors or "amd" in vendors or "igpu" in vendors:
51
+ return "vulkan"
52
+ return "cpu"
53
+
54
+
55
+ def select_release_asset(
56
+ release_data: dict[str, Any],
57
+ *,
58
+ sys_platform: str,
59
+ arch: str,
60
+ backend: str,
61
+ ) -> ReleaseAssetChoice | None:
62
+ """Pick the matching official llama.cpp prebuilt archive for OS, arch, and backend."""
63
+ tag = str(release_data.get("tag_name") or "").strip()
64
+ assets = release_data.get("assets")
65
+ if not tag or not isinstance(assets, list):
66
+ return None
67
+
68
+ arch_l = arch.lower()
69
+ is_arm = arch_l in {"arm64", "aarch64"}
70
+ is_x64 = arch_l in {"x86_64", "amd64", "x64"}
71
+
72
+ def is_archive(name: str) -> bool:
73
+ low = name.lower()
74
+ return (low.endswith((".zip", ".tar.gz", ".tgz"))) and (
75
+ "cudart" not in low and "xcframework" not in low
76
+ )
77
+
78
+ candidates = [
79
+ a
80
+ for a in assets
81
+ if isinstance(a, dict) and isinstance(a.get("name"), str) and is_archive(str(a["name"]))
82
+ ]
83
+
84
+ patterns: list[list[str]] = []
85
+ if sys_platform == "darwin":
86
+ if is_arm:
87
+ patterns = [["macos", "arm64"]]
88
+ elif is_x64:
89
+ patterns = [["macos", "x64"]]
90
+ elif sys_platform == "win32":
91
+ if is_arm:
92
+ patterns = [["win", "arm64"]]
93
+ elif is_x64:
94
+ if backend == "cuda":
95
+ patterns = [["win", "cuda", "x64"], ["win", "vulkan", "x64"], ["win", "cpu", "x64"]]
96
+ elif backend == "vulkan":
97
+ patterns = [["win", "vulkan", "x64"], ["win", "cpu", "x64"]]
98
+ else:
99
+ patterns = [["win", "cpu", "x64"], ["win", "vulkan", "x64"]]
100
+ else:
101
+ # Linux
102
+ if is_arm:
103
+ patterns = [["ubuntu", "arm64"], ["linux", "arm64"]]
104
+ elif is_x64:
105
+ if backend == "vulkan":
106
+ patterns = [["ubuntu", "vulkan", "x64"], ["ubuntu", "x64"]]
107
+ elif backend == "cuda":
108
+ patterns = [
109
+ ["ubuntu", "cuda", "x64"],
110
+ ["ubuntu", "vulkan", "x64"],
111
+ ["ubuntu", "x64"],
112
+ ]
113
+ else:
114
+ patterns = [["ubuntu", "x64"]]
115
+
116
+ for required_tokens in patterns:
117
+ for asset in candidates:
118
+ name_low = str(asset["name"]).lower()
119
+ if all(tok in name_low for tok in required_tokens):
120
+ # Avoid picking vulkan/cuda when plain ubuntu-x64 CPU was specifically requested
121
+ if required_tokens == ["ubuntu", "x64"] and any(
122
+ extra in name_low for extra in ("vulkan", "cuda", "rocm", "sycl", "kompute")
123
+ ):
124
+ continue
125
+ return ReleaseAssetChoice(
126
+ tag=tag,
127
+ asset_name=str(asset["name"]),
128
+ download_url=str(asset.get("browser_download_url") or ""),
129
+ size_bytes=int(asset.get("size") or 0),
130
+ backend=backend,
131
+ )
132
+ return None
133
+
134
+
135
+ def _safe_extract_archive(data: bytes, asset_name: str, dest: Path) -> None:
136
+ """Safely extract .zip or .tar.gz archive blocking path traversal."""
137
+ dest.mkdir(parents=True, exist_ok=True)
138
+ dest_resolved = dest.resolve()
139
+
140
+ if asset_name.lower().endswith(".zip"):
141
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
142
+ for member in zf.infolist():
143
+ target = (dest / member.filename).resolve()
144
+ if not target.is_relative_to(dest_resolved):
145
+ raise ValueError(f"Ruta insegura en zip: {member.filename!r}")
146
+ if member.is_dir():
147
+ target.mkdir(parents=True, exist_ok=True)
148
+ else:
149
+ target.parent.mkdir(parents=True, exist_ok=True)
150
+ target.write_bytes(zf.read(member))
151
+ return
152
+
153
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:*") as tf:
154
+ for member in tf.getmembers():
155
+ target = (dest / member.name).resolve()
156
+ if not target.is_relative_to(dest_resolved):
157
+ raise ValueError(f"Ruta insegura en tar: {member.name!r}")
158
+ if member.issym() or member.islnk():
159
+ link_target = (target.parent / member.linkname).resolve()
160
+ if not link_target.is_relative_to(dest_resolved):
161
+ raise ValueError(f"Enlace inseguro en tar: {member.name!r}")
162
+ tf.extractall(dest, filter="data")
163
+
164
+
165
+ def _find_extracted_binary(root: Path, sys_platform: str) -> Path | None:
166
+ exe_name = "llama-server.exe" if sys_platform == "win32" else "llama-server"
167
+ for dirpath, _, filenames in os.walk(root):
168
+ if exe_name in filenames:
169
+ return Path(dirpath) / exe_name
170
+ return None
171
+
172
+
173
+ def _read_installed_meta(base_dir: Path) -> dict[str, object]:
174
+ meta_file = base_dir / "installed.json"
175
+ if not meta_file.is_file():
176
+ return {}
177
+ try:
178
+ data = json.loads(meta_file.read_text(encoding="utf-8"))
179
+ return data if isinstance(data, dict) else {}
180
+ except (OSError, json.JSONDecodeError):
181
+ return {}
182
+
183
+
184
+ def fetch_release_info(*, tag: str | None = None) -> dict[str, Any]:
185
+ """Query GitHub API for latest (or specific tag) ggml-org/llama.cpp release."""
186
+ url = f"{LLAMA_CPP_RELEASES_API}/tags/{tag}" if tag else f"{LLAMA_CPP_RELEASES_API}/latest"
187
+ data = request_json(
188
+ url,
189
+ headers={"Accept": "application/vnd.github+json"},
190
+ timeout=20.0,
191
+ )
192
+ if not isinstance(data, dict):
193
+ raise HttpError("Respuesta inesperada de GitHub Releases.", url=url)
194
+ return data
195
+
196
+
197
+ def install_llama_server(
198
+ config: AppConfig,
199
+ console: Console,
200
+ *,
201
+ tag: str | None = None,
202
+ backend_pref: str = "auto",
203
+ install_dir: Path | None = None,
204
+ dry_run: bool = False,
205
+ update_only_if_newer: bool = False,
206
+ ) -> int:
207
+ """Download and install an official llama-server binary and persist its path in config.toml."""
208
+ hw = detect_hardware(sys_platform=config.sys_platform, arch=platform.machine())
209
+ accel = infer_accel_backend(hw, backend_pref)
210
+ base_dir = install_dir if install_dir is not None else (config.state_dir / "bin" / "llama.cpp")
211
+
212
+ try:
213
+ release = fetch_release_info(tag=tag)
214
+ except HttpError as exc:
215
+ console.error(f"No se pudo consultar GitHub Releases de llama.cpp: {exc}")
216
+ return 1
217
+
218
+ choice = select_release_asset(
219
+ release,
220
+ sys_platform=config.sys_platform,
221
+ arch=hw.arch,
222
+ backend=accel,
223
+ )
224
+ if choice is None or not choice.download_url:
225
+ console.error(
226
+ f"No se encontró un binario oficial de llama.cpp para "
227
+ f"{config.sys_platform}/{hw.arch} (backend={accel})."
228
+ )
229
+ return 1
230
+
231
+ existing = _read_installed_meta(base_dir)
232
+ if update_only_if_newer and existing.get("tag") == choice.tag and existing.get("binary"):
233
+ existing_bin = Path(str(existing["binary"]))
234
+ if existing_bin.is_file():
235
+ if console.json_mode:
236
+ console.emit_json(
237
+ {
238
+ "up_to_date": True,
239
+ "tag": choice.tag,
240
+ "binary": str(existing_bin),
241
+ }
242
+ )
243
+ else:
244
+ console.ok(f"llama-server ya está actualizado ({choice.tag}) en {existing_bin}.")
245
+ return 0
246
+
247
+ if dry_run:
248
+ if console.json_mode:
249
+ console.emit_json({"dry_run": True, "asset": choice.to_dict(), "dest": str(base_dir)})
250
+ else:
251
+ console.header("Instalación simulada (--dry-run)")
252
+ console.info(f"Release: {choice.tag} | Backend: {choice.backend}")
253
+ console.info(f"Asset: {choice.asset_name} ({format_bytes(choice.size_bytes)})")
254
+ console.info(f"URL: {choice.download_url}")
255
+ console.info(f"Destino: {base_dir}")
256
+ return 0
257
+
258
+ if not console.json_mode:
259
+ console.line(
260
+ f"Descargando {choice.asset_name} ({format_bytes(choice.size_bytes)}, "
261
+ f"release {choice.tag}, backend {choice.backend})..."
262
+ )
263
+
264
+ last_pct = -10
265
+
266
+ def _progress(done: int, total: int | None) -> None:
267
+ nonlocal last_pct
268
+ if console.json_mode or not total:
269
+ return
270
+ pct = int((done * 100) / total)
271
+ if pct >= last_pct + 20 or pct == 100:
272
+ last_pct = pct
273
+ console.stdout.write(
274
+ f"\r Progreso: {pct}% ({format_bytes(done)} / {format_bytes(total)})"
275
+ )
276
+ console.stdout.flush()
277
+
278
+ try:
279
+ archive = download_bytes(choice.download_url, timeout=300.0, on_progress=_progress)
280
+ except HttpError as exc:
281
+ console.error(f"Error descargando {choice.asset_name}: {exc}")
282
+ return 1
283
+
284
+ if not console.json_mode and last_pct >= 0:
285
+ console.stdout.write("\n")
286
+ console.stdout.flush()
287
+
288
+ version_dir = base_dir / choice.tag
289
+ if version_dir.exists():
290
+ shutil.rmtree(version_dir)
291
+
292
+ try:
293
+ _safe_extract_archive(archive, choice.asset_name, version_dir)
294
+ except (tarfile.TarError, zipfile.BadZipFile, ValueError) as exc:
295
+ console.error(f"Error extrayendo {choice.asset_name}: {exc}")
296
+ return 1
297
+
298
+ server_bin = _find_extracted_binary(version_dir, config.sys_platform)
299
+ if server_bin is None:
300
+ console.error(f"El archivo descargado no contenía llama-server en {version_dir}.")
301
+ return 1
302
+
303
+ if config.sys_platform != "win32":
304
+ mode = server_bin.stat().st_mode
305
+ server_bin.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
306
+
307
+ # Maintain a `current/` directory pointing to the extracted folder containing the binary
308
+ current_dir = base_dir / "current"
309
+ if current_dir.is_symlink() or current_dir.is_file():
310
+ current_dir.unlink()
311
+ elif current_dir.is_dir():
312
+ shutil.rmtree(current_dir)
313
+ shutil.copytree(server_bin.parent, current_dir)
314
+ final_bin = current_dir / server_bin.name
315
+
316
+ meta_payload = {
317
+ "tag": choice.tag,
318
+ "asset": choice.asset_name,
319
+ "backend": choice.backend,
320
+ "binary": str(final_bin),
321
+ }
322
+ (base_dir / "installed.json").write_text(json.dumps(meta_payload, indent=2), encoding="utf-8")
323
+ set_config_server_binary(config.config_file, final_bin)
324
+
325
+ if console.json_mode:
326
+ console.emit_json(
327
+ {"installed": True, **meta_payload, "config_file": str(config.config_file)}
328
+ )
329
+ else:
330
+ console.ok(f"llama-server {choice.tag} instalado en {final_bin}.")
331
+ console.info(f"Ruta guardada automáticamente en {config.config_file}.")
332
+ return 0
333
+
334
+
335
+ def server_install_info(config: AppConfig, console: Console) -> int:
336
+ """Display installed/detected llama-server binary metadata."""
337
+ base_dir = config.state_dir / "bin" / "llama.cpp"
338
+ meta = _read_installed_meta(base_dir)
339
+ payload = {
340
+ "active_binary": str(config.server_binary) if config.server_binary else None,
341
+ "managed_dir": str(base_dir),
342
+ "managed_install": meta or None,
343
+ }
344
+ if console.json_mode:
345
+ console.emit_json(payload)
346
+ return 0
347
+ console.header("Binario llama-server")
348
+ console.line(f" Detectado: {payload['active_binary'] or '(no encontrado)'}")
349
+ console.line(f" Gestionado: {meta.get('tag', 'ninguno')} ({meta.get('backend', '-')})")
350
+ return 0
@@ -0,0 +1,42 @@
1
+ """Service backend factory and exports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from llmctl.config import AppConfig
6
+ from llmctl.service.base import ServiceActionResult, ServiceBackend, ServiceStatus
7
+ from llmctl.service.launchd import LaunchdBackend, is_launchd_available
8
+ from llmctl.service.process import ProcessBackend
9
+ from llmctl.service.remote import RemoteBackend
10
+ from llmctl.service.systemd import SystemdBackend, is_systemd_user_available
11
+
12
+
13
+ def select_backend(config: AppConfig) -> ServiceBackend:
14
+ """Choose the right ServiceBackend from explicit config or automatic OS detection."""
15
+ requested = config.backend.strip().lower()
16
+ if requested == "remote" or (requested == "auto" and config.is_remote):
17
+ return RemoteBackend(config)
18
+ if requested == "systemd":
19
+ return SystemdBackend(config)
20
+ if requested == "launchd":
21
+ return LaunchdBackend(config)
22
+ if requested == "process":
23
+ return ProcessBackend(config)
24
+
25
+ # Auto-detection for local endpoints
26
+ if config.sys_platform.startswith("linux") and is_systemd_user_available():
27
+ return SystemdBackend(config)
28
+ if config.sys_platform == "darwin" and is_launchd_available():
29
+ return LaunchdBackend(config)
30
+ return ProcessBackend(config)
31
+
32
+
33
+ __all__ = [
34
+ "LaunchdBackend",
35
+ "ProcessBackend",
36
+ "RemoteBackend",
37
+ "ServiceActionResult",
38
+ "ServiceBackend",
39
+ "ServiceStatus",
40
+ "SystemdBackend",
41
+ "select_backend",
42
+ ]
llmctl/service/base.py ADDED
@@ -0,0 +1,282 @@
1
+ """Base service backend abstraction, API helpers, and portable log tailing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import time
7
+ from abc import ABC, abstractmethod
8
+ from collections import deque
9
+ from dataclasses import asdict, dataclass, field
10
+ from pathlib import Path
11
+ from typing import TextIO
12
+
13
+ from llmctl.config import AppConfig
14
+ from llmctl.http_client import HttpError, check_json_endpoint, request_json
15
+
16
+
17
+ @dataclass
18
+ class ServiceStatus:
19
+ """Normalized status of llama-server across backends."""
20
+
21
+ backend: str
22
+ running: bool
23
+ api_reachable: bool
24
+ api_root: str
25
+ pid: int | None = None
26
+ detail: str = ""
27
+ loaded_models: list[str] = field(default_factory=list)
28
+
29
+ def to_dict(self) -> dict[str, object]:
30
+ return asdict(self)
31
+
32
+
33
+ @dataclass
34
+ class ServiceActionResult:
35
+ """Result returned by lifecycle actions (start/stop/restart/install/free)."""
36
+
37
+ ok: bool
38
+ message: str
39
+ backend: str
40
+
41
+ def to_dict(self) -> dict[str, object]:
42
+ return asdict(self)
43
+
44
+
45
+ def is_in_container() -> bool:
46
+ """Detect common container runtimes (Docker, Podman, Kubernetes, LXC)."""
47
+ if Path("/.dockerenv").exists() or Path("/run/.containerenv").exists():
48
+ return True
49
+ cgroup = Path("/proc/1/cgroup")
50
+ if cgroup.is_file():
51
+ try:
52
+ text = cgroup.read_text(encoding="utf-8", errors="ignore").lower()
53
+ if any(tok in text for tok in ("docker", "podman", "kubepods", "containerd", "lxc")):
54
+ return True
55
+ except OSError:
56
+ pass
57
+ return False
58
+
59
+
60
+ def build_server_argv(config: AppConfig) -> list[str]:
61
+ """Construct the argv list to launch llama-server in router mode."""
62
+ if not config.server_binary:
63
+ raise FileNotFoundError(
64
+ "No se encontró el binario 'llama-server'. Configúralo en PATH, "
65
+ "LLMCTL_SERVER_BIN o [server].binary en config.toml."
66
+ )
67
+ argv = [
68
+ str(config.server_binary),
69
+ "--models-preset",
70
+ str(config.models_ini),
71
+ "--models-max",
72
+ str(config.models_max),
73
+ "--host",
74
+ config.host,
75
+ "--port",
76
+ str(config.port),
77
+ ]
78
+ if config.api_key:
79
+ argv.extend(["--api-key", config.api_key])
80
+ argv.extend(config.extra_args)
81
+ return argv
82
+
83
+
84
+ def list_router_models(
85
+ config: AppConfig, *, timeout: float = 3.0
86
+ ) -> tuple[bool, list[dict[str, str]]]:
87
+ """Query router /models (falling back to /v1/models) and return model status entries."""
88
+ reachable, payload = check_json_endpoint(
89
+ config.router_models_url, token=config.api_key, timeout=timeout
90
+ )
91
+ if reachable and isinstance(payload, dict) and isinstance(payload.get("data"), list):
92
+ rows: list[dict[str, str]] = []
93
+ for item in payload["data"]:
94
+ if not isinstance(item, dict) or not item.get("id"):
95
+ continue
96
+ status_obj = item.get("status")
97
+ status_val = (
98
+ str(
99
+ status_obj.get("value") if isinstance(status_obj, dict) else status_obj or ""
100
+ ).strip()
101
+ or "unknown"
102
+ )
103
+ rows.append(
104
+ {
105
+ "id": str(item["id"]),
106
+ "status": status_val,
107
+ "owned_by": str(item.get("owned_by") or "llama.cpp"),
108
+ }
109
+ )
110
+ return True, rows
111
+
112
+ v1_ok, v1_payload = check_json_endpoint(
113
+ config.models_url, token=config.api_key, timeout=timeout
114
+ )
115
+ if v1_ok and isinstance(v1_payload, dict) and isinstance(v1_payload.get("data"), list):
116
+ rows = [
117
+ {
118
+ "id": str(item["id"]),
119
+ "status": "available",
120
+ "owned_by": str(item.get("owned_by") or "llama.cpp"),
121
+ }
122
+ for item in v1_payload["data"]
123
+ if isinstance(item, dict) and item.get("id")
124
+ ]
125
+ return True, rows
126
+ return False, []
127
+
128
+
129
+ def probe_api_status(config: AppConfig, *, timeout: float = 2.0) -> tuple[bool, list[str]]:
130
+ """Check whether llama-server HTTP API responds and list any reported models."""
131
+ reachable, payload = check_json_endpoint(
132
+ config.models_url, token=config.api_key, timeout=timeout
133
+ )
134
+ if reachable and isinstance(payload, dict):
135
+ data = payload.get("data")
136
+ models = (
137
+ [str(entry["id"]) for entry in data if isinstance(entry, dict) and entry.get("id")]
138
+ if isinstance(data, list)
139
+ else []
140
+ )
141
+ return True, models
142
+
143
+ health_ok, _ = check_json_endpoint(config.health_url, token=config.api_key, timeout=timeout)
144
+ return health_ok, []
145
+
146
+
147
+ def try_api_unload(config: AppConfig, *, timeout: float = 5.0) -> tuple[bool, str]:
148
+ """Try unloading active models via llama-server router API before falling back to restart."""
149
+ reachable, payload = check_json_endpoint(
150
+ config.router_models_url, token=config.api_key, timeout=timeout
151
+ )
152
+ if not reachable or not isinstance(payload, dict):
153
+ return False, "Endpoint /models no disponible."
154
+
155
+ entries = payload.get("data") if isinstance(payload.get("data"), list) else []
156
+ loaded_ids: list[str] = []
157
+ for item in entries:
158
+ if not isinstance(item, dict):
159
+ continue
160
+ model_id = str(item.get("id") or "").strip()
161
+ status_obj = item.get("status")
162
+ status_val = (
163
+ str(status_obj.get("value") if isinstance(status_obj, dict) else status_obj or "")
164
+ .strip()
165
+ .lower()
166
+ )
167
+ if model_id and status_val == "loaded":
168
+ loaded_ids.append(model_id)
169
+
170
+ if not loaded_ids:
171
+ return True, "No había modelos cargados en VRAM (router activo)."
172
+
173
+ unload_url = f"{config.api_root}/models/unload"
174
+ unloaded: list[str] = []
175
+ for model_id in loaded_ids:
176
+ try:
177
+ request_json(
178
+ unload_url,
179
+ method="POST",
180
+ payload={"model": model_id},
181
+ token=config.api_key,
182
+ timeout=timeout,
183
+ )
184
+ unloaded.append(model_id)
185
+ except HttpError:
186
+ return False, f"El servidor no soportó /models/unload para {model_id}."
187
+
188
+ return True, f"VRAM liberada vía API (descargados: {', '.join(unloaded)})."
189
+
190
+
191
+ def tail_file(
192
+ log_path: Path,
193
+ *,
194
+ lines: int = 50,
195
+ follow: bool = False,
196
+ stream: TextIO | None = None,
197
+ poll_interval: float = 0.25,
198
+ ) -> int:
199
+ """Portable pure-Python implementation of `tail -n <lines> [-f]`."""
200
+ out = sys.stdout if stream is None else stream
201
+ if not log_path.is_file():
202
+ print(f"No existe el archivo de logs: {log_path}", file=sys.stderr)
203
+ return 1
204
+
205
+ with log_path.open("r", encoding="utf-8", errors="replace") as fh:
206
+ recent = deque(fh, maxlen=max(0, lines))
207
+ for line in recent:
208
+ out.write(line)
209
+ out.flush()
210
+
211
+ if not follow:
212
+ return 0
213
+
214
+ try:
215
+ while True:
216
+ chunk = fh.readline()
217
+ if chunk:
218
+ out.write(chunk)
219
+ out.flush()
220
+ else:
221
+ time.sleep(poll_interval)
222
+ except KeyboardInterrupt:
223
+ return 0
224
+
225
+
226
+ class ServiceBackend(ABC):
227
+ """Abstract interface implemented by platform-specific service backends."""
228
+
229
+ name: str = "base"
230
+
231
+ def __init__(self, config: AppConfig) -> None:
232
+ self.config = config
233
+
234
+ @abstractmethod
235
+ def start(self) -> ServiceActionResult:
236
+ """Start llama-server."""
237
+
238
+ @abstractmethod
239
+ def stop(self) -> ServiceActionResult:
240
+ """Stop llama-server."""
241
+
242
+ @abstractmethod
243
+ def restart(self) -> ServiceActionResult:
244
+ """Restart llama-server."""
245
+
246
+ @abstractmethod
247
+ def status(self) -> ServiceStatus:
248
+ """Return normalized service & API status."""
249
+
250
+ @abstractmethod
251
+ def logs(self, *, follow: bool = True, lines: int = 50) -> int:
252
+ """Stream or print server logs and return an exit code."""
253
+
254
+ @abstractmethod
255
+ def install(self) -> ServiceActionResult:
256
+ """Install/write OS service definition if applicable."""
257
+
258
+ @abstractmethod
259
+ def uninstall(self) -> ServiceActionResult:
260
+ """Remove OS service definition if applicable."""
261
+
262
+ def info(self) -> dict[str, object]:
263
+ """Return diagnostic metadata about this backend."""
264
+ return {
265
+ "backend": self.name,
266
+ "api_root": self.config.api_root,
267
+ "server_binary": str(self.config.server_binary) if self.config.server_binary else None,
268
+ }
269
+
270
+ def free_vram(self) -> ServiceActionResult:
271
+ """Unload active model from VRAM via router API, falling back to restart."""
272
+ ok, msg = try_api_unload(self.config)
273
+ if ok:
274
+ return ServiceActionResult(ok=True, message=msg, backend=self.name)
275
+ res = self.restart()
276
+ if res.ok:
277
+ return ServiceActionResult(
278
+ ok=True,
279
+ message="VRAM liberada reiniciando el router (listo bajo demanda).",
280
+ backend=self.name,
281
+ )
282
+ return res