Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Unsloth Desktop: Create, Edit, and Delete Skills from the Skills Menu (#11800)
Leo Borcherdingc0ebb4cd7437
diff --git a/studio/backend/core/inference/skills.py b/studio/backend/core/inference/skills.pyindex b85bef3b2a0..68e2284bf18 100644--- a/studio/backend/core/inference/skills.py+++ b/studio/backend/core/inference/skills.py@@ -7,6 +7,7 @@ import errnoimport jsonimport loggingimport os+import shutilimport statimport tempfileimport threading@@ -59,6 +60,10 @@ class SkillNotFoundError(SkillError):pass+class SkillExistsError(SkillError):+ pass++def _normalize_skill_name(name: str) -> str:if not isinstance(name, str) or not name.strip():raise SkillError("Skill name must be a non-empty string.")@@ -100,6 +105,29 @@ def _require_unlinked_agent_path(base: Path, *paths: Path) -> None:raise SkillError("Agent Skills directory is missing or unsafe.") from exc+def _agents_base(home: Optional[Path]) -> tuple[Path, Optional[Path]]:+ if home is not None:+ return home, None+ if is_owner_context():+ return _owner_home(), None+ return workspace_root(), Path(_MANAGED_SKILLS_DIR)+++def _agents_ancestors(base: Path, root: Optional[Path]) -> tuple[Path, ...]:+ if root is None:+ return (base / ".agents", base / ".agents" / "skills")+ return (base / root,)+++def _agents_root_linked(home: Optional[Path]) -> bool:+ base, root = _agents_base(home)+ try:+ base = base.resolve(strict = True)+ except OSError:+ return False+ return any(_is_linked_path(path) for path in _agents_ancestors(base, root))++def _write_new_skill_manifest(base: Path,name: str,@@ -108,15 +136,8 @@ def _write_new_skill_manifest(root: Optional[Path] = None,) -> None:base = base.resolve(strict = True)- if root is None:- # The owner's home: ~/.agents/skills, both levels checked.- agents = base / ".agents"- root = agents / "skills"- ancestors: tuple[Path, ...] = (agents, root)- else:- # A managed account's private workspace: <workspace>/skills.- root = base / root- ancestors = (root,)+ ancestors = _agents_ancestors(base, root)+ root = ancestors[-1]_require_unlinked_agent_path(base, *ancestors)root.mkdir(mode = 0o700, parents = True, exist_ok = True)_require_unlinked_agent_path(base, *ancestors)@@ -260,14 +281,14 @@ def _read_limited(return raw-def _parse_skill_markdown(raw: bytes, parent_name: Optional[str] = None) -> dict:+def _split_skill_markdown(raw: bytes) -> tuple[dict, str]:if len(raw) > MAX_SKILL_MD_BYTES:raise SkillError("SKILL.md exceeds the 512 KB limit.")try:text = raw.decode("utf-8")except UnicodeDecodeError as exc:raise SkillError("SKILL.md must be UTF-8 text.") from exc- lines = text.splitlines()+ lines = text.splitlines(keepends = True)if not lines or lines[0].strip() != "---":raise SkillError("SKILL.md must start with YAML frontmatter.")# Exact match: an indented `---` inside a block scalar is YAML content, not the closer.@@ -277,7 +298,7 @@ def _parse_skill_markdown(raw: bytes, parent_name: Optional[str] = None) -> dictif closing is None:raise SkillError("SKILL.md YAML frontmatter is not closed.")try:- frontmatter = yaml.safe_load("\n".join(lines[1:closing]))+ frontmatter = yaml.safe_load("".join(lines[1:closing]))except (yaml.YAMLError,AttributeError,@@ -290,6 +311,11 @@ def _parse_skill_markdown(raw: bytes, parent_name: Optional[str] = None) -> dictraise SkillError("SKILL.md contains invalid YAML frontmatter.") from excif not isinstance(frontmatter, dict):raise SkillError("SKILL.md frontmatter must be a mapping.")+ return frontmatter, "".join(lines[closing + 1 :])+++def _parse_skill_markdown(raw: bytes, parent_name: Optional[str] = None) -> dict:+ frontmatter, _ = _split_skill_markdown(raw)name = _normalize_skill_name(frontmatter.get("name"))if parent_name is not None and name != parent_name:@@ -485,6 +511,8 @@ def _discover(home: Optional[Path]) -> list[tuple[dict, Optional[Path], Optionaloverrides = _load_overrides()found: list[tuple[dict, Optional[Path], Optional[os.stat_result]]] = []selected: dict[str, dict] = {}+ # A linked Agents root makes every skill under it read-only, like a linked entry.+ agents_linked = _agents_root_linked(home)for source, root in _skill_roots(home):try:candidates = _candidate_dirs(root)@@ -499,6 +527,7 @@ def _discover(home: Optional[Path]) -> list[tuple[dict, Optional[Path], Optional"enabled": False,"valid": False,"shadowed": False,+ "linked": False,"error": str(exc),},None,@@ -514,6 +543,7 @@ def _discover(home: Optional[Path]) -> list[tuple[dict, Optional[Path], Optional"enabled": False,"valid": False,"shadowed": False,+ "linked": _is_linked_path(candidate) or (source == "agents" and agents_linked),}try:metadata, skill_dir = _validate_skill_dir(candidate)@@ -595,14 +625,7 @@ def set_skill_enabled(return {**record, "enabled": enabled}-def create_skill(- name: str,- description: str,- instructions: str,- *,- home: Optional[Path] = None,-) -> dict:- normalized = _normalize_skill_name(name)+def _validate_draft(description: str, instructions: str) -> str:if not isinstance(description, str) or not description.strip() or len(description) > 1024:raise SkillError("Skill description must be 1-1024 characters.")if not isinstance(instructions, str) or not instructions.strip():@@ -613,21 +636,28 @@ def create_skill(raise SkillError("Skill instructions must be valid UTF-8 text.") from excif len(instruction_bytes) > MAX_SKILL_INSTRUCTIONS_BYTES:raise SkillError("Skill instructions exceed the 256 KB limit.")+ return description.strip()- frontmatter = yaml.safe_dump(- {"name": normalized, "description": description.strip()},- allow_unicode = True,- sort_keys = False,- )- manifest = f"---\n{frontmatter}---\n\n{instructions.strip()}\n".encode("utf-8")++def _render_manifest(frontmatter: dict, instructions: str) -> bytes:+ dumped = yaml.safe_dump(frontmatter, allow_unicode = True, sort_keys = False)+ return f"---\n{dumped}---\n\n{instructions.strip()}\n".encode("utf-8")+++def create_skill(+ name: str,+ description: str,+ instructions: str,+ *,+ home: Optional[Path] = None,+) -> dict:+ normalized = _normalize_skill_name(name)+ description = _validate_draft(description, instructions)+ manifest = _render_manifest({"name": normalized, "description": description}, instructions)metadata = _parse_skill_markdown(manifest, normalized)- if home is not None:- base, root = home, None- elif is_owner_context():- base, root = _owner_home(), None- else:- base, root = workspace_root(), Path(_MANAGED_SKILLS_DIR)+ base, root = _agents_base(home)+ if root is not None:# A fresh account's workspace may not exist yet; its own private root is safe to make.base.mkdir(mode = 0o700, parents = True, exist_ok = True)with _LOCK:@@ -645,7 +675,7 @@ def create_skill(try:_write_new_skill_manifest(base, normalized, manifest, root = root)except FileExistsError as exc:- raise SkillError(f"Skill '{normalized}' already exists.") from exc+ raise SkillExistsError(f"Skill '{normalized}' already exists.") from excexcept OSError as exc:raise SkillError(f"Could not create skill '{normalized}'.") from excexcept Exception:@@ -668,6 +698,120 @@ def create_skill(}+def _editable_skill(+ name: str, *, home: Optional[Path]+) -> tuple[dict, Path, Optional[os.stat_result]]:+ """A plain, unlinked directory in the Agents root; anything else is read-only."""+ record, skill_dir, identity = _selected_skill(name, home = home)+ if record["source"] != "agents":+ raise SkillError(+ f"Skill '{record['name']}' is not in the Agents folder, so it cannot be changed here."+ )+ base, root = _agents_base(home)+ try:+ base = base.resolve(strict = True)+ except OSError as exc:+ raise SkillError("Agent Skills directory is missing or unsafe.") from exc+ # Same check as create_skill: a linked root would send the write outside it.+ ancestors = _agents_ancestors(base, root)+ _require_unlinked_agent_path(base, *ancestors)+ entry = ancestors[-1] / record["name"]+ if record["linked"] or _is_linked_path(entry) or skill_dir != entry:+ raise SkillError(f"Skill '{record['name']}' is a link, so it cannot be changed here.")+ if identity is not None and not os.path.samestat(+ os.stat(skill_dir, follow_symlinks = False), identity+ ):+ raise SkillError("Skill directory changed after it was selected.")+ return record, skill_dir, identity+++def _replace_skill_manifest(skill_dir: Path, manifest: bytes, identity) -> None:+ target = skill_dir / "SKILL.md"+ if _is_linked_path(target):+ raise SkillError("Skill resources cannot use symbolic links or reparse points.")+ fd, temporary = tempfile.mkstemp(prefix = ".SKILL-", suffix = ".md", dir = skill_dir)+ try:+ with os.fdopen(fd, "wb") as handle:+ handle.write(manifest)+ handle.flush()+ os.fsync(handle.fileno())+ if identity is not None and not os.path.samestat(+ os.stat(skill_dir, follow_symlinks = False), identity+ ):+ raise SkillError("Skill directory changed while the manifest was being written.")+ os.replace(temporary, target)+ except Exception:+ try:+ os.unlink(temporary)+ except OSError:+ pass+ raise+++def read_skill_manifest(name: str, *, home: Optional[Path] = None) -> dict:+ with _LOCK:+ record, skill_dir, identity = _selected_skill(name, home = home)+ raw = _read_limited(+ skill_dir / "SKILL.md", MAX_SKILL_MD_BYTES, contained_in = skill_dir, identity = identity+ )+ _, body = _split_skill_markdown(raw)+ display = {+ "agents": "~/.agents/skills" if is_owner_context() else _MANAGED_SKILLS_DIR,+ "claude": "~/.claude/skills",+ }.get(record["source"])+ return {+ **record,+ "instructions": body.strip(),+ **({"path": f"{display}/{record['name']}/SKILL.md"} if display else {}),+ }+++def update_skill(+ name: str,+ description: str,+ instructions: str,+ *,+ home: Optional[Path] = None,+) -> dict:+ description = _validate_draft(description, instructions)+ with _LOCK:+ record, skill_dir, identity = _editable_skill(name, home = home)+ raw = _read_limited(+ skill_dir / "SKILL.md", MAX_SKILL_MD_BYTES, contained_in = skill_dir, identity = identity+ )+ frontmatter, _ = _split_skill_markdown(raw)+ manifest = _render_manifest(+ {**frontmatter, "name": record["name"], "description": description}, instructions+ )+ metadata = _parse_skill_markdown(manifest, record["name"])+ try:+ _replace_skill_manifest(skill_dir, manifest, identity)+ except OSError as exc:+ raise SkillError(f"Could not save skill '{record['name']}'.") from exc+ return {**record, **metadata}+++def delete_skill(name: str, *, home: Optional[Path] = None) -> dict:+ with _LOCK:+ record, skill_dir, _ = _editable_skill(name, home = home)+ try:+ shutil.rmtree(skill_dir)+ except OSError as exc:+ raise SkillError(f"Could not delete skill '{record['name']}'.") from exc+ # A stale disable would otherwise apply to the next skill made by hand under this name.+ overrides = _load_overrides()+ if overrides.pop(record["name"], None) is not None:+ try:+ _save_overrides(overrides)+ except OSError as exc:+ logger.warning(+ "Deleted skill %s but could not clear its enable override: %s",+ record["name"],+ exc,+ )+ return record++def format_skill_catalog(skills: Optional[list[dict]] = None, *, budget: int = MAX_SKILL_CATALOG_BYTES) -> str:diff --git a/studio/backend/routes/skills.py b/studio/backend/routes/skills.pyindex 6342d35100f..46589b473c3 100644--- a/studio/backend/routes/skills.py+++ b/studio/backend/routes/skills.py@@ -3,11 +3,21 @@from typing import Any, Literal, Optional-from fastapi import APIRouter, Depends, HTTPException-from pydantic import BaseModel, ConfigDict, StrictBool+from fastapi import APIRouter, Depends, HTTPException, Response+from pydantic import BaseModel, ConfigDict, StrictBool, StrictStrfrom auth.authentication import get_current_subject-from core.inference.skills import SkillError, SkillNotFoundError, list_skills, set_skill_enabled+from core.inference.skills import (+ SkillError,+ SkillExistsError,+ SkillNotFoundError,+ create_skill,+ delete_skill,+ list_skills,+ read_skill_manifest,+ set_skill_enabled,+ update_skill,+)router = APIRouter()@@ -22,12 +32,18 @@ class SkillRecord(BaseModel):enabled: boolvalid: boolshadowed: bool+ linked: bool = Falseshadowed_by: Optional[Literal["agents", "claude", "bundled"]] = Noneerror: Optional[str] = Nonelicense: Optional[str] = Nonecompatibility: Optional[str] = Nonemetadata: Optional[dict[str, str]] = Noneallowed_tools: Optional[str] = None+ path: Optional[str] = None+++class SkillManifest(SkillRecord):+ instructions: strclass SkillEnabledRequest(BaseModel):@@ -36,6 +52,30 @@ class SkillEnabledRequest(BaseModel):enabled: StrictBool+class SkillDraft(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ description: StrictStr+ instructions: StrictStr+++class SkillCreateRequest(SkillDraft):+ name: StrictStr+++def _invalidate_catalog() -> None:+ from routes.inference import _invalidate_agent_skills_cache+ _invalidate_agent_skills_cache()+++def _http_error(exc: SkillError) -> HTTPException:+ if isinstance(exc, SkillNotFoundError):+ return HTTPException(status_code = 404, detail = str(exc))+ if isinstance(exc, SkillExistsError):+ return HTTPException(status_code = 409, detail = str(exc))+ return HTTPException(status_code = 400, detail = str(exc))++@router.get("", response_model = list[SkillRecord])def get_skills(current_subject: str = Depends(get_current_subject)) -> list[dict[str, Any]]:try:@@ -43,12 +83,54 @@ def get_skills(current_subject: str = Depends(get_current_subject)) -> list[dictexcept SkillError as exc:raise HTTPException(status_code = 500, detail = "Could not read Agent Skills.") from exc# The client just saw the folders; the next inference scan must not serve an older snapshot.- from routes.inference import _invalidate_agent_skills_cache-- _invalidate_agent_skills_cache()+ _invalidate_catalog()return records[email protected]("", response_model = SkillRecord, status_code = 201)+def create_skill_route(+ payload: SkillCreateRequest, current_subject: str = Depends(get_current_subject)+) -> dict[str, Any]:+ try:+ record = create_skill(payload.name, payload.description, payload.instructions)+ except SkillError as exc:+ raise _http_error(exc) from exc+ _invalidate_catalog()+ return record++[email protected]("/{name}", response_model = SkillManifest)+def get_skill(name: str, current_subject: str = Depends(get_current_subject)) -> dict[str, Any]:+ try:+ return read_skill_manifest(name)+ except SkillError as exc:+ raise _http_error(exc) from exc++[email protected]("/{name}", response_model = SkillRecord)+def update_skill_route(+ name: str,+ payload: SkillDraft,+ current_subject: str = Depends(get_current_subject),+) -> dict[str, Any]:+ try:+ record = update_skill(name, payload.description, payload.instructions)+ except SkillError as exc:+ raise _http_error(exc) from exc+ _invalidate_catalog()+ return record++[email protected]("/{name}", status_code = 204, response_class = Response)+def delete_skill_route(name: str, current_subject: str = Depends(get_current_subject)) -> Response:+ try:+ delete_skill(name)+ except SkillError as exc:+ raise _http_error(exc) from exc+ _invalidate_catalog()+ return Response(status_code = 204)++@router.put("/{name}/enabled", response_model = SkillRecord)def update_skill_enabled(name: str,@@ -57,9 +139,7 @@ def update_skill_enabled() -> dict[str, Any]:try:updated = set_skill_enabled(name, payload.enabled)- from routes.inference import _invalidate_agent_skills_cache-- _invalidate_agent_skills_cache()+ _invalidate_catalog()return updatedexcept SkillNotFoundError as exc:raise HTTPException(status_code = 404, detail = str(exc)) from excdiff --git a/studio/backend/tests/multi_account/factories.py b/studio/backend/tests/multi_account/factories.pyindex 0aa96b59a27..062c7024e09 100644--- a/studio/backend/tests/multi_account/factories.py+++ b/studio/backend/tests/multi_account/factories.py@@ -156,6 +156,14 @@ CORE_FACTORIES = {"routes.skills:PUT:/{name}/enabled": Factory("skill", {"enabled": False}, fragment = SKILL_NAME, absent = SENTINEL),+ "routes.skills:GET:/{name}": Factory("skill", fragment = SENTINEL, absent = SENTINEL),+ "routes.skills:PUT:/{name}": Factory(+ "skill",+ {"description": EDITED, "instructions": "Instructions"},+ fragment = EDITED,+ absent = SENTINEL,+ ),+ "routes.skills:DELETE:/{name}": Factory("skill", success = 204, absent = SENTINEL),}diff --git a/studio/backend/tests/test_skills.py b/studio/backend/tests/test_skills.pyindex a149af9a0f2..d58b936788d 100644--- a/studio/backend/tests/test_skills.py+++ b/studio/backend/tests/test_skills.py@@ -91,6 +91,7 @@ def test_discovers_both_roots_with_agents_precedence(isolated_skills):]assert records[0]["description"] == "Agent copy"assert records[0]["enabled"] is True+ assert records[0]["linked"] is Falseassert records[2]["shadowed_by"] == "agents"@@ -941,3 +942,218 @@ def test_oversized_scalar_fields_are_rejected(isolated_skills, field):record = next(r for r in skills.list_skills(home = home) if r["name"] == "wide")assert record["valid"] is False and "1024" in record["error"]+++def test_update_skill_rewrites_the_manifest_and_keeps_the_rest_of_its_frontmatter(isolated_skills):+ home, _ = isolated_skills+ folder = _write_skill(+ home,+ "agents",+ "notes",+ description = "Old description",+ frontmatter = "license: MIT\nmetadata:\n author: leo",+ body = "Old body",+ )+ skills.set_skill_enabled("notes", False, home = home)++ manifest = skills.read_skill_manifest("notes", home = home)+ assert (manifest["description"], manifest["instructions"]) == ("Old description", "Old body")+ assert manifest["path"] == "~/.agents/skills/notes/SKILL.md"++ record = skills.update_skill(+ "notes", " New description ", "# New body\n\nStep one.\n", home = home+ )++ assert record["description"] == "New description"+ assert record["license"] == "MIT" and record["metadata"] == {"author": "leo"}+ assert record["enabled"] is False+ text = (folder / "SKILL.md").read_text(encoding = "utf-8")+ assert text.startswith("---\nname: notes\ndescription: New description\nlicense: MIT\n")+ assert text.endswith("---\n\n# New body\n\nStep one.\n")+ assert (+ skills.read_skill_manifest("notes", home = home)["instructions"] == "# New body\n\nStep one."+ )+ assert [path.name for path in folder.iterdir()] == ["SKILL.md"]+ with pytest.raises(skills.SkillError, match = "1-1024"):+ skills.update_skill("notes", "", "Body", home = home)+ with pytest.raises(skills.SkillError, match = "non-empty"):+ skills.update_skill("notes", "Description", " ", home = home)+++def test_delete_skill_removes_the_folder_and_its_override(isolated_skills):+ home, _ = isolated_skills+ folder = _write_skill(home, "agents", "gone")+ (folder / "scripts").mkdir()+ (folder / "scripts" / "run.py").write_text("print(1)", encoding = "utf-8")+ _write_skill(home, "agents", "stays")+ skills.set_skill_enabled("gone", False, home = home)+ skills.set_skill_enabled("stays", False, home = home)+ assert skills._load_overrides() == {"gone": False, "stays": False}++ record = skills.delete_skill("gone", home = home)++ assert record["name"] == "gone"+ assert not folder.exists()+ assert skills._load_overrides() == {"stays": False}+ assert [item["name"] for item in skills.list_skills(home = home)] == ["stays"]+ with pytest.raises(skills.SkillNotFoundError):+ skills.delete_skill("gone", home = home)++[email protected]("operation", ("update", "delete"))+def test_only_agents_skills_can_be_changed_from_the_dialog(isolated_skills, monkeypatch, operation):+ home, _ = isolated_skills+ _write_skill(home, "claude", "claude-owned", body = "Claude body")+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ ("bundled", Path(skills.__file__).with_name("bundled_skills")),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)++ def change(name: str):+ if operation == "update":+ return skills.update_skill(name, "Description", "Instructions")+ return skills.delete_skill(name)++ for name in ("claude-owned", "skill-creator"):+ manifest = skills.read_skill_manifest(name)+ assert manifest["source"] != "agents" and manifest["instructions"]+ with pytest.raises(skills.SkillError, match = "cannot be changed here"):+ change(name)+ assert skills.read_skill_manifest("claude-owned")["instructions"] == "Claude body"+ with pytest.raises(skills.SkillNotFoundError):+ change("missing")+ with pytest.raises(skills.SkillNotFoundError):+ skills.read_skill_manifest("missing")+ assert (home / ".claude" / "skills" / "claude-owned" / "SKILL.md").is_file()+ assert (+ Path(skills.__file__).with_name("bundled_skills") / "skill-creator" / "SKILL.md"+ ).is_file()+++def test_linked_agents_skill_stays_read_only_in_the_dialog(isolated_skills, tmp_path):+ home, _ = isolated_skills+ real = _write_skill(tmp_path / "elsewhere", "agents", "linked")+ root = home / ".agents" / "skills"+ root.mkdir(parents = True)+ try:+ (root / "linked").symlink_to(real, target_is_directory = True)+ except (OSError, NotImplementedError):+ # Reason: Windows may deny symlink creation without Developer Mode.+ pytest.skip("symlinks are unavailable on this platform")+ listed = skills.list_skills(home = home)[0]+ assert (listed["valid"], listed["linked"]) == (True, True)++ assert skills.read_skill_manifest("linked", home = home)["linked"] is True+ with pytest.raises(skills.SkillError, match = "is a link"):+ skills.update_skill("linked", "Description", "Instructions", home = home)+ with pytest.raises(skills.SkillError, match = "is a link"):+ skills.delete_skill("linked", home = home)+ assert (real / "SKILL.md").is_file()+ assert (root / "linked").is_symlink()++[email protected]("linked_level", [".agents", "skills"])+def test_skill_under_a_linked_agents_root_stays_read_only(isolated_skills, tmp_path, linked_level):+ home, _ = isolated_skills+ outside = tmp_path / "outside"+ real = _write_skill(outside, "agents", "rooted").parent.parent+ try:+ if linked_level == ".agents":+ (home / ".agents").symlink_to(real, target_is_directory = True)+ else:+ (home / ".agents").mkdir()+ (home / ".agents" / "skills").symlink_to(real / "skills", target_is_directory = True)+ except (OSError, NotImplementedError):+ # Reason: Windows may deny symlink creation without Developer Mode.+ pytest.skip("symlinks are unavailable on this platform")++ assert skills.list_skills(home = home)[0]["linked"] is True+ with pytest.raises(skills.SkillError, match = "unsafe"):+ skills.update_skill("rooted", "Changed", "Changed", home = home)+ with pytest.raises(skills.SkillError, match = "unsafe"):+ skills.delete_skill("rooted", home = home)+ assert (+ (real / "skills" / "rooted" / "SKILL.md")+ .read_text(encoding = "utf-8")+ .endswith("\n---\nInstructions")+ )+++def test_authenticated_create_read_update_and_delete_routes(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)+ monkeypatch.setattr(skills, "_owner_home", lambda: home)+ from routes import inference as inference_routes++ app = FastAPI()+ app.include_router(router, prefix = "/api/skills")+ draft = {"name": "made", "description": "Made in the dialog.", "instructions": "Do the thing."}+ anonymous = TestClient(app)+ assert anonymous.post("/api/skills", json = draft).status_code in (401, 403)+ assert anonymous.delete("/api/skills/made").status_code in (401, 403)+ assert not (home / ".agents" / "skills" / "made").exists()+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ client = TestClient(app)++ monkeypatch.setattr(inference_routes, "_AGENT_SKILLS_CACHE", {None: (float("inf"), [])})+ response = client.post("/api/skills", json = draft)+ assert response.status_code == 201, response.text+ created = response.json()+ assert (created["name"], created["enabled"], created["source"]) == ("made", True, "agents")+ assert created["path"] == "~/.agents/skills/made/SKILL.md"+ assert (home / ".agents" / "skills" / "made" / "SKILL.md").is_file()+ assert inference_routes._AGENT_SKILLS_CACHE == {}+ assert client.post("/api/skills", json = draft).status_code == 409+ assert client.post("/api/skills", json = {**draft, "name": "Bad Name"}).status_code == 400+ assert client.post("/api/skills", json = {**draft, "name": 1}).status_code == 422+ assert client.post("/api/skills", json = {**draft, "extra": True}).status_code == 422++ response = client.get("/api/skills/made")+ assert response.status_code == 200, response.text+ assert response.json()["instructions"] == "Do the thing."+ assert client.get("/api/skills/missing").status_code == 404++ monkeypatch.setattr(inference_routes, "_AGENT_SKILLS_CACHE", {None: (float("inf"), [])})+ edit = {"description": "Edited.", "instructions": "Do it better."}+ response = client.put("/api/skills/made", json = edit)+ assert response.status_code == 200, response.text+ assert response.json()["description"] == "Edited."+ assert client.get("/api/skills/made").json()["instructions"] == "Do it better."+ assert inference_routes._AGENT_SKILLS_CACHE == {}+ assert client.put("/api/skills/made", json = {**edit, "description": ""}).status_code == 400+ assert client.put("/api/skills/missing", json = edit).status_code == 404++ monkeypatch.setattr(inference_routes, "_AGENT_SKILLS_CACHE", {None: (float("inf"), [])})+ assert client.delete("/api/skills/made").status_code == 204+ assert not (home / ".agents" / "skills" / "made").exists()+ assert inference_routes._AGENT_SKILLS_CACHE == {}+ assert client.delete("/api/skills/made").status_code == 404+++def test_managed_account_edits_and_deletes_only_its_own_skills(managed_accounts):+ from utils.account_context import run_as++ home, studio, alice, bob = managed_accounts+ owner_manifest = (+ _write_skill(home, "agents", "owner-made", description = "owner copy") / "SKILL.md"+ )+ run_as(bob, skills.create_skill, "bob-made", "Bob's skill", "Instructions")++ record = run_as(bob, skills.update_skill, "bob-made", "Bob's edited skill", "Edited")+ assert record["description"] == "Bob's edited skill"+ assert run_as(bob, skills.read_skill_manifest, "bob-made")["instructions"] == "Edited"+ with pytest.raises(skills.SkillNotFoundError):+ run_as(bob, skills.update_skill, "owner-made", "Hijacked", "Body")+ with pytest.raises(skills.SkillNotFoundError):+ run_as(alice, skills.delete_skill, "bob-made")+ assert "owner copy" in owner_manifest.read_text(encoding = "utf-8")++ run_as(bob, skills.delete_skill, "bob-made")+ assert not (studio / "accounts" / _BOB_ID / "skills" / "bob-made").exists()+ assert owner_manifest.is_file()diff --git a/studio/frontend/src/components/assistant-ui/skill-mention-token.ts b/studio/frontend/src/components/assistant-ui/skill-mention-token.tsnew file mode 100644index 00000000000..5f770c5404f--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/skill-mention-token.ts@@ -0,0 +1,25 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type MentionToken = { start: number; end: number; query: string };++// The @name token around the caret; accepting replaces all of it, not just up to the caret.+export function mentionTokenAt(text: string, caret: number): MentionToken | null {+ const prefix = text.slice(0, caret);+ const match = /(?:^|\s)@([a-z0-9-]*)$/i.exec(prefix);+ if (!match) return null;+ const tail = /^[a-z0-9-]*/i.exec(text.slice(caret))?.[0] ?? "";+ return { start: prefix.lastIndexOf("@"), end: caret + tail.length, query: match[1] ?? "" };+}++export function replaceMentionToken(+ text: string,+ token: MentionToken,+ directive: string,+): { text: string; caret: number } {+ const after = text.slice(token.end);+ return {+ text: `${text.slice(0, token.start)}${directive} ${after.startsWith(" ") ? after.slice(1) : after}`,+ caret: token.start + directive.length + 1,+ };+}diff --git a/studio/frontend/src/components/assistant-ui/skill-mentions.tsx b/studio/frontend/src/components/assistant-ui/skill-mentions.tsxindex e836755ebcf..8499d37df84 100644--- a/studio/frontend/src/components/assistant-ui/skill-mentions.tsx+++ b/studio/frontend/src/components/assistant-ui/skill-mentions.tsx@@ -16,6 +16,7 @@ import {ComposerPrimitive,unstable_useMentionAdapter,unstable_useTriggerPopoverScopeContext,+ useAui,} from "@assistant-ui/react";import { Scroll01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";@@ -32,6 +33,11 @@ import {useRef,useState,} from "react";+import {+ type MentionToken,+ mentionTokenAt,+ replaceMentionToken,+} from "./skill-mention-token";function enabled(records: readonly SkillRecord[]): readonly SkillRecord[] {return records.filter(@@ -125,6 +131,37 @@ function MentionOpenSignal({return null;}+// The library's insert stops at the caret, leaving "@calculator tor"; replace the whole token.+function MentionTokenReplacer(): null {+ const aui = useAui();+ const { registerSelectItemOverride, setCursorPosition } =+ unstable_useTriggerPopoverScopeContext();+ useEffect(+ () =>+ registerSelectItemOverride((item) => {+ const input = document.activeElement;+ if (!(input instanceof HTMLTextAreaElement)) return false;+ const text = aui.composer().getState().text;+ if (input.value !== text) return false;+ const token = mentionTokenAt(text, input.selectionStart);+ if (!token) return false;+ const next = replaceMentionToken(+ text,+ token,+ skillMentionFormatter.serialize(item),+ );+ aui.composer().setText(next.text);+ setCursorPosition(next.caret);+ requestAnimationFrame(() => {+ input.setSelectionRange(next.caret, next.caret);+ });+ return true;+ }),+ [aui, registerSelectItemOverride, setCursorPosition],+ );+ return null;+}+export function SkillMentionPopover({enabled: mentionsEnabled,onConsumesEnterChange,@@ -176,6 +213,7 @@ export function SkillMentionPopover({{...mention.directive}/><MentionOpenSignal onChange={onOpenChange} />+ <MentionTokenReplacer /><ComposerPrimitive.Unstable_TriggerPopoverItems>{(results) => (<>@@ -192,6 +230,8 @@ export function SkillMentionPopover({key={item.id}item={item}index={index}+ // Keep focus (and the caret) in the textarea so the token replacer sees it.+ onMouseDown={(event) => event.preventDefault()}className="flex w-full items-start gap-2.5 rounded-[11px] px-3 py-2 text-left outline-none transition-colors hover:bg-accent hover:text-accent-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground"><HugeiconsIcon@@ -219,15 +259,7 @@ export function SkillMentionPopover({);}-type MentionRange = { start: number; end: number; query: string } | null;--function mentionAtCaret(text: string, caret: number): MentionRange {- const prefix = text.slice(0, caret);- const match = /(?:^|\s)@([a-z0-9-]*)$/i.exec(prefix);- if (!match) return null;- const at = prefix.lastIndexOf("@");- return { start: at, end: caret, query: match[1] ?? "" };-}+type MentionRange = MentionToken | null;export function useTextareaSkillMentions({text,@@ -294,7 +326,7 @@ export function useTextareaSkillMentions({setRange(null);return;}- const next = mentionAtCaret(nextText, caret);+ const next = mentionTokenAt(nextText, caret);// A fresh @ re-reads the folders, so a skill written since page load is offered.if (next?.query === "") refreshSkillsCatalog();setRange(next);@@ -311,13 +343,12 @@ export function useTextareaSkillMentions({type: "skill",label: skill.name,});- const next = `${text.slice(0, range.start)}${directive} ${text.slice(range.end)}`;- const caret = range.start + directive.length + 1;- setText(next);+ const next = replaceMentionToken(text, range, directive);+ setText(next.text);setRange(null);requestAnimationFrame(() => {inputRef.current?.focus();- inputRef.current?.setSelectionRange(caret, caret);+ inputRef.current?.setSelectionRange(next.caret, next.caret);});},[inputRef, range, setText, text],diff --git a/studio/frontend/src/features/chat/api/skills-api.ts b/studio/frontend/src/features/chat/api/skills-api.tsindex 9a0baac3108..7716428e03c 100644--- a/studio/frontend/src/features/chat/api/skills-api.ts+++ b/studio/frontend/src/features/chat/api/skills-api.ts@@ -13,14 +13,24 @@ export type SkillRecord = {enabled: boolean;valid: boolean;shadowed: boolean;+ linked?: boolean;shadowed_by?: "agents" | "claude" | "bundled" | null;error?: string | null;license?: string | null;compatibility?: string | null;metadata?: Record<string, string> | null;allowed_tools?: string | null;+ path?: string | null;};+export type SkillDraft = {+ name: string;+ description: string;+ instructions: string;+};++export type SkillManifest = SkillRecord & { instructions: string };+type SkillsSnapshot = {skills: readonly SkillRecord[];loading: boolean;@@ -140,6 +150,56 @@ export async function setSkillEnabled(return updated;}+export const SKILL_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;++export function isValidSkillName(name: string): boolean {+ return SKILL_NAME_PATTERN.test(name) && !name.includes("--");+}++async function skillsMutated(): Promise<void> {+ channel?.postMessage("changed");+ void refreshContextUsage({ invalidate: true });+ await listSkills(true).catch(() => undefined);+}++export async function createSkill(draft: SkillDraft): Promise<SkillRecord> {+ const response = await authFetch("/api/skills", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(draft),+ });+ const created = await parseResponse<SkillRecord>(response);+ await skillsMutated();+ return created;+}++export async function getSkillManifest(name: string): Promise<SkillManifest> {+ const response = await authFetch(`/api/skills/${encodeURIComponent(name)}`);+ return parseResponse<SkillManifest>(response);+}++export async function updateSkill(+ name: string,+ draft: Omit<SkillDraft, "name">,+): Promise<SkillRecord> {+ const response = await authFetch(`/api/skills/${encodeURIComponent(name)}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(draft),+ });+ const updated = await parseResponse<SkillRecord>(response);+ await skillsMutated();+ return updated;+}++export async function deleteSkill(name: string): Promise<void> {+ const response = await authFetch(`/api/skills/${encodeURIComponent(name)}`, {+ method: "DELETE",+ });+ await parseResponse<unknown>(response);+ await skillsMutated();+}+// Spec skill names only, ending at a word boundary: `@example.com`, `@3pm`, `@Probe` are not mentions.export const SKILL_MENTION_PATTERN =/(^|\s)@([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)(?=$|\s|[.,;:!?)\]'"]+(?:$|\s))/g;diff --git a/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsxindex f62c05b8e8e..bec4f2b5e59 100644--- a/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx+++ b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx@@ -1,6 +1,16 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import {@@ -10,20 +20,67 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";import { Spinner } from "@/components/ui/spinner";import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";import { useT } from "@/i18n";import { toast } from "@/lib/toast";-import { Scroll01Icon } from "@hugeicons/core-free-icons";+import { cn } from "@/lib/utils";+import {+ ArrowLeft01Icon,+ ArrowRight01Icon,+ PlusSignIcon,+ RefreshIcon,+ Scroll01Icon,+ Search01Icon,+} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { RefreshCwIcon } from "lucide-react";-import { type ReactElement, useEffect, useState } from "react";import {+ type KeyboardEvent,+ type ReactElement,+ type ReactNode,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ createSkill,+ deleteSkill,+ getSkillManifest,+ isValidSkillName,listSkills,setSkillEnabled,+ type SkillDraft,+ type SkillManifest,+ type SkillRecord,+ updateSkill,useSkillsCatalog,} from "../api/skills-api";+type EditDraft = { description: string; instructions: string };+type View = { kind: "library" } | { kind: "new" } | { kind: "skill"; key: string };++const EMPTY_DRAFT: SkillDraft = { name: "", description: "", instructions: "" };+const LIBRARY: View = { kind: "library" };+const SECTIONS: ReadonlyArray<SkillRecord["source"]> = ["agents", "claude", "bundled"];++// A shadowed row shares its name with the one that wins, so skills are keyed by source too.+const keyOf = (skill: SkillRecord) => `${skill.source}:${skill.name}`;++function describe(cause: unknown): string | undefined {+ return cause instanceof Error ? cause.message : undefined;+}++function isChord(event: KeyboardEvent): boolean {+ return event.key === "Enter" && (event.metaKey || event.ctrlKey);+}++function isEditable(skill: SkillRecord): boolean {+ return skill.valid && skill.source === "agents" && !skill.linked;+}+export function ChatSkillsDialog({open,onOpenChange,@@ -33,131 +90,837 @@ export function ChatSkillsDialog({}): ReactElement {const t = useT();const { skills, loading, error } = useSkillsCatalog();+ const [searchQuery, setSearchQuery] = useState("");+ const [view, setView] = useState<View>(LIBRARY);+ const [newDraft, setNewDraft] = useState<SkillDraft>(EMPTY_DRAFT);+ const [draft, setDraft] = useState<EditDraft | null>(null);+ const [manifests, setManifests] = useState<ReadonlyMap<string, SkillManifest>>(+ () => new Map(),+ );+ const inflight = useRef(new Set<string>());+ // Bumped when the catalog changes, so a read started before that change cannot land after it.+ const manifestGeneration = useRef(0);+ const [pending, setPending] = useState<string | null>(null);+ const [creating, setCreating] = useState(false);const [changing, setChanging] = useState<string | null>(null);- const sourceLabel = (source: "agents" | "claude" | "bundled") =>+ const [confirmingDelete, setConfirmingDelete] = useState<SkillRecord | null>(null);+ const [confirmingDiscard, setConfirmingDiscard] = useState<(() => void) | null>(null);+ // Reseeded on render so the first frame after opening is already reset.+ const [seenOpen, setSeenOpen] = useState(open);+ if (open !== seenOpen) {+ setSeenOpen(open);+ if (open) {+ setSearchQuery("");+ setView(LIBRARY);+ setNewDraft(EMPTY_DRAFT);+ setDraft(null);+ setManifests(new Map());+ setConfirmingDelete(null);+ setConfirmingDiscard(null);+ }+ }+ useEffect(() => {+ if (open) void listSkills(true).catch(() => undefined);+ }, [open]);++ const sourceLabel = (source: SkillRecord["source"]) =>source === "agents"? t("skills.sourceAgents"): source === "claude"? t("skills.sourceClaude"): t("skills.sourceBundled");- // Skills are added by writing files, so each open re-reads the folders.++ const query = searchQuery.trim().toLowerCase();+ const narrowed = query !== "";+ const filtered = useMemo(+ () =>+ skills.filter(+ (skill) =>+ !query ||+ skill.name.toLowerCase().includes(query) ||+ skill.description.toLowerCase().includes(query),+ ),+ [skills, query],+ );+ const sections = SECTIONS.map((source) => ({+ source,+ skills: filtered.filter((skill) => skill.source === source),+ })).filter((section) => section.skills.length > 0 || (section.source === "agents" && !narrowed));++ const selected =+ view.kind === "skill" ? (skills.find((skill) => keyOf(skill) === view.key) ?? null) : null;+ if (open && view.kind === "skill" && !loading && selected === null) {+ setView(LIBRARY);+ setDraft(null);+ }+ const readable = selected !== null && selected.valid && !selected.shadowed;++ const readManifest = (skill: SkillRecord, replace = false) => {+ const name = skill.name;+ if (!skill.valid || skill.shadowed || (!replace && inflight.current.has(name))) return;+ inflight.current.add(name);+ const generation = manifestGeneration.current;+ getSkillManifest(name)+ .then((manifest) => {+ if (generation !== manifestGeneration.current) return;+ setManifests((prev) =>+ replace || !prev.has(name) ? new Map(prev).set(name, manifest) : prev,+ );+ })+ .catch((cause: unknown) => {+ if (generation !== manifestGeneration.current) return;+ toast.error(t("skills.openError"), { description: describe(cause) });+ setView((current) =>+ current.kind === "skill" && current.key === keyOf(skill) ? LIBRARY : current,+ );+ })+ .finally(() => {+ inflight.current.delete(name);+ });+ };++ // Keyed by name, so only the readable (winning) row may use it; a shadowed copy shares the name.+ const manifest = readable ? (manifests.get(selected.name) ?? null) : null;++ // A catalog refresh may mean a changed file: re-read the open one, keep any draft.+ const [seenSkills, setSeenSkills] = useState(skills);+ if (skills !== seenSkills) {+ setSeenSkills(skills);+ setManifests((prev) => {+ const kept = selected ? prev.get(selected.name) : undefined;+ return kept && selected ? new Map([[selected.name, kept]]) : new Map();+ });+ }useEffect(() => {- if (open) void listSkills(true).catch(() => undefined);- }, [open]);+ manifestGeneration.current += 1;+ if (selected) readManifest(selected, true);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the catalog alone+ }, [skills]);+ const editable = selected !== null && isEditable(selected);+ const newStarted =+ newDraft.name !== "" || newDraft.description !== "" || newDraft.instructions !== "";+ const dirty = view.kind === "new" ? newStarted : draft !== null;+ const busy = pending !== null || creating;++ const trimmedName = newDraft.name.trim();+ const nameInvalid = trimmedName.length > 0 && !isValidSkillName(trimmedName);+ const canCreate =+ trimmedName.length > 0 &&+ !nameInvalid &&+ newDraft.description.trim().length > 0 &&+ newDraft.instructions.trim().length > 0;+ const canSave =+ editable &&+ draft !== null &&+ draft.description.trim().length > 0 &&+ draft.instructions.trim().length > 0;++ const leaveTo = (next: () => void) => {+ if (dirty) setConfirmingDiscard(() => next);+ else next();+ };+ const goLibrary = () =>+ leaveTo(() => {+ setView(LIBRARY);+ setDraft(null);+ setNewDraft(EMPTY_DRAFT);+ });+ const openSkill = (skill: SkillRecord) =>+ leaveTo(() => {+ setDraft(null);+ setNewDraft(EMPTY_DRAFT);+ setView({ kind: "skill", key: keyOf(skill) });+ if (!manifests.has(skill.name)) readManifest(skill);+ });+ const openNew = () =>+ leaveTo(() => {+ setDraft(null);+ setView({ kind: "new" });+ });++ function handleOpenChange(next: boolean) {+ if (!next && busy) return;+ if (!next && dirty) {+ setConfirmingDiscard(() => () => onOpenChange(false));+ return;+ }+ onOpenChange(next);+ }++ const refresh = () => {+ setManifests(new Map());+ void listSkills(true).catch(() => undefined);+ if (selected) readManifest(selected);+ };const toggle = async (name: string, enabled: boolean) => {setChanging(name);try {await setSkillEnabled(name, enabled);} catch (cause) {- toast.error(t("skills.updateError"), {- description: cause instanceof Error ? cause.message : undefined,- });+ toast.error(t("skills.updateError"), { description: describe(cause) });} finally {setChanging(null);}};+ const editDraft = (patch: Partial<EditDraft>) => {+ if (!manifest) return;+ setDraft((prev) => {+ const current = prev ?? {+ description: manifest.description,+ instructions: manifest.instructions,+ };+ const next = { ...current, ...patch };+ return next.description === manifest.description &&+ next.instructions === manifest.instructions+ ? null+ : next;+ });+ };++ async function save() {+ if (!selected || !manifest || !draft || !canSave || pending !== null) return;+ const name = selected.name;+ const description = draft.description.trim();+ const instructions = draft.instructions.trim();+ setPending(name);+ try {+ await updateSkill(name, { description, instructions });+ setManifests((prev) =>+ new Map(prev).set(name, { ...manifest, description, instructions }),+ );+ setDraft(null);+ toast.success(t("skills.saved", { name }));+ } catch (cause) {+ toast.error(t("skills.saveError"), { description: describe(cause) });+ } finally {+ setPending(null);+ }+ }++ async function create() {+ if (creating || !canCreate) return;+ setCreating(true);+ try {+ const created = await createSkill({+ name: trimmedName,+ description: newDraft.description.trim(),+ instructions: newDraft.instructions.trim(),+ });+ toast.success(t("skills.created", { name: created.name }), {+ description: created.path ?? undefined,+ });+ setNewDraft(EMPTY_DRAFT);+ setView({ kind: "skill", key: keyOf(created) });+ readManifest(created);+ } catch (cause) {+ toast.error(t("skills.saveError"), { description: describe(cause) });+ } finally {+ setCreating(false);+ }+ }++ async function remove(skill: SkillRecord) {+ if (pending !== null) return;+ setPending(skill.name);+ try {+ await deleteSkill(skill.name);+ setManifests((prev) => {+ const map = new Map(prev);+ map.delete(skill.name);+ return map;+ });+ setDraft(null);+ setView(LIBRARY);+ toast.success(t("skills.deleted", { name: skill.name }));+ } catch (cause) {+ toast.error(t("skills.deleteError"), { description: describe(cause) });+ } finally {+ setPending(null);+ }+ }++ const sourceBadge = (source: SkillRecord["source"]) => (+ <Badge variant={source === "agents" ? "secondary" : "outline"}>{sourceLabel(source)}</Badge>+ );+return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="rounded-xl shadow-border ring-0 [--radius:1.1rem] max-sm:flex max-sm:flex-col max-sm:overflow-hidden sm:max-w-xl">- <DialogHeader>- <div className="flex items-center gap-2">- <HugeiconsIcon- icon={Scroll01Icon}- strokeWidth={1.75}- className="size-5 text-primary"- />- <DialogTitle>{t("skills.title")}</DialogTitle>- </div>- <DialogDescription>{t("skills.description")}</DialogDescription>- </DialogHeader>-- <div className="flex items-center justify-between gap-3">- <p className="text-xs text-muted-foreground">- {t("skills.precedence")}- </p>- <Button- type="button"- size="sm"- variant="outline"- disabled={loading}- onClick={() => void listSkills(true).catch(() => undefined)}- >- {loading ? <Spinner /> : <RefreshCwIcon />}- {t("skills.refresh")}- </Button>- </div>+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="rounded-xl shadow-border ring-0 [--radius:1.1rem] max-sm:flex max-sm:flex-col max-sm:overflow-hidden sm:max-w-2xl">+ {view.kind === "library" ? (+ <>+ <DialogHeader>+ <div className="flex items-center gap-2">+ <HugeiconsIcon icon={Scroll01Icon} strokeWidth={1.75} className="size-5 text-primary" />+ <DialogTitle>{t("skills.title")}</DialogTitle>+ </div>+ <DialogDescription>{t("skills.description")}</DialogDescription>+ </DialogHeader>- <div className="hover-scrollbar min-h-0 max-h-[min(58dvh,520px)] space-y-2 overflow-y-auto pr-1 max-sm:flex-1 max-sm:max-h-none">- {error ? (- <div className="rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">- {error}+ <div className="flex items-center gap-2">+ <div className="relative min-w-0 flex-1">+ <HugeiconsIcon+ icon={Search01Icon}+ strokeWidth={2}+ className="pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2 text-muted-foreground/60"+ />+ <Input+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Escape" && searchQuery) {+ event.stopPropagation();+ setSearchQuery("");+ }+ }}+ placeholder={t("skills.search")}+ aria-label={t("skills.search")}+ className="h-8 pl-8 text-sm"+ />+ </div>+ <Button+ type="button"+ size="icon-sm"+ variant="outline"+ disabled={loading}+ onClick={refresh}+ aria-label={t("skills.refresh")}+ title={t("skills.refresh")}+ >+ {loading ? <Spinner /> : <HugeiconsIcon icon={RefreshIcon} strokeWidth={2} />}+ </Button>+ <Button type="button" size="sm" onClick={openNew}>+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={2} />+ {t("skills.newSkill")}+ </Button></div>- ) : null}- {!loading && !error && skills.length === 0 ? (- <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">- {t("skills.empty")}++ <div className="hover-scrollbar min-h-0 max-h-[min(58dvh,520px)] space-y-5 overflow-y-auto pr-1 max-sm:flex-1 max-sm:max-h-none">+ {error ? (+ <div className="rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">+ {error}+ </div>+ ) : null}+ {sections.some((section) => section.skills.length > 0) ? (+ sections+ .filter((section) => section.skills.length > 0)+ .map((section) => (+ <section key={section.source} className="space-y-2">+ <div className="flex items-baseline justify-between gap-3 px-1">+ <h3 className="text-xs font-medium text-muted-foreground">+ {t(`skills.section${sectionSuffix(section.source)}`)}+ </h3>+ <p className="truncate text-ui-11 text-muted-foreground/70">+ {t(`skills.section${sectionSuffix(section.source)}Hint`)}+ </p>+ </div>+ {section.skills.map((skill) => (+ <SkillRow+ key={keyOf(skill)}+ skill={skill}+ changing={changing === skill.name}+ onOpen={() => openSkill(skill)}+ onToggle={(enabled) => void toggle(skill.name, enabled)}+ />+ ))}+ </section>+ ))+ ) : loading ? (+ <div className="flex justify-center p-6">+ <Spinner />+ </div>+ ) : narrowed ? (+ <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">+ {t("skills.noMatch", { query: searchQuery.trim() })}{" "}+ <button+ type="button"+ onClick={() => setSearchQuery("")}+ className="text-primary hover:underline"+ >+ {t("skills.clearSearch")}+ </button>+ </div>+ ) : (+ <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">+ {t("skills.empty")}+ </div>+ )}</div>- ) : null}- {skills.map((skill) => {- const selectable = skill.valid && !skill.shadowed;- return (- <div- key={`${skill.source}:${skill.name}`}- className="rounded-xl border border-border/60 bg-muted/20 p-4 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))]"- >- <div className="flex items-start gap-3">- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">- <span className="truncate font-medium">{skill.name}</span>- <Badge variant="outline">{sourceLabel(skill.source)}</Badge>- {skill.shadowed ? (- <Badge variant="secondary">{t("skills.shadowed")}</Badge>- ) : null}- {skill.valid ? null : (- <Badge variant="destructive">{t("skills.invalid")}</Badge>- )}- </div>- {skill.description ? (- <p className="mt-1 text-sm text-muted-foreground">- {skill.description}- </p>- ) : null}- {skill.compatibility ? (- <p className="mt-2 text-xs text-muted-foreground">- {t("skills.compatibility", { value: skill.compatibility })}- </p>- ) : null}- {skill.shadowed_by ? (- <p className="mt-2 text-xs text-muted-foreground">- {t("skills.shadowedBy", {- source: sourceLabel(skill.shadowed_by),- })}- </p>- ) : null}- {skill.error ? (- <p className="mt-2 text-xs text-destructive">- {skill.error}- </p>- ) : null}+ </>+ ) : (+ <>+ <DialogHeader className="pr-8">+ <div className="flex min-w-0 items-center gap-2">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ disabled={busy}+ onClick={goLibrary}+ aria-label={t("skills.title")}+ className="-ml-2 shrink-0"+ >+ <HugeiconsIcon icon={ArrowLeft01Icon} strokeWidth={2} />+ </Button>+ <DialogTitle className="truncate">+ {view.kind === "new" ? t("skills.newSkill") : (selected?.name ?? "")}+ </DialogTitle>+ {selected ? sourceBadge(selected.source) : null}+ {dirty && view.kind === "skill" ? (+ <span className="shrink-0 text-xs text-muted-foreground">{t("skills.unsaved")}</span>+ ) : null}+ </div>+ <DialogDescription className="truncate">+ {view.kind === "new"+ ? t("skills.createDescription")+ : (manifest?.path ?? selected?.path ?? sourceLabel(selected?.source ?? "agents"))}+ </DialogDescription>+ </DialogHeader>++ <div className="hover-scrollbar min-h-0 max-h-[min(62dvh,640px)] overflow-y-auto pr-1 max-sm:flex-1 max-sm:max-h-none">+ {view.kind === "new" ? (+ <Editor+ formId="skill-new-form"+ nameField={+ <Field+ htmlFor="skill-name"+ label={t("skills.nameLabel")}+ hint={nameInvalid ? t("skills.nameInvalid") : t("skills.nameHint")}+ invalid={nameInvalid}+ >+ <Input+ id="skill-name"+ value={newDraft.name}+ autoFocus={true}+ autoComplete="off"+ spellCheck={false}+ maxLength={64}+ disabled={creating}+ aria-label={t("skills.nameLabel")}+ aria-invalid={nameInvalid || undefined}+ placeholder={t("skills.namePlaceholder")}+ onChange={(event) =>+ setNewDraft((prev) => ({ ...prev, name: event.target.value }))+ }+ className="font-mono text-sm"+ />+ </Field>+ }+ description={newDraft.description}+ instructions={newDraft.instructions}+ readOnly={false}+ disabled={creating}+ onDescription={(value) => setNewDraft((prev) => ({ ...prev, description: value }))}+ onInstructions={(value) =>+ setNewDraft((prev) => ({ ...prev, instructions: value }))+ }+ onSubmit={() => void create()}+ />+ ) : selected ? (+ readable && !manifest ? (+ <div className="flex justify-center p-10">+ <Spinner /></div>+ ) : (+ <Editor+ formId="skill-edit-form"+ description={draft?.description ?? manifest?.description ?? selected.description}+ instructions={draft?.instructions ?? manifest?.instructions ?? ""}+ readOnly={!editable}+ disabled={pending === selected.name}+ notice={+ !selected.valid+ ? { tone: "error", text: selected.error ?? t("skills.invalid") }+ : selected.shadowed+ ? {+ tone: "muted",+ text: t("skills.shadowedBy", {+ source: selected.shadowed_by+ ? sourceLabel(selected.shadowed_by)+ : "",+ }),+ }+ : editable+ ? null+ : {+ tone: "muted",+ text: selected.linked+ ? t("skills.readOnlyLinked")+ : selected.source === "claude"+ ? t("skills.readOnlyClaude")+ : t("skills.readOnlyBundled"),+ }+ }+ onDescription={(value) => editDraft({ description: value })}+ onInstructions={(value) => editDraft({ instructions: value })}+ details={detailsOf(selected, t)}+ onSubmit={() => void save()}+ />+ )+ ) : null}+ </div>++ <div className="flex flex-wrap items-center gap-2">+ {selected ? (+ <label className="flex items-center gap-2 text-sm text-muted-foreground"><Switch- aria-label={t(skill.enabled ? "skills.disable" : "skills.enable", {- name: skill.name,+ checked={selected.valid && !selected.shadowed && selected.enabled}+ disabled={!selected.valid || selected.shadowed || changing === selected.name}+ aria-label={t(selected.enabled ? "skills.disable" : "skills.enable", {+ name: selected.name,})}- checked={selectable && skill.enabled}- disabled={!selectable || changing === skill.name}- onCheckedChange={(checked) =>- void toggle(skill.name, checked)- }+ onCheckedChange={(checked) => void toggle(selected.name, checked)}/>- </div>+ {t("skills.enabledLabel")}+ </label>+ ) : null}+ <div className="ml-auto flex items-center gap-2">+ {view.kind === "new" ? (+ <>+ <Button type="button" variant="ghost" disabled={creating} onClick={goLibrary}>+ {t("common.cancel")}+ </Button>+ <Button type="submit" form="skill-new-form" disabled={creating || !canCreate}>+ {creating ? <Spinner /> : null}+ {t("skills.create")}+ </Button>+ </>+ ) : editable && selected ? (+ <>+ <Button+ type="button"+ variant="ghost"+ disabled={pending !== null}+ onClick={() => setConfirmingDelete(selected)}+ aria-label={t("skills.delete", { name: selected.name })}+ className="text-destructive hover:text-destructive"+ >+ {t("common.delete")}+ </Button>+ <Button+ type="button"+ variant="outline"+ disabled={!dirty || pending !== null}+ onClick={() => setDraft(null)}+ >+ {t("skills.revert")}+ </Button>+ <Button type="submit" form="skill-edit-form" disabled={pending !== null || !canSave}>+ {pending !== null ? <Spinner /> : null}+ {t("skills.save")}+ </Button>+ </>+ ) : null}</div>- );- })}- </div>+ </div>+ </>+ )}</DialogContent>++ <AlertDialog+ open={open && confirmingDelete !== null}+ onOpenChange={(next) => {+ if (!next) setConfirmingDelete(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("skills.deleteTitle")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("skills.deleteDescription", { name: confirmingDelete?.name ?? "" })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ const skill = confirmingDelete;+ setConfirmingDelete(null);+ if (skill) void remove(skill);+ }}+ >+ {t("common.delete")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <AlertDialog+ open={open && confirmingDiscard !== null}+ onOpenChange={(next) => {+ if (!next) setConfirmingDiscard(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("skills.discardTitle")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("skills.discardDescription", {+ name: view.kind === "skill" ? (selected?.name ?? "") : t("skills.newSkill"),+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ const next = confirmingDiscard;+ setConfirmingDiscard(null);+ setDraft(null);+ setNewDraft(EMPTY_DRAFT);+ next?.();+ }}+ >+ {t("skills.discard")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></Dialog>);}++function sectionSuffix(source: SkillRecord["source"]): "Agents" | "Claude" | "Bundled" {+ return source === "agents" ? "Agents" : source === "claude" ? "Claude" : "Bundled";+}++function detailsOf(+ skill: SkillRecord,+ t: ReturnType<typeof useT>,+): Array<[string, string]> {+ return [+ ...(skill.license ? [[t("skills.licenseLabel"), skill.license] as [string, string]] : []),+ ...(skill.compatibility+ ? [[t("skills.compatibilityLabel"), skill.compatibility] as [string, string]]+ : []),+ ...(skill.allowed_tools+ ? [[t("skills.allowedToolsLabel"), skill.allowed_tools] as [string, string]]+ : []),+ ...Object.entries(skill.metadata ?? {}).map(([key, value]) => [key, value] as [string, string]),+ ];+}++function SkillRow({+ skill,+ changing,+ onOpen,+ onToggle,+}: {+ skill: SkillRecord;+ changing: boolean;+ onOpen: () => void;+ onToggle: (enabled: boolean) => void;+}): ReactElement {+ const t = useT();+ const usable = skill.valid && !skill.shadowed;+ return (+ <div+ role="button"+ tabIndex={0}+ aria-label={skill.name}+ onClick={onOpen}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onOpen();+ }+ }}+ className={cn(+ "group flex cursor-pointer items-center gap-3 rounded-xl border border-border/60 bg-muted/20 px-4 py-3 transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))]",+ skill.shadowed && "opacity-60",+ )}+ >+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="truncate font-medium">{skill.name}</span>+ {skill.shadowed ? <Badge variant="secondary">{t("skills.shadowed")}</Badge> : null}+ {skill.linked ? <Badge variant="outline">{t("skills.linked")}</Badge> : null}+ {skill.valid ? null : <Badge variant="destructive">{t("skills.invalid")}</Badge>}+ </div>+ <p+ className={cn(+ "mt-0.5 line-clamp-2 text-sm",+ skill.valid ? "text-muted-foreground" : "text-destructive",+ )}+ >+ {skill.valid ? skill.description : skill.error}+ </p>+ </div>+ <span+ className="shrink-0"+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ >+ <Switch+ checked={usable && skill.enabled}+ disabled={!usable || changing}+ aria-label={t(skill.enabled ? "skills.disable" : "skills.enable", { name: skill.name })}+ onCheckedChange={onToggle}+ />+ </span>+ <HugeiconsIcon+ icon={ArrowRight01Icon}+ strokeWidth={2}+ className="size-4 shrink-0 text-muted-foreground/50 transition-colors group-hover:text-foreground"+ />+ </div>+ );+}++function Field({+ htmlFor,+ label,+ hint,+ trailing,+ invalid,+ className,+ children,+}: {+ htmlFor: string;+ label: string;+ hint?: string;+ trailing?: ReactNode;+ invalid?: boolean;+ className?: string;+ children: ReactNode;+}): ReactElement {+ return (+ <div className={cn("flex flex-col gap-1.5", className)}>+ <div className="flex items-baseline justify-between gap-2">+ <label htmlFor={htmlFor} className="text-sm font-medium">+ {label}+ </label>+ {trailing}+ </div>+ {children}+ {hint ? (+ <p className={cn("text-xs", invalid ? "text-destructive" : "text-muted-foreground")}>+ {hint}+ </p>+ ) : null}+ </div>+ );+}++function Editor({+ formId,+ nameField,+ description,+ instructions,+ readOnly,+ disabled,+ notice,+ details,+ onDescription,+ onInstructions,+ onSubmit,+}: {+ formId: string;+ nameField?: ReactNode;+ description: string;+ instructions: string;+ readOnly: boolean;+ disabled: boolean;+ notice?: { tone: "muted" | "error"; text: string } | null;+ details?: Array<[string, string]>;+ onDescription: (value: string) => void;+ onInstructions: (value: string) => void;+ onSubmit: () => void;+}): ReactElement {+ const t = useT();+ return (+ <form+ id={formId}+ className="flex flex-col gap-4 py-1"+ onSubmit={(event) => {+ event.preventDefault();+ if (!readOnly) onSubmit();+ }}+ onKeyDown={(event) => {+ if (isChord(event) && !readOnly) {+ event.preventDefault();+ onSubmit();+ }+ }}+ >+ {notice ? (+ <p+ className={cn(+ "rounded-xl px-4 py-3 text-xs leading-relaxed",+ notice.tone === "error"+ ? "border border-destructive/30 bg-destructive/5 text-destructive"+ : "bg-muted/50 text-muted-foreground",+ )}+ >+ {notice.text}+ </p>+ ) : null}+ {details && details.length > 0 ? (+ <dl className="flex flex-wrap gap-x-6 gap-y-1 text-xs">+ {details.map(([label, value]) => (+ <div key={label} className="flex min-w-0 gap-2">+ <dt className="shrink-0 text-muted-foreground">{label}</dt>+ <dd className="truncate">{value}</dd>+ </div>+ ))}+ </dl>+ ) : null}+ {nameField}+ <Field+ htmlFor={`${formId}-description`}+ label={t("skills.descriptionLabel")}+ hint={t("skills.descriptionHint")}+ trailing={+ <span className="text-ui-11 tabular-nums text-muted-foreground/60">+ {description.length}/1024+ </span>+ }+ >+ <Textarea+ id={`${formId}-description`}+ value={description}+ rows={2}+ maxLength={1024}+ readOnly={readOnly}+ disabled={disabled}+ aria-label={t("skills.descriptionLabel")}+ placeholder={t("skills.descriptionPlaceholder")}+ onChange={(event) => onDescription(event.target.value)}+ className={cn(+ "max-h-[min(12rem,30vh)] min-h-[calc(4.5rem*var(--ui-space-scale,1))] overflow-y-auto leading-relaxed",+ readOnly && "text-muted-foreground",+ )}+ />+ </Field>+ <Field+ htmlFor={`${formId}-instructions`}+ label={t("skills.instructionsLabel")}+ hint={t("skills.instructionsHint")}+ trailing={+ <span className="text-ui-11 tabular-nums text-muted-foreground/60">+ {t("skills.characters", { count: instructions.length.toLocaleString() })}+ </span>+ }+ >+ <Textarea+ id={`${formId}-instructions`}+ value={instructions}+ fieldSizing="fixed"+ readOnly={readOnly}+ disabled={disabled}+ spellCheck={false}+ aria-label={t("skills.instructionsLabel")}+ placeholder={t("skills.instructionsPlaceholder")}+ onChange={(event) => onInstructions(event.target.value)}+ className={cn(+ "h-[min(15rem,32dvh)] min-h-28 resize-y font-mono text-ui-13 leading-relaxed",+ readOnly && "text-muted-foreground",+ )}+ />+ </Field>+ </form>+ );+}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 7420d3edb8a..0487311f1c6 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -3007,6 +3007,52 @@ export const ar = {enable: "تفعيل {name}",disable: "تعطيل {name}",updateError: "تعذّر تحديث المهارة",+ newSkill: "مهارة جديدة",+ delete: "حذف {name}",+ createDescription: "تُحفظ كملف SKILL.md في مجلد جديد ضمن ~/.agents/skills وتُفعَّل فور إنشائها.",+ nameLabel: "الاسم",+ namePlaceholder: "مثل code-arithmetic",+ nameHint: "أحرف لاتينية صغيرة وأرقام وشرطات مفردة. وهو أيضًا اسم المجلد.",+ nameInvalid: "استخدم من 1 إلى 64 حرفًا لاتينيًا صغيرًا أو رقمًا أو شرطة مفردة، دون أن يبدأ الاسم بشرطة أو ينتهي بها.",+ descriptionLabel: "الوصف",+ descriptionPlaceholder: "تُستخدم عندما يطلب المستخدم عملية حسابية. احسبها دائمًا بأداة الكود.",+ descriptionHint: "السطر الذي يراه النموذج في فهرس المهارات. ومنه يقرر متى يقرأ المهارة.",+ instructionsLabel: "التعليمات",+ instructionsPlaceholder: "ما يجب فعله عندما تنطبق هذه المهارة، بصيغة Markdown.",+ instructionsHint: "متن SKILL.md، ويقرؤه النموذج كاملًا بعد اختيار المهارة.",+ create: "إنشاء المهارة",+ save: "حفظ التغييرات",+ created: "تم إنشاء {name}",+ saved: "تم حفظ {name}",+ deleted: "تم حذف {name}",+ saveError: "تعذّر حفظ المهارة",+ openError: "تعذّر فتح المهارة",+ deleteError: "تعذّر حذف المهارة",+ deleteTitle: "حذف المهارة",+ deleteDescription: 'هل تريد حذف "{name}" وكل ما في مجلدها ضمن ~/.agents/skills؟ لا يمكن التراجع عن هذا الإجراء.',+ search: "ابحث عن المهارات بالاسم أو الوصف…",+ noMatch: 'لا توجد مهارات تطابق "{query}"',+ clearSearch: "مسح البحث",+ readOnlyClaude: "للقراءة فقط: موجودة في ~/.claude/skills. عدّل الملف هناك.",+ readOnlyBundled: "للقراءة فقط: مضمّنة مع Unsloth.",+ readOnlyLinked: "للقراءة فقط: هذا الإدخال رابط. عدّل الملفات في مكانها الأصلي.",+ characters: "{count} حرفًا",+ unsaved: "تغييرات غير محفوظة",+ revert: "تراجع",+ enabledLabel: "مفعّلة",+ licenseLabel: "الترخيص",+ compatibilityLabel: "التوافق",+ allowedToolsLabel: "الأدوات المسموح بها",+ sectionAgents: "مهاراتك",+ sectionAgentsHint: "محفوظة في ~/.agents/skills. أنشئها وعدّلها واحذفها من هنا.",+ sectionClaude: "مهارات Claude",+ sectionClaudeHint: "موجودة في ~/.claude/skills. للقراءة فقط هنا؛ عدّل الملفات هناك.",+ sectionBundled: "مضمّنة",+ sectionBundledHint: "تأتي مع Unsloth. للقراءة فقط.",+ linked: "رابط",+ discardTitle: "هل تريد تجاهل التغييرات؟",+ discardDescription: "ستُفقد التعديلات غير المحفوظة على {name}.",+ discard: "تجاهل",mentions: "المهارات",},library: {diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex c0ea1b73967..c5f391d0c35 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -3076,6 +3076,52 @@ export const de = {enable: "{name} aktivieren",disable: "{name} deaktivieren",updateError: "Fähigkeit konnte nicht aktualisiert werden",+ newSkill: "Neue Fähigkeit",+ delete: "{name} löschen",+ createDescription: "Wird als SKILL.md in einem neuen Ordner unter ~/.agents/skills gespeichert und sofort aktiviert.",+ nameLabel: "Name",+ namePlaceholder: "z. B. code-arithmetic",+ nameHint: "Kleinbuchstaben, Ziffern und einzelne Bindestriche. Zugleich der Ordnername.",+ nameInvalid: "1-64 Kleinbuchstaben, Ziffern oder einzelne Bindestriche, nicht mit einem Bindestrich beginnend oder endend.",+ descriptionLabel: "Beschreibung",+ descriptionPlaceholder: "Verwenden, wenn der Nutzer Rechenaufgaben stellt. Immer mit dem Code-Tool berechnen.",+ descriptionHint: "Die Zeile, die das Modell in seinem Fähigkeitenkatalog sieht. Daran entscheidet es, wann es die Fähigkeit liest.",+ instructionsLabel: "Anweisungen",+ instructionsPlaceholder: "Was zu tun ist, wenn diese Fähigkeit greift, in Markdown.",+ instructionsHint: "Der Inhalt von SKILL.md, den das Modell vollständig liest, sobald es die Fähigkeit auswählt.",+ create: "Fähigkeit erstellen",+ save: "Änderungen speichern",+ created: "{name} erstellt",+ saved: "{name} gespeichert",+ deleted: "{name} gelöscht",+ saveError: "Fähigkeit konnte nicht gespeichert werden",+ openError: "Fähigkeit konnte nicht geöffnet werden",+ deleteError: "Fähigkeit konnte nicht gelöscht werden",+ deleteTitle: "Fähigkeit löschen",+ deleteDescription: "„{name}“ samt allem in seinem Ordner unter ~/.agents/skills löschen? Das lässt sich nicht rückgängig machen.",+ search: "Fähigkeiten nach Name oder Beschreibung suchen…",+ noMatch: "Keine Fähigkeiten passen zu „{query}“",+ clearSearch: "Suche leeren",+ readOnlyClaude: "Schreibgeschützt: liegt in ~/.claude/skills. Bearbeite die Datei dort.",+ readOnlyBundled: "Schreibgeschützt: mit Unsloth mitgeliefert.",+ readOnlyLinked: "Schreibgeschützt: dieser Eintrag ist eine Verknüpfung. Bearbeite die Dateien an ihrem Speicherort.",+ characters: "{count} Zeichen",+ unsaved: "ungespeicherte Änderungen",+ revert: "Verwerfen",+ enabledLabel: "Aktiviert",+ licenseLabel: "Lizenz",+ compatibilityLabel: "Kompatibilität",+ allowedToolsLabel: "Erlaubte Tools",+ sectionAgents: "Deine Fähigkeiten",+ sectionAgentsHint: "Gespeichert in ~/.agents/skills. Hier anlegen, bearbeiten und löschen.",+ sectionClaude: "Claude-Fähigkeiten",+ sectionClaudeHint: "Gefunden in ~/.claude/skills. Hier schreibgeschützt; die Dateien dort bearbeiten.",+ sectionBundled: "Mitgeliefert",+ sectionBundledHint: "Mit Unsloth ausgeliefert. Schreibgeschützt.",+ linked: "Verknüpfung",+ discardTitle: "Änderungen verwerfen?",+ discardDescription: "Nicht gespeicherte Änderungen an {name} gehen verloren.",+ discard: "Verwerfen",mentions: "Fähigkeiten",},library: {diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 6e4fd993d55..5a968343885 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2992,6 +2992,52 @@ export const en = {enable: "Enable {name}",disable: "Disable {name}",updateError: "Could not update skill",+ newSkill: "New skill",+ delete: "Delete {name}",+ createDescription: "Saved as SKILL.md in a new folder under ~/.agents/skills, and enabled as soon as it exists.",+ nameLabel: "Name",+ namePlaceholder: "e.g. code-arithmetic",+ nameHint: "Lowercase letters, numbers and single hyphens. This is also the folder name.",+ nameInvalid: "Use 1-64 lowercase letters, numbers or single hyphens, not starting or ending with a hyphen.",+ descriptionLabel: "Description",+ descriptionPlaceholder: "Use when the user asks for arithmetic. Always compute it with the code tool.",+ descriptionHint: "The line the model sees in its skill catalog. It decides from this when to read the skill.",+ instructionsLabel: "Instructions",+ instructionsPlaceholder: "What to do when this skill applies, in Markdown.",+ instructionsHint: "The body of SKILL.md, read in full once the model picks the skill.",+ create: "Create skill",+ save: "Save changes",+ created: "Created {name}",+ saved: "Saved {name}",+ deleted: "Deleted {name}",+ saveError: "Could not save skill",+ openError: "Could not open skill",+ deleteError: "Could not delete skill",+ deleteTitle: "Delete skill",+ deleteDescription: 'Delete "{name}" and everything in its folder under ~/.agents/skills? This cannot be undone.',+ search: "Search skills by name or description…",+ noMatch: "No skills match “{query}”",+ clearSearch: "Clear search",+ readOnlyClaude: "Read-only: found in ~/.claude/skills. Edit the file there.",+ readOnlyBundled: "Read-only: bundled with Unsloth.",+ readOnlyLinked: "Read-only: this entry is a link. Edit the files where they live.",+ characters: "{count} characters",+ unsaved: "unsaved changes",+ revert: "Revert",+ enabledLabel: "Enabled",+ licenseLabel: "License",+ compatibilityLabel: "Compatibility",+ allowedToolsLabel: "Allowed tools",+ sectionAgents: "Your skills",+ sectionAgentsHint: "Saved in ~/.agents/skills. Create, edit and delete them here.",+ sectionClaude: "Claude skills",+ sectionClaudeHint: "Found in ~/.claude/skills. Read-only here; edit the files there.",+ sectionBundled: "Bundled",+ sectionBundledHint: "Shipped with Unsloth. Read-only.",+ linked: "Link",+ discardTitle: "Discard changes?",+ discardDescription: "Edits to {name} that are not saved will be lost.",+ discard: "Discard",mentions: "Skills",},// The Library page, its file viewer, and the menus and toasts that act on its files.diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex f4f27bf6fc6..3b220d993ce 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -3073,6 +3073,52 @@ export const es = {enable: "Activar {name}",disable: "Desactivar {name}",updateError: "No se pudo actualizar la habilidad",+ newSkill: "Nueva habilidad",+ delete: "Eliminar {name}",+ createDescription: "Se guarda como SKILL.md en una carpeta nueva dentro de ~/.agents/skills y se activa en cuanto existe.",+ nameLabel: "Nombre",+ namePlaceholder: "p. ej. code-arithmetic",+ nameHint: "Minúsculas, números y guiones simples. También es el nombre de la carpeta.",+ nameInvalid: "Usa de 1 a 64 minúsculas, números o guiones simples, sin empezar ni terminar con guion.",+ descriptionLabel: "Descripción",+ descriptionPlaceholder: "Usar cuando el usuario pida cálculos aritméticos. Calcularlos siempre con la herramienta de código.",+ descriptionHint: "La línea que el modelo ve en su catálogo de habilidades. Con ella decide cuándo leer la habilidad.",+ instructionsLabel: "Instrucciones",+ instructionsPlaceholder: "Qué hacer cuando aplica esta habilidad, en Markdown.",+ instructionsHint: "El cuerpo de SKILL.md, que el modelo lee completo cuando elige la habilidad.",+ create: "Crear habilidad",+ save: "Guardar cambios",+ created: "{name} creada",+ saved: "{name} guardada",+ deleted: "{name} eliminada",+ saveError: "No se pudo guardar la habilidad",+ openError: "No se pudo abrir la habilidad",+ deleteError: "No se pudo eliminar la habilidad",+ deleteTitle: "Eliminar habilidad",+ deleteDescription: '¿Eliminar "{name}" y todo lo que hay en su carpeta dentro de ~/.agents/skills? Esto no se puede deshacer.',+ search: "Buscar habilidades por nombre o descripción…",+ noMatch: "Ninguna habilidad coincide con “{query}”",+ clearSearch: "Borrar búsqueda",+ readOnlyClaude: "Solo lectura: está en ~/.claude/skills. Edita el archivo allí.",+ readOnlyBundled: "Solo lectura: incluida con Unsloth.",+ readOnlyLinked: "Solo lectura: esta entrada es un enlace. Edita los archivos donde residen.",+ characters: "{count} caracteres",+ unsaved: "cambios sin guardar",+ revert: "Revertir",+ enabledLabel: "Activada",+ licenseLabel: "Licencia",+ compatibilityLabel: "Compatibilidad",+ allowedToolsLabel: "Herramientas permitidas",+ sectionAgents: "Tus habilidades",+ sectionAgentsHint: "Guardadas en ~/.agents/skills. Créalas, edítalas y elimínalas aquí.",+ sectionClaude: "Habilidades de Claude",+ sectionClaudeHint: "Encontradas en ~/.claude/skills. Solo lectura aquí; edita los archivos allí.",+ sectionBundled: "Incluidas",+ sectionBundledHint: "Vienen con Unsloth. Solo lectura.",+ linked: "Enlace",+ discardTitle: "¿Descartar los cambios?",+ discardDescription: "Los cambios en {name} que no se hayan guardado se perderán.",+ discard: "Descartar",mentions: "Habilidades",},library: {diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 0282bb81f23..a0483a70345 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -3087,6 +3087,52 @@ export const fr = {enable: "Activer {name}",disable: "Désactiver {name}",updateError: "Impossible de mettre à jour la compétence",+ newSkill: "Nouvelle compétence",+ delete: "Supprimer {name}",+ createDescription: "Enregistrée comme SKILL.md dans un nouveau dossier sous ~/.agents/skills, et activée dès sa création.",+ nameLabel: "Nom",+ namePlaceholder: "ex. code-arithmetic",+ nameHint: "Minuscules, chiffres et tirets simples. C'est aussi le nom du dossier.",+ nameInvalid: "Utilisez 1 à 64 minuscules, chiffres ou tirets simples, sans tiret au début ni à la fin.",+ descriptionLabel: "Description",+ descriptionPlaceholder: "À utiliser quand l'utilisateur demande un calcul. Toujours calculer avec l'outil de code.",+ descriptionHint: "La ligne que le modèle voit dans son catalogue de compétences. C'est sur elle qu'il décide quand lire la compétence.",+ instructionsLabel: "Instructions",+ instructionsPlaceholder: "Que faire quand cette compétence s'applique, en Markdown.",+ instructionsHint: "Le corps de SKILL.md, lu en entier une fois que le modèle choisit la compétence.",+ create: "Créer la compétence",+ save: "Enregistrer les modifications",+ created: "{name} créée",+ saved: "{name} enregistrée",+ deleted: "{name} supprimée",+ saveError: "Impossible d'enregistrer la compétence",+ openError: "Impossible d'ouvrir la compétence",+ deleteError: "Impossible de supprimer la compétence",+ deleteTitle: "Supprimer la compétence",+ deleteDescription: "Supprimer « {name} » et tout le contenu de son dossier sous ~/.agents/skills ? Cette action est irréversible.",+ search: "Rechercher des compétences par nom ou description…",+ noMatch: "Aucune compétence ne correspond à « {query} »",+ clearSearch: "Effacer la recherche",+ readOnlyClaude: "Lecture seule : située dans ~/.claude/skills. Modifiez le fichier à cet endroit.",+ readOnlyBundled: "Lecture seule : intégrée à Unsloth.",+ readOnlyLinked: "Lecture seule : cette entrée est un lien. Modifiez les fichiers à leur emplacement réel.",+ characters: "{count} caractères",+ unsaved: "modifications non enregistrées",+ revert: "Annuler les modifications",+ enabledLabel: "Activée",+ licenseLabel: "Licence",+ compatibilityLabel: "Compatibilité",+ allowedToolsLabel: "Outils autorisés",+ sectionAgents: "Vos compétences",+ sectionAgentsHint: "Enregistrées dans ~/.agents/skills. Créez, modifiez et supprimez-les ici.",+ sectionClaude: "Compétences Claude",+ sectionClaudeHint: "Trouvées dans ~/.claude/skills. Lecture seule ici ; modifiez les fichiers à cet endroit.",+ sectionBundled: "Intégrées",+ sectionBundledHint: "Livrées avec Unsloth. Lecture seule.",+ linked: "Lien",+ discardTitle: "Abandonner les modifications ?",+ discardDescription: "Les modifications non enregistrées de {name} seront perdues.",+ discard: "Abandonner",mentions: "Compétences",},library: {diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex ad60edcd3a6..06bcae0dd48 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -3014,6 +3014,52 @@ export const hi = {enable: "{name} सक्षम करें",disable: "{name} अक्षम करें",updateError: "कौशल अपडेट नहीं हो सका",+ newSkill: "नया कौशल",+ delete: "{name} हटाएँ",+ createDescription: "~/.agents/skills के नए फ़ोल्डर में SKILL.md के रूप में सहेजा जाता है और बनते ही सक्षम हो जाता है।",+ nameLabel: "नाम",+ namePlaceholder: "जैसे code-arithmetic",+ nameHint: "छोटे अंग्रेज़ी अक्षर, अंक और एकल हाइफ़न। यही फ़ोल्डर का नाम भी है।",+ nameInvalid: "1 से 64 छोटे अंग्रेज़ी अक्षर, अंक या एकल हाइफ़न उपयोग करें, जो हाइफ़न से शुरू या समाप्त न हो।",+ descriptionLabel: "विवरण",+ descriptionPlaceholder: "जब उपयोगकर्ता अंकगणित माँगे तब उपयोग करें। हमेशा कोड टूल से गणना करें।",+ descriptionHint: "वह पंक्ति जो मॉडल अपने कौशल कैटलॉग में देखता है। इसी से वह तय करता है कि कौशल कब पढ़ना है।",+ instructionsLabel: "निर्देश",+ instructionsPlaceholder: "यह कौशल लागू होने पर क्या करना है, Markdown में।",+ instructionsHint: "SKILL.md का मुख्य भाग, जिसे मॉडल कौशल चुनने पर पूरा पढ़ता है।",+ create: "कौशल बनाएँ",+ save: "बदलाव सहेजें",+ created: "{name} बनाया गया",+ saved: "{name} सहेजा गया",+ deleted: "{name} हटाया गया",+ saveError: "कौशल सहेजा नहीं जा सका",+ openError: "कौशल खोला नहीं जा सका",+ deleteError: "कौशल हटाया नहीं जा सका",+ deleteTitle: "कौशल हटाएँ",+ deleteDescription: '"{name}" और ~/.agents/skills में उसके फ़ोल्डर की सभी सामग्री हटाएँ? इसे पूर्ववत नहीं किया जा सकता।',+ search: "नाम या विवरण से कौशल खोजें…",+ noMatch: "“{query}” से मेल खाने वाला कोई कौशल नहीं",+ clearSearch: "खोज साफ़ करें",+ readOnlyClaude: "केवल पढ़ने के लिए: ~/.claude/skills में मिला। फ़ाइल वहीं संपादित करें।",+ readOnlyBundled: "केवल पढ़ने के लिए: Unsloth के साथ बंडल्ड।",+ readOnlyLinked: "केवल पढ़ने के लिए: यह प्रविष्टि एक लिंक है। फ़ाइलें उनके वास्तविक स्थान पर संपादित करें।",+ characters: "{count} अक्षर",+ unsaved: "असहेजे बदलाव",+ revert: "पूर्ववत करें",+ enabledLabel: "सक्षम",+ licenseLabel: "लाइसेंस",+ compatibilityLabel: "संगतता",+ allowedToolsLabel: "अनुमत टूल",+ sectionAgents: "आपके कौशल",+ sectionAgentsHint: "~/.agents/skills में सहेजे गए। इन्हें यहाँ बनाएँ, संपादित करें और हटाएँ।",+ sectionClaude: "Claude कौशल",+ sectionClaudeHint: "~/.claude/skills में मिले। यहाँ केवल पढ़ने के लिए; फ़ाइलें वहीं संपादित करें।",+ sectionBundled: "बंडल्ड",+ sectionBundledHint: "Unsloth के साथ आते हैं। केवल पढ़ने के लिए।",+ linked: "लिंक",+ discardTitle: "बदलाव छोड़ दें?",+ discardDescription: "{name} में असहेजे बदलाव खो जाएँगे।",+ discard: "छोड़ें",mentions: "कौशल",},library: {diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex c43c8467104..6d6b02b9745 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -3074,6 +3074,52 @@ export const it = {enable: "Attiva {name}",disable: "Disattiva {name}",updateError: "Impossibile aggiornare la competenza",+ newSkill: "Nuova competenza",+ delete: "Elimina {name}",+ createDescription: "Salvata come SKILL.md in una nuova cartella in ~/.agents/skills e attivata appena esiste.",+ nameLabel: "Nome",+ namePlaceholder: "es. code-arithmetic",+ nameHint: "Minuscole, numeri e trattini singoli. È anche il nome della cartella.",+ nameInvalid: "Usa da 1 a 64 minuscole, numeri o trattini singoli, senza trattino iniziale o finale.",+ descriptionLabel: "Descrizione",+ descriptionPlaceholder: "Usare quando l'utente chiede calcoli aritmetici. Calcolarli sempre con lo strumento di codice.",+ descriptionHint: "La riga che il modello vede nel suo catalogo di competenze. Da questa decide quando leggere la competenza.",+ instructionsLabel: "Istruzioni",+ instructionsPlaceholder: "Cosa fare quando questa competenza si applica, in Markdown.",+ instructionsHint: "Il corpo di SKILL.md, letto per intero quando il modello sceglie la competenza.",+ create: "Crea competenza",+ save: "Salva modifiche",+ created: "{name} creata",+ saved: "{name} salvata",+ deleted: "{name} eliminata",+ saveError: "Impossibile salvare la competenza",+ openError: "Impossibile aprire la competenza",+ deleteError: "Impossibile eliminare la competenza",+ deleteTitle: "Elimina competenza",+ deleteDescription: "Eliminare \"{name}\" e tutto il contenuto della sua cartella in ~/.agents/skills? L'operazione non può essere annullata.",+ search: "Cerca competenze per nome o descrizione…",+ noMatch: "Nessuna competenza corrisponde a “{query}”",+ clearSearch: "Cancella ricerca",+ readOnlyClaude: "Sola lettura: si trova in ~/.claude/skills. Modifica il file lì.",+ readOnlyBundled: "Sola lettura: inclusa in Unsloth.",+ readOnlyLinked: "Sola lettura: questa voce è un collegamento. Modifica i file dove risiedono.",+ characters: "{count} caratteri",+ unsaved: "modifiche non salvate",+ revert: "Ripristina",+ enabledLabel: "Attiva",+ licenseLabel: "Licenza",+ compatibilityLabel: "Compatibilità",+ allowedToolsLabel: "Strumenti consentiti",+ sectionAgents: "Le tue competenze",+ sectionAgentsHint: "Salvate in ~/.agents/skills. Creale, modificale ed eliminale qui.",+ sectionClaude: "Competenze Claude",+ sectionClaudeHint: "Trovate in ~/.claude/skills. Sola lettura qui; modifica i file lì.",+ sectionBundled: "Incluse",+ sectionBundledHint: "Fornite con Unsloth. Sola lettura.",+ linked: "Collegamento",+ discardTitle: "Scartare le modifiche?",+ discardDescription: "Le modifiche non salvate a {name} andranno perse.",+ discard: "Scarta",mentions: "Competenze",},library: {diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 0a7cc301173..6eb4a0c99e5 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -2955,6 +2955,52 @@ export const ja = {enable: "{name} を有効化",disable: "{name} を無効化",updateError: "スキルを更新できませんでした",+ newSkill: "新しいスキル",+ delete: "{name} を削除",+ createDescription: "~/.agents/skills の新しいフォルダーに SKILL.md として保存され、作成と同時に有効になります。",+ nameLabel: "名前",+ namePlaceholder: "例: code-arithmetic",+ nameHint: "小文字の英字、数字、単一のハイフン。フォルダー名にもなります。",+ nameInvalid: "1〜64 文字の小文字英字、数字、単一のハイフンを使い、先頭と末尾をハイフンにしないでください。",+ descriptionLabel: "説明",+ descriptionPlaceholder: "ユーザーが計算を求めたときに使う。必ずコードツールで計算する。",+ descriptionHint: "モデルがスキルカタログで見る一行です。モデルはこれを基にスキルを読むタイミングを決めます。",+ instructionsLabel: "手順",+ instructionsPlaceholder: "このスキルが適用されるときに行うことを Markdown で。",+ instructionsHint: "SKILL.md の本文です。モデルがスキルを選ぶと全文を読みます。",+ create: "スキルを作成",+ save: "変更を保存",+ created: "{name} を作成しました",+ saved: "{name} を保存しました",+ deleted: "{name} を削除しました",+ saveError: "スキルを保存できませんでした",+ openError: "スキルを開けませんでした",+ deleteError: "スキルを削除できませんでした",+ deleteTitle: "スキルを削除",+ deleteDescription: '"{name}" と ~/.agents/skills 内のそのフォルダーの中身をすべて削除しますか?この操作は取り消せません。',+ search: "名前または説明でスキルを検索…",+ noMatch: "“{query}” に一致するスキルはありません",+ clearSearch: "検索をクリア",+ readOnlyClaude: "読み取り専用: ~/.claude/skills にあります。ファイルはそこで編集してください。",+ readOnlyBundled: "読み取り専用: Unsloth に同梱されています。",+ readOnlyLinked: "読み取り専用: このエントリはリンクです。ファイルは実体の場所で編集してください。",+ characters: "{count} 文字",+ unsaved: "未保存の変更",+ revert: "元に戻す",+ enabledLabel: "有効",+ licenseLabel: "ライセンス",+ compatibilityLabel: "互換性",+ allowedToolsLabel: "許可されたツール",+ sectionAgents: "あなたのスキル",+ sectionAgentsHint: "~/.agents/skills に保存されます。ここで作成・編集・削除できます。",+ sectionClaude: "Claude のスキル",+ sectionClaudeHint: "~/.claude/skills で見つかりました。ここでは読み取り専用です。ファイルはそこで編集してください。",+ sectionBundled: "同梱",+ sectionBundledHint: "Unsloth に同梱。読み取り専用です。",+ linked: "リンク",+ discardTitle: "変更を破棄しますか?",+ discardDescription: "{name} の保存されていない変更は失われます。",+ discard: "破棄",mentions: "スキル",},library: {diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 38421f5b12b..6c7d0a24759 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -3001,6 +3001,52 @@ export const ko = {enable: "{name} 활성화",disable: "{name} 비활성화",updateError: "스킬을 업데이트할 수 없습니다",+ newSkill: "새 스킬",+ delete: "{name} 삭제",+ createDescription: "~/.agents/skills의 새 폴더에 SKILL.md로 저장되며 만들어지는 즉시 활성화됩니다.",+ nameLabel: "이름",+ namePlaceholder: "예: code-arithmetic",+ nameHint: "소문자, 숫자, 단일 하이픈만 사용합니다. 폴더 이름으로도 쓰입니다.",+ nameInvalid: "1~64자의 소문자, 숫자 또는 단일 하이픈을 사용하고, 하이픈으로 시작하거나 끝나지 않아야 합니다.",+ descriptionLabel: "설명",+ descriptionPlaceholder: "사용자가 산술 계산을 요청할 때 사용합니다. 항상 코드 도구로 계산합니다.",+ descriptionHint: "모델이 스킬 카탈로그에서 보는 한 줄입니다. 모델은 이를 보고 스킬을 읽을 시점을 정합니다.",+ instructionsLabel: "지침",+ instructionsPlaceholder: "이 스킬이 적용될 때 할 일을 Markdown으로 적습니다.",+ instructionsHint: "SKILL.md 본문입니다. 모델이 스킬을 선택하면 전체를 읽습니다.",+ create: "스킬 만들기",+ save: "변경 사항 저장",+ created: "{name} 생성됨",+ saved: "{name} 저장됨",+ deleted: "{name} 삭제됨",+ saveError: "스킬을 저장할 수 없습니다",+ openError: "스킬을 열 수 없습니다",+ deleteError: "스킬을 삭제할 수 없습니다",+ deleteTitle: "스킬 삭제",+ deleteDescription: '"{name}"과(와) ~/.agents/skills에 있는 해당 폴더의 모든 내용을 삭제할까요? 이 작업은 되돌릴 수 없습니다.',+ search: "이름 또는 설명으로 스킬 검색…",+ noMatch: "“{query}”과(와) 일치하는 스킬이 없습니다",+ clearSearch: "검색 지우기",+ readOnlyClaude: "읽기 전용: ~/.claude/skills에 있습니다. 파일은 그곳에서 편집하세요.",+ readOnlyBundled: "읽기 전용: Unsloth에 기본 제공됩니다.",+ readOnlyLinked: "읽기 전용: 이 항목은 링크입니다. 파일은 실제 위치에서 편집하세요.",+ characters: "{count}자",+ unsaved: "저장되지 않은 변경 사항",+ revert: "되돌리기",+ enabledLabel: "활성화",+ licenseLabel: "라이선스",+ compatibilityLabel: "호환성",+ allowedToolsLabel: "허용된 도구",+ sectionAgents: "내 스킬",+ sectionAgentsHint: "~/.agents/skills에 저장됩니다. 여기서 만들고, 편집하고, 삭제하세요.",+ sectionClaude: "Claude 스킬",+ sectionClaudeHint: "~/.claude/skills에서 찾았습니다. 여기서는 읽기 전용이며, 파일은 그곳에서 편집하세요.",+ sectionBundled: "기본 제공",+ sectionBundledHint: "Unsloth와 함께 제공됩니다. 읽기 전용입니다.",+ linked: "링크",+ discardTitle: "변경 사항을 버릴까요?",+ discardDescription: "{name}의 저장되지 않은 변경 사항이 사라집니다.",+ discard: "버리기",mentions: "스킬",},library: {diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex a34b70cffff..162b5c1727c 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -3035,6 +3035,52 @@ export const ptBR = {enable: "Ativar {name}",disable: "Desativar {name}",updateError: "Não foi possível atualizar a habilidade",+ newSkill: "Nova habilidade",+ delete: "Excluir {name}",+ createDescription: "Salva como SKILL.md em uma nova pasta em ~/.agents/skills e ativada assim que existir.",+ nameLabel: "Nome",+ namePlaceholder: "ex.: code-arithmetic",+ nameHint: "Minúsculas, números e hífens simples. Também é o nome da pasta.",+ nameInvalid: "Use de 1 a 64 minúsculas, números ou hífens simples, sem começar nem terminar com hífen.",+ descriptionLabel: "Descrição",+ descriptionPlaceholder: "Usar quando o usuário pedir cálculos aritméticos. Sempre calcular com a ferramenta de código.",+ descriptionHint: "A linha que o modelo vê no catálogo de habilidades. É por ela que decide quando ler a habilidade.",+ instructionsLabel: "Instruções",+ instructionsPlaceholder: "O que fazer quando esta habilidade se aplica, em Markdown.",+ instructionsHint: "O corpo do SKILL.md, lido por inteiro quando o modelo escolhe a habilidade.",+ create: "Criar habilidade",+ save: "Salvar alterações",+ created: "{name} criada",+ saved: "{name} salva",+ deleted: "{name} excluída",+ saveError: "Não foi possível salvar a habilidade",+ openError: "Não foi possível abrir a habilidade",+ deleteError: "Não foi possível excluir a habilidade",+ deleteTitle: "Excluir habilidade",+ deleteDescription: 'Excluir "{name}" e tudo o que está na pasta dela em ~/.agents/skills? Isso não pode ser desfeito.',+ search: "Buscar habilidades por nome ou descrição…",+ noMatch: "Nenhuma habilidade corresponde a “{query}”",+ clearSearch: "Limpar busca",+ readOnlyClaude: "Somente leitura: está em ~/.claude/skills. Edite o arquivo lá.",+ readOnlyBundled: "Somente leitura: incluída no Unsloth.",+ readOnlyLinked: "Somente leitura: esta entrada é um link. Edite os arquivos onde eles estão.",+ characters: "{count} caracteres",+ unsaved: "alterações não salvas",+ revert: "Reverter",+ enabledLabel: "Ativada",+ licenseLabel: "Licença",+ compatibilityLabel: "Compatibilidade",+ allowedToolsLabel: "Ferramentas permitidas",+ sectionAgents: "Suas habilidades",+ sectionAgentsHint: "Salvas em ~/.agents/skills. Crie, edite e exclua aqui.",+ sectionClaude: "Habilidades do Claude",+ sectionClaudeHint: "Encontradas em ~/.claude/skills. Somente leitura aqui; edite os arquivos lá.",+ sectionBundled: "Incluídas",+ sectionBundledHint: "Vêm com o Unsloth. Somente leitura.",+ linked: "Link",+ discardTitle: "Descartar as alterações?",+ discardDescription: "As alterações não salvas em {name} serão perdidas.",+ discard: "Descartar",mentions: "Habilidades",},library: {diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 09b670faf33..ddc2b882d1c 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -3034,6 +3034,52 @@ export const ru = {enable: "Включить {name}",disable: "Отключить {name}",updateError: "Не удалось обновить навык",+ newSkill: "Новый навык",+ delete: "Удалить {name}",+ createDescription: "Сохраняется как SKILL.md в новой папке в ~/.agents/skills и сразу включается.",+ nameLabel: "Имя",+ namePlaceholder: "например, code-arithmetic",+ nameHint: "Строчные латинские буквы, цифры и одиночные дефисы. Это же имя папки.",+ nameInvalid: "От 1 до 64 строчных латинских букв, цифр или одиночных дефисов, без дефиса в начале и в конце.",+ descriptionLabel: "Описание",+ descriptionPlaceholder: "Использовать, когда пользователь просит посчитать. Всегда считать инструментом кода.",+ descriptionHint: "Строка, которую модель видит в каталоге навыков. По ней она решает, когда прочитать навык.",+ instructionsLabel: "Инструкции",+ instructionsPlaceholder: "Что делать, когда навык применим, в Markdown.",+ instructionsHint: "Тело SKILL.md, которое модель читает целиком, выбрав навык.",+ create: "Создать навык",+ save: "Сохранить изменения",+ created: "{name} создан",+ saved: "{name} сохранён",+ deleted: "{name} удалён",+ saveError: "Не удалось сохранить навык",+ openError: "Не удалось открыть навык",+ deleteError: "Не удалось удалить навык",+ deleteTitle: "Удалить навык",+ deleteDescription: "Удалить «{name}» вместе со всем содержимым его папки в ~/.agents/skills? Это действие нельзя отменить.",+ search: "Поиск навыков по имени или описанию…",+ noMatch: "Нет навыков, соответствующих «{query}»",+ clearSearch: "Очистить поиск",+ readOnlyClaude: "Только чтение: находится в ~/.claude/skills. Редактируйте файл там.",+ readOnlyBundled: "Только чтение: встроен в Unsloth.",+ readOnlyLinked: "Только чтение: эта запись является ссылкой. Редактируйте файлы там, где они находятся.",+ characters: "{count} символов",+ unsaved: "несохранённые изменения",+ revert: "Отменить изменения",+ enabledLabel: "Включён",+ licenseLabel: "Лицензия",+ compatibilityLabel: "Совместимость",+ allowedToolsLabel: "Разрешённые инструменты",+ sectionAgents: "Ваши навыки",+ sectionAgentsHint: "Хранятся в ~/.agents/skills. Создавайте, изменяйте и удаляйте их здесь.",+ sectionClaude: "Навыки Claude",+ sectionClaudeHint: "Найдены в ~/.claude/skills. Здесь только для чтения; редактируйте файлы там.",+ sectionBundled: "Встроенные",+ sectionBundledHint: "Поставляются с Unsloth. Только чтение.",+ linked: "Ссылка",+ discardTitle: "Отменить изменения?",+ discardDescription: "Несохранённые изменения в {name} будут потеряны.",+ discard: "Отменить",mentions: "Навыки",},library: {diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 281d82bb5aa..80fcf710d3c 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2914,6 +2914,52 @@ export const zhCN = {enable: "启用 {name}",disable: "禁用 {name}",updateError: "无法更新技能",+ newSkill: "新建技能",+ delete: "删除 {name}",+ createDescription: "保存为 ~/.agents/skills 下新文件夹中的 SKILL.md,创建后立即启用。",+ nameLabel: "名称",+ namePlaceholder: "例如 code-arithmetic",+ nameHint: "小写字母、数字和单个连字符。同时也是文件夹名。",+ nameInvalid: "请使用 1 到 64 个小写字母、数字或单个连字符,且不能以连字符开头或结尾。",+ descriptionLabel: "描述",+ descriptionPlaceholder: "当用户要求做算术时使用。始终用代码工具计算。",+ descriptionHint: "模型在技能目录中看到的这一行。模型据此决定何时读取该技能。",+ instructionsLabel: "说明",+ instructionsPlaceholder: "该技能适用时要做什么,用 Markdown 编写。",+ instructionsHint: "SKILL.md 的正文,模型选中技能后会完整读取。",+ create: "创建技能",+ save: "保存更改",+ created: "已创建 {name}",+ saved: "已保存 {name}",+ deleted: "已删除 {name}",+ saveError: "无法保存技能",+ openError: "无法打开技能",+ deleteError: "无法删除技能",+ deleteTitle: "删除技能",+ deleteDescription: "删除“{name}”以及 ~/.agents/skills 下其文件夹中的全部内容?此操作无法撤销。",+ search: "按名称或描述搜索技能…",+ noMatch: "没有与“{query}”匹配的技能",+ clearSearch: "清除搜索",+ readOnlyClaude: "只读:位于 ~/.claude/skills。请在那里编辑文件。",+ readOnlyBundled: "只读:Unsloth 内置。",+ readOnlyLinked: "只读:此条目是一个链接。请在文件的实际位置编辑。",+ characters: "{count} 个字符",+ unsaved: "未保存的更改",+ revert: "还原",+ enabledLabel: "已启用",+ licenseLabel: "许可证",+ compatibilityLabel: "兼容性",+ allowedToolsLabel: "允许的工具",+ sectionAgents: "你的技能",+ sectionAgentsHint: "保存在 ~/.agents/skills。可在此创建、编辑和删除。",+ sectionClaude: "Claude 技能",+ sectionClaudeHint: "来自 ~/.claude/skills。此处只读,请在那里编辑文件。",+ sectionBundled: "内置",+ sectionBundledHint: "随 Unsloth 提供。只读。",+ linked: "链接",+ discardTitle: "放弃更改?",+ discardDescription: "对 {name} 未保存的修改将会丢失。",+ discard: "放弃",mentions: "技能",},library: {diff --git a/studio/frontend/tests/skill-mention-token.test.ts b/studio/frontend/tests/skill-mention-token.test.tsnew file mode 100644index 00000000000..1ead89eef63--- /dev/null+++ b/studio/frontend/tests/skill-mention-token.test.ts@@ -0,0 +1,65 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import assert from "node:assert/strict";+import test from "node:test";+import {+ mentionTokenAt,+ replaceMentionToken,+} from "../src/components/assistant-ui/skill-mention-token.ts";+import { readSrc } from "./helpers/kit.ts";++test("the token runs from the @ to the end of the name, whichever side of the caret", () => {+ assert.deepEqual(mentionTokenAt("@calc", 5), { start: 0, end: 5, query: "calc" });+ assert.deepEqual(mentionTokenAt("@calculator", 5), { start: 0, end: 11, query: "calc" });+ assert.deepEqual(mentionTokenAt("@calculator", 1), { start: 0, end: 11, query: "" });+ assert.deepEqual(mentionTokenAt("use @calculator now", 8), {+ start: 4,+ end: 15,+ query: "cal",+ });+ assert.equal(mentionTokenAt("@calculator", 1)?.query, "");+});++test("no token without an @ at a word start, or with a name character the rule refuses", () => {+ assert.equal(mentionTokenAt("mail foo@example", 16), null);+ assert.equal(mentionTokenAt("plain text", 5), null);+ assert.equal(mentionTokenAt("@calc.md", 8), null);+ assert.notEqual(mentionTokenAt("x @b", 3), null);+});++test("replacing the token keeps one space after the mention and puts the caret past it", () => {+ const token = mentionTokenAt("@calculator", 5);+ assert.ok(token);+ assert.deepEqual(replaceMentionToken("@calculator", token, "@calculator"), {+ text: "@calculator ",+ caret: 12,+ });+ const mid = mentionTokenAt("ask @calc for it", 9);+ assert.ok(mid);+ assert.deepEqual(replaceMentionToken("ask @calc for it", mid, "@calculator"), {+ text: "ask @calculator for it",+ caret: 16,+ });+ const wholeWord = mentionTokenAt("@calculator tor", 11);+ assert.ok(wholeWord);+ assert.equal(+ replaceMentionToken("@calculator tor", wholeWord, "@calculator").text,+ "@calculator tor",+ );+});++test("both composers replace the whole token", () => {+ const mentions = readSrc("components/assistant-ui/skill-mention-token.ts");+ assert.match(mentions, /const tail = \/\^\[a-z0-9-\]\*\/i\.exec\(text\.slice\(caret\)\)/);+ const popover = readSrc("components/assistant-ui/skill-mentions.tsx");+ assert.match(popover, /const next = mentionTokenAt\(nextText, caret\);/);+ assert.match(popover, /const next = replaceMentionToken\(text, range, directive\);/);+ assert.match(+ popover,+ /registerSelectItemOverride\(\(item\) => \{\n\s*const input = document\.activeElement;\n\s*if \(!\(input instanceof HTMLTextAreaElement\)\) return false;/,+ );+ assert.match(popover, /aui\.composer\(\)\.setText\(next\.text\);\n\s*setCursorPosition\(next\.caret\);/);+ assert.match(popover, /<MentionTokenReplacer \/>/);+});diff --git a/studio/frontend/tests/skills-dialog-create-edit.test.ts b/studio/frontend/tests/skills-dialog-create-edit.test.tsnew file mode 100644index 00000000000..c331955e3d9--- /dev/null+++ b/studio/frontend/tests/skills-dialog-create-edit.test.ts@@ -0,0 +1,131 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import assert from "node:assert/strict";+import test from "node:test";+import { readSrc } from "./helpers/kit.ts";++const API = readSrc("features/chat/api/skills-api.ts");+const DIALOG = readSrc("features/chat/components/chat-skills-dialog.tsx");++const declaration = /export const SKILL_NAME_PATTERN = (\/.*\/);/.exec(API);+assert.ok(declaration, "SKILL_NAME_PATTERN declaration not found");+const SKILL_NAME_PATTERN = new RegExp(declaration[1].slice(1, -1));+assert.match(+ API,+ /return SKILL_NAME_PATTERN\.test\(name\) && !name\.includes\("--"\);/,+);+const isValidSkillName = (name: string): boolean =>+ SKILL_NAME_PATTERN.test(name) && !name.includes("--");++test("the name check agrees with the backend", () => {+ for (const name of [+ "a",+ "a1",+ "release-notes",+ "code-arithmetic-2",+ "x".repeat(64),+ ]) {+ assert.ok(isValidSkillName(name), `${name} should be accepted`);+ }+ for (const name of [+ "",+ "-a",+ "a-",+ "a--b",+ "Release",+ "release notes",+ "notes.md",+ "../escape",+ "x".repeat(65),+ "ünder",+ ]) {+ assert.ok(!isValidSkillName(name), `${name} should be refused`);+ }+});++test("the api speaks to the four skill routes", () => {+ assert.match(API, /authFetch\("\/api\/skills", \{\n\s*method: "POST",/);+ assert.match(+ API,+ /authFetch\(`\/api\/skills\/\$\{encodeURIComponent\(name\)\}`\);\n\s*return parseResponse<SkillManifest>/,+ );+ assert.match(+ API,+ /authFetch\(`\/api\/skills\/\$\{encodeURIComponent\(name\)\}`, \{\n\s*method: "PUT",/,+ );+ assert.match(+ API,+ /authFetch\(`\/api\/skills\/\$\{encodeURIComponent\(name\)\}`, \{\n\s*method: "DELETE",/,+ );+});++test("every write re-reads the folders and tells the other windows", () => {+ assert.equal((API.match(/await skillsMutated\(\);/g) ?? []).length, 3);+ assert.match(+ API,+ /async function skillsMutated\(\): Promise<void> \{\n\s*channel\?\.postMessage\("changed"\);\n\s*void refreshContextUsage\(\{ invalidate: true \}\);\n\s*await listSkills\(true\)/,+ );+});++test("save and delete are offered only on skills the dialog can write", () => {+ assert.match(+ DIALOG,+ /function isEditable\(skill: SkillRecord\): boolean \{\n\s*return skill\.valid && skill\.source === "agents" && !skill\.linked;/,+ );+ assert.match(DIALOG, /const editable = selected !== null && isEditable\(selected\);/);+ assert.match(DIALOG, /readOnly=\{!editable\}/);+ assert.match(DIALOG, /\) : editable && selected \? \([^]*?onClick=\{\(\) => setConfirmingDelete\(selected\)\}/);+ assert.match(+ DIALOG,+ /<AlertDialogAction\n\s*variant="destructive"\n\s*onClick=\{\(\) => \{\n\s*const skill = confirmingDelete;/,+ );+ assert.match(DIALOG, /if \(skill\) void remove\(skill\);/);+});++test("the new-skill form holds back an invalid or incomplete draft", () => {+ assert.match(+ DIALOG,+ /const nameInvalid = trimmedName\.length > 0 && !isValidSkillName\(trimmedName\);/,+ );+ assert.match(DIALOG, /aria-invalid=\{nameInvalid \|\| undefined\}/);+ assert.match(+ DIALOG,+ /hint=\{nameInvalid \? t\("skills\.nameInvalid"\) : t\("skills\.nameHint"\)\}/,+ );+ assert.match(DIALOG, /disabled=\{creating \|\| !canCreate\}/);+ assert.match(DIALOG, /if \(creating \|\| !canCreate\) return;/);+ assert.doesNotMatch(DIALOG, /id="skill-edit-name"/);+});++test("save is held back until the draft differs from the file and is complete", () => {+ assert.match(+ DIALOG,+ /const canSave =\n\s*editable &&\n\s*draft !== null &&\n\s*draft\.description\.trim\(\)\.length > 0 &&\n\s*draft\.instructions\.trim\(\)\.length > 0;/,+ );+ assert.match(+ DIALOG,+ /if \(!selected \|\| !manifest \|\| !draft \|\| !canSave \|\| pending !== null\) return;/,+ );+ assert.match(+ DIALOG,+ /return next\.description === manifest\.description &&\n\s*next\.instructions === manifest\.instructions\n\s*\? null\n\s*: next;/,+ );+});++test("the dialog guards writes and drafts, and reopens on the library", () => {+ assert.match(DIALOG, /if \(!next && busy\) return;/);+ assert.match(+ DIALOG,+ /if \(!next && dirty\) \{\n\s*setConfirmingDiscard\(\(\) => \(\) => onOpenChange\(false\)\);\n\s*return;/,+ );+ assert.match(+ DIALOG,+ /const leaveTo = \(next: \(\) => void\) => \{\n\s*if \(dirty\) setConfirmingDiscard\(\(\) => next\);/,+ );+ assert.match(+ DIALOG,+ /if \(open !== seenOpen\) \{\n\s*setSeenOpen\(open\);\n\s*if \(open\) \{\n\s*setSearchQuery\(""\);\n\s*setView\(LIBRARY\);/,+ );+});