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,190 @@
1
+ """macOS launchd LaunchAgent service backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import plistlib
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from llmctl.config import AppConfig
14
+ from llmctl.presets import ensure_ini
15
+ from llmctl.service.base import (
16
+ ServiceActionResult,
17
+ ServiceBackend,
18
+ ServiceStatus,
19
+ build_server_argv,
20
+ probe_api_status,
21
+ tail_file,
22
+ )
23
+
24
+ LAUNCHD_LABEL = "io.github.ana-alonso.llmctl.llama-server"
25
+
26
+
27
+ def is_launchd_available() -> bool:
28
+ """Return True on macOS when launchctl is present."""
29
+ return sys.platform == "darwin" and bool(shutil.which("launchctl"))
30
+
31
+
32
+ class LaunchdBackend(ServiceBackend):
33
+ """Manage llama-server as a per-user macOS LaunchAgent."""
34
+
35
+ name = "launchd"
36
+
37
+ def __init__(self, config: AppConfig, *, agents_dir: Path | None = None) -> None:
38
+ super().__init__(config)
39
+ self.agents_dir = (
40
+ agents_dir if agents_dir is not None else Path.home() / "Library" / "LaunchAgents"
41
+ )
42
+
43
+ @property
44
+ def plist_path(self) -> Path:
45
+ return self.agents_dir / f"{LAUNCHD_LABEL}.plist"
46
+
47
+ @property
48
+ def log_path(self) -> Path:
49
+ return self.config.log_dir / "llama-server.log"
50
+
51
+ @property
52
+ def domain_target(self) -> str:
53
+ uid = os.getuid() if hasattr(os, "getuid") else 501
54
+ return f"gui/{uid}"
55
+
56
+ @property
57
+ def service_target(self) -> str:
58
+ return f"{self.domain_target}/{LAUNCHD_LABEL}"
59
+
60
+ def build_plist_dict(self) -> dict[str, object]:
61
+ argv = build_server_argv(self.config)
62
+ return {
63
+ "Label": LAUNCHD_LABEL,
64
+ "ProgramArguments": argv,
65
+ "RunAtLoad": False,
66
+ "KeepAlive": {"SuccessfulExit": False},
67
+ "StandardOutPath": str(self.log_path),
68
+ "StandardErrorPath": str(self.log_path),
69
+ "WorkingDirectory": str(Path.home()),
70
+ }
71
+
72
+ def _run_launchctl(self, *args: str) -> subprocess.CompletedProcess[str]:
73
+ return subprocess.run(
74
+ ["launchctl", *args],
75
+ capture_output=True,
76
+ text=True,
77
+ check=False,
78
+ )
79
+
80
+ def install(self) -> ServiceActionResult:
81
+ ensure_ini(self.config.models_ini)
82
+ try:
83
+ payload = self.build_plist_dict()
84
+ except FileNotFoundError as exc:
85
+ return ServiceActionResult(ok=False, message=str(exc), backend=self.name)
86
+
87
+ self.agents_dir.mkdir(parents=True, exist_ok=True)
88
+ self.log_path.parent.mkdir(parents=True, exist_ok=True)
89
+ self.plist_path.write_bytes(plistlib.dumps(payload, fmt=plistlib.FMT_XML))
90
+ return ServiceActionResult(
91
+ ok=True,
92
+ message=f"LaunchAgent instalado en {self.plist_path}.",
93
+ backend=self.name,
94
+ )
95
+
96
+ def uninstall(self) -> ServiceActionResult:
97
+ self._run_launchctl("bootout", self.service_target)
98
+ if self.plist_path.exists():
99
+ self.plist_path.unlink()
100
+ return ServiceActionResult(
101
+ ok=True,
102
+ message=f"LaunchAgent eliminado ({self.plist_path}).",
103
+ backend=self.name,
104
+ )
105
+ return ServiceActionResult(
106
+ ok=True,
107
+ message="No había LaunchAgent instalado.",
108
+ backend=self.name,
109
+ )
110
+
111
+ def start(self) -> ServiceActionResult:
112
+ if not self.plist_path.exists():
113
+ installed = self.install()
114
+ if not installed.ok:
115
+ return installed
116
+ self.log_path.parent.mkdir(parents=True, exist_ok=True)
117
+ proc = self._run_launchctl("bootstrap", self.domain_target, str(self.plist_path))
118
+ if proc.returncode != 0:
119
+ # Already bootstrapped: kickstart it instead
120
+ kick = self._run_launchctl("kickstart", "-k", self.service_target)
121
+ if kick.returncode != 0:
122
+ return ServiceActionResult(
123
+ ok=False,
124
+ message=kick.stderr.strip() or proc.stderr.strip() or "Falló launchctl start.",
125
+ backend=self.name,
126
+ )
127
+ return ServiceActionResult(
128
+ ok=True,
129
+ message=f"llama-server activo en {self.config.api_root} (launchd).",
130
+ backend=self.name,
131
+ )
132
+
133
+ def stop(self) -> ServiceActionResult:
134
+ proc = self._run_launchctl("bootout", self.service_target)
135
+ if proc.returncode != 0 and "Could not find service" not in proc.stderr:
136
+ return ServiceActionResult(
137
+ ok=False,
138
+ message=proc.stderr.strip() or "No se pudo detener el LaunchAgent.",
139
+ backend=self.name,
140
+ )
141
+ return ServiceActionResult(
142
+ ok=True,
143
+ message="llama-server detenido (launchd).",
144
+ backend=self.name,
145
+ )
146
+
147
+ def restart(self) -> ServiceActionResult:
148
+ if not self.plist_path.exists():
149
+ return self.start()
150
+ proc = self._run_launchctl("kickstart", "-k", self.service_target)
151
+ if proc.returncode != 0:
152
+ self.stop()
153
+ return self.start()
154
+ return ServiceActionResult(
155
+ ok=True,
156
+ message=f"llama-server reiniciado en {self.config.api_root} (launchd).",
157
+ backend=self.name,
158
+ )
159
+
160
+ def status(self) -> ServiceStatus:
161
+ proc = self._run_launchctl("print", self.service_target)
162
+ running = False
163
+ pid: int | None = None
164
+ if proc.returncode == 0:
165
+ match_pid = re.search(r"\bpid\s*=\s*(\d+)", proc.stdout)
166
+ if match_pid:
167
+ pid = int(match_pid.group(1))
168
+ running = pid > 0
169
+ elif "state = running" in proc.stdout:
170
+ running = True
171
+
172
+ api_ok, models = probe_api_status(self.config)
173
+ return ServiceStatus(
174
+ backend=self.name,
175
+ running=running,
176
+ api_reachable=api_ok,
177
+ api_root=self.config.api_root,
178
+ pid=pid,
179
+ detail="activo (launchd)" if running else "detenido (launchd)",
180
+ loaded_models=models,
181
+ )
182
+
183
+ def logs(self, *, follow: bool = True, lines: int = 50) -> int:
184
+ return tail_file(self.log_path, lines=lines, follow=follow)
185
+
186
+ def info(self) -> dict[str, object]:
187
+ base = super().info()
188
+ base["plist_path"] = str(self.plist_path)
189
+ base["log_path"] = str(self.log_path)
190
+ return base
@@ -0,0 +1,300 @@
1
+ """Portable background-process backend (Windows, containers, WSL, and POSIX fallback)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import signal
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+
14
+ from llmctl.config import AppConfig
15
+ from llmctl.presets import ensure_ini
16
+ from llmctl.service.base import (
17
+ ServiceActionResult,
18
+ ServiceBackend,
19
+ ServiceStatus,
20
+ build_server_argv,
21
+ probe_api_status,
22
+ tail_file,
23
+ )
24
+
25
+
26
+ def is_pid_alive(pid: int, *, sys_platform: str | None = None) -> bool:
27
+ """Check whether *pid* is currently running on POSIX or Windows."""
28
+ if pid <= 0:
29
+ return False
30
+ plat = sys.platform if sys_platform is None else sys_platform
31
+ if plat == "win32":
32
+ try:
33
+ import ctypes
34
+
35
+ windll = getattr(ctypes, "windll", None)
36
+ if windll is None:
37
+ return False
38
+ kernel32 = windll.kernel32
39
+ process_query_limited_info = 0x1000
40
+ still_active = 259
41
+ handle = kernel32.OpenProcess(process_query_limited_info, False, pid)
42
+ if not handle:
43
+ return False
44
+ try:
45
+ exit_code = ctypes.c_ulong()
46
+ if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
47
+ return False
48
+ return exit_code.value == still_active
49
+ finally:
50
+ kernel32.CloseHandle(handle)
51
+ except Exception:
52
+ return False
53
+
54
+ try:
55
+ os.kill(pid, 0)
56
+ except ProcessLookupError:
57
+ return False
58
+ except PermissionError:
59
+ return True
60
+ except OSError:
61
+ return False
62
+
63
+ # On Linux, a terminated but unreaped child (zombie) still responds to os.kill(pid, 0).
64
+ stat_path = Path(f"/proc/{pid}/status")
65
+ if stat_path.is_file():
66
+ try:
67
+ for line in stat_path.read_text(encoding="utf-8", errors="ignore").splitlines():
68
+ if (line.startswith("State:") and "\tZ" in line) or line.startswith("State: Z"):
69
+ return False
70
+ except OSError:
71
+ pass
72
+ return True
73
+
74
+
75
+ def _reap_if_child(pid: int) -> None:
76
+ if hasattr(os, "waitpid") and hasattr(os, "WNOHANG"):
77
+ with contextlib.suppress(ChildProcessError, OSError):
78
+ os.waitpid(pid, os.WNOHANG)
79
+
80
+
81
+ def terminate_pid(pid: int, *, timeout: float = 5.0, sys_platform: str | None = None) -> bool:
82
+ """Gracefully terminate *pid*, escalating to force-kill if needed."""
83
+ plat = sys.platform if sys_platform is None else sys_platform
84
+ if not is_pid_alive(pid, sys_platform=plat):
85
+ return True
86
+
87
+ if plat == "win32":
88
+ subprocess.run(
89
+ ["taskkill", "/PID", str(pid), "/T", "/F"],
90
+ capture_output=True,
91
+ check=False,
92
+ )
93
+ return not is_pid_alive(pid, sys_platform=plat)
94
+
95
+ try:
96
+ os.kill(pid, signal.SIGTERM)
97
+ except OSError:
98
+ _reap_if_child(pid)
99
+ return not is_pid_alive(pid, sys_platform=plat)
100
+
101
+ deadline = time.monotonic() + timeout
102
+ while time.monotonic() < deadline:
103
+ _reap_if_child(pid)
104
+ if not is_pid_alive(pid, sys_platform=plat):
105
+ return True
106
+ time.sleep(0.1)
107
+
108
+ sigkill = getattr(signal, "SIGKILL", signal.SIGTERM)
109
+ with contextlib.suppress(OSError):
110
+ os.kill(pid, sigkill)
111
+ time.sleep(0.1)
112
+ _reap_if_child(pid)
113
+ return not is_pid_alive(pid, sys_platform=plat)
114
+
115
+
116
+ class ProcessBackend(ServiceBackend):
117
+ """Manage llama-server as a detached user process with PID file and log file."""
118
+
119
+ name = "process"
120
+
121
+ def __init__(self, config: AppConfig) -> None:
122
+ super().__init__(config)
123
+
124
+ @property
125
+ def pid_file(self) -> Path:
126
+ return self.config.state_dir / "llama-server.pid.json"
127
+
128
+ @property
129
+ def log_path(self) -> Path:
130
+ return self.config.log_dir / "llama-server.log"
131
+
132
+ def _read_pid_state(self) -> dict[str, object] | None:
133
+ if not self.pid_file.is_file():
134
+ return None
135
+ try:
136
+ data = json.loads(self.pid_file.read_text(encoding="utf-8"))
137
+ return data if isinstance(data, dict) else None
138
+ except (OSError, json.JSONDecodeError):
139
+ return None
140
+
141
+ def _active_pid(self) -> int | None:
142
+ state = self._read_pid_state()
143
+ if not state:
144
+ return None
145
+ raw_pid = state.get("pid")
146
+ if not isinstance(raw_pid, int):
147
+ return None
148
+ if is_pid_alive(raw_pid, sys_platform=self.config.sys_platform):
149
+ return raw_pid
150
+ # Clean up stale PID file
151
+ self.pid_file.unlink(missing_ok=True)
152
+ return None
153
+
154
+ def _write_pid_state(self, pid: int, argv: list[str]) -> None:
155
+ self.pid_file.parent.mkdir(parents=True, exist_ok=True)
156
+ payload = {
157
+ "pid": pid,
158
+ "argv": argv,
159
+ "api_root": self.config.api_root,
160
+ "log_path": str(self.log_path),
161
+ "started_at": time.time(),
162
+ }
163
+ self.pid_file.write_text(json.dumps(payload, indent=2), encoding="utf-8")
164
+
165
+ def start(self) -> ServiceActionResult:
166
+ existing = self._active_pid()
167
+ if existing is not None:
168
+ return ServiceActionResult(
169
+ ok=True,
170
+ message=(
171
+ f"llama-server ya está en ejecución (PID {existing}, {self.config.api_root})."
172
+ ),
173
+ backend=self.name,
174
+ )
175
+
176
+ ensure_ini(self.config.models_ini)
177
+ try:
178
+ argv = build_server_argv(self.config)
179
+ except FileNotFoundError as exc:
180
+ return ServiceActionResult(ok=False, message=str(exc), backend=self.name)
181
+
182
+ self.log_path.parent.mkdir(parents=True, exist_ok=True)
183
+ try:
184
+ with self.log_path.open("a", encoding="utf-8") as log_fh:
185
+ if self.config.sys_platform == "win32":
186
+ create_new_group = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
187
+ detached = getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
188
+ proc = subprocess.Popen(
189
+ argv,
190
+ stdin=subprocess.DEVNULL,
191
+ stdout=log_fh,
192
+ stderr=subprocess.STDOUT,
193
+ close_fds=True,
194
+ creationflags=create_new_group | detached,
195
+ )
196
+ else:
197
+ proc = subprocess.Popen(
198
+ argv,
199
+ stdin=subprocess.DEVNULL,
200
+ stdout=log_fh,
201
+ stderr=subprocess.STDOUT,
202
+ close_fds=True,
203
+ start_new_session=True,
204
+ )
205
+ except OSError as exc:
206
+ return ServiceActionResult(
207
+ ok=False,
208
+ message=f"No se pudo lanzar llama-server: {exc}",
209
+ backend=self.name,
210
+ )
211
+
212
+ self._write_pid_state(proc.pid, argv)
213
+ return ServiceActionResult(
214
+ ok=True,
215
+ message=(
216
+ f"llama-server iniciado en segundo plano (PID {proc.pid}, {self.config.api_root})."
217
+ ),
218
+ backend=self.name,
219
+ )
220
+
221
+ def stop(self) -> ServiceActionResult:
222
+ pid = self._active_pid()
223
+ if pid is None:
224
+ self.pid_file.unlink(missing_ok=True)
225
+ return ServiceActionResult(
226
+ ok=True,
227
+ message="llama-server ya estaba detenido.",
228
+ backend=self.name,
229
+ )
230
+
231
+ stopped = terminate_pid(pid, sys_platform=self.config.sys_platform)
232
+ self.pid_file.unlink(missing_ok=True)
233
+ if not stopped:
234
+ return ServiceActionResult(
235
+ ok=False,
236
+ message=f"No se pudo detener el proceso PID {pid}.",
237
+ backend=self.name,
238
+ )
239
+ return ServiceActionResult(
240
+ ok=True,
241
+ message=f"llama-server detenido (PID {pid}).",
242
+ backend=self.name,
243
+ )
244
+
245
+ def restart(self) -> ServiceActionResult:
246
+ stop_res = self.stop()
247
+ if not stop_res.ok:
248
+ return stop_res
249
+ return self.start()
250
+
251
+ def status(self) -> ServiceStatus:
252
+ pid = self._active_pid()
253
+ api_ok, models = probe_api_status(self.config)
254
+ running = pid is not None
255
+ if running:
256
+ detail = f"activo (proceso gestionado PID {pid})"
257
+ elif api_ok:
258
+ detail = "endpoint accesible (proceso externo)"
259
+ else:
260
+ detail = "detenido (modo proceso)"
261
+ return ServiceStatus(
262
+ backend=self.name,
263
+ running=running,
264
+ api_reachable=api_ok,
265
+ api_root=self.config.api_root,
266
+ pid=pid,
267
+ detail=detail,
268
+ loaded_models=models,
269
+ )
270
+
271
+ def logs(self, *, follow: bool = True, lines: int = 50) -> int:
272
+ return tail_file(self.log_path, lines=lines, follow=follow)
273
+
274
+ def install(self) -> ServiceActionResult:
275
+ self.config.state_dir.mkdir(parents=True, exist_ok=True)
276
+ self.config.log_dir.mkdir(parents=True, exist_ok=True)
277
+ ensure_ini(self.config.models_ini)
278
+ return ServiceActionResult(
279
+ ok=True,
280
+ message=(
281
+ f"Backend 'process' listo (estado: {self.pid_file}, logs: {self.log_path}). "
282
+ "No requiere instalación de servicio del sistema."
283
+ ),
284
+ backend=self.name,
285
+ )
286
+
287
+ def uninstall(self) -> ServiceActionResult:
288
+ res = self.stop()
289
+ self.pid_file.unlink(missing_ok=True)
290
+ return ServiceActionResult(
291
+ ok=res.ok,
292
+ message="Estado del backend 'process' limpiado.",
293
+ backend=self.name,
294
+ )
295
+
296
+ def info(self) -> dict[str, object]:
297
+ base = super().info()
298
+ base["pid_file"] = str(self.pid_file)
299
+ base["log_path"] = str(self.log_path)
300
+ return base
@@ -0,0 +1,80 @@
1
+ """Remote HTTP-only service backend for managing a llama-server on another machine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from llmctl.service.base import (
8
+ ServiceActionResult,
9
+ ServiceBackend,
10
+ ServiceStatus,
11
+ probe_api_status,
12
+ try_api_unload,
13
+ )
14
+
15
+
16
+ class RemoteBackend(ServiceBackend):
17
+ """Client-only backend when targeting a remote llama-server via LLMCTL_API_URL."""
18
+
19
+ name = "remote"
20
+
21
+ def _unsupported(self, action: str) -> ServiceActionResult:
22
+ return ServiceActionResult(
23
+ ok=False,
24
+ message=(
25
+ f"La acción '{action}' no está disponible en modo remoto ({self.config.api_root}). "
26
+ "Gestiona el ciclo de vida en el host del servidor."
27
+ ),
28
+ backend=self.name,
29
+ )
30
+
31
+ def start(self) -> ServiceActionResult:
32
+ return self._unsupported("start")
33
+
34
+ def stop(self) -> ServiceActionResult:
35
+ return self._unsupported("stop")
36
+
37
+ def restart(self) -> ServiceActionResult:
38
+ return self._unsupported("restart")
39
+
40
+ def install(self) -> ServiceActionResult:
41
+ return self._unsupported("service install")
42
+
43
+ def uninstall(self) -> ServiceActionResult:
44
+ return self._unsupported("service uninstall")
45
+
46
+ def status(self) -> ServiceStatus:
47
+ api_ok, models = probe_api_status(self.config)
48
+ return ServiceStatus(
49
+ backend=self.name,
50
+ running=api_ok,
51
+ api_reachable=api_ok,
52
+ api_root=self.config.api_root,
53
+ pid=None,
54
+ detail=(
55
+ f"endpoint remoto accesible ({self.config.api_root})"
56
+ if api_ok
57
+ else f"endpoint remoto no accesible ({self.config.api_root})"
58
+ ),
59
+ loaded_models=models,
60
+ )
61
+
62
+ def logs(self, *, follow: bool = True, lines: int = 50) -> int:
63
+ print(
64
+ f"Los logs locales no están disponibles en modo remoto ({self.config.api_root}).",
65
+ file=sys.stderr,
66
+ )
67
+ return 1
68
+
69
+ def free_vram(self) -> ServiceActionResult:
70
+ ok, msg = try_api_unload(self.config)
71
+ if ok:
72
+ return ServiceActionResult(ok=True, message=msg, backend=self.name)
73
+ return ServiceActionResult(
74
+ ok=False,
75
+ message=(
76
+ f"No se pudo descargar el modelo vía API en el servidor remoto "
77
+ f"({self.config.api_root}): {msg}"
78
+ ),
79
+ backend=self.name,
80
+ )