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.
llmctl/cli.py ADDED
@@ -0,0 +1,1275 @@
1
+ """Main CLI entrypoint, command dispatch, and interactive menu for llmctl."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ import threading
8
+ import time
9
+ from collections.abc import Sequence
10
+ from pathlib import Path
11
+
12
+ from llmctl import __version__
13
+ from llmctl.bench import DEFAULT_BENCH_PROMPT, run_benchmark
14
+ from llmctl.cache import (
15
+ delete_cached_models,
16
+ dir_size_bytes,
17
+ find_orphan_models,
18
+ find_repo_cache_matches,
19
+ format_bytes,
20
+ is_repo_shared,
21
+ )
22
+ from llmctl.chat import run_chat
23
+ from llmctl.completions import generate_completion
24
+ from llmctl.config import (
25
+ AppConfig,
26
+ delete_profile,
27
+ list_profiles,
28
+ load_config,
29
+ save_profile,
30
+ set_active_profile,
31
+ write_default_config,
32
+ )
33
+ from llmctl.doctor import run_doctor
34
+ from llmctl.hardware import detect_hardware
35
+ from llmctl.hf import add_local_model_preset, add_model_preset, run_interactive_add
36
+ from llmctl.http_client import HttpError, request_json
37
+ from llmctl.presets import ensure_ini, list_presets, remove_preset, set_preset_options
38
+ from llmctl.server_installer import install_llama_server, server_install_info
39
+ from llmctl.service import select_backend
40
+ from llmctl.service.base import list_router_models
41
+ from llmctl.skills import add_skill, import_local_skills, list_skills, remove_skill, run_skill
42
+ from llmctl.tester import run_test_suite
43
+ from llmctl.ui import Console, open_in_editor
44
+
45
+
46
+ def _add_global_flags(parser: argparse.ArgumentParser, *, suppress_defaults: bool = False) -> None:
47
+ default_bool = argparse.SUPPRESS if suppress_defaults else False
48
+ default_none = argparse.SUPPRESS if suppress_defaults else None
49
+ parser.add_argument(
50
+ "--json",
51
+ dest="json_mode",
52
+ action="store_true",
53
+ default=default_bool,
54
+ help="Formatear salida como JSON",
55
+ )
56
+ parser.add_argument(
57
+ "-y",
58
+ "--yes",
59
+ dest="assume_yes",
60
+ action="store_true",
61
+ default=default_bool,
62
+ help="Confirmar automáticamente",
63
+ )
64
+ parser.add_argument(
65
+ "--no-color",
66
+ action="store_true",
67
+ default=default_bool,
68
+ help="Desactivar colores ANSI en la salida",
69
+ )
70
+ parser.add_argument("--config", default=default_none, help="Ruta alternativa a config.toml")
71
+ parser.add_argument("--ini", default=default_none, help="Ruta alternativa a models.ini")
72
+ parser.add_argument(
73
+ "--api-url",
74
+ default=default_none,
75
+ help="URL base de llama-server (ej: http://127.0.0.1:8080 o servidor remoto)",
76
+ )
77
+ parser.add_argument(
78
+ "--api-key",
79
+ default=default_none,
80
+ help="API key Bearer para servidores protegidos con --api-key",
81
+ )
82
+ parser.add_argument(
83
+ "--profile",
84
+ default=default_none,
85
+ help="Nombre de perfil en config.toml (ej: local, homelab, default)",
86
+ )
87
+ parser.add_argument(
88
+ "--backend",
89
+ choices=["auto", "systemd", "launchd", "process", "remote"],
90
+ default=default_none,
91
+ help="Forzar backend de servicio",
92
+ )
93
+
94
+
95
+ def _build_parser() -> argparse.ArgumentParser:
96
+ parser = argparse.ArgumentParser(
97
+ prog="llmctl",
98
+ description=(
99
+ "Gestor CLI multiplataforma para presets de llama-server (modo router), "
100
+ "modelos GGUF de Hugging Face, hardware y skills."
101
+ ),
102
+ )
103
+ parser.add_argument("-V", "--version", action="version", version=f"llmctl {__version__}")
104
+ parser.add_argument(
105
+ "-i", "--interactive", action="store_true", help="Abrir el menú interactivo principal"
106
+ )
107
+ _add_global_flags(parser, suppress_defaults=False)
108
+
109
+ shared = argparse.ArgumentParser(add_help=False)
110
+ _add_global_flags(shared, suppress_defaults=True)
111
+
112
+ sub = parser.add_subparsers(dest="command", metavar="<comando>")
113
+
114
+ # add / buscar
115
+ p_add = sub.add_parser(
116
+ "add", aliases=["buscar"], parents=[shared], help="Añadir o buscar un modelo GGUF"
117
+ )
118
+ p_add.add_argument(
119
+ "repo",
120
+ nargs="?",
121
+ help="Repositorio HF (org/modelo:Q4_K_M) o ruta a un archivo .gguf local",
122
+ )
123
+ p_add.add_argument(
124
+ "-i", "--interactive", action="store_true", help="Búsqueda interactiva en vivo en HF"
125
+ )
126
+ p_add.add_argument("-n", "--name", help="Alias personalizado para el preset")
127
+ p_add.add_argument("--file", dest="hf_file", help="Nombre exacto de archivo .gguf (hf-file)")
128
+ p_add.add_argument("--mmproj", dest="mmproj_file", help="Ruta local a un archivo mmproj .gguf")
129
+ p_add.add_argument(
130
+ "--mmproj-url", help="URL directa al proyector multimodal .gguf (mmproj-url)"
131
+ )
132
+ p_add.add_argument(
133
+ "--auto-mmproj",
134
+ action="store_true",
135
+ help="Detectar y añadir automáticamente mmproj-url si existe en el repo HF",
136
+ )
137
+ p_add.add_argument(
138
+ "--cpu-optimize",
139
+ action="store_true",
140
+ help="Configurar threads (núcleos físicos) y ctx-size óptimos para CPU",
141
+ )
142
+ p_add.add_argument(
143
+ "--cpu-moe", action="store_true", help="Activar offload automático de expertos MoE a RAM"
144
+ )
145
+ p_add.add_argument("--n-cpu-moe", type=int, help="Número exacto de capas MoE en RAM (ej: 30)")
146
+ p_add.add_argument(
147
+ "--no-restart", action="store_true", help="No reiniciar el router tras editar models.ini"
148
+ )
149
+
150
+ # set
151
+ p_set = sub.add_parser(
152
+ "set", parents=[shared], help="Modificar o eliminar opciones de un preset en models.ini"
153
+ )
154
+ p_set.add_argument("alias", help="Alias del preset existente")
155
+ p_set.add_argument(
156
+ "pairs", nargs="*", help="Pares clave=valor (ej: ctx-size=16384 threads=8 temp=0.2)"
157
+ )
158
+ p_set.add_argument(
159
+ "--unset", action="append", default=[], help="Eliminar una clave del preset (repetible)"
160
+ )
161
+ p_set.add_argument(
162
+ "--no-restart", action="store_true", help="No reiniciar el router tras editar models.ini"
163
+ )
164
+
165
+ # rm / borrar
166
+ p_rm = sub.add_parser(
167
+ "rm", aliases=["borrar"], parents=[shared], help="Eliminar un preset de models.ini"
168
+ )
169
+ p_rm.add_argument("alias", nargs="?", help="Alias del preset a eliminar")
170
+ p_rm.add_argument(
171
+ "-i", "--interactive", action="store_true", help="Elegir modelo de forma interactiva"
172
+ )
173
+ p_rm.add_argument(
174
+ "-p", "--purge", action="store_true", help="Borrar también su carpeta de caché HF"
175
+ )
176
+ p_rm.add_argument(
177
+ "--no-restart", action="store_true", help="No reiniciar el router tras eliminar"
178
+ )
179
+
180
+ # ls / list
181
+ p_ls = sub.add_parser(
182
+ "ls", aliases=["list"], parents=[shared], help="Listar presets y espacio en caché"
183
+ )
184
+ p_ls.add_argument(
185
+ "--names-only",
186
+ action="store_true",
187
+ help="Imprimir solo los nombres de alias (útil para autocompletado)",
188
+ )
189
+
190
+ # ps
191
+ sub.add_parser("ps", parents=[shared], help="Ver modelos cargados y disponibles en el router")
192
+
193
+ # chat
194
+ p_chat = sub.add_parser(
195
+ "chat", parents=[shared], help="Chatear en terminal (streaming SSE + soporte de pipes)"
196
+ )
197
+ p_chat.add_argument("alias", help="Alias del modelo configurado")
198
+ p_chat.add_argument("prompt", nargs="*", help="Prompt opcional (modo one-shot si se indica)")
199
+ p_chat.add_argument("-s", "--system", default="", help="Prompt de sistema opcional")
200
+ p_chat.add_argument("--temp", type=float, default=0.7, help="Temperatura (default: 0.7)")
201
+ p_chat.add_argument("--max-tokens", type=int, help="Límite máximo de tokens generados")
202
+ p_chat.add_argument("--no-stream", action="store_true", help="Desactivar streaming SSE")
203
+
204
+ # bench
205
+ p_bench = sub.add_parser(
206
+ "bench", parents=[shared], help="Comparar TTFT y tokens/s entre uno o varios modelos"
207
+ )
208
+ p_bench.add_argument("aliases", nargs="+", help="Uno o más alias de modelos a comparar")
209
+ p_bench.add_argument("--runs", type=int, default=1, help="Repeticiones por modelo (default: 1)")
210
+ p_bench.add_argument(
211
+ "--max-tokens", type=int, default=128, help="Tokens máximos por ejecución (default: 128)"
212
+ )
213
+ p_bench.add_argument(
214
+ "--prompt", default=DEFAULT_BENCH_PROMPT, help="Prompt personalizado para el benchmark"
215
+ )
216
+
217
+ # pull
218
+ p_pull = sub.add_parser(
219
+ "pull", parents=[shared], help="Pre-descargar y cargar un modelo vía llama-server"
220
+ )
221
+ p_pull.add_argument("alias", help="Alias del modelo configurado en models.ini")
222
+
223
+ # clean
224
+ p_clean = sub.add_parser(
225
+ "clean", parents=[shared], help="Detectar y borrar modelos huérfanos en caché"
226
+ )
227
+ p_clean.add_argument("--dry-run", action="store_true", help="Mostrar huérfanos sin borrar nada")
228
+
229
+ # test
230
+ p_test = sub.add_parser(
231
+ "test", parents=[shared], help="Probar capacidades, rendimiento y VRAM de un modelo"
232
+ )
233
+ p_test.add_argument("alias", help="Alias del modelo a probar")
234
+ mode_grp = p_test.add_mutually_exclusive_group()
235
+ mode_grp.add_argument("--text", action="store_const", dest="mode", const="text")
236
+ mode_grp.add_argument("--vision", action="store_const", dest="mode", const="vision")
237
+ mode_grp.add_argument("--tools", action="store_const", dest="mode", const="tools")
238
+ mode_grp.add_argument("--embed", action="store_const", dest="mode", const="embed")
239
+ mode_grp.add_argument("--fim", action="store_const", dest="mode", const="fim")
240
+ mode_grp.add_argument("--all", action="store_const", dest="mode", const="all")
241
+ p_test.set_defaults(mode="auto")
242
+
243
+ # gpu / vram
244
+ sub.add_parser(
245
+ "gpu", aliases=["vram"], parents=[shared], help="Ver uso actual de VRAM/Metal y RAM"
246
+ )
247
+
248
+ # doctor
249
+ sub.add_parser(
250
+ "doctor", parents=[shared], help="Comprobar dependencias, hardware, rutas y servicio"
251
+ )
252
+
253
+ # free / unload
254
+ sub.add_parser(
255
+ "free", aliases=["unload"], parents=[shared], help="Descargar modelo activo de la VRAM"
256
+ )
257
+
258
+ # service lifecycle shortcuts
259
+ sub.add_parser("on", aliases=["start"], parents=[shared], help="Iniciar llama-server")
260
+ sub.add_parser("off", aliases=["stop"], parents=[shared], help="Detener llama-server")
261
+ sub.add_parser("restart", parents=[shared], help="Reiniciar llama-server")
262
+ sub.add_parser("status", parents=[shared], help="Ver estado del servicio y del endpoint")
263
+
264
+ p_logs = sub.add_parser("logs", parents=[shared], help="Mostrar logs de llama-server")
265
+ p_logs.add_argument("-n", "--lines", type=int, default=50, help="Número inicial de líneas")
266
+ p_logs.add_argument(
267
+ "--no-follow", action="store_true", help="Mostrar últimas líneas y salir sin seguir"
268
+ )
269
+
270
+ # config
271
+ p_cfg = sub.add_parser(
272
+ "config", parents=[shared], help="Editar o inspeccionar models.ini / config.toml"
273
+ )
274
+ p_cfg.add_argument(
275
+ "--app", action="store_true", help="Abrir config.toml en lugar de models.ini"
276
+ )
277
+ p_cfg.add_argument(
278
+ "--init", action="store_true", help="Crear config.toml por defecto si no existe"
279
+ )
280
+ p_cfg.add_argument(
281
+ "--show", action="store_true", help="Mostrar la configuración efectiva resuelta"
282
+ )
283
+
284
+ # service management
285
+ p_svc = sub.add_parser(
286
+ "service", parents=[shared], help="Gestionar la definición del servicio del SO"
287
+ )
288
+ p_svc.add_argument("action", choices=["install", "uninstall", "info"])
289
+
290
+ # profile management
291
+ p_prof = sub.add_parser(
292
+ "profile", parents=[shared], help="Gestionar perfiles locales y remotos en config.toml"
293
+ )
294
+ prof_sub = p_prof.add_subparsers(dest="profile_cmd", metavar="<acción>")
295
+ prof_sub.add_parser("list", aliases=["ls"], parents=[shared], help="Listar perfiles")
296
+
297
+ p_prof_set = prof_sub.add_parser("set", parents=[shared], help="Crear o actualizar un perfil")
298
+ p_prof_set.add_argument("name", help="Nombre del perfil (ej: homelab, laptop)")
299
+ p_prof_set.add_argument("--url", dest="prof_api_url", help="URL base del servidor")
300
+ p_prof_set.add_argument(
301
+ "--prof-backend",
302
+ choices=["auto", "systemd", "launchd", "process", "remote"],
303
+ help="Backend de servicio para este perfil",
304
+ )
305
+ p_prof_set.add_argument("--key", dest="prof_api_key", help="API key Bearer del perfil")
306
+ p_prof_set.add_argument("--host", dest="prof_host", help="Host local del perfil")
307
+ p_prof_set.add_argument("--port", dest="prof_port", type=int, help="Puerto local del perfil")
308
+ p_prof_set.add_argument("--models-ini", dest="prof_ini", help="Ruta models.ini del perfil")
309
+ p_prof_set.add_argument("--use", action="store_true", help="Activar este perfil al guardarlo")
310
+
311
+ p_prof_use = prof_sub.add_parser(
312
+ "use", parents=[shared], help="Activar un perfil ('default' para volver al base)"
313
+ )
314
+ p_prof_use.add_argument("name", help="Nombre del perfil o 'default'")
315
+
316
+ p_prof_rm = prof_sub.add_parser("rm", parents=[shared], help="Eliminar un perfil")
317
+ p_prof_rm.add_argument("name", help="Nombre del perfil a eliminar")
318
+
319
+ # official llama-server binary installer
320
+ p_srv = sub.add_parser(
321
+ "server",
322
+ parents=[shared],
323
+ help="Instalar o actualizar binarios oficiales de ggml-org/llama.cpp",
324
+ )
325
+ srv_sub = p_srv.add_subparsers(dest="server_cmd", metavar="<acción>")
326
+
327
+ p_srv_inst = srv_sub.add_parser(
328
+ "install", parents=[shared], help="Descargar e instalar llama-server oficial"
329
+ )
330
+ p_srv_inst.add_argument("--tag", help="Tag concreto de release (default: última release)")
331
+ p_srv_inst.add_argument(
332
+ "--accel",
333
+ choices=["auto", "cuda", "metal", "vulkan", "cpu"],
334
+ default="auto",
335
+ help="Sabor del binario (default: auto según hardware)",
336
+ )
337
+ p_srv_inst.add_argument("--install-dir", help="Carpeta destino personalizada")
338
+ p_srv_inst.add_argument("--dry-run", action="store_true", help="Mostrar asset sin descargar")
339
+
340
+ p_srv_upd = srv_sub.add_parser(
341
+ "update", parents=[shared], help="Actualizar llama-server si hay nueva release"
342
+ )
343
+ p_srv_upd.add_argument(
344
+ "--accel",
345
+ choices=["auto", "cuda", "metal", "vulkan", "cpu"],
346
+ default="auto",
347
+ help="Sabor del binario (default: auto según hardware)",
348
+ )
349
+ p_srv_upd.add_argument("--install-dir", help="Carpeta destino personalizada")
350
+ p_srv_upd.add_argument("--dry-run", action="store_true", help="Mostrar asset sin descargar")
351
+
352
+ srv_sub.add_parser("info", parents=[shared], help="Ver binario detectado y gestionado")
353
+
354
+ # skill
355
+ p_skill = sub.add_parser(
356
+ "skill", parents=[shared], help="Gestionar y ejecutar skills centralizadas"
357
+ )
358
+ skill_sub = p_skill.add_subparsers(dest="skill_cmd", metavar="<acción>")
359
+
360
+ p_sk_add = skill_sub.add_parser(
361
+ "add", parents=[shared], help="Instalar skill desde GitHub o ruta local"
362
+ )
363
+ p_sk_add.add_argument("source", help="owner/repo[/subpath], URL de GitHub o carpeta local")
364
+ p_sk_add.add_argument(
365
+ "--skill", dest="skill_name", help="Nombre de skill si el repo tiene varias"
366
+ )
367
+ p_sk_add.add_argument(
368
+ "--all",
369
+ dest="install_all",
370
+ action="store_true",
371
+ help="Instalar todas las skills encontradas",
372
+ )
373
+ p_sk_add.add_argument(
374
+ "--via-npx",
375
+ action="store_true",
376
+ help="Usar 'npx skills add' en lugar del descargador nativo",
377
+ )
378
+ p_sk_add.add_argument("extra_args", nargs="*", help="Flags extra para --via-npx")
379
+
380
+ skill_sub.add_parser(
381
+ "import", parents=[shared], help="Importar skills locales existentes al almacén central"
382
+ )
383
+
384
+ p_sk_ls = skill_sub.add_parser(
385
+ "list", aliases=["ls"], parents=[shared], help="Listar skills centralizadas"
386
+ )
387
+ p_sk_ls.add_argument("--names-only", action="store_true", help="Imprimir solo nombres")
388
+
389
+ p_sk_rm = skill_sub.add_parser("rm", parents=[shared], help="Eliminar una skill instalada")
390
+ p_sk_rm.add_argument("name", help="Nombre de la skill a eliminar")
391
+
392
+ p_sk_run = skill_sub.add_parser(
393
+ "run", parents=[shared], help="Ejecutar una skill contra el servidor LLM"
394
+ )
395
+ p_sk_run.add_argument("skill_ref", help="Nombre de skill o ruta a SKILL.md")
396
+ p_sk_run.add_argument("alias", help="Alias del modelo configurado")
397
+ p_sk_run.add_argument("-p", "--prompt", default="", help="Instrucción del usuario")
398
+ p_sk_run.add_argument("-f", "--file", dest="file_ctx", help="Archivo de contexto a adjuntar")
399
+ p_sk_run.add_argument("extra_prompt", nargs="*", help="Texto adicional para el prompt")
400
+
401
+ # completion
402
+ p_comp = sub.add_parser(
403
+ "completion", parents=[shared], help="Generar script de autocompletado de shell"
404
+ )
405
+ p_comp.add_argument("shell", choices=["bash", "zsh", "fish", "powershell"])
406
+
407
+ return parser
408
+
409
+
410
+ def _cmd_ls(config: AppConfig, console: Console, *, names_only: bool = False) -> int:
411
+ presets = list_presets(config.models_ini)
412
+ if names_only:
413
+ for p in presets:
414
+ console.line(p.name)
415
+ return 0
416
+
417
+ cache_bytes = dir_size_bytes(config.hf_cache)
418
+ if console.json_mode:
419
+ console.emit_json(
420
+ {
421
+ "models_ini": str(config.models_ini),
422
+ "presets": [p.to_dict() for p in presets],
423
+ "cache_dir": str(config.hf_cache),
424
+ "cache_bytes": cache_bytes,
425
+ "cache_human": format_bytes(cache_bytes),
426
+ }
427
+ )
428
+ return 0
429
+
430
+ console.header(f"Presets en {config.models_ini}")
431
+ if not presets:
432
+ console.line(" (Ninguno)")
433
+ else:
434
+ rows = [
435
+ [
436
+ p.name,
437
+ p.hf_repo or p.model_path or "-",
438
+ p.hf_file or ("(local)" if p.model_path else "-"),
439
+ "sí" if p.has_vision_config else "-",
440
+ ]
441
+ for p in presets
442
+ ]
443
+ console.print_table(["ALIAS", "ORIGEN (HF / LOCAL)", "ARCHIVO", "MMPROJ"], rows)
444
+
445
+ console.line("")
446
+ console.header(f"Espacio en caché ({config.hf_cache})")
447
+ console.line(f" {format_bytes(cache_bytes)}")
448
+ return 0
449
+
450
+
451
+ def _cmd_rm(
452
+ config: AppConfig,
453
+ console: Console,
454
+ *,
455
+ alias: str | None,
456
+ interactive: bool,
457
+ purge: bool,
458
+ no_restart: bool,
459
+ ) -> int:
460
+ if not config.models_ini.is_file():
461
+ console.error(f"No existe {config.models_ini}")
462
+ return 1
463
+
464
+ presets = list_presets(config.models_ini)
465
+ if not presets:
466
+ console.warn("No hay presets configurados para borrar.")
467
+ return 0
468
+
469
+ ask_cache = False
470
+ if interactive:
471
+ console.header(f"Presets en {config.models_ini}")
472
+ for idx, p in enumerate(presets, 1):
473
+ console.line(f" [{idx}] {p.name} ({p.hf_repo or 'sin hf-repo'})")
474
+ try:
475
+ choice = int(console.prompt("\n¿Qué modelo quieres borrar? (número)")) - 1
476
+ target = presets[choice]
477
+ except (ValueError, IndexError, KeyboardInterrupt):
478
+ console.line("Cancelado.")
479
+ return 0
480
+ ask_cache = True
481
+ else:
482
+ if not alias:
483
+ console.error("Uso: llmctl rm <alias> [--purge] o llmctl rm -i")
484
+ return 1
485
+ match = next((p for p in presets if p.name == alias), None)
486
+ if not match:
487
+ available = ", ".join(p.name for p in presets)
488
+ console.error(f"No existe el alias [{alias}] en {config.models_ini}.")
489
+ console.info(f"Alias disponibles: {available}")
490
+ return 1
491
+ target = match
492
+
493
+ shared = bool(target.hf_repo) and is_repo_shared(
494
+ config.models_ini, target.hf_repo, exclude_alias=target.name
495
+ )
496
+ remove_preset(config.models_ini, target.name)
497
+
498
+ freed_bytes = 0
499
+ cache_note = ""
500
+ if target.hf_repo and config.hf_cache.is_dir():
501
+ matches = find_repo_cache_matches(target.hf_repo, config.hf_cache)
502
+ if matches:
503
+ total_bytes = sum(m.size_bytes for m in matches)
504
+ if shared:
505
+ cache_note = (
506
+ f"Caché conservada ({format_bytes(total_bytes)}): otro preset sigue "
507
+ f"usando {target.repo_id}."
508
+ )
509
+ else:
510
+ do_delete = purge
511
+ if ask_cache and not purge:
512
+ console.line(f"Encontrada caché en disco (~{format_bytes(total_bytes)}):")
513
+ for item in matches:
514
+ console.line(f" - {item.name}")
515
+ do_delete = console.confirm(
516
+ "¿Borrar también esta carpeta del disco?", default=False
517
+ )
518
+ if do_delete:
519
+ freed_bytes = delete_cached_models(matches)
520
+ cache_note = f"Caché eliminada ({format_bytes(freed_bytes)} liberados)."
521
+ else:
522
+ cache_note = (
523
+ f"Nota: hay ~{format_bytes(total_bytes)} en caché. "
524
+ "Usa '--purge' si quieres borrarlos también."
525
+ )
526
+
527
+ restarted = False
528
+ restart_note = ""
529
+ if not no_restart:
530
+ backend = select_backend(config)
531
+ if backend.name != "remote":
532
+ res = backend.restart()
533
+ restarted = res.ok
534
+ restart_note = res.message
535
+
536
+ if console.json_mode:
537
+ console.emit_json(
538
+ {
539
+ "removed": target.name,
540
+ "freed_bytes": freed_bytes,
541
+ "shared_cache_preserved": shared,
542
+ "cache_note": cache_note,
543
+ "restarted": restarted,
544
+ }
545
+ )
546
+ return 0
547
+
548
+ console.ok(f"Preset [{target.name}] eliminado de {config.models_ini}.")
549
+ if cache_note:
550
+ console.info(cache_note)
551
+ if restart_note:
552
+ if restarted:
553
+ console.ok(restart_note)
554
+ else:
555
+ console.warn(restart_note)
556
+ return 0
557
+
558
+
559
+ def _cmd_pull(config: AppConfig, console: Console, *, alias: str) -> int:
560
+ if not console.json_mode:
561
+ console.line(f"Descargando/cargando [{alias}] vía {config.api_root}...")
562
+ console.info("Detalle completo en tiempo real disponible en: llmctl logs")
563
+
564
+ payload = {
565
+ "model": alias,
566
+ "messages": [{"role": "user", "content": "hi"}],
567
+ "max_tokens": 1,
568
+ }
569
+ t0 = time.monotonic()
570
+ err_box: list[HttpError] = []
571
+
572
+ def _worker() -> None:
573
+ try:
574
+ request_json(
575
+ config.chat_completions_url,
576
+ method="POST",
577
+ payload=payload,
578
+ token=config.api_key,
579
+ timeout=None,
580
+ )
581
+ except HttpError as exc:
582
+ err_box.append(exc)
583
+
584
+ thread = threading.Thread(target=_worker, daemon=True)
585
+ thread.start()
586
+
587
+ frames = ("|", "/", "-", "\\")
588
+ frame_idx = 0
589
+ show_spinner = (not console.json_mode) and console.is_interactive()
590
+ while thread.is_alive():
591
+ thread.join(timeout=0.2)
592
+ if show_spinner and thread.is_alive():
593
+ elapsed_live = time.monotonic() - t0
594
+ ch = frames[frame_idx % len(frames)]
595
+ frame_idx += 1
596
+ console.stdout.write(f"\r [{ch}] Cargando [{alias}]... {elapsed_live:.1f}s")
597
+ console.stdout.flush()
598
+
599
+ if show_spinner and frame_idx > 0:
600
+ console.stdout.write("\r" + " " * 60 + "\r")
601
+ console.stdout.flush()
602
+
603
+ elapsed = round(time.monotonic() - t0, 2)
604
+ if err_box:
605
+ console.error(str(err_box[0]))
606
+ return 1
607
+
608
+ if console.json_mode:
609
+ console.emit_json(
610
+ {"ok": True, "alias": alias, "api_root": config.api_root, "elapsed_s": elapsed}
611
+ )
612
+ else:
613
+ console.ok(f"Listo: [{alias}] descargado y cargado correctamente ({elapsed:.2f}s).")
614
+ return 0
615
+
616
+
617
+ def _cmd_clean(config: AppConfig, console: Console, *, dry_run: bool = False) -> int:
618
+ if not config.hf_cache.is_dir():
619
+ if console.json_mode:
620
+ console.emit_json({"orphans": [], "freed_bytes": 0, "dry_run": dry_run})
621
+ else:
622
+ console.info(f"La carpeta de caché no existe ({config.hf_cache}).")
623
+ return 0
624
+
625
+ orphans = find_orphan_models(config.models_ini, config.hf_cache)
626
+ if not orphans:
627
+ if console.json_mode:
628
+ console.emit_json({"orphans": [], "freed_bytes": 0, "dry_run": dry_run})
629
+ else:
630
+ console.ok("Caché limpia: no hay modelos huérfanos.")
631
+ return 0
632
+
633
+ total_bytes = sum(o.size_bytes for o in orphans)
634
+ if dry_run:
635
+ if console.json_mode:
636
+ console.emit_json(
637
+ {
638
+ "dry_run": True,
639
+ "orphans": [o.to_dict() for o in orphans],
640
+ "reclaimable_bytes": total_bytes,
641
+ }
642
+ )
643
+ else:
644
+ console.line(
645
+ f"Encontrados {len(orphans)} modelo(s) huérfanos (~{format_bytes(total_bytes)}):"
646
+ )
647
+ for item in orphans:
648
+ console.line(f" - {item.name} ({format_bytes(item.size_bytes)})")
649
+ console.info("Modo --dry-run: no se eliminó ningún archivo.")
650
+ return 0
651
+
652
+ if not console.json_mode:
653
+ console.line(
654
+ f"Encontrados {len(orphans)} modelo(s) huérfanos (~{format_bytes(total_bytes)}):"
655
+ )
656
+ for item in orphans:
657
+ console.line(f" - {item.name} ({format_bytes(item.size_bytes)})")
658
+
659
+ if not console.confirm("\n¿Eliminar estas carpetas del disco?", default=False):
660
+ if console.json_mode:
661
+ console.emit_json({"cancelled": True, "freed_bytes": 0})
662
+ else:
663
+ console.line("Cancelado.")
664
+ return 0
665
+
666
+ freed = delete_cached_models(orphans)
667
+ if console.json_mode:
668
+ console.emit_json(
669
+ {"deleted": [o.name for o in orphans], "freed_bytes": freed, "dry_run": False}
670
+ )
671
+ else:
672
+ console.ok(f"Eliminados (~{format_bytes(freed)} liberados).")
673
+ return 0
674
+
675
+
676
+ def _cmd_gpu(config: AppConfig, console: Console) -> int:
677
+ hw = detect_hardware(sys_platform=config.sys_platform)
678
+ if console.json_mode:
679
+ console.emit_json(hw.to_dict())
680
+ return 0
681
+
682
+ console.header("Acelerador / VRAM")
683
+ if hw.gpus:
684
+ rows = []
685
+ for g in hw.gpus:
686
+ used_str = f"{g.vram_used_gb:.2f} GiB" if g.vram_used_gb is not None else "N/A"
687
+ util_str = f"{g.utilization_pct:.0f}%" if g.utilization_pct is not None else "N/A"
688
+ rows.append(
689
+ [g.vendor.upper(), g.name, used_str, f"{g.vram_total_gb:.2f} GiB", util_str]
690
+ )
691
+ console.print_table(["VENDOR", "DISPOSITIVO", "USADA", "TOTAL", "USO"], rows)
692
+ if hw.unified_memory:
693
+ console.info(f"Memoria unificada: presupuesto acelerador ~{hw.vram_safe_gb:.1f} GiB.")
694
+ else:
695
+ console.line(" Sin GPU dedicada/Metal/Vulkan detectada (modo CPU/RAM).")
696
+
697
+ console.line("")
698
+ console.header("RAM y CPU (Sistema)")
699
+ avail_str = f"{hw.ram_available_gb:.2f} GiB" if hw.ram_available_gb is not None else "N/A"
700
+ console.line(
701
+ f" RAM Total: {hw.ram_total_gb:.2f} GiB | Disponible: {avail_str} | "
702
+ f"Presupuesto modelos: ~{hw.ram_usable_gb:.2f} GiB"
703
+ )
704
+ console.line(
705
+ f" CPU: {hw.cpu_cores_physical} núcleos físicos / {hw.cpu_cores_logical} hilos lógicos"
706
+ )
707
+ return 0
708
+
709
+
710
+ def _cmd_set(
711
+ config: AppConfig,
712
+ console: Console,
713
+ *,
714
+ alias: str,
715
+ pairs: list[str],
716
+ unset_keys: list[str],
717
+ no_restart: bool,
718
+ ) -> int:
719
+ updates: dict[str, str | None] = {}
720
+ for pair in pairs:
721
+ if "=" not in pair:
722
+ console.error(f"Formato inválido {pair!r}. Usa clave=valor (ej: ctx-size=16384).")
723
+ return 1
724
+ k, v = pair.split("=", 1)
725
+ key = k.strip()
726
+ if not key:
727
+ console.error(f"Clave vacía en {pair!r}.")
728
+ return 1
729
+ updates[key] = v.strip()
730
+
731
+ for key in unset_keys:
732
+ clean_key = key.strip()
733
+ if clean_key:
734
+ updates[clean_key] = None
735
+
736
+ if not updates:
737
+ console.error("Indica al menos un par clave=valor o --unset <clave>.")
738
+ return 1
739
+
740
+ try:
741
+ preset = set_preset_options(config.models_ini, alias, updates)
742
+ except (FileNotFoundError, KeyError) as exc:
743
+ console.error(str(exc))
744
+ return 1
745
+
746
+ restarted = False
747
+ restart_note = ""
748
+ if not no_restart:
749
+ backend = select_backend(config)
750
+ if backend.name != "remote":
751
+ res = backend.restart()
752
+ restarted = res.ok
753
+ restart_note = res.message
754
+
755
+ if console.json_mode:
756
+ console.emit_json(
757
+ {
758
+ "updated": preset.to_dict(),
759
+ "changes": updates,
760
+ "restarted": restarted,
761
+ }
762
+ )
763
+ return 0
764
+
765
+ console.ok(f"Preset [{preset.name}] actualizado en {config.models_ini}.")
766
+ if restart_note:
767
+ if restarted:
768
+ console.ok(restart_note)
769
+ else:
770
+ console.warn(restart_note)
771
+ return 0
772
+
773
+
774
+ def _cmd_ps(config: AppConfig, console: Console) -> int:
775
+ reachable, models = list_router_models(config)
776
+ if not reachable:
777
+ if console.json_mode:
778
+ console.emit_json({"reachable": False, "api_root": config.api_root, "models": []})
779
+ else:
780
+ console.error(f"No se pudo conectar con {config.api_root}.")
781
+ return 1
782
+
783
+ if console.json_mode:
784
+ console.emit_json({"reachable": True, "api_root": config.api_root, "models": models})
785
+ return 0
786
+
787
+ console.header(f"Modelos en router ({config.api_root})")
788
+ if not models:
789
+ console.line(" (Ninguno reportado)")
790
+ return 0
791
+ rows = [[m["id"], m["status"], m["owned_by"]] for m in models]
792
+ console.print_table(["MODELO", "ESTADO", "PROVEEDOR"], rows)
793
+ return 0
794
+
795
+
796
+ def _cmd_profile(config: AppConfig, console: Console, args: argparse.Namespace) -> int:
797
+ sub_cmd = args.profile_cmd or "list"
798
+ if sub_cmd in {"list", "ls"}:
799
+ active, profiles = list_profiles(config.config_file)
800
+ if console.json_mode:
801
+ console.emit_json(
802
+ {
803
+ "config_file": str(config.config_file),
804
+ "active": active or "default",
805
+ "profiles": profiles,
806
+ }
807
+ )
808
+ return 0
809
+ console.header(f"Perfiles en {config.config_file}")
810
+ if not profiles:
811
+ console.line(
812
+ " (Solo perfil 'default'; crea uno con 'llmctl profile set <nombre> ...')"
813
+ )
814
+ return 0
815
+ rows = []
816
+ for name, sec in sorted(profiles.items()):
817
+ mark = "*" if name == active else ""
818
+ url = str(sec.get("api_url") or "-")
819
+ bck = str(sec.get("backend") or "auto")
820
+ has_key = "sí" if sec.get("api_key") else "-"
821
+ rows.append([mark, name, url, bck, has_key])
822
+ console.print_table(["ACT", "PERFIL", "API URL", "BACKEND", "API KEY"], rows)
823
+ return 0
824
+
825
+ if sub_cmd == "set":
826
+ try:
827
+ saved = save_profile(
828
+ config.config_file,
829
+ args.name,
830
+ api_url=args.prof_api_url,
831
+ backend=args.prof_backend,
832
+ api_key=args.prof_api_key,
833
+ host=args.prof_host,
834
+ port=args.prof_port,
835
+ models_ini=args.prof_ini,
836
+ activate=args.use,
837
+ )
838
+ except ValueError as exc:
839
+ console.error(str(exc))
840
+ return 1
841
+ if console.json_mode:
842
+ console.emit_json({"profile": args.name, "activated": args.use, "settings": saved})
843
+ else:
844
+ console.ok(f"Perfil '{args.name}' guardado en {config.config_file}.")
845
+ if args.use:
846
+ console.info(f"Perfil '{args.name}' activado.")
847
+ return 0
848
+
849
+ if sub_cmd == "use":
850
+ try:
851
+ active_name = set_active_profile(config.config_file, args.name)
852
+ except KeyError as exc:
853
+ console.error(str(exc))
854
+ return 1
855
+ if console.json_mode:
856
+ console.emit_json({"active": active_name})
857
+ else:
858
+ console.ok(f"Perfil activo: '{active_name}'.")
859
+ return 0
860
+
861
+ if sub_cmd == "rm":
862
+ removed = delete_profile(config.config_file, args.name)
863
+ if console.json_mode:
864
+ console.emit_json({"removed": removed, "name": args.name})
865
+ elif removed:
866
+ console.ok(f"Perfil '{args.name}' eliminado.")
867
+ else:
868
+ console.error(f"No existe el perfil '{args.name}' en {config.config_file}.")
869
+ return 0 if removed else 1
870
+
871
+ console.error(f"Acción de perfil desconocida: {sub_cmd}")
872
+ return 1
873
+
874
+
875
+ def _cmd_server(config: AppConfig, console: Console, args: argparse.Namespace) -> int:
876
+ sc = args.server_cmd or "info"
877
+ if sc == "info":
878
+ return server_install_info(config, console)
879
+ if sc == "install":
880
+ dest = Path(args.install_dir).expanduser() if args.install_dir else None
881
+ return install_llama_server(
882
+ config,
883
+ console,
884
+ tag=args.tag,
885
+ backend_pref=args.accel,
886
+ install_dir=dest,
887
+ dry_run=args.dry_run,
888
+ update_only_if_newer=False,
889
+ )
890
+ if sc == "update":
891
+ dest = Path(args.install_dir).expanduser() if args.install_dir else None
892
+ return install_llama_server(
893
+ config,
894
+ console,
895
+ tag=None,
896
+ backend_pref=args.accel,
897
+ install_dir=dest,
898
+ dry_run=args.dry_run,
899
+ update_only_if_newer=True,
900
+ )
901
+ console.error(f"Acción de server desconocida: {sc}")
902
+ return 1
903
+
904
+
905
+ def _cmd_service_action(config: AppConfig, console: Console, action: str) -> int:
906
+ backend = select_backend(config)
907
+ if action == "status":
908
+ st = backend.status()
909
+ if console.json_mode:
910
+ console.emit_json(st.to_dict())
911
+ return 0 if (st.running or st.api_reachable) else 1
912
+ console.line(f"Backend: {st.backend}")
913
+ console.line(f"Estado: {st.detail}")
914
+ console.line(
915
+ f"Endpoint: {st.api_root} ({'accesible' if st.api_reachable else 'no accesible'})"
916
+ )
917
+ if st.pid:
918
+ console.line(f"PID: {st.pid}")
919
+ if st.loaded_models:
920
+ console.line(f"Modelos: {', '.join(st.loaded_models)}")
921
+ return 0 if (st.running or st.api_reachable) else 1
922
+
923
+ if action == "info":
924
+ info = backend.info()
925
+ if console.json_mode:
926
+ console.emit_json(info)
927
+ else:
928
+ console.header(f"Servicio ({backend.name})")
929
+ for key, val in info.items():
930
+ console.line(f" {key}: {val}")
931
+ return 0
932
+
933
+ fn = getattr(backend, action)
934
+ res = fn()
935
+ if console.json_mode:
936
+ console.emit_json(res.to_dict())
937
+ elif res.ok:
938
+ console.ok(res.message)
939
+ else:
940
+ console.error(res.message)
941
+ return 0 if res.ok else 1
942
+
943
+
944
+ def _cmd_config(
945
+ config: AppConfig,
946
+ console: Console,
947
+ *,
948
+ app_cfg: bool,
949
+ init_cfg: bool,
950
+ show_cfg: bool,
951
+ ) -> int:
952
+ if init_cfg:
953
+ created = write_default_config(config.config_file)
954
+ if console.json_mode:
955
+ console.emit_json({"config_file": str(created)})
956
+ else:
957
+ console.ok(f"Archivo de configuración listo en {created}.")
958
+ return 0
959
+
960
+ if show_cfg:
961
+ data = config.to_dict()
962
+ if console.json_mode:
963
+ console.emit_json(data)
964
+ else:
965
+ console.header("Configuración efectiva")
966
+ for k, v in data.items():
967
+ console.line(f" {k}: {v}")
968
+ return 0
969
+
970
+ target = write_default_config(config.config_file) if app_cfg else ensure_ini(config.models_ini)
971
+ return open_in_editor(
972
+ target,
973
+ configured_editor=config.editor,
974
+ console=console,
975
+ sys_platform=config.sys_platform,
976
+ )
977
+
978
+
979
+ def _cmd_skill(config: AppConfig, console: Console, args: argparse.Namespace) -> int:
980
+ sc = args.skill_cmd or "list"
981
+ if sc == "add":
982
+ return add_skill(
983
+ args.source,
984
+ config.skills_dir,
985
+ console,
986
+ skill_filter=args.skill_name,
987
+ install_all=args.install_all,
988
+ via_npx=args.via_npx,
989
+ npx_extra_args=args.extra_args,
990
+ )
991
+ if sc == "import":
992
+ imported = import_local_skills(config.skills_dir)
993
+ if console.json_mode:
994
+ console.emit_json({"imported": imported, "skills_dir": str(config.skills_dir)})
995
+ elif imported:
996
+ console.ok(f"Importadas {len(imported)} skills en {config.skills_dir}:")
997
+ for name in imported:
998
+ console.line(f" - {name}")
999
+ else:
1000
+ console.info(f"No se encontraron skills locales para importar en {config.skills_dir}.")
1001
+ return 0
1002
+ if sc in {"list", "ls"}:
1003
+ entries = list_skills(config.skills_dir)
1004
+ if getattr(args, "names_only", False):
1005
+ for entry in entries:
1006
+ console.line(entry.name)
1007
+ return 0
1008
+ if console.json_mode:
1009
+ console.emit_json(
1010
+ {"skills_dir": str(config.skills_dir), "skills": [e.to_dict() for e in entries]}
1011
+ )
1012
+ return 0
1013
+ if not entries:
1014
+ console.info(f"No hay skills centralizadas en {config.skills_dir}.")
1015
+ console.info("Usa 'llmctl skill add <owner/repo>' o 'llmctl skill import'.")
1016
+ return 0
1017
+ rows = [[e.name, e.description or str(e.path)] for e in entries]
1018
+ console.print_table(["SKILL", "DESCRIPCIÓN / RUTA"], rows)
1019
+ return 0
1020
+ if sc == "rm":
1021
+ removed = remove_skill(config.skills_dir, args.name)
1022
+ if console.json_mode:
1023
+ console.emit_json({"removed": removed, "name": args.name})
1024
+ elif removed:
1025
+ console.ok(f"Skill '{args.name}' eliminada.")
1026
+ else:
1027
+ console.error(f"No se encontró la skill '{args.name}' en {config.skills_dir}.")
1028
+ return 0 if removed else 1
1029
+ if sc == "run":
1030
+ extra = " ".join(args.extra_prompt).strip()
1031
+ full_prompt = " ".join(p for p in (args.prompt, extra) if p).strip()
1032
+ return run_skill(
1033
+ args.skill_ref,
1034
+ args.alias,
1035
+ config,
1036
+ console,
1037
+ prompt=full_prompt,
1038
+ file_ctx=args.file_ctx,
1039
+ )
1040
+
1041
+ console.error(f"Subcomando skill desconocido: {sc}")
1042
+ return 1
1043
+
1044
+
1045
+ def _run_interactive_menu(config: AppConfig, console: Console) -> int:
1046
+ console.header("Gestor IA Local (llama-server)")
1047
+ console.line(" [1] Buscar / añadir modelos (llmctl add -i)")
1048
+ console.line(" [2] Borrar un modelo (llmctl rm -i)")
1049
+ console.line(" [3] Listar modelos y espacio en disco (llmctl ls)")
1050
+ console.line(" [4] Ver uso de VRAM y RAM (llmctl gpu)")
1051
+ console.line(" [5] Limpiar caché huérfana (llmctl clean)")
1052
+ console.line(" [6] Vaciar VRAM sin apagar el router (llmctl free)")
1053
+ console.line(" [7] Encender / Apagar servidor (llmctl on / llmctl off)")
1054
+ console.line(" [8] Ver logs en directo (llmctl logs)")
1055
+ console.line(" [9] Diagnóstico del entorno (llmctl doctor)")
1056
+ console.line("")
1057
+ opt = console.prompt("Opción")
1058
+
1059
+ if opt == "1":
1060
+ return run_interactive_add(config, console)
1061
+ if opt == "2":
1062
+ return _cmd_rm(config, console, alias=None, interactive=True, purge=False, no_restart=False)
1063
+ if opt == "3":
1064
+ return _cmd_ls(config, console)
1065
+ if opt == "4":
1066
+ return _cmd_gpu(config, console)
1067
+ if opt == "5":
1068
+ return _cmd_clean(config, console)
1069
+ if opt == "6":
1070
+ return _cmd_service_action(config, console, "free_vram")
1071
+ if opt == "7":
1072
+ backend = select_backend(config)
1073
+ st = backend.status()
1074
+ return _cmd_service_action(config, console, "stop" if st.running else "start")
1075
+ if opt == "8":
1076
+ return select_backend(config).logs(follow=True, lines=50)
1077
+ if opt == "9":
1078
+ return run_doctor(config, console)
1079
+
1080
+ console.line("Cancelado.")
1081
+ return 0
1082
+
1083
+
1084
+ def main(argv: Sequence[str] | None = None) -> int:
1085
+ """CLI entrypoint returning a POSIX-style exit code."""
1086
+ parser = _build_parser()
1087
+ raw_args = list(sys.argv[1:] if argv is None else argv)
1088
+ if not raw_args:
1089
+ parser.print_help()
1090
+ return 0
1091
+
1092
+ args = parser.parse_args(raw_args)
1093
+ config = load_config(
1094
+ config_path=args.config,
1095
+ ini_override=args.ini,
1096
+ api_url_override=args.api_url,
1097
+ api_key_override=args.api_key,
1098
+ backend_override=args.backend,
1099
+ profile_override=args.profile,
1100
+ no_color=args.no_color,
1101
+ )
1102
+ console = Console(
1103
+ json_mode=args.json_mode,
1104
+ color_mode=config.color,
1105
+ assume_yes=args.assume_yes,
1106
+ )
1107
+
1108
+ try:
1109
+ if args.interactive and not args.command:
1110
+ return _run_interactive_menu(config, console)
1111
+
1112
+ cmd = args.command
1113
+ if not cmd:
1114
+ parser.print_help()
1115
+ return 0
1116
+
1117
+ if cmd in {"add", "buscar"}:
1118
+ if args.interactive:
1119
+ return run_interactive_add(config, console, no_restart=args.no_restart)
1120
+ if not args.repo:
1121
+ console.line(
1122
+ "Uso: llmctl add <repo|archivo.gguf> [-n alias] [--cpu-moe] o llmctl add -i"
1123
+ )
1124
+ return 0
1125
+ local_candidate = Path(args.repo).expanduser()
1126
+ if local_candidate.is_file() or args.repo.lower().endswith(".gguf"):
1127
+ return add_local_model_preset(
1128
+ config,
1129
+ console,
1130
+ model_file=local_candidate,
1131
+ name=args.name,
1132
+ mmproj_file=Path(args.mmproj_file) if args.mmproj_file else None,
1133
+ auto_mmproj=args.auto_mmproj,
1134
+ cpu_moe=args.cpu_moe,
1135
+ n_cpu_moe=args.n_cpu_moe,
1136
+ cpu_optimize=args.cpu_optimize,
1137
+ no_restart=args.no_restart,
1138
+ )
1139
+ return add_model_preset(
1140
+ config,
1141
+ console,
1142
+ repo=args.repo,
1143
+ name=args.name,
1144
+ hf_file=args.hf_file,
1145
+ cpu_moe=args.cpu_moe,
1146
+ n_cpu_moe=args.n_cpu_moe,
1147
+ mmproj_url=args.mmproj_url,
1148
+ auto_mmproj=args.auto_mmproj,
1149
+ cpu_optimize=args.cpu_optimize,
1150
+ no_restart=args.no_restart,
1151
+ )
1152
+
1153
+ if cmd == "set":
1154
+ return _cmd_set(
1155
+ config,
1156
+ console,
1157
+ alias=args.alias,
1158
+ pairs=args.pairs,
1159
+ unset_keys=args.unset,
1160
+ no_restart=args.no_restart,
1161
+ )
1162
+
1163
+ if cmd in {"rm", "borrar"}:
1164
+ return _cmd_rm(
1165
+ config,
1166
+ console,
1167
+ alias=args.alias,
1168
+ interactive=args.interactive,
1169
+ purge=args.purge,
1170
+ no_restart=args.no_restart,
1171
+ )
1172
+
1173
+ if cmd in {"ls", "list"}:
1174
+ return _cmd_ls(config, console, names_only=args.names_only)
1175
+
1176
+ if cmd == "ps":
1177
+ return _cmd_ps(config, console)
1178
+
1179
+ if cmd == "chat":
1180
+ return run_chat(
1181
+ args.alias,
1182
+ config,
1183
+ console,
1184
+ prompt=" ".join(args.prompt).strip(),
1185
+ system_prompt=args.system,
1186
+ temperature=args.temp,
1187
+ max_tokens=args.max_tokens,
1188
+ stream=not args.no_stream,
1189
+ )
1190
+
1191
+ if cmd == "bench":
1192
+ return run_benchmark(
1193
+ args.aliases,
1194
+ config,
1195
+ console,
1196
+ runs=args.runs,
1197
+ max_tokens=args.max_tokens,
1198
+ prompt=args.prompt,
1199
+ )
1200
+
1201
+ if cmd == "pull":
1202
+ return _cmd_pull(config, console, alias=args.alias)
1203
+
1204
+ if cmd == "clean":
1205
+ return _cmd_clean(config, console, dry_run=args.dry_run)
1206
+
1207
+ if cmd == "test":
1208
+ return run_test_suite(args.alias, config, console, mode=args.mode)
1209
+
1210
+ if cmd in {"gpu", "vram"}:
1211
+ return _cmd_gpu(config, console)
1212
+
1213
+ if cmd == "doctor":
1214
+ return run_doctor(config, console)
1215
+
1216
+ if cmd in {"free", "unload"}:
1217
+ return _cmd_service_action(config, console, "free_vram")
1218
+
1219
+ if cmd in {"on", "start"}:
1220
+ return _cmd_service_action(config, console, "start")
1221
+
1222
+ if cmd in {"off", "stop"}:
1223
+ return _cmd_service_action(config, console, "stop")
1224
+
1225
+ if cmd == "restart":
1226
+ return _cmd_service_action(config, console, "restart")
1227
+
1228
+ if cmd == "status":
1229
+ return _cmd_service_action(config, console, "status")
1230
+
1231
+ if cmd == "logs":
1232
+ return select_backend(config).logs(follow=not args.no_follow, lines=args.lines)
1233
+
1234
+ if cmd == "config":
1235
+ return _cmd_config(
1236
+ config,
1237
+ console,
1238
+ app_cfg=args.app,
1239
+ init_cfg=args.init,
1240
+ show_cfg=args.show,
1241
+ )
1242
+
1243
+ if cmd == "service":
1244
+ return _cmd_service_action(config, console, args.action)
1245
+
1246
+ if cmd == "profile":
1247
+ return _cmd_profile(config, console, args)
1248
+
1249
+ if cmd == "server":
1250
+ return _cmd_server(config, console, args)
1251
+
1252
+ if cmd == "skill":
1253
+ return _cmd_skill(config, console, args)
1254
+
1255
+ if cmd == "completion":
1256
+ console.line(generate_completion(args.shell).rstrip("\n"))
1257
+ return 0
1258
+
1259
+ parser.print_help()
1260
+ return 1
1261
+ except KeyboardInterrupt:
1262
+ console.line("\nCancelado.")
1263
+ return 130
1264
+
1265
+
1266
+ def main_add_compat(argv: Sequence[str] | None = None) -> int:
1267
+ """Backwards-compatible console script entrypoint for `llmctl-hf`."""
1268
+ raw = list(sys.argv[1:] if argv is None else argv)
1269
+ return main(["add", *raw])
1270
+
1271
+
1272
+ def main_rm_compat(argv: Sequence[str] | None = None) -> int:
1273
+ """Backwards-compatible console script entrypoint for `llmctl-rm`."""
1274
+ raw = list(sys.argv[1:] if argv is None else argv)
1275
+ return main(["rm", *raw])