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/__init__.py +12 -0
- llmctl/__main__.py +10 -0
- llmctl/bench.py +192 -0
- llmctl/cache.py +109 -0
- llmctl/chat.py +199 -0
- llmctl/cli.py +1275 -0
- llmctl/completions.py +321 -0
- llmctl/config.py +718 -0
- llmctl/doctor.py +204 -0
- llmctl/hardware.py +506 -0
- llmctl/hf.py +580 -0
- llmctl/http_client.py +187 -0
- llmctl/presets.py +288 -0
- llmctl/server_installer.py +350 -0
- llmctl/service/__init__.py +42 -0
- llmctl/service/base.py +282 -0
- llmctl/service/launchd.py +190 -0
- llmctl/service/process.py +300 -0
- llmctl/service/remote.py +80 -0
- llmctl/service/systemd.py +212 -0
- llmctl/skills.py +418 -0
- llmctl/tester.py +408 -0
- llmctl/ui.py +194 -0
- llmctl_cli-0.4.1.dist-info/METADATA +173 -0
- llmctl_cli-0.4.1.dist-info/RECORD +28 -0
- llmctl_cli-0.4.1.dist-info/WHEEL +4 -0
- llmctl_cli-0.4.1.dist-info/entry_points.txt +5 -0
- llmctl_cli-0.4.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Linux systemd --user service backend."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from llmctl.config import AppConfig
|
|
10
|
+
from llmctl.presets import ensure_ini
|
|
11
|
+
from llmctl.service.base import (
|
|
12
|
+
ServiceActionResult,
|
|
13
|
+
ServiceBackend,
|
|
14
|
+
ServiceStatus,
|
|
15
|
+
build_server_argv,
|
|
16
|
+
is_in_container,
|
|
17
|
+
probe_api_status,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
UNIT_NAME = "llama-server.service"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _systemd_quote(arg: str) -> str:
|
|
24
|
+
if not arg or any(ch.isspace() or ch in {'"', "'", "\\", "$", "%"} for ch in arg):
|
|
25
|
+
escaped = arg.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%")
|
|
26
|
+
return f'"{escaped}"'
|
|
27
|
+
return arg
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_systemd_user_available() -> bool:
|
|
31
|
+
"""Return True when systemd --user is present and responsive on the host."""
|
|
32
|
+
if is_in_container() or not shutil.which("systemctl"):
|
|
33
|
+
return False
|
|
34
|
+
try:
|
|
35
|
+
proc = subprocess.run(
|
|
36
|
+
["systemctl", "--user", "list-units", "--no-pager"],
|
|
37
|
+
capture_output=True,
|
|
38
|
+
text=True,
|
|
39
|
+
timeout=3.0,
|
|
40
|
+
check=False,
|
|
41
|
+
)
|
|
42
|
+
return proc.returncode == 0
|
|
43
|
+
except (OSError, subprocess.SubprocessError):
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SystemdBackend(ServiceBackend):
|
|
48
|
+
"""Manage llama-server as a systemd --user unit on Linux."""
|
|
49
|
+
|
|
50
|
+
name = "systemd"
|
|
51
|
+
|
|
52
|
+
def __init__(self, config: AppConfig, *, unit_dir: Path | None = None) -> None:
|
|
53
|
+
super().__init__(config)
|
|
54
|
+
self.unit_dir = (
|
|
55
|
+
unit_dir if unit_dir is not None else Path.home() / ".config" / "systemd" / "user"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def unit_path(self) -> Path:
|
|
60
|
+
return self.unit_dir / UNIT_NAME
|
|
61
|
+
|
|
62
|
+
def render_unit(self) -> str:
|
|
63
|
+
argv = build_server_argv(self.config)
|
|
64
|
+
exec_start = " ".join(_systemd_quote(part) for part in argv)
|
|
65
|
+
return (
|
|
66
|
+
"[Unit]\n"
|
|
67
|
+
"Description=llama.cpp Local Router Server (managed by llmctl)\n"
|
|
68
|
+
"After=network.target\n\n"
|
|
69
|
+
"[Service]\n"
|
|
70
|
+
"Type=simple\n"
|
|
71
|
+
f"ExecStart={exec_start}\n"
|
|
72
|
+
"Restart=on-failure\n"
|
|
73
|
+
"RestartSec=5\n\n"
|
|
74
|
+
"[Install]\n"
|
|
75
|
+
"WantedBy=default.target\n"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def _run_systemctl(self, *args: str) -> subprocess.CompletedProcess[str]:
|
|
79
|
+
return subprocess.run(
|
|
80
|
+
["systemctl", "--user", *args],
|
|
81
|
+
capture_output=True,
|
|
82
|
+
text=True,
|
|
83
|
+
check=False,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def install(self) -> ServiceActionResult:
|
|
87
|
+
ensure_ini(self.config.models_ini)
|
|
88
|
+
try:
|
|
89
|
+
content = self.render_unit()
|
|
90
|
+
except FileNotFoundError as exc:
|
|
91
|
+
return ServiceActionResult(ok=False, message=str(exc), backend=self.name)
|
|
92
|
+
|
|
93
|
+
self.unit_dir.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
self.unit_path.write_text(content, encoding="utf-8")
|
|
95
|
+
proc = self._run_systemctl("daemon-reload")
|
|
96
|
+
if proc.returncode != 0:
|
|
97
|
+
err = proc.stderr.strip()
|
|
98
|
+
return ServiceActionResult(
|
|
99
|
+
ok=False,
|
|
100
|
+
message=f"Unit escrita en {self.unit_path}, pero falló daemon-reload: {err}",
|
|
101
|
+
backend=self.name,
|
|
102
|
+
)
|
|
103
|
+
return ServiceActionResult(
|
|
104
|
+
ok=True,
|
|
105
|
+
message=f"Servicio systemd instalado en {self.unit_path}.",
|
|
106
|
+
backend=self.name,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
def uninstall(self) -> ServiceActionResult:
|
|
110
|
+
self._run_systemctl("disable", "--now", "llama-server")
|
|
111
|
+
if self.unit_path.exists():
|
|
112
|
+
self.unit_path.unlink()
|
|
113
|
+
self._run_systemctl("daemon-reload")
|
|
114
|
+
return ServiceActionResult(
|
|
115
|
+
ok=True,
|
|
116
|
+
message=f"Servicio systemd eliminado ({self.unit_path}).",
|
|
117
|
+
backend=self.name,
|
|
118
|
+
)
|
|
119
|
+
return ServiceActionResult(
|
|
120
|
+
ok=True,
|
|
121
|
+
message="No había unit systemd instalada en el usuario.",
|
|
122
|
+
backend=self.name,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def start(self) -> ServiceActionResult:
|
|
126
|
+
if not self.unit_path.exists():
|
|
127
|
+
installed = self.install()
|
|
128
|
+
if not installed.ok:
|
|
129
|
+
return installed
|
|
130
|
+
proc = self._run_systemctl("start", "llama-server")
|
|
131
|
+
if proc.returncode != 0:
|
|
132
|
+
return ServiceActionResult(
|
|
133
|
+
ok=False,
|
|
134
|
+
message=proc.stderr.strip() or "No se pudo iniciar llama-server vía systemd.",
|
|
135
|
+
backend=self.name,
|
|
136
|
+
)
|
|
137
|
+
return ServiceActionResult(
|
|
138
|
+
ok=True,
|
|
139
|
+
message=f"llama-server activo en {self.config.api_root} (systemd --user).",
|
|
140
|
+
backend=self.name,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def stop(self) -> ServiceActionResult:
|
|
144
|
+
proc = self._run_systemctl("stop", "llama-server")
|
|
145
|
+
if proc.returncode != 0:
|
|
146
|
+
return ServiceActionResult(
|
|
147
|
+
ok=False,
|
|
148
|
+
message=proc.stderr.strip() or "No se pudo detener llama-server.",
|
|
149
|
+
backend=self.name,
|
|
150
|
+
)
|
|
151
|
+
return ServiceActionResult(
|
|
152
|
+
ok=True,
|
|
153
|
+
message="llama-server detenido (VRAM libre).",
|
|
154
|
+
backend=self.name,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def restart(self) -> ServiceActionResult:
|
|
158
|
+
proc = self._run_systemctl("restart", "llama-server")
|
|
159
|
+
if proc.returncode != 0:
|
|
160
|
+
return ServiceActionResult(
|
|
161
|
+
ok=False,
|
|
162
|
+
message=proc.stderr.strip() or "No se pudo reiniciar llama-server.",
|
|
163
|
+
backend=self.name,
|
|
164
|
+
)
|
|
165
|
+
return ServiceActionResult(
|
|
166
|
+
ok=True,
|
|
167
|
+
message=f"llama-server reiniciado en {self.config.api_root} (systemd --user).",
|
|
168
|
+
backend=self.name,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
def status(self) -> ServiceStatus:
|
|
172
|
+
active_proc = self._run_systemctl("is-active", "llama-server")
|
|
173
|
+
is_running = active_proc.returncode == 0
|
|
174
|
+
pid: int | None = None
|
|
175
|
+
if is_running:
|
|
176
|
+
pid_proc = self._run_systemctl("show", "-p", "MainPID", "--value", "llama-server")
|
|
177
|
+
raw_pid = pid_proc.stdout.strip()
|
|
178
|
+
if raw_pid.isdigit() and int(raw_pid) > 0:
|
|
179
|
+
pid = int(raw_pid)
|
|
180
|
+
|
|
181
|
+
api_ok, models = probe_api_status(self.config)
|
|
182
|
+
detail = (
|
|
183
|
+
"activo (systemd --user)"
|
|
184
|
+
if is_running
|
|
185
|
+
else (f"inactivo ({active_proc.stdout.strip() or 'stopped'})")
|
|
186
|
+
)
|
|
187
|
+
return ServiceStatus(
|
|
188
|
+
backend=self.name,
|
|
189
|
+
running=is_running,
|
|
190
|
+
api_reachable=api_ok,
|
|
191
|
+
api_root=self.config.api_root,
|
|
192
|
+
pid=pid,
|
|
193
|
+
detail=detail,
|
|
194
|
+
loaded_models=models,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def logs(self, *, follow: bool = True, lines: int = 50) -> int:
|
|
198
|
+
if not shutil.which("journalctl"):
|
|
199
|
+
return 1
|
|
200
|
+
cmd = ["journalctl", "--user", "-u", "llama-server", "-n", str(lines), "--no-pager"]
|
|
201
|
+
if follow:
|
|
202
|
+
cmd.append("-f")
|
|
203
|
+
try:
|
|
204
|
+
return subprocess.run(cmd, check=False).returncode
|
|
205
|
+
except KeyboardInterrupt:
|
|
206
|
+
return 0
|
|
207
|
+
|
|
208
|
+
def info(self) -> dict[str, object]:
|
|
209
|
+
base = super().info()
|
|
210
|
+
base["unit_path"] = str(self.unit_path)
|
|
211
|
+
base["unit_installed"] = self.unit_path.exists()
|
|
212
|
+
return base
|
llmctl/skills.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Centralized skills manager (native GitHub/local installer, import, list, rm, run)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import tarfile
|
|
11
|
+
import tempfile
|
|
12
|
+
from dataclasses import asdict, dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from urllib.parse import urlparse
|
|
15
|
+
|
|
16
|
+
from llmctl.config import AppConfig
|
|
17
|
+
from llmctl.http_client import HttpError, download_bytes, request_json
|
|
18
|
+
from llmctl.ui import Console
|
|
19
|
+
|
|
20
|
+
OWNER_REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:/.*)?$")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class SkillEntry:
|
|
25
|
+
"""Metadata for an installed SKILL.md bundle."""
|
|
26
|
+
|
|
27
|
+
name: str
|
|
28
|
+
path: Path
|
|
29
|
+
description: str = ""
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict[str, object]:
|
|
32
|
+
data = asdict(self)
|
|
33
|
+
data["path"] = str(self.path)
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _extract_frontmatter_description(skill_md: Path) -> str:
|
|
38
|
+
try:
|
|
39
|
+
text = skill_md.read_text(encoding="utf-8", errors="replace")
|
|
40
|
+
except OSError:
|
|
41
|
+
return ""
|
|
42
|
+
if not text.startswith("---"):
|
|
43
|
+
return ""
|
|
44
|
+
parts = text.split("---", 2)
|
|
45
|
+
if len(parts) < 3:
|
|
46
|
+
return ""
|
|
47
|
+
for line in parts[1].splitlines():
|
|
48
|
+
if line.strip().lower().startswith("description:"):
|
|
49
|
+
return line.split(":", 1)[1].strip().strip('"').strip("'")
|
|
50
|
+
return ""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def list_skills(skills_dir: Path) -> list[SkillEntry]:
|
|
54
|
+
"""List installed skills containing a SKILL.md file."""
|
|
55
|
+
if not skills_dir.is_dir():
|
|
56
|
+
return []
|
|
57
|
+
found: list[SkillEntry] = []
|
|
58
|
+
for entry in sorted(skills_dir.iterdir(), key=lambda p: p.name.lower()):
|
|
59
|
+
skill_md = entry / "SKILL.md"
|
|
60
|
+
if entry.is_dir() and skill_md.is_file():
|
|
61
|
+
found.append(
|
|
62
|
+
SkillEntry(
|
|
63
|
+
name=entry.name,
|
|
64
|
+
path=skill_md,
|
|
65
|
+
description=_extract_frontmatter_description(skill_md),
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
return found
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _safe_extract_tarball(data: bytes, dest: Path) -> None:
|
|
72
|
+
"""Safely extract a gzip/tar archive while blocking path traversal and escaping links."""
|
|
73
|
+
dest_resolved = dest.resolve()
|
|
74
|
+
with tarfile.open(fileobj=io.BytesIO(data), mode="r:*") as tf:
|
|
75
|
+
for member in tf.getmembers():
|
|
76
|
+
member_path = (dest / member.name).resolve()
|
|
77
|
+
if not member_path.is_relative_to(dest_resolved):
|
|
78
|
+
raise ValueError(f"Ruta insegura en archivo descargado: {member.name!r}")
|
|
79
|
+
if member.issym() or member.islnk():
|
|
80
|
+
target_path = (member_path.parent / member.linkname).resolve()
|
|
81
|
+
if not target_path.is_relative_to(dest_resolved):
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"Enlace simbólico inseguro: {member.name!r} -> {member.linkname!r}"
|
|
84
|
+
)
|
|
85
|
+
tf.extractall(dest, filter="data")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def parse_github_source(source: str) -> tuple[str, str, str | None, str | None] | None:
|
|
89
|
+
"""Parse 'owner/repo[/subpath]' or GitHub URL into (owner, repo, ref, subpath)."""
|
|
90
|
+
cleaned = source.strip().rstrip("/")
|
|
91
|
+
if cleaned.startswith(("http://", "https://")):
|
|
92
|
+
parsed = urlparse(cleaned)
|
|
93
|
+
if parsed.netloc.lower() not in {"github.com", "www.github.com"}:
|
|
94
|
+
return None
|
|
95
|
+
parts = [p for p in parsed.path.strip("/").split("/") if p]
|
|
96
|
+
if len(parts) < 2:
|
|
97
|
+
return None
|
|
98
|
+
owner, repo = parts[0], parts[1].removesuffix(".git")
|
|
99
|
+
ref: str | None = None
|
|
100
|
+
subpath: str | None = None
|
|
101
|
+
if len(parts) >= 4 and parts[2] in {"tree", "blob"}:
|
|
102
|
+
ref = parts[3]
|
|
103
|
+
subpath = "/".join(parts[4:]) or None
|
|
104
|
+
elif len(parts) > 2:
|
|
105
|
+
subpath = "/".join(parts[2:])
|
|
106
|
+
return owner, repo, ref, subpath
|
|
107
|
+
|
|
108
|
+
if OWNER_REPO_RE.match(cleaned):
|
|
109
|
+
parts = cleaned.split("/")
|
|
110
|
+
owner, repo = parts[0], parts[1].removesuffix(".git")
|
|
111
|
+
subpath = "/".join(parts[2:]) or None
|
|
112
|
+
return owner, repo, None, subpath
|
|
113
|
+
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _discover_skill_dirs(root: Path) -> list[Path]:
|
|
118
|
+
"""Find every directory under *root* containing a SKILL.md file."""
|
|
119
|
+
if not root.exists():
|
|
120
|
+
return []
|
|
121
|
+
if (root / "SKILL.md").is_file():
|
|
122
|
+
return [root]
|
|
123
|
+
|
|
124
|
+
discovered: list[Path] = []
|
|
125
|
+
for current_root, dirnames, filenames in os.walk(root):
|
|
126
|
+
dirnames[:] = sorted(d for d in dirnames if not d.startswith("."))
|
|
127
|
+
if "SKILL.md" in filenames:
|
|
128
|
+
discovered.append(Path(current_root))
|
|
129
|
+
dirnames[:] = [] # don't descend into nested skill dirs
|
|
130
|
+
return discovered
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _install_skill_dir(src_dir: Path, skills_dir: Path, *, name_override: str | None = None) -> str:
|
|
134
|
+
skills_dir.mkdir(parents=True, exist_ok=True)
|
|
135
|
+
skill_name = (name_override or src_dir.name).strip()
|
|
136
|
+
if not skill_name or "/" in skill_name or "\\" in skill_name or skill_name in {".", ".."}:
|
|
137
|
+
raise ValueError(f"Nombre de skill inválido: {skill_name!r}")
|
|
138
|
+
dst_dir = skills_dir / skill_name
|
|
139
|
+
if dst_dir.exists():
|
|
140
|
+
shutil.rmtree(dst_dir)
|
|
141
|
+
shutil.copytree(src_dir, dst_dir, symlinks=False)
|
|
142
|
+
return skill_name
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def add_skill(
|
|
146
|
+
source: str,
|
|
147
|
+
skills_dir: Path,
|
|
148
|
+
console: Console,
|
|
149
|
+
*,
|
|
150
|
+
skill_filter: str | None = None,
|
|
151
|
+
install_all: bool = False,
|
|
152
|
+
via_npx: bool = False,
|
|
153
|
+
npx_extra_args: list[str] | None = None,
|
|
154
|
+
) -> int:
|
|
155
|
+
"""Install one or more skills from a local directory or GitHub repository (no npx needed)."""
|
|
156
|
+
if via_npx:
|
|
157
|
+
if not shutil.which("npx"):
|
|
158
|
+
console.error("'npx' no está disponible en PATH.")
|
|
159
|
+
return 1
|
|
160
|
+
skills_dir.mkdir(parents=True, exist_ok=True)
|
|
161
|
+
subprocess.run(
|
|
162
|
+
["npx", "--yes", "skills", "add", source, "-y", *(npx_extra_args or [])],
|
|
163
|
+
check=False,
|
|
164
|
+
)
|
|
165
|
+
imported = import_local_skills(skills_dir)
|
|
166
|
+
if console.json_mode:
|
|
167
|
+
console.emit_json({"installed": imported, "skills_dir": str(skills_dir)})
|
|
168
|
+
else:
|
|
169
|
+
console.ok(f"Sincronizadas {len(imported)} skills en {skills_dir}.")
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
local_path = Path(source).expanduser()
|
|
173
|
+
if local_path.exists():
|
|
174
|
+
if local_path.is_file() and local_path.name == "SKILL.md":
|
|
175
|
+
local_path = local_path.parent
|
|
176
|
+
candidates = _discover_skill_dirs(local_path)
|
|
177
|
+
return _finish_skill_install(
|
|
178
|
+
candidates, skills_dir, console, skill_filter=skill_filter, install_all=install_all
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
gh = parse_github_source(source)
|
|
182
|
+
if gh is None:
|
|
183
|
+
console.error(
|
|
184
|
+
f"Origen no reconocido: {source!r}. Usa 'owner/repo', URL de GitHub o una ruta local."
|
|
185
|
+
)
|
|
186
|
+
return 1
|
|
187
|
+
|
|
188
|
+
owner, repo, ref, subpath = gh
|
|
189
|
+
tar_url = (
|
|
190
|
+
f"https://api.github.com/repos/{owner}/{repo}/tarball/{ref}"
|
|
191
|
+
if ref
|
|
192
|
+
else f"https://api.github.com/repos/{owner}/{repo}/tarball"
|
|
193
|
+
)
|
|
194
|
+
if not console.json_mode:
|
|
195
|
+
console.line(f"Descargando {owner}/{repo} desde GitHub...")
|
|
196
|
+
|
|
197
|
+
try:
|
|
198
|
+
archive_bytes = download_bytes(
|
|
199
|
+
tar_url,
|
|
200
|
+
headers={"Accept": "application/vnd.github+json"},
|
|
201
|
+
timeout=60.0,
|
|
202
|
+
)
|
|
203
|
+
except HttpError as exc:
|
|
204
|
+
console.error(f"Error descargando {tar_url}: {exc}")
|
|
205
|
+
return 1
|
|
206
|
+
|
|
207
|
+
with tempfile.TemporaryDirectory(prefix="llmctl-skill-") as tmp:
|
|
208
|
+
tmp_path = Path(tmp)
|
|
209
|
+
try:
|
|
210
|
+
_safe_extract_tarball(archive_bytes, tmp_path)
|
|
211
|
+
except (tarfile.TarError, ValueError) as exc:
|
|
212
|
+
console.error(f"Error extrayendo archivo de skills: {exc}")
|
|
213
|
+
return 1
|
|
214
|
+
|
|
215
|
+
top_dirs = [p for p in tmp_path.iterdir() if p.is_dir()]
|
|
216
|
+
repo_root = top_dirs[0] if len(top_dirs) == 1 else tmp_path
|
|
217
|
+
search_root = (repo_root / subpath) if subpath else repo_root
|
|
218
|
+
candidates = _discover_skill_dirs(search_root)
|
|
219
|
+
|
|
220
|
+
# If root itself is a single skill, name it after the repo (or subpath leaf)
|
|
221
|
+
name_map: dict[Path, str] = {}
|
|
222
|
+
if len(candidates) == 1 and candidates[0] == repo_root:
|
|
223
|
+
name_map[candidates[0]] = Path(subpath).name if subpath else repo
|
|
224
|
+
|
|
225
|
+
return _finish_skill_install(
|
|
226
|
+
candidates,
|
|
227
|
+
skills_dir,
|
|
228
|
+
console,
|
|
229
|
+
skill_filter=skill_filter,
|
|
230
|
+
install_all=install_all,
|
|
231
|
+
name_map=name_map,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _finish_skill_install(
|
|
236
|
+
candidates: list[Path],
|
|
237
|
+
skills_dir: Path,
|
|
238
|
+
console: Console,
|
|
239
|
+
*,
|
|
240
|
+
skill_filter: str | None = None,
|
|
241
|
+
install_all: bool = False,
|
|
242
|
+
name_map: dict[Path, str] | None = None,
|
|
243
|
+
) -> int:
|
|
244
|
+
if not candidates:
|
|
245
|
+
console.error("No se encontró ningún archivo SKILL.md en el origen indicado.")
|
|
246
|
+
return 1
|
|
247
|
+
|
|
248
|
+
names: dict[Path, str] = {
|
|
249
|
+
c: (name_map[c] if name_map and c in name_map else c.name) for c in candidates
|
|
250
|
+
}
|
|
251
|
+
selected = candidates
|
|
252
|
+
|
|
253
|
+
if skill_filter:
|
|
254
|
+
selected = [c for c in candidates if names[c].lower() == skill_filter.lower()]
|
|
255
|
+
if not selected:
|
|
256
|
+
available = ", ".join(names[c] for c in candidates)
|
|
257
|
+
console.error(f"No se encontró la skill '{skill_filter}'. Disponibles: {available}")
|
|
258
|
+
return 1
|
|
259
|
+
elif (
|
|
260
|
+
len(candidates) > 1
|
|
261
|
+
and not install_all
|
|
262
|
+
and console.is_interactive()
|
|
263
|
+
and not console.assume_yes
|
|
264
|
+
and not console.json_mode
|
|
265
|
+
):
|
|
266
|
+
console.line(f"Se encontraron {len(candidates)} skills:")
|
|
267
|
+
for idx, cand in enumerate(candidates, 1):
|
|
268
|
+
console.line(f" [{idx}] {names[cand]}")
|
|
269
|
+
console.line(" [a] Instalar todas")
|
|
270
|
+
choice = console.prompt("Elige número o 'a' para todas", default="a").lower()
|
|
271
|
+
if choice != "a":
|
|
272
|
+
try:
|
|
273
|
+
selected = [candidates[int(choice) - 1]]
|
|
274
|
+
except (ValueError, IndexError):
|
|
275
|
+
console.line("Cancelado.")
|
|
276
|
+
return 0
|
|
277
|
+
|
|
278
|
+
installed = [
|
|
279
|
+
_install_skill_dir(cand, skills_dir, name_override=names[cand]) for cand in selected
|
|
280
|
+
]
|
|
281
|
+
|
|
282
|
+
if console.json_mode:
|
|
283
|
+
console.emit_json({"installed": installed, "skills_dir": str(skills_dir)})
|
|
284
|
+
else:
|
|
285
|
+
console.ok(f"Instaladas {len(installed)} skill(s) en {skills_dir}: {', '.join(installed)}")
|
|
286
|
+
return 0
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def import_local_skills(
|
|
290
|
+
skills_dir: Path, *, cwd: Path | None = None, home: Path | None = None
|
|
291
|
+
) -> list[str]:
|
|
292
|
+
"""Import local skills from common agent directories into *skills_dir*."""
|
|
293
|
+
user_home = Path.home() if home is None else home
|
|
294
|
+
work_dir = Path.cwd() if cwd is None else cwd
|
|
295
|
+
skills_dir.mkdir(parents=True, exist_ok=True)
|
|
296
|
+
|
|
297
|
+
candidate_roots = [
|
|
298
|
+
user_home / ".agents" / "skills",
|
|
299
|
+
user_home / ".claude" / "skills",
|
|
300
|
+
work_dir / "skills",
|
|
301
|
+
work_dir / ".agents" / "skills",
|
|
302
|
+
]
|
|
303
|
+
|
|
304
|
+
imported: list[str] = []
|
|
305
|
+
seen: set[str] = set()
|
|
306
|
+
|
|
307
|
+
for root in candidate_roots:
|
|
308
|
+
if not root.is_dir():
|
|
309
|
+
continue
|
|
310
|
+
for entry in sorted(root.iterdir(), key=lambda p: p.name.lower()):
|
|
311
|
+
if entry.is_dir() and (entry / "SKILL.md").is_file() and entry.name not in seen:
|
|
312
|
+
_install_skill_dir(entry, skills_dir)
|
|
313
|
+
seen.add(entry.name)
|
|
314
|
+
imported.append(entry.name)
|
|
315
|
+
return imported
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def remove_skill(skills_dir: Path, name: str) -> bool:
|
|
319
|
+
"""Remove an installed skill directory by name."""
|
|
320
|
+
target = skills_dir / name
|
|
321
|
+
if not target.is_dir() or not (target / "SKILL.md").is_file():
|
|
322
|
+
return False
|
|
323
|
+
shutil.rmtree(target)
|
|
324
|
+
return True
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def resolve_skill_file(skill_ref: str, skills_dir: Path, *, cwd: Path | None = None) -> Path | None:
|
|
328
|
+
"""Locate SKILL.md given a skill name, folder path, or direct SKILL.md path."""
|
|
329
|
+
work_dir = Path.cwd() if cwd is None else cwd
|
|
330
|
+
ref_path = Path(skill_ref).expanduser()
|
|
331
|
+
|
|
332
|
+
candidates: list[Path] = []
|
|
333
|
+
if ref_path.is_file():
|
|
334
|
+
candidates.append(ref_path)
|
|
335
|
+
elif ref_path.is_dir():
|
|
336
|
+
candidates.append(ref_path / "SKILL.md")
|
|
337
|
+
else:
|
|
338
|
+
candidates.append(skills_dir / skill_ref / "SKILL.md")
|
|
339
|
+
candidates.append(work_dir / skill_ref / "SKILL.md")
|
|
340
|
+
|
|
341
|
+
for cand in candidates:
|
|
342
|
+
if cand.is_file():
|
|
343
|
+
return cand
|
|
344
|
+
return None
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def run_skill(
|
|
348
|
+
skill_ref: str,
|
|
349
|
+
alias: str,
|
|
350
|
+
config: AppConfig,
|
|
351
|
+
console: Console,
|
|
352
|
+
*,
|
|
353
|
+
prompt: str = "",
|
|
354
|
+
file_ctx: str | None = None,
|
|
355
|
+
) -> int:
|
|
356
|
+
"""Execute a SKILL.md instruction against a configured model via llama-server."""
|
|
357
|
+
skill_file = resolve_skill_file(skill_ref, config.skills_dir)
|
|
358
|
+
if not skill_file:
|
|
359
|
+
console.error(f"No se encontró SKILL.md para '{skill_ref}' en {config.skills_dir}.")
|
|
360
|
+
console.info("Usa 'llmctl skill add <owner/repo>' o 'llmctl skill import' primero.")
|
|
361
|
+
return 1
|
|
362
|
+
|
|
363
|
+
skill_md = skill_file.read_text(encoding="utf-8", errors="replace")
|
|
364
|
+
user_parts: list[str] = []
|
|
365
|
+
if prompt:
|
|
366
|
+
user_parts.append(prompt)
|
|
367
|
+
if file_ctx:
|
|
368
|
+
ctx_path = Path(file_ctx).expanduser()
|
|
369
|
+
if not ctx_path.is_file():
|
|
370
|
+
console.error(f"No se encontró el archivo de entrada: {file_ctx}")
|
|
371
|
+
return 1
|
|
372
|
+
ctx_text = ctx_path.read_text(encoding="utf-8", errors="replace")
|
|
373
|
+
user_parts.append(f"Contenido de referencia ({file_ctx}):\n```\n{ctx_text}\n```")
|
|
374
|
+
if not user_parts:
|
|
375
|
+
user_parts.append("Aplica las instrucciones de esta skill y resume los pasos o resultados.")
|
|
376
|
+
|
|
377
|
+
sys_prompt = f"Sigue estrictamente las siguientes instrucciones de skill:\n\n{skill_md}"
|
|
378
|
+
payload = {
|
|
379
|
+
"model": alias,
|
|
380
|
+
"messages": [
|
|
381
|
+
{"role": "system", "content": sys_prompt},
|
|
382
|
+
{"role": "user", "content": "\n\n".join(user_parts)},
|
|
383
|
+
],
|
|
384
|
+
"temperature": 0.2,
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
try:
|
|
388
|
+
data = request_json(
|
|
389
|
+
config.chat_completions_url,
|
|
390
|
+
method="POST",
|
|
391
|
+
payload=payload,
|
|
392
|
+
token=config.api_key,
|
|
393
|
+
timeout=300.0,
|
|
394
|
+
)
|
|
395
|
+
except HttpError as exc:
|
|
396
|
+
console.error(str(exc))
|
|
397
|
+
return 1
|
|
398
|
+
|
|
399
|
+
choices = data.get("choices") if isinstance(data, dict) else None
|
|
400
|
+
msg = choices[0].get("message", {}) if isinstance(choices, list) and choices else {}
|
|
401
|
+
content_out = str(msg.get("content") or "").strip()
|
|
402
|
+
reasoning_out = str(msg.get("reasoning_content") or "").strip()
|
|
403
|
+
|
|
404
|
+
if console.json_mode:
|
|
405
|
+
console.emit_json(
|
|
406
|
+
{
|
|
407
|
+
"skill": str(skill_file),
|
|
408
|
+
"model": alias,
|
|
409
|
+
"content": content_out,
|
|
410
|
+
"reasoning_content": reasoning_out,
|
|
411
|
+
}
|
|
412
|
+
)
|
|
413
|
+
return 0
|
|
414
|
+
|
|
415
|
+
if reasoning_out:
|
|
416
|
+
console.line(f"[Thinking]\n{reasoning_out}\n")
|
|
417
|
+
console.line(content_out or "(Sin contenido en 'content')")
|
|
418
|
+
return 0
|