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
Studio: import and export skills as a ZIP from the Skills dialog (#14181)
Samih Qureshid6604ac30e61
diff --git a/scripts/risky_loaders_baseline.json b/scripts/risky_loaders_baseline.jsonindex c423b9ab833..d1ff8670aca 100644--- a/scripts/risky_loaders_baseline.json+++ b/scripts/risky_loaders_baseline.json@@ -202,6 +202,14 @@"count": 1,"reason": "Module name comes from a fixed table or constant in this file, not from a model, request or download."},+ {+ "file": "studio/backend/core/inference/skills.py",+ "rule": "unsafe-deserialize",+ "sink": "yaml.load",+ "digest": "df424636e7148b98",+ "count": 2,+ "reason": "Loader is _FrontmatterLoader, a yaml.SafeLoader subclass that only adds a merge-key pair budget; no Python object construction."+ },{"file": "studio/backend/core/inference/video_wan_fused.py","rule": "dynamic-import",diff --git a/studio/backend/core/inference/skills.py b/studio/backend/core/inference/skills.pyindex a948da1ee06..92d196be16a 100644--- a/studio/backend/core/inference/skills.py+++ b/studio/backend/core/inference/skills.py@@ -4,6 +4,7 @@from __future__ import annotationsimport errno+import ioimport jsonimport loggingimport os@@ -13,6 +14,7 @@ import statimport tempfileimport threadingimport unicodedata+import zipfilefrom pathlib import Path, PurePosixPath, PureWindowsPathfrom typing import Optional@@ -34,6 +36,9 @@ MAX_SKILL_RESOURCE_PATH_BYTES = 400MAX_SKILL_PATH_COMPONENTS = 256MAX_SKILLS_PER_ROOT = 1_000MAX_SKILL_INSTRUCTIONS_BYTES = 256 * 1024+MAX_SKILL_ARCHIVE_BYTES = 20 * 1024 * 1024+MAX_SKILL_ARCHIVE_FILES = 200+MAX_SKILL_FRONTMATTER_PAIRS = 10_000logger = logging.getLogger(__name__)@@ -56,6 +61,40 @@ _FRONTMATTER_KEY = re.compile(r"([a-zA-Z_-]+):[ \t]+(?=[^\s\"'|>&!\[{])(?![-?:]\MAX_FRONTMATTER_REPAIRS = 16+class _FrontmatterLoader(yaml.SafeLoader):+ # Nested merge keys expand exponentially (2 KB -> billions of pairs): count before PyYAML merges.+ def __init__(self, stream):+ super().__init__(stream)+ self._pairs_left = MAX_SKILL_FRONTMATTER_PAIRS++ def construct_mapping(+ self,+ node,+ deep = False,+ ):+ if isinstance(node, yaml.MappingNode):+ self.flatten_mapping(node)+ self._pairs_left -= len(node.value)+ if self._pairs_left < 0:+ raise yaml.YAMLError("YAML frontmatter has too many keys.")+ return super().construct_mapping(node, deep = deep)++ def flatten_mapping(self, node):+ total = len(node.value)+ for key, value in node.value:+ if key.tag != "tag:yaml.org,2002:merge":+ continue+ for merged in value.value if isinstance(value, yaml.SequenceNode) else (value,):+ if isinstance(merged, yaml.MappingNode):+ self.flatten_mapping(merged)+ total += len(merged.value)+ if total > MAX_SKILL_FRONTMATTER_PAIRS:+ raise yaml.YAMLError("YAML merge keys expand too far.")+ if total > MAX_SKILL_FRONTMATTER_PAIRS:+ raise yaml.YAMLError("YAML frontmatter has too many keys.")+ super().flatten_mapping(node)++class SkillError(ValueError):pass@@ -308,7 +347,7 @@ def _load_frontmatter(text: str):repaired = []for _ in range(MAX_FRONTMATTER_REPAIRS):try:- frontmatter = yaml.safe_load(text)+ frontmatter = yaml.load(text, Loader = _FrontmatterLoader)breakexcept (yaml.scanner.ScannerError, yaml.composer.ComposerError) as exc:# Agent skill loaders accept unquoted values such as `description: Use when: ...`.@@ -321,7 +360,7 @@ def _load_frontmatter(text: str):text, key, value = repairrepaired.append((key, value))else:- frontmatter = yaml.safe_load(text)+ frontmatter = yaml.load(text, Loader = _FrontmatterLoader)# A line that only looked top-level, such as one inside a flow mapping, would not read back.if repaired and (not isinstance(frontmatter, dict)@@ -735,7 +774,17 @@ def create_skill(description = _validate_draft(description, instructions)manifest = _render_manifest({"name": normalized, "description": description}, instructions)metadata = _parse_skill_markdown(manifest, normalized)+ return _install_new_skill(normalized, manifest, metadata, home = home)++def _install_new_skill(+ normalized: str,+ manifest: bytes,+ metadata: dict,+ *,+ files = (),+ home: Optional[Path] = None,+) -> dict: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.@@ -758,6 +807,25 @@ def create_skill(raise SkillExistsError(f"Skill '{normalized}' already exists.") from excexcept OSError as exc:raise SkillError(f"Could not create skill '{normalized}'.") from exc+ if files:+ skill_dir = _agents_ancestors(base.resolve(strict = True), root)[-1] / normalized+ flags = (+ os.O_WRONLY+ | os.O_CREAT+ | os.O_EXCL+ | getattr(os, "O_BINARY", 0)+ | getattr(os, "O_NOFOLLOW", 0)+ )+ try:+ for path, content, executable in files:+ target = skill_dir.joinpath(*path.parts)+ target.parent.mkdir(mode = 0o700, parents = True, exist_ok = True)+ mode = 0o700 if executable else 0o600+ with os.fdopen(os.open(target, flags, mode), "wb") as handle:+ handle.write(content)+ except OSError as exc:+ shutil.rmtree(skill_dir, ignore_errors = True)+ raise SkillError(f"Could not import skill '{normalized}'.") from excexcept Exception:if had_override:try:@@ -892,6 +960,148 @@ def delete_skill(name: str, *, home: Optional[Path] = None) -> dict:return record+def export_skill(name: str, *, home: Optional[Path] = None) -> tuple[str, bytes]:+ """The skill folder as a ZIP under ``<name>/``."""+ with _LOCK:+ record, skill_dir, identity = _selected_skill(name, home = home)+ paths: list[Path] = []++ def unreadable(exc: OSError) -> None:+ raise SkillError("Could not read the skill folder.") from exc++ for directory, folders, files in os.walk(skill_dir, onerror = unreadable):+ folders[:] = sorted(folder for folder in folders if not folder.startswith("."))+ if any(_is_linked_path(Path(directory) / folder) for folder in folders):+ raise SkillError("Skill resources cannot use symbolic links or reparse points.")+ paths.extend(+ Path(directory) / file for file in sorted(files) if not file.startswith(".")+ )+ if len(paths) > MAX_SKILL_ARCHIVE_FILES:+ raise SkillError(f"Skill archive exceeds the {MAX_SKILL_ARCHIVE_FILES}-file limit.")+ output = io.BytesIO()+ total = 0+ seen: set[str] = set()+ with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:+ for path in paths:+ relative = _normalize_resource_path(path.relative_to(skill_dir).as_posix())+ # Import refuses case-insensitive duplicates, so export must too.+ key = relative.as_posix().casefold()+ if key in seen:+ raise SkillError(+ f"Skill archive contains '{relative.as_posix()}' more than once."+ )+ seen.add(key)+ content = _read_limited(+ path, MAX_SKILL_FILE_BYTES, contained_in = skill_dir, identity = identity+ )+ total += len(content)+ if total > MAX_SKILL_ARCHIVE_BYTES:+ raise SkillError("Skill archive exceeds the 20 MB limit.")+ # Bare ZipInfo keeps 1980 timestamps: reproducible archives.+ info = zipfile.ZipInfo(f"{record['name']}/{relative.as_posix()}")+ info.external_attr = (0o755 if os.stat(path).st_mode & 0o111 else 0o644) << 16+ archive.writestr(info, content, compress_type = zipfile.ZIP_DEFLATED)+ return record["name"], output.getvalue()+++def _archive_skill_folders(names: list[str]) -> list[str]:+ """Skill roots in a ZIP; a lone folder without SKILL.md is a skills folder."""+ if "SKILL.md" in names:+ return [""]+ wrapper = ""+ tops = {name.split("/", 1)[0] for name in names}+ if len(tops) == 1 and all("/" in name for name in names):+ (top,) = tops+ if f"{top}/SKILL.md" not in names:+ wrapper = f"{top}/"+ tops = {name[len(wrapper) :].split("/", 1)[0] for name in names}+ folders = sorted(f"{wrapper}{top}/" for top in tops)+ if not folders:+ raise SkillError("Skill archive must contain a skill folder with a SKILL.md at its top.")+ for folder in folders:+ if f"{folder}SKILL.md" not in names:+ raise SkillError(+ f"Skill archive must hold only skill folders with a SKILL.md at their top; "+ f"'{folder.rstrip('/')}' has none."+ )+ return folders+++def import_skill_archive(data: bytes, *, home: Optional[Path] = None) -> dict:+ """Unsafe archives are refused whole; otherwise each skill lands in imported or failed."""+ if len(data) > MAX_SKILL_ARCHIVE_BYTES:+ raise SkillError("Skill archive exceeds the 20 MB limit.")+ try:+ archive = zipfile.ZipFile(io.BytesIO(data))+ except (zipfile.BadZipFile, NotImplementedError, OSError, ValueError) as exc:+ raise SkillError("Skill archive must be a ZIP file.") from exc+ with archive:+ members: list[tuple[str, zipfile.ZipInfo]] = []+ for info in archive.infolist():+ name = info.filename.replace("\\", "/")+ parts = PurePosixPath(name).parts+ # ".." survives so the path check refuses it.+ if (+ name.endswith("/")+ or parts[:1] == ("__MACOSX",)+ or any(part.startswith(".") and part != ".." for part in parts)+ ):+ continue+ if info.flag_bits & 0x1:+ raise SkillError("Skill archive cannot contain encrypted files.")+ if stat.S_ISLNK(info.external_attr >> 16):+ raise SkillError("Skill archive cannot contain symbolic links.")+ # LZMA/BZIP2 decoders allocate what the member header asks for, before any limit applies.+ if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):+ raise SkillError("Skill archive must use stored or deflated entries.")+ members.append((name, info))+ if len(members) > MAX_SKILL_ARCHIVE_FILES:+ raise SkillError(f"Skill archive exceeds the {MAX_SKILL_ARCHIVE_FILES}-file limit.")++ bundles: list[tuple[str, bytes, list[tuple[PurePosixPath, bytes, bool]]]] = []+ total = 0+ for folder in _archive_skill_folders([name for name, _ in members]):+ manifest = b""+ files: list[tuple[PurePosixPath, bytes, bool]] = []+ seen: set[str] = set()+ for name, info in members:+ if not name.startswith(folder):+ continue+ path = _normalize_resource_path(name[len(folder) :])+ key = path.as_posix().casefold()+ if key in seen:+ raise SkillError(f"Skill archive contains '{path.as_posix()}' more than once.")+ seen.add(key)+ limit = MAX_SKILL_MD_BYTES if key == "skill.md" else MAX_SKILL_FILE_BYTES+ # Declared sizes are untrusted; any decoder or CRC error is the archive's.+ try:+ with archive.open(info) as handle:+ content = handle.read(limit + 1)+ except Exception as exc:+ raise SkillError("Skill archive is damaged.") from exc+ if len(content) > limit:+ raise SkillError(f"{path.as_posix()} exceeds the {limit // 1024} KB limit.")+ total += len(content)+ if total > MAX_SKILL_ARCHIVE_BYTES:+ raise SkillError("Skill archive exceeds the 20 MB limit.")+ if path.as_posix() == "SKILL.md":+ manifest = content+ else:+ files.append((path, content, bool((info.external_attr >> 16) & 0o111)))+ bundles.append((folder.rstrip("/").rsplit("/", 1)[-1], manifest, files))++ imported: list[dict] = []+ failed: list[dict] = []+ for name, manifest, files in bundles:+ try:+ metadata = _parse_skill_markdown(manifest)+ name = metadata["name"]+ imported.append(_install_new_skill(name, manifest, metadata, files = files, home = home))+ except SkillError as exc:+ failed.append({"name": name or "SKILL.md", "error": str(exc)})+ return {"imported": imported, "failed": failed}++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 50d3f846593..829d2b4c0fd 100644--- a/studio/backend/routes/skills.py+++ b/studio/backend/routes/skills.py@@ -3,16 +3,19 @@from typing import Any, Literal, Optional-from fastapi import APIRouter, Depends, HTTPException, Response+from fastapi import APIRouter, Depends, File, HTTPException, Response, UploadFilefrom pydantic import BaseModel, ConfigDict, StrictBool, StrictStrfrom auth.authentication import get_current_subjectfrom core.inference.skills import (+ MAX_SKILL_ARCHIVE_BYTES,SkillError,SkillExistsError,SkillNotFoundError,create_skill,delete_skill,+ export_skill,+ import_skill_archive,list_skills,read_skill_manifest,set_all_skills_enabled,@@ -71,6 +74,20 @@ class SkillCreateRequest(SkillDraft):name: StrictStr+class SkillImportFailure(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ name: str+ error: str+++class SkillImportResult(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ imported: list[SkillRecord]+ failed: list[SkillImportFailure]++def _invalidate_catalog() -> None:from routes.inference import _invalidate_agent_skills_cache_invalidate_agent_skills_cache()@@ -119,6 +136,22 @@ def create_skill_route(return record+# 200, not 201: results can be partial.[email protected]("/import", response_model = SkillImportResult)+def import_skill_route(+ file: UploadFile = File(...), current_subject: str = Depends(get_current_subject)+) -> dict[str, Any]:+ data = file.file.read(MAX_SKILL_ARCHIVE_BYTES + 1)+ if len(data) > MAX_SKILL_ARCHIVE_BYTES:+ raise HTTPException(status_code = 413, detail = "Skill archive exceeds the 20 MB limit.")+ try:+ result = import_skill_archive(data)+ except SkillError as exc:+ raise _http_error(exc) from exc+ _invalidate_catalog()+ return result++@router.get("/{name}", response_model = SkillManifest)def get_skill(name: str, current_subject: str = Depends(get_current_subject)) -> dict[str, Any]:try:@@ -127,6 +160,22 @@ def get_skill(name: str, current_subject: str = Depends(get_current_subject)) ->raise _http_error(exc) from exc[email protected]("/{name}/export", response_class = Response)+def export_skill_route(name: str, current_subject: str = Depends(get_current_subject)) -> Response:+ try:+ skill_name, archive = export_skill(name)+ except SkillError as exc:+ raise _http_error(exc) from exc+ return Response(+ content = archive,+ media_type = "application/zip",+ headers = {+ "Content-Disposition": f'attachment; filename="{skill_name}.zip"',+ "Cache-Control": "no-store",+ },+ )++@router.put("/{name}", response_model = SkillRecord)def update_skill_route(name: str,diff --git a/studio/backend/tests/multi_account/factories.py b/studio/backend/tests/multi_account/factories.pyindex 6f7dbcd8659..d6321e1343b 100644--- a/studio/backend/tests/multi_account/factories.py+++ b/studio/backend/tests/multi_account/factories.py@@ -176,6 +176,7 @@ CORE_FACTORIES = {"skill", {"enabled": False}, fragment = SKILL_NAME, absent = SENTINEL),"routes.skills:GET:/{name}": Factory("skill", fragment = SENTINEL, absent = SENTINEL),+ "routes.skills:GET:/{name}/export": Factory("skill", fragment = SKILL_NAME),"routes.skills:PUT:/{name}": Factory("skill",{"description": EDITED, "instructions": "Instructions"},diff --git a/studio/backend/tests/test_skill_archive.py b/studio/backend/tests/test_skill_archive.pynew file mode 100644index 00000000000..c4e9a7e3813--- /dev/null+++ b/studio/backend/tests/test_skill_archive.py@@ -0,0 +1,414 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Skill ZIP export/import; every refusal must leave nothing behind."""++import io+import json+import os+import stat+import tracemalloc+import zipfile++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth.authentication import get_current_subject+from core.inference import skills+from routes.skills import router+from .test_skills import _BOB_ID, _write_skill, isolated_skills, managed_accounts # noqa: F401++_MANIFEST = (+ b"---\nname: packed\ndescription: Use this skill for archive tests.\n---\nInstructions\n"+)+++def _zip(*members, compression = zipfile.ZIP_DEFLATED) -> bytes:+ output = io.BytesIO()+ with zipfile.ZipFile(output, "w", compression) as archive:+ for name, content in members:+ archive.writestr(name, content)+ return output.getvalue()+++def _symlink(name: str) -> zipfile.ZipInfo:+ info = zipfile.ZipInfo(name)+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ return info+++def _future_version(archive: bytes) -> bytes:+ at = archive.index(b"PK\x01\x02") + 6+ return archive[:at] + (99).to_bytes(2, "little") + archive[at + 2 :]+++def _corrupt_member(archive: bytes) -> bytes:+ # Flip the stored CRC of the last member so reading it fails.+ at = archive.rindex(b"PK\x01\x02") + 16+ return archive[:at] + bytes(b ^ 0xFF for b in archive[at : at + 4]) + archive[at + 4 :]+++def _files(skill_dir) -> dict[str, bytes]:+ return {+ path.relative_to(skill_dir).as_posix(): path.read_bytes()+ for path in skill_dir.rglob("*")+ if path.is_file()+ }+++def test_an_exported_skill_imports_back_with_the_same_files(isolated_skills):+ home, _ = isolated_skills+ skill_dir = _write_skill(+ home, "agents", "packed", frontmatter = "license: Apache-2.0\nmetadata:\n author: tester"+ )+ (skill_dir / "references").mkdir()+ (skill_dir / "references" / "guide.md").write_bytes(b"# Guide\n")+ (skill_dir / "run.sh").write_bytes(b"echo hi\n")+ (skill_dir / "run.sh").chmod(0o755)+ before = _files(skill_dir)++ name, archive = skills.export_skill("packed", home = home)+ infos = zipfile.ZipFile(io.BytesIO(archive)).infolist()+ assert name == "packed"+ assert [info.filename for info in infos] == [+ "packed/SKILL.md",+ "packed/run.sh",+ "packed/references/guide.md",+ ]+ assert {info.date_time for info in infos} == {(1980, 1, 1, 0, 0, 0)}++ skills.delete_skill("packed", home = home)+ [record] = skills.import_skill_archive(archive, home = home)["imported"]++ assert (record["name"], record["source"], record["enabled"]) == ("packed", "agents", True)+ assert (record["license"], record["metadata"]) == ("Apache-2.0", {"author": "tester"})+ assert _files(skill_dir) == before+ if os.name == "posix":+ assert os.access(skill_dir / "run.sh", os.X_OK)+ assert not os.access(skill_dir / "SKILL.md", os.X_OK)++[email protected]("prefix", ["", "my-skill-main/"])+def test_import_takes_skill_md_at_the_top_or_inside_one_folder(isolated_skills, prefix):+ home, _ = isolated_skills+ archive = _zip(+ (f"{prefix}scripts/", b""),+ (f"{prefix}SKILL.md", _MANIFEST),+ (f"{prefix}scripts/run.py", b"print('hi')\n"),+ (f"{prefix}.DS_Store", b"junk"),+ ("__MACOSX/._SKILL.md", b"junk"),+ )++ imported = skills.import_skill_archive(archive, home = home)["imported"]+ assert [record["name"] for record in imported] == ["packed"]+ assert _files(home / ".agents" / "skills" / "packed") == {+ "SKILL.md": _MANIFEST,+ "scripts/run.py": b"print('hi')\n",+ }+++ "archive,reason",+ [+ pytest.param(+ _zip(("SKILL.md", _MANIFEST), ("../escape.md", b"x")), "inside", id = "traversal"+ ),+ pytest.param(+ _zip(("SKILL.md", _MANIFEST), ("/tmp/escape.md", b"x")), "inside", id = "absolute"+ ),+ pytest.param(_zip(("SKILL.md", _MANIFEST), ("C:\\escape.md", b"x")), "inside", id = "drive"),+ pytest.param(+ _zip(("SKILL.md", _MANIFEST), (_symlink("link.md"), b"/etc")), "symbolic", id = "symlink"+ ),+ pytest.param(+ _zip(("one/SKILL.md", _MANIFEST), ("README.md", b"x")),+ "'README.md' has none",+ id = "stray-file",+ ),+ pytest.param(_zip(("README.md", b"x")), "'README.md' has none", id = "no-manifest"),+ pytest.param(_zip(), "a skill folder", id = "empty"),+ pytest.param(b"not a zip", "ZIP file", id = "not-a-zip"),+ pytest.param(+ _future_version(_zip(("SKILL.md", _MANIFEST))), "ZIP file", id = "future-version"+ ),+ pytest.param(+ _zip(("SKILL.md", _MANIFEST), compression = zipfile.ZIP_LZMA),+ "stored or deflated",+ id = "lzma",+ ),+ pytest.param(+ _corrupt_member(_zip(("SKILL.md", _MANIFEST), ("ref.md", b"x" * 100))),+ "damaged",+ id = "bad-crc",+ ),+ pytest.param(+ _zip(("SKILL.md", _MANIFEST), ("big.bin", b"x" * (skills.MAX_SKILL_FILE_BYTES + 1))),+ "big.bin exceeds",+ id = "oversized-member",+ ),+ pytest.param(+ _zip(("SKILL.md", _MANIFEST), ("Guide.md", b"a"), ("guide.md", b"b")),+ "more than once",+ id = "case-duplicates",+ ),+ ],+)+def test_import_refuses_an_unsafe_archive_and_leaves_nothing(isolated_skills, archive, reason):+ home, _ = isolated_skills+ with pytest.raises(skills.SkillError, match = reason):+ skills.import_skill_archive(archive, home = home)+ assert not (home / ".agents").exists()+++def _manifest(name: str) -> bytes:+ return f"---\nname: {name}\ndescription: The {name} skill.\n---\nInstructions\n".encode()++[email protected]("wrapper", ["", "skills/"])+def test_import_takes_a_folder_of_skills(isolated_skills, wrapper):+ home, _ = isolated_skills+ archive = _zip(+ (f"{wrapper}sandbox-scout/SKILL.md", _manifest("sandbox-scout")),+ (f"{wrapper}train-replay/SKILL.md", _manifest("train-replay")),+ (f"{wrapper}train-replay/scripts/replay.py", b"print('replay')\n"),+ ("__MACOSX/._skills", b"junk"),+ )++ result = skills.import_skill_archive(archive, home = home)++ assert [record["name"] for record in result["imported"]] == ["sandbox-scout", "train-replay"]+ assert result["failed"] == []+ root = home / ".agents" / "skills"+ assert _files(root / "train-replay") == {+ "SKILL.md": _manifest("train-replay"),+ "scripts/replay.py": b"print('replay')\n",+ }+ assert _files(root / "sandbox-scout") == {"SKILL.md": _manifest("sandbox-scout")}+++def test_a_folder_of_skills_reports_each_skill_it_could_not_install(isolated_skills):+ home, _ = isolated_skills+ existing = _write_skill(home, "agents", "train-replay", body = "Original")+ before = _files(existing)+ archive = _zip(+ ("broken/SKILL.md", b"no frontmatter"),+ ("sandbox-scout/SKILL.md", _manifest("sandbox-scout")),+ ("train-replay/SKILL.md", _manifest("train-replay")),+ )++ result = skills.import_skill_archive(archive, home = home)++ assert [record["name"] for record in result["imported"]] == ["sandbox-scout"]+ assert result["failed"] == [+ {"name": "broken", "error": "SKILL.md must start with YAML frontmatter."},+ {"name": "train-replay", "error": "Skill 'train-replay' already exists."},+ ]+ assert not (home / ".agents" / "skills" / "broken").exists()+ assert _files(existing) == before+++def _nested_merges() -> str:+ lines = ["l0: &l0 {" + ", ".join(f"k{i}: v" for i in range(10)) + "}"]+ for level in range(1, 7):+ lines.append(f"l{level}: &l{level}")+ lines.append(" <<: [" + ", ".join([f"*l{level - 1}"] * 10) + "]")+ lines += [f" x{level}_{i}: v" for i in range(10)]+ return "\n".join(lines)+++def _wide_merge() -> str:+ pairs = ", ".join(f"k{i}: v" for i in range(3000))+ return f"a: &a {{{pairs}}}\nb:\n <<: [" + ", ".join(["*a"] * 3000) + "]"+++def _many_merges() -> str:+ pairs = ", ".join(f"k{i}: v" for i in range(5000))+ return f"a: &a {{{pairs}}}\n" + "\n".join(f"c{i}: {{<<: *a}}" for i in range(5000))++[email protected]("frontmatter", [_nested_merges, _wide_merge, _many_merges])+def test_import_refuses_frontmatter_whose_merge_keys_explode(isolated_skills, frontmatter):+ home, _ = isolated_skills+ manifest = f"---\nname: bomb\ndescription: Looks normal.\n{frontmatter()}\n---\nHi\n".encode()++ tracemalloc.start()+ try:+ result = skills.import_skill_archive(_zip(("bomb/SKILL.md", manifest)), home = home)+ peak = tracemalloc.get_traced_memory()[1]+ finally:+ tracemalloc.stop()++ assert result == {+ "imported": [],+ "failed": [{"name": "bomb", "error": "SKILL.md contains invalid YAML frontmatter."}],+ }+ assert peak < 48 * 1024 * 1024+ assert not (home / ".agents" / "skills" / "bomb").exists()+++def test_small_yaml_merges_still_load(isolated_skills):+ home, _ = isolated_skills+ manifest = (+ b"---\nname: merged\ndescription: Uses a merge.\n"+ b"base: &base {owner: team}\nmetadata:\n <<: *base\n tier: gold\n---\nHi\n"+ )++ result = skills.import_skill_archive(_zip(("merged/SKILL.md", manifest)), home = home)++ assert result["failed"] == []+ assert result["imported"][0]["metadata"] == {"owner": "team", "tier": "gold"}+++def test_import_reads_backslash_separators_like_slashes(isolated_skills):+ home, _ = isolated_skills+ archive = _zip(+ ("my-skill\\SKILL.md", _MANIFEST),+ ("my-skill\\ref.md", b"ref"),+ ("my-skill\\.git\\config", b"junk"),+ )++ skills.import_skill_archive(archive, home = home)++ assert _files(home / ".agents" / "skills" / "packed") == {+ "SKILL.md": _MANIFEST,+ "ref.md": b"ref",+ }+++def test_import_refuses_too_many_files_or_too_many_bytes(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ monkeypatch.setattr(skills, "MAX_SKILL_ARCHIVE_FILES", 2)+ with pytest.raises(skills.SkillError, match = "2-file limit"):+ skills.import_skill_archive(+ _zip(("SKILL.md", _MANIFEST), ("a.md", b"a"), ("b.md", b"b")), home = home+ )++ archive = _zip(("SKILL.md", _MANIFEST), ("big.md", b"x" * 100_000))+ monkeypatch.setattr(skills, "MAX_SKILL_ARCHIVE_BYTES", len(archive))+ with pytest.raises(skills.SkillError, match = "20 MB limit"):+ skills.import_skill_archive(archive, home = home)+ monkeypatch.setattr(skills, "MAX_SKILL_ARCHIVE_BYTES", len(archive) - 1)+ with pytest.raises(skills.SkillError, match = "20 MB limit"):+ skills.import_skill_archive(archive, home = home)+ assert not (home / ".agents").exists()+++def test_a_failed_resource_write_removes_the_half_imported_skill(isolated_skills, monkeypatch):+ home, studio = isolated_skills+ studio.mkdir()+ (studio / "skill-overrides.json").write_text(json.dumps({"packed": False}), encoding = "utf-8")+ real_open = os.open++ def refuse_guide(path, flags, *args, **kwargs):+ if str(path).endswith("guide.md"):+ raise PermissionError("disk refused")+ return real_open(path, flags, *args, **kwargs)++ monkeypatch.setattr(skills.os, "open", refuse_guide)+ archive = _zip(("SKILL.md", _MANIFEST), ("references/guide.md", b"x"))+ result = skills.import_skill_archive(archive, home = home)++ assert result["failed"] == [{"name": "packed", "error": "Could not import skill 'packed'."}]++ assert not (home / ".agents" / "skills" / "packed").exists()+ assert skills._load_overrides() == {"packed": False}+++def test_a_managed_account_imports_into_its_own_workspace(managed_accounts):+ from utils.account_context import run_as++ home, studio, alice, bob = managed_accounts+ archive = _zip(("SKILL.md", _MANIFEST), ("notes.md", b"notes"))++ [record] = run_as(bob, skills.import_skill_archive, archive)["imported"]++ assert record["path"] == "skills/packed/SKILL.md"+ assert (studio / "accounts" / _BOB_ID / "skills" / "packed" / "notes.md").is_file()+ assert not (home / ".agents" / "skills" / "packed").exists()+ with pytest.raises(skills.SkillNotFoundError):+ run_as(alice, skills.export_skill, "packed")+++def test_export_refuses_a_file_name_import_would_refuse(isolated_skills):+ home, _ = isolated_skills+ skill_dir = _write_skill(home, "agents", "packed")+ (skill_dir / "con.md").write_text("x", encoding = "utf-8")++ with pytest.raises(skills.SkillError, match = "reserved device name"):+ skills.export_skill("packed", home = home)+++def test_export_refuses_names_that_differ_only_in_case(isolated_skills):+ home, _ = isolated_skills+ skill_dir = _write_skill(home, "agents", "packed")+ (skill_dir / "Guide.md").write_text("a", encoding = "utf-8")+ try:+ (skill_dir / "guide.md").write_text("b", encoding = "utf-8")+ except FileExistsError:+ pass+ if len(list(skill_dir.glob("[Gg]uide.md"))) < 2:+ pytest.skip(reason = "case-insensitive filesystem")++ with pytest.raises(skills.SkillError, match = "more than once"):+ skills.export_skill("packed", home = home)++[email protected]("kind", ["file", "folder"])+def test_export_refuses_a_linked_resource(isolated_skills, kind):+ home, _ = isolated_skills+ skill_dir = _write_skill(home, "agents", "packed")+ outside = home.parent / "outside"+ outside.mkdir()+ (outside / "secret.txt").write_text("secret", encoding = "utf-8")+ target = outside if kind == "folder" else outside / "secret.txt"+ try:+ (skill_dir / "leak").symlink_to(target, target_is_directory = kind == "folder")+ except (OSError, NotImplementedError):+ pytest.skip(reason = "symlinks are unavailable on this platform")++ with pytest.raises(skills.SkillError, match = "symbolic links"):+ skills.export_skill("packed", home = home)+++def test_authenticated_import_and_export_routes(isolated_skills, monkeypatch):+ from routes import inference as inference_routes+ from routes import skills as skills_routes++ home, _ = isolated_skills+ monkeypatch.setattr(skills, "_owner_home", lambda: home)+ app = FastAPI()+ app.include_router(router, prefix = "/api/skills")+ upload = {"file": ("packed.zip", _zip(("SKILL.md", _MANIFEST)), "application/zip")}+ anonymous = TestClient(app)+ assert anonymous.post("/api/skills/import", files = upload).status_code in (401, 403)+ assert anonymous.get("/api/skills/packed/export").status_code in (401, 403)+ assert not (home / ".agents").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/import", files = upload)+ assert response.status_code == 200, response.text+ imported = response.json()["imported"]+ assert [record["path"] for record in imported] == ["~/.agents/skills/packed/SKILL.md"]+ assert inference_routes._AGENT_SKILLS_CACHE == {}+ response = client.post("/api/skills/import", files = upload)+ assert response.status_code == 200, response.text+ assert response.json() == {+ "imported": [],+ "failed": [{"name": "packed", "error": "Skill 'packed' already exists."}],+ }+ bad = {"file": ("bad.zip", b"not a zip", "application/zip")}+ assert client.post("/api/skills/import", files = bad).status_code == 400++ response = client.get("/api/skills/packed/export")+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/zip"+ assert response.headers["content-disposition"] == 'attachment; filename="packed.zip"'+ assert response.headers["cache-control"] == "no-store"+ assert zipfile.ZipFile(io.BytesIO(response.content)).namelist() == ["packed/SKILL.md"]+ assert client.get("/api/skills/missing/export").status_code == 404++ monkeypatch.setattr(skills_routes, "MAX_SKILL_ARCHIVE_BYTES", 8)+ assert client.post("/api/skills/import", files = upload).status_code == 413diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex b352a92784e..7a8af3576bd 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -409,8 +409,11 @@ export const BUDGET = {// The waiting-for-approval mark, Desktop attention request and tool_approved handling (#14877): measured// 6,929,942 B raw / 2,087,788 B transfer merged with main at b3004af53 (Node 24, 99 chunks). Set to// that plus about 300 B raw / 100 B transfer, as for #14568.- transferBytes: 2_087_890,- rawBytes: 6_930_250,+ // Skill ZIP import/export (#14181) adds 2,721 B raw / 758 B transfer to the eager Skills dialog+ // and locale strings (6,929,934 -> 6,932,655 B raw, 2,087,782 -> 2,088,540 B transfer against+ // fb104d2b57, one machine and build, Node 22.23.2, unchanged at 99 chunks). Raised by that growth.+ transferBytes: 2_088_648,+ rawBytes: 6_932_971,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/features/chat/api/skills-api.ts b/studio/frontend/src/features/chat/api/skills-api.tsindex b5eefcc7e02..045d9fe0af1 100644--- a/studio/frontend/src/features/chat/api/skills-api.ts+++ b/studio/frontend/src/features/chat/api/skills-api.ts@@ -35,6 +35,11 @@ export type SkillDraft = {export type SkillManifest = SkillRecord & { instructions: string };+export type SkillImportResult = {+ imported: SkillRecord[];+ failed: { name: string; error: string }[];+};+type SkillsSnapshot = {skills: readonly SkillRecord[];loading: boolean;@@ -250,6 +255,27 @@ export async function deleteSkill(name: string): Promise<void> {await skillsMutated();}+export async function importSkills(file: File): Promise<SkillImportResult> {+ const form = new FormData();+ form.append("file", file);+ // No Content-Type: the browser sets the multipart boundary.+ const response = await authFetch("/api/skills/import", {+ method: "POST",+ body: form,+ });+ const result = await parseResponse<SkillImportResult>(response);+ await skillsMutated();+ return result;+}++export async function exportSkill(name: string): Promise<Blob> {+ const response = await authFetch(+ `/api/skills/${encodeURIComponent(name)}/export`,+ );+ if (!response.ok) await parseResponse<unknown>(response);+ return response.blob();+}+// authFetch has no deadline, so a hung /api/skills must not stall the send.const SETTLE_TIMEOUT_MS = 3000;diff --git a/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsxindex 024e0d0a6c4..3696638f3e7 100644--- a/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx+++ b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx@@ -37,17 +37,23 @@ import {ChevronLeftStandardIcon,ChevronRightStandardIcon,} from "@/lib/chevron-icons";+import { downloadFile, isDownloadCancelled } from "@/lib/native-files";+import { Tick02Icon } from "@/lib/tick-icon";import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";import {+ Cancel01Icon,+ Download01Icon,MoreHorizontalIcon,PlusSignIcon,Refresh01Icon,Scroll01Icon,Search01Icon,+ Upload01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import {+ type ChangeEvent,type ReactElement,type ReactNode,useEffect,@@ -59,12 +65,15 @@ import {import {createSkill,deleteSkill,+ exportSkill,getSkillManifest,+ importSkills,isValidSkillName,listSkills,setAllSkillsEnabled,setSkillEnabled,type SkillDraft,+ type SkillImportResult,type SkillManifest,type SkillRecord,updateSkill,@@ -91,6 +100,37 @@ function isEditable(skill: SkillRecord): boolean {return skill.valid && skill.source === "agents" && !skill.linked;}+function ImportResultList({ imported, failed }: SkillImportResult): ReactElement {+ return (+ <ul className="flex max-h-48 flex-col gap-1 overflow-y-auto rounded-md border border-border/60 px-2.5 py-2">+ {/* Failures first, so the scroll cap never hides the rows that need attention. */}+ {failed.map((failure) => (+ <li key={`failed:${failure.name}`} className="min-w-0">+ <div className="flex min-w-0 items-center gap-1.5">+ <HugeiconsIcon+ icon={Cancel01Icon}+ strokeWidth={2}+ className="size-3.5 shrink-0 text-destructive"+ />+ <span className="truncate">{failure.name}</span>+ </div>+ <p className="pl-5 text-xs break-words text-muted-foreground">{failure.error}</p>+ </li>+ ))}+ {imported.map((skill) => (+ <li key={keyOf(skill)} className="flex min-w-0 items-center gap-1.5">+ <HugeiconsIcon+ icon={Tick02Icon}+ strokeWidth={2}+ className="size-3.5 shrink-0 text-emerald-600 dark:text-emerald-500"+ />+ <span className="truncate">{skill.name}</span>+ </li>+ ))}+ </ul>+ );+}+export function ChatSkillsDialog({open,onOpenChange,@@ -112,6 +152,9 @@ export function ChatSkillsDialog({const manifestGeneration = useRef(0);const [pending, setPending] = useState<string | null>(null);const [creating, setCreating] = useState(false);+ const [importing, setImporting] = useState(false);+ const [exporting, setExporting] = useState(false);+ const fileInputRef = useRef<HTMLInputElement>(null);const [changing, setChanging] = useState<string | null>(null);const [confirmingDelete, setConfirmingDelete] = useState<SkillRecord | null>(null);const [confirmingDiscard, setConfirmingDiscard] = useState<(() => void) | null>(null);@@ -212,7 +255,7 @@ export function ChatSkillsDialog({const newStarted =newDraft.name !== "" || newDraft.description !== "" || newDraft.instructions !== "";const dirty = view.kind === "new" ? newStarted : draft !== null;- const busy = pending !== null || creating;+ const busy = pending !== null || creating || importing || exporting;const trimmedName = newDraft.name.trim();const nameInvalid = trimmedName.length > 0 && !isValidSkillName(trimmedName);@@ -345,6 +388,57 @@ export function ChatSkillsDialog({}}+ async function importFile(event: ChangeEvent<HTMLInputElement>) {+ const file = event.target.files?.[0];+ // Lets the same file fire change again.+ event.target.value = "";+ if (!file || importing) return;+ setImporting(true);+ try {+ const { imported, failed } = await importSkills(file);+ const count = imported.length;+ if (failed.length === 0) {+ toast.success(t(count === 1 ? "skills.importedOne" : "skills.importedMany", { count }), {+ description: <ImportResultList imported={imported} failed={failed} />,+ });+ if (count === 1) {+ // Never pull the user out of a skill they opened during the upload.+ setView((current) =>+ current.kind === "library" ? { kind: "skill", key: keyOf(imported[0]) } : current,+ );+ readManifest(imported[0]);+ }+ } else if (count === 0 && failed.length === 1) {+ toast.error(t("skills.importError"), { description: failed[0].error });+ } else {+ const notify = count > 0 ? toast.warning : toast.error;+ notify(t("skills.importPartial", { added: count, total: count + failed.length }), {+ description: <ImportResultList imported={imported} failed={failed} />,+ });+ }+ } catch (cause) {+ toast.error(t("skills.importError"), { description: describe(cause) });+ } finally {+ setImporting(false);+ }+ }++ async function exportSelected() {+ if (!selected || exporting) return;+ const name = selected.name;+ setExporting(true);+ try {+ const blob = await exportSkill(name);+ await downloadFile(blob, `${name}.zip`, "application/zip");+ } catch (cause) {+ if (!isDownloadCancelled(cause)) {+ toast.error(t("skills.exportError"), { description: describe(cause) });+ }+ } finally {+ setExporting(false);+ }+ }+async function remove(skill: SkillRecord) {if (pending !== null) return;setPending(skill.name);@@ -382,8 +476,9 @@ export function ChatSkillsDialog({<DialogDescription>{t("skills.description")}</DialogDescription></DialogHeader>- <div className="flex items-center gap-2">- <div className="relative min-w-0 flex-1">+ {/* Phones: search takes its own row, the actions wrap under it. */}+ <div className="flex items-center gap-2 max-sm:flex-wrap max-sm:justify-end">+ <div className="relative min-w-0 flex-1 max-sm:basis-full"><HugeiconsIconicon={Search01Icon}strokeWidth={2}@@ -450,6 +545,25 @@ export function ChatSkillsDialog({</DropdownMenuItem></DropdownMenuContent></DropdownMenu>+ <input+ ref={fileInputRef}+ type="file"+ accept=".zip,application/zip"+ className="hidden"+ onChange={(event) => void importFile(event)}+ />+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={importing}+ aria-label={t("skills.import")}+ title={t("skills.import")}+ onClick={() => fileInputRef.current?.click()}+ >+ {importing ? <Spinner /> : <HugeiconsIcon icon={Upload01Icon} strokeWidth={2} />}+ <span className="max-sm:hidden">{t("skills.import")}</span>+ </Button><Button variant="secondary" type="button" size="sm" onClick={openNew}><HugeiconsIcon icon={PlusSignIcon} strokeWidth={2} />{t("skills.newSkill")}@@ -641,6 +755,17 @@ export function ChatSkillsDialog({</label>) : null}<div className="ml-auto flex items-center gap-2">+ {readable ? (+ <Button+ type="button"+ variant="outline"+ disabled={busy}+ onClick={() => void exportSelected()}+ >+ {exporting ? <Spinner /> : <HugeiconsIcon icon={Download01Icon} strokeWidth={2} />}+ {t("common.export")}+ </Button>+ ) : null}{view.kind === "new" ? (<><Button type="button" variant="ghost" disabled={creating} onClick={goLibrary}>diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex dbc33ec04b5..0ca062ced7f 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -4199,6 +4199,7 @@ export const ar = {disable: "تعطيل {name}",updateError: "تعذّر تحديث المهارة",newSkill: "مهارة جديدة",+ import: "استيراد",delete: "حذف {name}",createDescription: "تُحفظ كملف SKILL.md في مجلد جديد ضمن ~/.agents/skills وتُفعَّل فور إنشائها.",nameLabel: "الاسم",@@ -4216,9 +4217,14 @@ export const ar = {created: "تم إنشاء {name}",saved: "تم حفظ {name}",deleted: "تم حذف {name}",+ importedOne: "تمت إضافة {count} مهارة",+ importedMany: "تمت إضافة {count} مهارات",+ importPartial: "تمت إضافة {added} من أصل {total} من المهارات",saveError: "تعذّر حفظ المهارة",openError: "تعذّر فتح المهارة",deleteError: "تعذّر حذف المهارة",+ importError: "تعذّر استيراد المهارة",+ exportError: "تعذّر تصدير المهارة",deleteTitle: "حذف المهارة",deleteDescription: 'هل تريد حذف "{name}" وكل ما في مجلدها ضمن ~/.agents/skills؟ لا يمكن التراجع عن هذا الإجراء.',search: "ابحث عن المهارات بالاسم أو الوصف…",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 301588080be..59575ebc367 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -4274,6 +4274,7 @@ export const de = {disable: "{name} deaktivieren",updateError: "Fähigkeit konnte nicht aktualisiert werden",newSkill: "Neue Fähigkeit",+ import: "Importieren",delete: "{name} löschen",createDescription: "Wird als SKILL.md in einem neuen Ordner unter ~/.agents/skills gespeichert und sofort aktiviert.",nameLabel: "Name",@@ -4291,9 +4292,14 @@ export const de = {created: "{name} erstellt",saved: "{name} gespeichert",deleted: "{name} gelöscht",+ importedOne: "{count} Fähigkeit hinzugefügt",+ importedMany: "{count} Fähigkeiten hinzugefügt",+ importPartial: "{added} von {total} Fähigkeiten hinzugefügt",saveError: "Fähigkeit konnte nicht gespeichert werden",openError: "Fähigkeit konnte nicht geöffnet werden",deleteError: "Fähigkeit konnte nicht gelöscht werden",+ importError: "Fähigkeit konnte nicht importiert werden",+ exportError: "Fähigkeit konnte nicht exportiert 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…",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 8b0303eb906..9443d1ae0cf 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -4249,6 +4249,7 @@ export const en = {disable: "Disable {name}",updateError: "Could not update skill",newSkill: "New skill",+ import: "Import",delete: "Delete {name}",createDescription: "Saved as SKILL.md in a new folder under ~/.agents/skills, and enabled as soon as it exists.",nameLabel: "Name",@@ -4266,9 +4267,14 @@ export const en = {created: "Created {name}",saved: "Saved {name}",deleted: "Deleted {name}",+ importedOne: "{count} skill added",+ importedMany: "{count} skills added",+ importPartial: "Added {added} of {total} skills",saveError: "Could not save skill",openError: "Could not open skill",deleteError: "Could not delete skill",+ importError: "Could not import skill",+ exportError: "Could not export 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…",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 130f8dcc1f9..9fc82aee40f 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -4273,6 +4273,7 @@ export const es = {disable: "Desactivar {name}",updateError: "No se pudo actualizar la habilidad",newSkill: "Nueva habilidad",+ import: "Importar",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",@@ -4290,9 +4291,14 @@ export const es = {created: "{name} creada",saved: "{name} guardada",deleted: "{name} eliminada",+ importedOne: "{count} habilidad añadida",+ importedMany: "{count} habilidades añadidas",+ importPartial: "{added} de {total} habilidades añadidas",saveError: "No se pudo guardar la habilidad",openError: "No se pudo abrir la habilidad",deleteError: "No se pudo eliminar la habilidad",+ importError: "No se pudo importar la habilidad",+ exportError: "No se pudo exportar 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…",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 0d674bddf6a..8603c89e43e 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -4285,6 +4285,7 @@ export const fr = {disable: "Désactiver {name}",updateError: "Impossible de mettre à jour la compétence",newSkill: "Nouvelle compétence",+ import: "Importer",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",@@ -4302,9 +4303,14 @@ export const fr = {created: "{name} créée",saved: "{name} enregistrée",deleted: "{name} supprimée",+ importedOne: "{count} compétence ajoutée",+ importedMany: "{count} compétences ajoutées",+ importPartial: "{added} compétences sur {total} ajoutées",saveError: "Impossible d'enregistrer la compétence",openError: "Impossible d'ouvrir la compétence",deleteError: "Impossible de supprimer la compétence",+ importError: "Impossible d'importer la compétence",+ exportError: "Impossible d'exporter 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…",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 2fb419ed900..36588cffde8 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -4309,6 +4309,7 @@ export const he = {disable: "השבת את {name}",updateError: "עדכון המיומנות נכשל",newSkill: "מיומנות חדשה",+ import: "ייבוא",delete: "מחק את {name}",createDescription:"נשמרת כ-SKILL.md בתיקייה חדשה תחת ~/.agents/skills, ומופעלת מיד עם יצירתה.",@@ -4331,9 +4332,14 @@ export const he = {created: "{name} נוצרה",saved: "{name} נשמרה",deleted: "{name} נמחקה",+ importedOne: "נוספה {count} מיומנות",+ importedMany: "נוספו {count} מיומנויות",+ importPartial: "נוספו {added} מתוך {total} מיומנויות",saveError: "שמירת המיומנות נכשלה",openError: "פתיחת המיומנות נכשלה",deleteError: "מחיקת המיומנות נכשלה",+ importError: "ייבוא המיומנות נכשל",+ exportError: "ייצוא המיומנות נכשל",deleteTitle: "מחיקת מיומנות",deleteDescription:'למחוק את "{name}" ואת כל מה שבתיקייה שלה תחת ~/.agents/skills? פעולה זו אינה ניתנת לביטול.',diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 6779ccce58f..eff99ca88e8 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -4210,6 +4210,7 @@ export const hi = {disable: "{name} अक्षम करें",updateError: "कौशल अपडेट नहीं हो सका",newSkill: "नया कौशल",+ import: "इंपोर्ट करें",delete: "{name} हटाएँ",createDescription: "~/.agents/skills के नए फ़ोल्डर में SKILL.md के रूप में सहेजा जाता है और बनते ही सक्षम हो जाता है।",nameLabel: "नाम",@@ -4227,9 +4228,14 @@ export const hi = {created: "{name} बनाया गया",saved: "{name} सहेजा गया",deleted: "{name} हटाया गया",+ importedOne: "{count} कौशल जोड़ा गया",+ importedMany: "{count} कौशल जोड़े गए",+ importPartial: "{total} में से {added} कौशल जोड़े गए",saveError: "कौशल सहेजा नहीं जा सका",openError: "कौशल खोला नहीं जा सका",deleteError: "कौशल हटाया नहीं जा सका",+ importError: "कौशल इंपोर्ट नहीं किया जा सका",+ exportError: "कौशल एक्सपोर्ट नहीं किया जा सका",deleteTitle: "कौशल हटाएँ",deleteDescription: '"{name}" और ~/.agents/skills में उसके फ़ोल्डर की सभी सामग्री हटाएँ? इसे पूर्ववत नहीं किया जा सकता।',search: "नाम या विवरण से कौशल खोजें…",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 396961c3e21..6225cea2fb6 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -4275,6 +4275,7 @@ export const it = {disable: "Disattiva {name}",updateError: "Impossibile aggiornare la competenza",newSkill: "Nuova competenza",+ import: "Importa",delete: "Elimina {name}",createDescription: "Salvata come SKILL.md in una nuova cartella in ~/.agents/skills e attivata appena esiste.",nameLabel: "Nome",@@ -4292,9 +4293,14 @@ export const it = {created: "{name} creata",saved: "{name} salvata",deleted: "{name} eliminata",+ importedOne: "{count} competenza aggiunta",+ importedMany: "{count} competenze aggiunte",+ importPartial: "{added} di {total} competenze aggiunte",saveError: "Impossibile salvare la competenza",openError: "Impossibile aprire la competenza",deleteError: "Impossibile eliminare la competenza",+ importError: "Impossibile importare la competenza",+ exportError: "Impossibile esportare 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…",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 89084377fcb..8a6e124da84 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -4149,6 +4149,7 @@ export const ja = {disable: "{name} を無効化",updateError: "スキルを更新できませんでした",newSkill: "新しいスキル",+ import: "インポート",delete: "{name} を削除",createDescription: "~/.agents/skills の新しいフォルダーに SKILL.md として保存され、作成と同時に有効になります。",nameLabel: "名前",@@ -4166,9 +4167,14 @@ export const ja = {created: "{name} を作成しました",saved: "{name} を保存しました",deleted: "{name} を削除しました",+ importedOne: "{count} 件のスキルを追加しました",+ importedMany: "{count} 件のスキルを追加しました",+ importPartial: "{total} 件中 {added} 件のスキルを追加しました",saveError: "スキルを保存できませんでした",openError: "スキルを開けませんでした",deleteError: "スキルを削除できませんでした",+ importError: "スキルをインポートできませんでした",+ exportError: "スキルをエクスポートできませんでした",deleteTitle: "スキルを削除",deleteDescription: '"{name}" と ~/.agents/skills 内のそのフォルダーの中身をすべて削除しますか?この操作は取り消せません。',search: "名前または説明でスキルを検索…",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 8b51ecb40fa..420882a0316 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -4188,6 +4188,7 @@ export const ko = {disable: "{name} 비활성화",updateError: "스킬을 업데이트할 수 없습니다",newSkill: "새 스킬",+ import: "가져오기",delete: "{name} 삭제",createDescription: "~/.agents/skills의 새 폴더에 SKILL.md로 저장되며 만들어지는 즉시 활성화됩니다.",nameLabel: "이름",@@ -4205,9 +4206,14 @@ export const ko = {created: "{name} 생성됨",saved: "{name} 저장됨",deleted: "{name} 삭제됨",+ importedOne: "스킬 {count}개 추가됨",+ importedMany: "스킬 {count}개 추가됨",+ importPartial: "스킬 {total}개 중 {added}개 추가됨",saveError: "스킬을 저장할 수 없습니다",openError: "스킬을 열 수 없습니다",deleteError: "스킬을 삭제할 수 없습니다",+ importError: "스킬을 가져올 수 없습니다",+ exportError: "스킬을 내보낼 수 없습니다",deleteTitle: "스킬 삭제",deleteDescription: '"{name}"과(와) ~/.agents/skills에 있는 해당 폴더의 모든 내용을 삭제할까요? 이 작업은 되돌릴 수 없습니다.',search: "이름 또는 설명으로 스킬 검색…",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex ca98570090b..9b051f00938 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -4233,6 +4233,7 @@ export const ptBR = {disable: "Desativar {name}",updateError: "Não foi possível atualizar a habilidade",newSkill: "Nova habilidade",+ import: "Importar",delete: "Excluir {name}",createDescription: "Salva como SKILL.md em uma nova pasta em ~/.agents/skills e ativada assim que existir.",nameLabel: "Nome",@@ -4250,9 +4251,14 @@ export const ptBR = {created: "{name} criada",saved: "{name} salva",deleted: "{name} excluída",+ importedOne: "{count} habilidade adicionada",+ importedMany: "{count} habilidades adicionadas",+ importPartial: "{added} de {total} habilidades adicionadas",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",+ importError: "Não foi possível importar a habilidade",+ exportError: "Não foi possível exportar 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…",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex aaed0fb34ef..ec56b42ec78 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -4231,6 +4231,7 @@ export const ru = {disable: "Отключить {name}",updateError: "Не удалось обновить навык",newSkill: "Новый навык",+ import: "Импорт",delete: "Удалить {name}",createDescription: "Сохраняется как SKILL.md в новой папке в ~/.agents/skills и сразу включается.",nameLabel: "Имя",@@ -4248,9 +4249,14 @@ export const ru = {created: "{name} создан",saved: "{name} сохранён",deleted: "{name} удалён",+ importedOne: "Добавлен {count} навык",+ importedMany: "Добавлено навыков: {count}",+ importPartial: "Добавлено навыков: {added} из {total}",saveError: "Не удалось сохранить навык",openError: "Не удалось открыть навык",deleteError: "Не удалось удалить навык",+ importError: "Не удалось импортировать навык",+ exportError: "Не удалось экспортировать навык",deleteTitle: "Удалить навык",deleteDescription: "Удалить «{name}» вместе со всем содержимым его папки в ~/.agents/skills? Это действие нельзя отменить.",search: "Поиск навыков по имени или описанию…",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex e23e0215996..44c8752b8d9 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -4440,6 +4440,7 @@ export const sv = {disable: "Inaktivera {name}",updateError: "Det gick inte att uppdatera färdigheten",newSkill: "Ny färdighet",+ import: "Importera",delete: "Ta bort {name}",createDescription:"Sparas som SKILL.md i en ny mapp under ~/.agents/skills och aktiveras så snart den finns.",@@ -4464,9 +4465,14 @@ export const sv = {created: "{name} skapades",saved: "{name} sparades",deleted: "{name} togs bort",+ importedOne: "{count} färdighet lades till",+ importedMany: "{count} färdigheter lades till",+ importPartial: "{added} av {total} färdigheter lades till",saveError: "Det gick inte att spara färdigheten",openError: "Det gick inte att öppna färdigheten",deleteError: "Det gick inte att ta bort färdigheten",+ importError: "Det gick inte att importera färdigheten",+ exportError: "Det gick inte att exportera färdigheten",deleteTitle: "Ta bort färdighet",deleteDescription:'Ta bort "{name}" och allt i dess mapp under ~/.agents/skills? Detta kan inte ångras.',diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex f21dd12072b..b86cdfbe06b 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -4101,6 +4101,7 @@ export const zhCN = {disable: "禁用 {name}",updateError: "无法更新技能",newSkill: "新建技能",+ import: "导入",delete: "删除 {name}",createDescription: "保存为 ~/.agents/skills 下新文件夹中的 SKILL.md,创建后立即启用。",nameLabel: "名称",@@ -4118,9 +4119,14 @@ export const zhCN = {created: "已创建 {name}",saved: "已保存 {name}",deleted: "已删除 {name}",+ importedOne: "已添加 {count} 个技能",+ importedMany: "已添加 {count} 个技能",+ importPartial: "已添加 {total} 个技能中的 {added} 个",saveError: "无法保存技能",openError: "无法打开技能",deleteError: "无法删除技能",+ importError: "无法导入技能",+ exportError: "无法导出技能",deleteTitle: "删除技能",deleteDescription: "删除“{name}”以及 ~/.agents/skills 下其文件夹中的全部内容?此操作无法撤销。",search: "按名称或描述搜索技能…",diff --git a/studio/frontend/tests/skills-dialog-create-edit.test.ts b/studio/frontend/tests/skills-dialog-create-edit.test.tsindex c331955e3d9..8f44ff8f5e6 100644--- a/studio/frontend/tests/skills-dialog-create-edit.test.ts+++ b/studio/frontend/tests/skills-dialog-create-edit.test.ts@@ -62,7 +62,7 @@ test("the api speaks to the four skill routes", () => {});test("every write re-reads the folders and tells the other windows", () => {- assert.equal((API.match(/await skillsMutated\(\);/g) ?? []).length, 3);+ assert.equal((API.match(/await skillsMutated\(\);/g) ?? []).length, 4);assert.match(API,/async function skillsMutated\(\): Promise<void> \{\n\s*channel\?\.postMessage\("changed"\);\n\s*void refreshContextUsage\(\{ invalidate: true \}\);\n\s*await listSkills\(true\)/,diff --git a/studio/frontend/tests/skills-dialog-import-export.test.ts b/studio/frontend/tests/skills-dialog-import-export.test.tsnew file mode 100644index 00000000000..e3ca3f45b7e--- /dev/null+++ b/studio/frontend/tests/skills-dialog-import-export.test.ts@@ -0,0 +1,56 @@+// 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 IMPORT = /export async function importSkills\([^]*?\n\}\n/.exec(API)?.[0] ?? "";+const EXPORT = /export async function exportSkill\([^]*?\n\}\n/.exec(API)?.[0] ?? "";+const IMPORT_FILE = /async function importFile\([^]*?\n {2}\}\n/.exec(DIALOG)?.[0] ?? "";+const RESULT_LIST = /function ImportResultList\([^]*?\n\}\n/.exec(DIALOG)?.[0] ?? "";++test("import posts multipart without a hand-set Content-Type and re-reads the folders", () => {+ assert.match(IMPORT, /form\.append\("file", file\);/);+ assert.match(IMPORT, /authFetch\("\/api\/skills\/import", \{\n\s*method: "POST",\n\s*body: form,/);+ // A hand-set Content-Type would drop the multipart boundary.+ assert.doesNotMatch(IMPORT, /headers:/);+ assert.match(IMPORT, /await skillsMutated\(\);/);+});++test("export reads a blob and surfaces the backend's error", () => {+ assert.match(EXPORT, /`\/api\/skills\/\$\{encodeURIComponent\(name\)\}\/export`/);+ assert.match(EXPORT, /if \(!response\.ok\) await parseResponse<unknown>\(response\);/);+ assert.match(EXPORT, /return response\.blob\(\);/);+ assert.match(DIALOG, /await downloadFile\(blob, `\$\{name\}\.zip`, "application\/zip"\);/);+ assert.match(DIALOG, /if \(!isDownloadCancelled\(cause\)\)/);+});++test("only a clean one-skill import changes the view, and never out of an open skill", () => {+ assert.match(DIALOG, /event\.target\.value = "";/);+ assert.equal(IMPORT_FILE.match(/setView\(/g)?.length, 1);+ assert.match(+ IMPORT_FILE,+ /if \(failed\.length === 0\) \{[^]*?if \(count === 1\) \{[^]*?current\.kind === "library" \? \{ kind: "skill", key: keyOf\(imported\[0\]\) \} : current/,+ );+ assert.match(IMPORT_FILE, /const notify = count > 0 \? toast\.warning : toast\.error;/);+});++test("the result list puts failures, with their reason, before the added skills", () => {+ assert.ok(RESULT_LIST.indexOf("failed.map(") > 0);+ assert.ok(RESULT_LIST.indexOf("failed.map(") < RESULT_LIST.indexOf("imported.map("));+ assert.match(RESULT_LIST, /\{failure\.error\}/);+});++test("export is offered on every readable skill, not only editable ones", () => {+ assert.match(DIALOG, /\{readable \? \(\n\s*<Button[^]*?onClick=\{\(\) => void exportSelected\(\)\}/);+});++test("on phones search gets its own row and Import keeps its name as an icon", () => {+ assert.match(DIALOG, /max-sm:flex-wrap max-sm:justify-end">\n\s*<div className="relative min-w-0 flex-1 max-sm:basis-full">/);+ assert.match(DIALOG, /aria-label=\{t\("skills\.import"\)\}/);+ assert.match(DIALOG, /<span className="max-sm:hidden">\{t\("skills\.import"\)\}<\/span>/);+});