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
Add Agent Skills support to Studio (#10247)
Wasim Yousef Said85ea7304aa0a
diff --git a/pyproject.toml b/pyproject.tomlindex c39ebb92de9..25c9e30baa4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -76,6 +76,7 @@ studio = ["backend/assets/docs_ui/*","backend/core/data_recipe/oxc-validator/*.json","backend/core/data_recipe/oxc-validator/*.mjs",+ "backend/core/inference/bundled_skills/**/*.md",][tool.setuptools.packages.find]diff --git a/studio/backend/core/inference/bundled_skills/skill-creator/SKILL.md b/studio/backend/core/inference/bundled_skills/skill-creator/SKILL.mdnew file mode 100644index 00000000000..d881cc76d73--- /dev/null+++ b/studio/backend/core/inference/bundled_skills/skill-creator/SKILL.md@@ -0,0 +1,19 @@+---+name: skill-creator+description: Create a reusable Agent Skill when the user wants Studio to learn a repeatable workflow or set of instructions.+allowed-tools: create_skill+---++# Create an Agent Skill++Use this skill when the user asks to create, save, or teach Studio a reusable workflow.++1. Identify the narrow task the skill should handle and when it should activate.+2. Ask only for missing details that materially change the workflow.+3. Choose a short lowercase name with letters, numbers, and single hyphens.+4. Write a specific description that states when to use the skill.+5. Write concise Markdown instructions with ordered steps, important constraints, and a clear completion check. Do not include secrets, credentials, or machine-specific paths.+6. Call `create_skill` once with the name, description, and complete instructions. It will not overwrite an existing skill.+7. Report the created skill name and suggest invoking it with `@skill-name`.++Prefer one focused skill over a broad collection of unrelated instructions. Do not create scripts or reference files unless the user explicitly asks for them; the creation tool intentionally writes only `SKILL.md`.diff --git a/studio/backend/core/inference/skills.py b/studio/backend/core/inference/skills.pynew file mode 100644index 00000000000..b85bef3b2a0--- /dev/null+++ b/studio/backend/core/inference/skills.py@@ -0,0 +1,786 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import errno+import json+import logging+import os+import stat+import tempfile+import threading+import unicodedata+from pathlib import Path, PurePosixPath, PureWindowsPath+from typing import Optional++import yaml++from utils.account_context import is_owner_context+from utils.paths import studio_root, workspace_root+++MAX_SKILL_MD_BYTES = 512 * 1024+# Per skill, expanded: keeps a full catalog of 2,000 skills to tens of MB on the listing route.+MAX_SKILL_METADATA_BYTES = 16 * 1024+MAX_SKILL_FILE_BYTES = 2 * 1024 * 1024+MAX_SKILL_PAGE_CHARS = 8_000+MIN_SKILL_PAGE_CHARS = 64+MAX_SKILL_CATALOG_BYTES = 1_536+LARGE_SKILL_CATALOG_BYTES = 4_096+MAX_SKILL_RESOURCE_PATH_BYTES = 400+MAX_SKILL_PATH_COMPONENTS = 256+MAX_SKILLS_PER_ROOT = 1_000+MAX_SKILL_INSTRUCTIONS_BYTES = 256 * 1024++logger = logging.getLogger(__name__)++_LOCK = threading.RLock()+_OVERRIDES_NAME = "skill-overrides.json"+# dir_fd opens pin reads to the discovered directory; Windows re-walks and checks identity.+_DIR_FD_OPENS = (+ hasattr(os, "O_DIRECTORY") and os.open in os.supports_dir_fd and os.stat in os.supports_dir_fd+)+_WINDOWS_RESERVED_STEMS = frozenset(+ {"con", "prn", "aux", "nul", "conin$", "conout$"}+ | {f"com{index}" for index in range(1, 10)}+ | {f"lpt{index}" for index in range(1, 10)}+ | {f"com{index}" for index in "¹²³"}+ | {f"lpt{index}" for index in "¹²³"}+)+_WINDOWS_INVALID_CHARS = frozenset('<>:"|?*')+++class SkillError(ValueError):+ pass+++class SkillNotFoundError(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.")+ normalized = unicodedata.normalize("NFKC", name.strip())+ if (+ len(normalized) > 64+ or normalized != normalized.lower()+ or normalized.startswith("-")+ or normalized.endswith("-")+ or "--" in normalized+ or not all(+ "a" <= character <= "z" or "0" <= character <= "9" or character == "-"+ for character in normalized+ )+ ):+ raise SkillError("Skill name must be 1-64 lowercase letters, numbers, or single hyphens.")+ if normalized.casefold() in _WINDOWS_RESERVED_STEMS:+ raise SkillError("Skill name cannot use a Windows reserved device name.")+ return normalized+++def _is_linked_path(path: Path) -> bool:+ try:+ status = os.lstat(path)+ except OSError:+ return False+ attributes = getattr(status, "st_file_attributes", 0)+ reparse_point = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)+ return stat.S_ISLNK(status.st_mode) or bool(reparse_point and attributes & reparse_point)+++def _require_unlinked_agent_path(base: Path, *paths: Path) -> None:+ for path in paths:+ if _is_linked_path(path) or (path.exists() and not path.is_dir()):+ raise SkillError("Agent Skills directory is missing or unsafe.")+ try:+ path.relative_to(base)+ except ValueError as exc:+ raise SkillError("Agent Skills directory is missing or unsafe.") from exc+++def _write_new_skill_manifest(+ base: Path,+ name: str,+ manifest: bytes,+ *,+ 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,)+ _require_unlinked_agent_path(base, *ancestors)+ root.mkdir(mode = 0o700, parents = True, exist_ok = True)+ _require_unlinked_agent_path(base, *ancestors)++ skill_dir = root / name+ skill_dir.mkdir(mode = 0o700)+ skill_file = skill_dir / "SKILL.md"+ directories = (*ancestors, skill_dir)+ expected = [os.stat(path, follow_symlinks = False) for path in directories]++ def revalidate(descriptor: int) -> None:+ _require_unlinked_agent_path(base, *directories)+ current = [os.stat(path, follow_symlinks = False) for path in directories]+ file_status = os.stat(skill_file, follow_symlinks = False)+ if (+ not all(map(os.path.samestat, expected, current))+ or _is_linked_path(skill_file)+ or not os.path.samestat(file_status, os.fstat(descriptor))+ ):+ raise SkillError("Agent Skill path changed while the manifest was being written.")++ descriptor: Optional[int] = None++ created_status = None+ try:+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)+ descriptor = os.open(skill_file, flags, 0o600)++ created_status = os.fstat(descriptor)+ revalidate(descriptor)+ with os.fdopen(descriptor, "wb") as handle:+ descriptor = None+ handle.write(manifest)+ handle.flush()+ os.fsync(handle.fileno())+ revalidate(handle.fileno())+ except Exception:+ # Closed before the cleanup: Windows refuses to unlink a file with an open handle.+ if descriptor is not None:+ os.close(descriptor)+ descriptor = None+ try:+ current = [os.stat(path, follow_symlinks = False) for path in directories]+ if all(map(os.path.samestat, expected, current)):+ # Remove only the manifest this call created; another writer's file stays.+ if created_status is not None and os.path.samestat(+ os.stat(skill_file, follow_symlinks = False), created_status+ ):+ skill_file.unlink()+ skill_dir.rmdir()+ except OSError:+ pass+ raise+ finally:+ if descriptor is not None:+ os.close(descriptor)+++def _open_within(root: Path, identity, parts: tuple[str, ...]) -> int:+ """Open ``root/parts`` one component at a time relative to the previous directory+ descriptor, so a root or ancestor swapped for a link mid-walk cannot redirect the read."""+ flags = os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_NONBLOCK", 0)+ descriptor = os.open(root, flags | os.O_DIRECTORY)+ try:+ if identity is not None and not os.path.samestat(os.fstat(descriptor), identity):+ raise SkillError("Skill directory changed after it was selected.")+ for index, part in enumerate(parts):+ last = index == len(parts) - 1+ part_flags = flags | (getattr(os, "O_BINARY", 0) if last else os.O_DIRECTORY)+ opened = os.open(part, part_flags, dir_fd = descriptor)+ os.close(descriptor)+ descriptor = opened+ except BaseException:+ os.close(descriptor)+ raise+ return descriptor+++def _read_limited(+ path: Path,+ limit: int,+ *,+ contained_in: Optional[Path] = None,+ identity = None,+) -> bytes:+ descriptor: Optional[int] = None+ try:+ if contained_in is not None and _is_linked_path(path):+ raise SkillError("Skill resources cannot use symbolic links or reparse points.")+ flags = (+ os.O_RDONLY+ | getattr(os, "O_BINARY", 0)+ | getattr(os, "O_NONBLOCK", 0)+ | getattr(os, "O_NOFOLLOW", 0)+ )+ if contained_in is not None and _DIR_FD_OPENS:+ descriptor = _open_within(contained_in, identity, path.relative_to(contained_in).parts)+ else:+ descriptor = os.open(path, flags)+ status = os.fstat(descriptor)+ if not stat.S_ISREG(status.st_mode):+ raise SkillError(f"{path.name} must be a regular file.")+ if contained_in is not None and not _DIR_FD_OPENS:+ if _is_linked_path(contained_in):+ raise SkillError("Skill resources cannot use symbolic links or reparse points.")+ root_status = os.stat(contained_in, follow_symlinks = False)+ if identity is not None and not os.path.samestat(root_status, identity):+ raise SkillError("Skill directory changed after it was selected.")+ root = contained_in.resolve(strict = True)+ relative = path.relative_to(contained_in)+ current = contained_in+ for part in relative.parts:+ current = current / part+ if _is_linked_path(current):+ raise SkillError("Skill resources cannot use symbolic links or reparse points.")+ path.resolve(strict = True).relative_to(root)+ current_status = os.stat(path, follow_symlinks = False)+ if not os.path.samestat(status, current_status):+ raise SkillError("Skill resource changed while it was being opened.")+ if status.st_size > limit:+ raise SkillError(f"{path.name} exceeds the {limit // 1024} KB limit.")+ with os.fdopen(descriptor, "rb") as handle:+ descriptor = None+ raw = handle.read(limit + 1)+ except SkillError:+ raise+ except (OSError, ValueError) as exc:+ if isinstance(exc, OSError) and exc.errno == errno.ELOOP:+ raise SkillError(+ "Skill resources cannot use symbolic links or reparse points."+ ) from exc+ raise SkillError(f"Could not read {path.name}.") from exc+ finally:+ if descriptor is not None:+ try:+ os.close(descriptor)+ except OSError:+ pass+ if len(raw) > limit:+ raise SkillError(f"{path.name} exceeds the {limit // 1024} KB limit.")+ return raw+++def _parse_skill_markdown(raw: bytes, parent_name: Optional[str] = None) -> dict:+ 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()+ 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.+ closing = next(+ (index for index, line in enumerate(lines[1:], 1) if line.rstrip() == "---"), None+ )+ if closing is None:+ raise SkillError("SKILL.md YAML frontmatter is not closed.")+ try:+ frontmatter = yaml.safe_load("\n".join(lines[1:closing]))+ except (+ yaml.YAMLError,+ AttributeError,+ IndexError,+ KeyError,+ OverflowError,+ RecursionError,+ ValueError,+ ) as exc:+ raise SkillError("SKILL.md contains invalid YAML frontmatter.") from exc+ if not isinstance(frontmatter, dict):+ raise SkillError("SKILL.md frontmatter must be a mapping.")++ name = _normalize_skill_name(frontmatter.get("name"))+ if parent_name is not None and name != parent_name:+ raise SkillError(f"Skill name '{name}' must match its parent directory '{parent_name}'.")+ description = frontmatter.get("description")+ if not isinstance(description, str) or not description.strip() or len(description) > 1024:+ raise SkillError("Skill description must be 1-1024 characters.")++ compatibility = frontmatter.get("compatibility")+ if compatibility is not None and (+ not isinstance(compatibility, str) or not compatibility or len(compatibility) > 500+ ):+ raise SkillError("Skill compatibility must be 1-500 characters when provided.")+ metadata = frontmatter.get("metadata")+ if metadata is not None and (+ not isinstance(metadata, dict)+ or any(+ not isinstance(key, str) or not isinstance(value, str)+ for key, value in metadata.items()+ )+ ):+ raise SkillError("Skill metadata keys and values must be strings.")+ # Aliases let a small file expand on serialisation; bound the expanded size.+ if (+ metadata is not None+ and sum(len(k) + len(v) for k, v in metadata.items()) > MAX_SKILL_METADATA_BYTES+ ):+ raise SkillError("Skill metadata exceeds the 16 KB limit.")+ allowed_tools = frontmatter.get("allowed-tools")+ if allowed_tools is not None and (+ not isinstance(allowed_tools, str) or len(allowed_tools) > 1024+ ):+ raise SkillError(+ "Skill allowed-tools must be a space-separated string of at most 1024 characters."+ )+ license_value = frontmatter.get("license")+ if license_value is not None and (+ not isinstance(license_value, str) or len(license_value) > 1024+ ):+ raise SkillError("Skill license must be a string of at most 1024 characters.")++ parsed = {+ "name": name,+ "description": description.strip(),+ **({"license": license_value} if license_value is not None else {}),+ **({"compatibility": compatibility} if compatibility is not None else {}),+ **({"metadata": metadata} if metadata is not None else {}),+ **({"allowed_tools": allowed_tools} if allowed_tools is not None else {}),+ }+ try:+ json.dumps(parsed, ensure_ascii = False).encode("utf-8")+ except UnicodeEncodeError as exc:+ raise SkillError("Skill fields must contain valid Unicode.") from exc+ return parsed+++def _validate_skill_dir(skill_dir: Path) -> tuple[dict, Path]:+ """Metadata plus the real directory. A linked entry (npx skills, Zed, dotfiles) is+ followed once here; every later read is pinned to the resolved directory, not the link."""+ target = skill_dir+ if _is_linked_path(skill_dir):+ try:+ target = skill_dir.resolve(strict = True)+ except OSError as exc:+ raise SkillError("Skill directory is missing or unsafe.") from exc+ if _is_linked_path(target) or not target.is_dir():+ raise SkillError("Skill directory is missing or unsafe.")+ manifest = target / "SKILL.md"+ if _is_linked_path(manifest) or not manifest.is_file():+ raise SkillError("Skill directory must contain a regular SKILL.md file.")+ metadata = _parse_skill_markdown(+ _read_limited(manifest, MAX_SKILL_MD_BYTES, contained_in = target),+ skill_dir.name,+ )+ return metadata, target+++_BUNDLED_ROOT = ("bundled", Path(__file__).with_name("bundled_skills"))+_MANAGED_SKILLS_DIR = "skills"+++def _owner_home() -> Path:+ # Seam for tests: the installation owner's home, where ~/.agents and ~/.claude live.+ return Path.home()+++def _skill_roots(home: Optional[Path] = None) -> tuple[tuple[str, Path], ...]:+ if home is not None:+ base = home+ return (("agents", base / ".agents" / "skills"), ("claude", base / ".claude" / "skills"))+ if not is_owner_context():+ # Managed accounts read their own workspace plus bundled skills, never the host home.+ return (("agents", workspace_root() / _MANAGED_SKILLS_DIR), _BUNDLED_ROOT)+ base = _owner_home()+ return (+ ("agents", base / ".agents" / "skills"),+ ("claude", base / ".claude" / "skills"),+ _BUNDLED_ROOT,+ )+++def _default_enabled(source: str) -> bool:+ # Bundled skills ship disabled so a fresh install does not add skill tools to every chat.+ return source != "bundled"+++def _override_path() -> Path:+ # The owner keeps the install-root file; a managed account has its own inside its workspace.+ root = studio_root() if is_owner_context() else workspace_root()+ return root / _OVERRIDES_NAME+++def _load_overrides() -> dict[str, bool]:+ # A damaged toggle file counts as empty; the next toggle rewrites it.+ path = _override_path()+ try:+ payload = json.loads(path.read_text(encoding = "utf-8"))+ except FileNotFoundError:+ return {}+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:+ logger.warning("Ignoring unreadable skill overrides at %s: %s", path, exc)+ return {}+ if not isinstance(payload, dict):+ logger.warning("Ignoring skill overrides at %s: not a mapping", path)+ return {}+ overrides: dict[str, bool] = {}+ for name, enabled in payload.items():+ try:+ normalized = _normalize_skill_name(name)+ except SkillError:+ logger.warning("Ignoring skill override for invalid name %r in %s", name, path)+ continue+ if not isinstance(enabled, bool):+ logger.warning("Ignoring non-boolean skill override for %s in %s", normalized, path)+ continue+ overrides[normalized] = enabled+ return overrides+++def _save_overrides(overrides: dict[str, bool]) -> None:+ path = _override_path()+ path.parent.mkdir(parents = True, exist_ok = True)+ fd, temporary_name = tempfile.mkstemp(+ prefix = ".skill-overrides-", suffix = ".json", dir = path.parent+ )+ try:+ with os.fdopen(fd, "w", encoding = "utf-8") as handle:+ json.dump(overrides, handle, sort_keys = True, separators = (",", ":"))+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary_name, path)+ except Exception:+ try:+ os.unlink(temporary_name)+ except OSError:+ pass+ raise+++def _candidate_dirs(root: Path) -> list[Path]:+ try:+ resolved_root = root.expanduser().resolve(strict = True)+ if not resolved_root.is_dir():+ return []+ candidates = sorted(resolved_root.iterdir(), key = lambda path: path.name)+ except (FileNotFoundError, NotADirectoryError):+ return []+ except OSError as exc:+ raise SkillError("Could not scan an Agent Skills directory.") from exc+ visible = []+ for candidate in candidates:+ if candidate.name.startswith("."):+ continue+ try:+ candidate.name.encode("utf-8")+ except UnicodeEncodeError:+ continue+ # Stray files are skipped; links still go through validation so they are reported.+ try:+ if not candidate.is_dir() and not _is_linked_path(candidate):+ continue+ except OSError:+ continue+ visible.append(candidate)+ if len(visible) > MAX_SKILLS_PER_ROOT:+ raise SkillError(f"Agent Skills directory exceeds the {MAX_SKILLS_PER_ROOT}-entry limit.")+ return visible+++def _discover(home: Optional[Path]) -> list[tuple[dict, Optional[Path], Optional[os.stat_result]]]:+ """Every record with, for a valid skill, the directory it was read from and that+ directory's identity at discovery time, so a later read can refuse a swapped tree."""+ overrides = _load_overrides()+ found: list[tuple[dict, Optional[Path], Optional[os.stat_result]]] = []+ selected: dict[str, dict] = {}+ for source, root in _skill_roots(home):+ try:+ candidates = _candidate_dirs(root)+ except SkillError as exc:+ # One unreadable or oversized root must not hide the other roots' skills.+ found.append(+ (+ {+ "name": source,+ "description": "",+ "source": source,+ "enabled": False,+ "valid": False,+ "shadowed": False,+ "error": str(exc),+ },+ None,+ None,+ )+ )+ continue+ for candidate in candidates:+ base = {+ "name": candidate.name,+ "description": "",+ "source": source,+ "enabled": False,+ "valid": False,+ "shadowed": False,+ }+ try:+ metadata, skill_dir = _validate_skill_dir(candidate)+ identity = os.stat(skill_dir, follow_symlinks = False)+ except OSError:+ found.append(+ ({**base, "error": "Skill directory is missing or unsafe."}, None, None)+ )+ continue+ except SkillError as exc:+ found.append(({**base, "error": str(exc)}, None, None))+ continue+ name = metadata["name"]+ if name in selected:+ found.append(+ (+ {+ **base,+ **metadata,+ "valid": True,+ "shadowed": True,+ "shadowed_by": selected[name]["source"],+ },+ None,+ None,+ )+ )+ continue+ record = {+ **base,+ **metadata,+ "enabled": overrides.get(name, _default_enabled(source)),+ "valid": True,+ }+ selected[name] = record+ found.append((record, skill_dir, identity))+ return found+++def list_skills(*, home: Optional[Path] = None) -> list[dict]:+ with _LOCK:+ return [record for record, _, _ in _discover(home)]+++def enabled_skills(*, home: Optional[Path] = None) -> list[dict]:+ return [+ skill+ for skill in list_skills(home = home)+ if skill["valid"] and not skill["shadowed"] and skill["enabled"]+ ]+++def _selected_skill(+ name: str, *, home: Optional[Path] = None+) -> tuple[dict, Path, Optional[os.stat_result]]:+ normalized = _normalize_skill_name(name)+ for record, skill_dir, identity in _discover(home):+ if record["valid"] and not record["shadowed"] and record["name"] == normalized:+ return record, skill_dir, identity+ raise SkillNotFoundError(f"Skill '{normalized}' was not found.")+++def set_skill_enabled(+ name: str,+ enabled: bool,+ *,+ home: Optional[Path] = None,+) -> dict:+ if not isinstance(enabled, bool):+ raise SkillError("Skill enabled state must be a boolean.")+ with _LOCK:+ record, _, _ = _selected_skill(name, home = home)+ overrides = _load_overrides()+ if enabled == _default_enabled(record["source"]):+ overrides.pop(record["name"], None)+ else:+ overrides[record["name"]] = enabled+ _save_overrides(overrides)+ return {**record, "enabled": enabled}+++def create_skill(+ name: str,+ description: str,+ instructions: str,+ *,+ home: Optional[Path] = None,+) -> dict:+ normalized = _normalize_skill_name(name)+ 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():+ raise SkillError("Skill instructions must be non-empty UTF-8 text.")+ try:+ instruction_bytes = instructions.strip().encode("utf-8")+ except UnicodeEncodeError as exc:+ raise SkillError("Skill instructions must be valid UTF-8 text.") from exc+ if len(instruction_bytes) > MAX_SKILL_INSTRUCTIONS_BYTES:+ raise SkillError("Skill instructions exceed the 256 KB limit.")++ 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")+ 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)+ # 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:+ overrides = _load_overrides()+ had_override = normalized in overrides+ if had_override:+ enabled_overrides = dict(overrides)+ enabled_overrides.pop(normalized)+ try:+ _save_overrides(enabled_overrides)+ except OSError as exc:+ raise SkillError("Could not update skill enable overrides.") from exc++ try:+ try:+ _write_new_skill_manifest(base, normalized, manifest, root = root)+ except FileExistsError as exc:+ raise SkillError(f"Skill '{normalized}' already exists.") from exc+ except OSError as exc:+ raise SkillError(f"Could not create skill '{normalized}'.") from exc+ except Exception:+ if had_override:+ try:+ _save_overrides(overrides)+ except OSError:+ pass+ raise++ # The path as the user would name it, not the resolved host path.+ display = "~/.agents/skills" if root is None else f"{_MANAGED_SKILLS_DIR}"+ return {+ **metadata,+ "source": "agents",+ "enabled": True,+ "valid": True,+ "shadowed": False,+ "path": f"{display}/{normalized}/SKILL.md",+ }+++def format_skill_catalog(+ skills: Optional[list[dict]] = None, *, budget: int = MAX_SKILL_CATALOG_BYTES+) -> str:+ candidates = enabled_skills() if skills is None else skills+ lines: list[str] = []+ size = 0+ dropped = 0+ for skill in candidates:+ line = f"- {skill['name']}: {' '.join(skill['description'].split())}"+ encoded = line.encode("utf-8")+ separator = 1 if lines else 0+ if size + separator + len(encoded) > budget:+ dropped += 1+ continue+ lines.append(line)+ size += separator + len(encoded)+ if dropped:+ # read_skill accepts any enabled name, so the model must know the list is cut.+ lines.append(f"- {dropped} more enabled skills not listed; mention one as @skill-name.")+ return "\n".join(lines)+++def _normalize_resource_path(resource: str) -> PurePosixPath:+ if not isinstance(resource, str):+ raise SkillError("Skill resource path must be a string.")+ normalized = resource.replace("\\", "/").strip() or "SKILL.md"+ path = PurePosixPath(normalized)+ if (+ normalized.startswith("/")+ or PureWindowsPath(resource).is_absolute()+ or not path.parts+ or len(path.parts) > MAX_SKILL_PATH_COMPONENTS+ or any(part in ("", ".", "..") for part in path.parts)+ or any(PureWindowsPath(part).drive for part in path.parts)+ or any(+ not part.rstrip(" .")+ or part != part.rstrip(" .")+ or any(character in _WINDOWS_INVALID_CHARS or ord(character) < 32 for character in part)+ for part in path.parts+ )+ ):+ raise SkillError("Skill resource path must stay inside the skill directory.")+ # Rejected on every OS: a portable skill cannot carry a name Windows refuses.+ if any(part.split(".", 1)[0].casefold() in _WINDOWS_RESERVED_STEMS for part in path.parts):+ raise SkillError("Skill resource path cannot use a Windows reserved device name.")+ try:+ if len(path.as_posix().encode("utf-8")) > MAX_SKILL_RESOURCE_PATH_BYTES or any(+ len(part.encode("utf-8")) > 255 for part in path.parts+ ):+ raise SkillError("Skill resource path is too long.")+ except UnicodeEncodeError as exc:+ raise SkillError("Skill resource path must contain valid Unicode.") from exc+ return path+++def read_skill_resource(+ name: str,+ resource: str = "SKILL.md",+ offset: int = 0,+ *,+ page_chars: int = MAX_SKILL_PAGE_CHARS,+ home: Optional[Path] = None,+) -> str:+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:+ raise SkillError("Skill resource offset must be a non-negative integer.")+ if isinstance(page_chars, bool) or not isinstance(page_chars, int) or page_chars <= 0:+ raise SkillError("Skill resource page size must be a positive integer.")+ with _LOCK:+ record, skill_dir, identity = _selected_skill(name, home = home)+ if not record["enabled"]:+ raise SkillError(f"Skill '{record['name']}' is disabled.")+ path = _normalize_resource_path(resource)+ try:+ if _is_linked_path(skill_dir):+ raise SkillError("Skill resources cannot use symbolic links or reparse points.")+ 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.")+ root = skill_dir.resolve(strict = True)+ candidate = skill_dir.joinpath(*path.parts)+ current = skill_dir+ for part in path.parts:+ current = current / part+ if _is_linked_path(current):+ raise SkillError("Skill resources cannot use symbolic links or reparse points.")+ candidate.resolve(strict = True).relative_to(root)+ except SkillError:+ raise+ except (FileNotFoundError, NotADirectoryError) as exc:+ raise SkillError(f"Skill resource '{path.as_posix()}' was not found.") from exc+ except (OSError, ValueError) as exc:+ raise SkillError("Skill resource path must stay inside the skill directory.") from exc+ raw = _read_limited(+ candidate, MAX_SKILL_FILE_BYTES, contained_in = skill_dir, identity = identity+ )+ try:+ content = raw.decode("utf-8")+ except UnicodeDecodeError as exc:+ raise SkillError("Skill resources must be UTF-8 text.") from exc+ if "\x00" in content:+ raise SkillError("Skill resources must be UTF-8 text, not binary data.")+ if offset > len(content):+ raise SkillError("Skill resource offset is past the end of the file.")+ end = min(offset + min(page_chars, MAX_SKILL_PAGE_CHARS), len(content))+ normalized = path.as_posix()+ result = (+ f"Skill: {record['name']}\nResource: {normalized}\n"+ f"Characters: {offset}-{end} of {len(content)}\n\n{content[offset:end]}"+ )+ if end < len(content):+ result += (+ "\n\nResource continues. Call read_skill again with "+ f'name="{record["name"]}", resource="{normalized}", offset={end}.'+ )+ return resultdiff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 477ddb25abf..43dc69fc731 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -4225,7 +4225,13 @@ def _render_html_reaches_network(arguments: dict) -> bool:# and reaches nothing: it only reports that the user's own armed research is starting, and without it here# is_high_risk_tool_call's unknown-name default would prompt on every handoff._ALWAYS_SAFE_TOOLS = frozenset(- {"web_search", "search_knowledge_base", "search_conversation", "deep_research"}+ {+ "web_search",+ "search_knowledge_base",+ "search_conversation",+ "read_skill",+ "deep_research",+ })@@ -9506,6 +9512,65 @@ SEARCH_CONVERSATION_TOOL = {},},}+READ_SKILL_TOOL = {+ "type": "function",+ "function": {+ "name": "read_skill",+ "description": (+ "Read instructions or a UTF-8 resource from an enabled Agent Skill. "+ "Start with SKILL.md, then read referenced resources only when needed. "+ "This tool reads files; it does not execute scripts."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Enabled skill name from the system skill catalog.",+ },+ "resource": {+ "type": "string",+ "description": "Relative resource path. Defaults to SKILL.md.",+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "description": "Character offset for the next page. Defaults to 0.",+ },+ },+ "required": ["name"],+ },+ },+}+CREATE_SKILL_TOOL = {+ "type": "function",+ "function": {+ "name": "create_skill",+ "description": (+ "Create a new Agent Skill in ~/.agents/skills. Use the skill-creator instructions "+ "first. Existing skills are never overwritten."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Lowercase skill name using letters, numbers, and single hyphens.",+ },+ "description": {+ "type": "string",+ "description": "When the skill should be used, in 1-1024 characters.",+ },+ "instructions": {+ "type": "string",+ "description": "Complete Markdown instructions for the skill body.",+ },+ },+ "required": ["name", "description", "instructions"],+ },+ },+}+ALL_TOOLS = [WEB_SEARCH_TOOL,@@ -9806,6 +9871,58 @@ def execute_tool("split across smaller calls if the content is long.")effective_timeout = _EXEC_TIMEOUT if timeout is _TIMEOUT_UNSET else timeout+ if name == "create_skill":+ from .skills import SkillError, create_skill++ try:+ record = create_skill(+ arguments.get("name", ""),+ arguments.get("description", ""),+ arguments.get("instructions", ""),+ )+ except SkillError as exc:+ return f"Error: {exc}"+ # The next turn must see the new skill, not the 1 s catalog snapshot.+ from routes.inference import _invalidate_agent_skills_cache++ _invalidate_agent_skills_cache()+ return (+ f"Created Agent Skill '{record['name']}' at {record['path']}. "+ f"It is enabled and ready to use."+ )++ if name == "read_skill":+ from .skills import (+ MAX_SKILL_PAGE_CHARS,+ MIN_SKILL_PAGE_CHARS,+ SkillError,+ read_skill_resource,+ )+ try:+ page_chars = MAX_SKILL_PAGE_CHARS+ # A model that spells out every optional argument sends null, not nothing.+ resource = arguments.get("resource")+ offset = arguments.get("offset")+ while True:+ result = read_skill_resource(+ arguments.get("name") or "",+ "SKILL.md" if resource is None else resource,+ 0 if offset is None else offset,+ page_chars = page_chars,+ )+ fitted = _fit_result_to_room(result, name)+ if fitted == result:+ return result+ # Below this the page is nothing but its own header and footer.+ if page_chars < MIN_SKILL_PAGE_CHARS:+ return (+ "Error: Not enough context room to read this skill resource. "+ "Reduce the conversation context and retry the same read_skill call."+ )+ page_chars //= 2+ except SkillError as exc:+ return f"Error: {exc}"+if name == "search_knowledge_base":return _fit_result_to_room(_search_knowledge_base_with_budget(diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 30dad4fe3d4..3dd780de1a7 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -296,6 +296,7 @@ from routes import (inference_router,inference_studio_router,mcp_servers_router,+ skills_router,models_router,providers_router,openai_codex_auth_router,@@ -1456,6 +1457,7 @@ app.include_router(openai_codex_auth_router, prefix = "/api/providers", tags = [app.include_router(settings_router, prefix = "/api/settings", tags = ["settings"])app.include_router(mcp_servers_router, prefix = "/api/mcp/servers", tags = ["mcp"])+app.include_router(skills_router, prefix = "/api/skills", tags = ["skills"])app.include_router(prompts_router, prefix = "/api/prompts", tags = ["prompts"])app.include_router(profile_stats_router, prefix = "/api/profile", tags = ["profile"])app.include_router(datasets_router, prefix = "/api/datasets", tags = ["datasets"])diff --git a/studio/backend/routes/__init__.py b/studio/backend/routes/__init__.pyindex a8d648a245b..9e99e7b37be 100644--- a/studio/backend/routes/__init__.py+++ b/studio/backend/routes/__init__.py@@ -19,6 +19,7 @@ from routes.providers import router as providers_routerfrom routes.openai_codex_auth import router as openai_codex_auth_routerfrom routes.mcp_servers import router as mcp_servers_router+from routes.skills import router as skills_routerfrom routes.rag import router as rag_routerfrom routes.research_runs import router as research_runs_routerfrom routes.chat_generation_runs import router as chat_generation_runs_router@@ -40,6 +41,7 @@ __all__ = ["providers_router","openai_codex_auth_router","mcp_servers_router",+ "skills_router","rag_router","research_runs_router","chat_generation_runs_router",diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex a4ac1620968..a4718728c2d 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -49,6 +49,7 @@ from utils.account_context import (account_thread,current_account,current_account_id,+ is_owner_context,run_as,)from utils.security.consent import MANAGED_REMOTE_CODE_REFUSAL, managed_remote_code_refused@@ -3843,7 +3844,11 @@ def _explicit_studio_tool_loop_requested(payload) -> bool:return policy is not False and (payload.enable_tools is True or bool(payload.mcp_enabled))-def _selects_only_provider_hosted_tools(payload, provider_type: str | None) -> bool:+def _selects_only_provider_hosted_tools(+ payload,+ provider_type: str | None,+ enabled_skills: list[dict] | None = None,+) -> bool:"""True when the request's tool selection is nothing but the provider's ownhosted builtins, so the provider must execute them as it always has.@@ -3875,6 +3880,15 @@ def _selects_only_provider_hosted_tools(payload, provider_type: str | None) -> b# reaches the loop anyway. Neither is a hosted-tool request.if not enabled or not isinstance(enabled, list):return False++ # Skill tools named with no skill enabled select nothing.+ if {"read_skill", "create_skill"} & set(enabled):+ if enabled_skills is None:+ enabled_skills = _enabled_agent_skills()+ if not enabled_skills:+ enabled = [name for name in enabled if name not in {"read_skill", "create_skill"}]+ if not enabled:+ return Trueif not provider_hosted_tools(provider_type):return False# Matched against the whole hosted vocabulary rather than this provider's own@@ -4848,6 +4862,69 @@ _TOOL_ARTIFACT_TIP = ()+_AGENT_SKILLS_CACHE_TTL_S = 1.0+_AGENT_SKILLS_CACHE_LOCK = threading.Lock()+# One entry per acting account (None is the owner); catalogs never cross accounts.+_AGENT_SKILLS_CACHE: dict[Optional[str], tuple[float, list[dict]]] = {}+++def _agent_skills_cache_key() -> Optional[str]:+ return None if is_owner_context() else current_account_id()+++def _invalidate_agent_skills_cache() -> None:+ with _AGENT_SKILLS_CACHE_LOCK:+ _AGENT_SKILLS_CACHE.clear()+++def _enabled_agent_skills() -> list[dict]:+ """The acting account's enabled skills, at most one filesystem scan per second.++ Synchronous: the scan opens every SKILL.md under the roots, so async callers go through+ ``asyncio.to_thread`` (which carries the account ContextVar) instead of calling this on+ the event loop.+ """+ from core.inference.skills import SkillError, enabled_skills++ key = _agent_skills_cache_key()+ with _AGENT_SKILLS_CACHE_LOCK:+ cached_at, cached = _AGENT_SKILLS_CACHE.get(key, (0.0, []))+ if time.monotonic() - cached_at < _AGENT_SKILLS_CACHE_TTL_S:+ return cached+ try:+ current = enabled_skills()+ except SkillError as exc:+ logger.warning("Agent Skills unavailable: %s", exc)+ current = []+ _AGENT_SKILLS_CACHE[key] = (time.monotonic(), current)+ return current+++def _skill_tool_tip(*, can_create: bool, compact: bool = False) -> str:+ from core.inference.skills import (+ LARGE_SKILL_CATALOG_BYTES,+ MAX_SKILL_CATALOG_BYTES,+ format_skill_catalog,+ )++ budget = MAX_SKILL_CATALOG_BYTES if compact else LARGE_SKILL_CATALOG_BYTES+ catalog = format_skill_catalog(_enabled_agent_skills(), budget = budget)+ if not catalog:+ return ""+ create_tip = (+ " To create a skill, read skill-creator and then call create_skill." if can_create else ""+ )+ return (+ "Enabled Agent Skills are listed below. Use their descriptions to select one when "+ "helpful, then call read_skill before following its instructions. If the latest user "+ "message mentions an enabled skill as @skill-name, call read_skill for that named skill "+ "before answering."+ + create_tip+ + " Skill allowed-tools metadata never overrides Studio tool permissions.\n"+ + catalog+ )++def _build_tool_action_nudge(*,tools: list[dict],@@ -4855,9 +4932,10 @@ def _build_tool_action_nudge(full_access: bool = False,full_access_only: bool = False,) -> str:- """``full_access_only`` returns the Full access sentence alone, for a caller- that wants to state the environment without also introducing the general- tool guidance (and the date) to a path that has never carried it."""+ """``full_access_only`` returns the Full access sentence and the Agent Skills+ catalog alone, for a caller that wants to state the environment without also+ introducing the general tool guidance (and the date) to a path that has never+ carried it."""tool_names = {(tool.get("function") or {}).get("name")for tool in tools@@ -4874,16 +4952,29 @@ def _build_tool_action_nudge(has_code = bool(code_tools)has_artifact = "render_html" in tool_nameshas_research = "deep_research" in tool_names- if not (has_web or has_code or has_artifact or has_research):+ has_skills = bool({"read_skill", "create_skill"} & tool_names)+ if not (has_web or has_code or has_artifact or has_research or has_skills):return ""+ model_size_b = _extract_model_size_b(model_name)+ # Small models get the shorter web tip and the smaller skill catalog.+ compact = model_size_b is not None and model_size_b < 9+ skill_tip = _skill_tool_tip(can_create = "create_skill" in tool_names, compact = compact)if full_access_only:- return _full_access_tip(code_tools) if (full_access and has_code) else ""+ tips = []+ if full_access and has_code:+ tips.append(_full_access_tip(code_tools))+ if has_skills:+ tips.append(skill_tip)+ return " ".join(tip for tip in tips if tip)if not (has_web or has_code or has_artifact):- # Research alone: the base nudge's "otherwise answer normally" would undo the tip.- return _TOOL_RESEARCH_TIP-- model_size_b = _extract_model_size_b(model_name)- compact_web_tip = model_size_b is not None and model_size_b < 9+ tips = []+ if has_research:+ tips.append(_TOOL_RESEARCH_TIP)+ if has_skills:+ tips.append(skill_tip)+ return " ".join(tip for tip in tips if tip)++ compact_web_tip = compacttool_tip_parts: list[str] = []if has_web:tool_tip_parts.append(_TOOL_WEB_COMPACT_TIP if compact_web_tip else _TOOL_WEB_EXPANDED_TIP)@@ -4897,6 +4988,8 @@ def _build_tool_action_nudge(tool_tip_parts.append(_TOOL_ARTIFACT_TIP)if has_research:tool_tip_parts.append(_TOOL_RESEARCH_TIP)+ if has_skills:+ tool_tip_parts.append(skill_tip)# the date rides on the system prompt instead, so a tool-less chat is not left date-blind.return _TOOL_BASE_NUDGE + " " + " ".join(tool_tip_parts)@@ -5227,6 +5320,22 @@ async def _select_request_tools(else:# Copy so the shared module-global tool list can't be mutated by callers.tools = list(ALL_TOOLS)+ tools = [+ tool for tool in tools if tool["function"]["name"] not in {"read_skill", "create_skill"}+ ]+ # Inline on purpose: an await here escapes the api_monitor cancel handling; the cache bounds it.+ enabled_skills = _enabled_agent_skills() if tools_on else []+ if enabled_skills:+ from core.inference.tools import CREATE_SKILL_TOOL, READ_SKILL_TOOL++ skill_tools = (READ_SKILL_TOOL,)+ if any(skill["name"] == "skill-creator" for skill in enabled_skills):+ skill_tools += (CREATE_SKILL_TOOL,)+ if payload.enabled_tools is not None:+ skill_tools = tuple(+ tool for tool in skill_tools if tool["function"]["name"] in payload.enabled_tools+ )+ tools.extend(skill_tools)# Drop the RAG tool without a scope: nothing to search over.if not payload.rag_scope:tools = [t for t in tools if t["function"]["name"] != "search_knowledge_base"]@@ -20981,7 +21090,8 @@ async def _proxy_to_external_provider(# a request for this loop. Checked here rather than inside the loop so the# whole path (catalog selection, nudge, confirm gate) is skipped and the# request proxies through byte-for-byte as it did before the loop existed.- and not _selects_only_provider_hosted_tools(payload, provider_type)+ # Last, so a request that never asked for tools never scans the skill roots.+ and not _selects_only_provider_hosted_tools(payload, provider_type, _enabled_agent_skills()))codex_studio_tool_loop = studio_tool_loop and provider_type == "openai_codex"# The loop relays the same control frames the local routes gate (see UI_STREAM_EVENTS_HEADER).@@ -21233,19 +21343,14 @@ async def _proxy_to_external_provider(tool_payloads = studio_tool_payloads# This path runs python/terminal locally too (disable_sandbox =# bypass_permissions), so it has the same false-isolation problem.- # Only the Full access sentence is added: the path has never carried- # the general tool nudge, and widening it would change every- # non-Full-access Codex run as a side effect.- if payload.bypass_permissions:- _codex_full_access_nudge = _build_tool_action_nudge(- tools = studio_tool_payloads,- model_name = model,- full_access = True,- full_access_only = True,- )- chat_messages = _append_to_codex_instructions(- chat_messages, _codex_full_access_nudge- )+ # Only the Full access sentence and the skill catalog; this path never carried the general nudge.+ _codex_nudge = _build_tool_action_nudge(+ tools = studio_tool_payloads,+ model_name = model,+ full_access = bool(payload.bypass_permissions),+ full_access_only = True,+ )+ chat_messages = _append_to_codex_instructions(chat_messages, _codex_nudge)chat_messages = _prepend_current_date_to_messages(chat_messages,request,@@ -21579,13 +21684,13 @@ async def _proxy_to_external_provider()# Built before the date, because whether a nudge exists decides whether the Modelfile# exemption is worth claiming: _append_to_system_message below displaces that prompt anyway.- # Full access disables the sandbox at execution time, so the schemas must say so too.+ # Full access disables the sandbox, so the schemas say so; the general nudge stays off this path._external_nudge = ""- if run_studio_tool_loop and payload.bypass_permissions:+ if run_studio_tool_loop:_external_nudge = _build_tool_action_nudge(tools = external_studio_tools,model_name = model,- full_access = True,+ full_access = bool(payload.bypass_permissions),full_access_only = True,)chat_messages = _prepend_current_date_to_messages(@@ -30552,6 +30657,7 @@ _STUDIO_ANTHROPIC_TOOL_ALIASES = {"web_fetch_20260209": "web_search","python": "python","terminal": "terminal",+ "read_skill": "read_skill",}# Server tools that never need a confirmation prompt (read-only / non code-# executing; mirrors the unconditional-safe names in is_potentially_unsafe_tool_call).@@ -30560,7 +30666,7 @@ _STUDIO_ANTHROPIC_TOOL_ALIASES = {# asks then. render_html is excluded because a networked canvas prompts in auto,# and this channel invokes the loop without confirm; auto/ask reject, off/full run._ANTHROPIC_UNPROMPTED_SAFE_TOOLS = frozenset(- {"web_search", "search_knowledge_base", "search_conversation"}+ {"web_search", "search_knowledge_base", "search_conversation", "read_skill"})@@ -30627,14 +30733,18 @@ def _select_anthropic_server_tools(all_tools: list[dict], requested_studio_tools: set[str], enabled_tools: Optional[list[str]]) -> list[dict]:"""Select Unsloth tools requested through Anthropic tools and extensions."""+ available = list(all_tools)+ if _enabled_agent_skills():+ from core.inference.tools import READ_SKILL_TOOL+ available.append(READ_SKILL_TOOL)if not requested_studio_tools and enabled_tools is None:- return all_tools+ return availableselected_names = set(requested_studio_tools)if enabled_tools is not None:selected_names.update(enabled_tools)- return [tool for tool in all_tools if tool["function"]["name"] in selected_names]+ return [tool for tool in available if tool["function"]["name"] in selected_names]def _image_bytes_to_png_b64(raw: bytes) -> str:@@ -31405,6 +31515,27 @@ async def anthropic_count_tokens(request,include_api_key = _count_server_tools,)+ if _count_server_tools:+ from core.inference.tools import ALL_TOOLS as _ANTHROPIC_COUNT_TOOLS++ openai_tools = _tools_for_search_images(+ _select_anthropic_server_tools(+ _ANTHROPIC_COUNT_TOOLS,+ _count_studio_tools,+ payload.enabled_tools,+ )+ )+ _count_full_access = bool(getattr(payload, "bypass_permissions", False))+ if _count_full_access:+ # Same schemas /messages renders under Full access, or the count prices a different prompt.+ from core.inference.tools import apply_full_access_tool_descriptions+ openai_tools = apply_full_access_tool_descriptions(openai_tools)+ _count_nudge = _build_tool_action_nudge(+ tools = openai_tools,+ model_name = _llama_public_model_id(llama_backend, payload.model),+ full_access = _count_full_access,+ )+ openai_messages = _append_to_system_message(openai_messages, _count_nudge)# Render with the same reasoning controls generation will use: on switchable# templates thinking / reasoning_effort / preserve_thinking change thediff --git a/studio/backend/routes/skills.py b/studio/backend/routes/skills.pynew file mode 100644index 00000000000..6342d35100f--- /dev/null+++ b/studio/backend/routes/skills.py@@ -0,0 +1,67 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from typing import Any, Literal, Optional++from fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModel, ConfigDict, StrictBool++from auth.authentication import get_current_subject+from core.inference.skills import SkillError, SkillNotFoundError, list_skills, set_skill_enabled+++router = APIRouter()+++class SkillRecord(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ name: str+ description: str+ source: Literal["agents", "claude", "bundled"]+ enabled: bool+ valid: bool+ shadowed: bool+ shadowed_by: Optional[Literal["agents", "claude", "bundled"]] = None+ error: Optional[str] = None+ license: Optional[str] = None+ compatibility: Optional[str] = None+ metadata: Optional[dict[str, str]] = None+ allowed_tools: Optional[str] = None+++class SkillEnabledRequest(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ enabled: StrictBool++[email protected]("", response_model = list[SkillRecord])+def get_skills(current_subject: str = Depends(get_current_subject)) -> list[dict[str, Any]]:+ try:+ records = list_skills()+ except 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()+ return records++[email protected]("/{name}/enabled", response_model = SkillRecord)+def update_skill_enabled(+ name: str,+ payload: SkillEnabledRequest,+ current_subject: str = Depends(get_current_subject),+) -> dict[str, Any]:+ try:+ updated = set_skill_enabled(name, payload.enabled)+ from routes.inference import _invalidate_agent_skills_cache++ _invalidate_agent_skills_cache()+ return updated+ except SkillNotFoundError as exc:+ raise HTTPException(status_code = 404, detail = str(exc)) from exc+ except SkillError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from excdiff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex ef86ae43004..c9346c86eaf 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -80,6 +80,32 @@ def _studio_home_root(tmp_path_factory):_studio_home_counter = itertools.count()[email protected](scope = "session")+def _skills_home_root(tmp_path_factory):+ # One mktemp per session; see _studio_home_root for why a per-test mktemp is quadratic.+ return tmp_path_factory.mktemp("skills_homes")+++_skills_home_counter = itertools.count()++[email protected](autouse = True)+def _isolate_agent_skills(_skills_home_root, monkeypatch):+ # A developer's own ~/.agents or ~/.claude skills must not leak into tool-selection tests.+ from core.inference import skills as _skills++ home = _skills_home_root / f"h{next(_skills_home_counter)}"+ home.mkdir()+ # Owner home under tmp, bundled root empty; managed-account roots stay for the account matrix.+ monkeypatch.setattr(_skills, "_owner_home", lambda: home)+ monkeypatch.setattr(_skills, "_BUNDLED_ROOT", ("bundled", home / "bundled-absent"))+ try:+ from routes import inference as _inference_routes+ except Exception:+ return+ monkeypatch.setattr(_inference_routes, "_AGENT_SKILLS_CACHE", {})++@pytest.fixture(autouse = True)def _contain_installer_venv_root(tmp_path_factory, monkeypatch):"""Mechanism: tests/_shared/installer_venv_root.py.diff --git a/studio/backend/tests/multi_account/factories.py b/studio/backend/tests/multi_account/factories.pyindex f97986ec017..b409b0ec9e4 100644--- a/studio/backend/tests/multi_account/factories.py+++ b/studio/backend/tests/multi_account/factories.py@@ -100,6 +100,31 @@ def seed_mcp(account) -> dict[str, str]:return {"server_id": SERVER_ID}+SKILL_NAME = "matrix-skill"+++@seeder("skill")+def seed_skill(account) -> dict[str, str]:+ # Skills of a managed account live in its own workspace; the owner reads the home folders.+ from core.inference import skills as skills_module++ if account.is_owner:+ root = skills_module._owner_home() / ".agents" / "skills" / SKILL_NAME+ else:+ root = run_as(account, workspace_root) / "skills" / SKILL_NAME+ root.mkdir(parents = True, exist_ok = True)+ # Quoted: the sentinel carries a colon, which a plain YAML scalar cannot.+ (root / "SKILL.md").write_text(+ f"---\nname: {SKILL_NAME}\ndescription: {json.dumps(SENTINEL, ensure_ascii = False)}\n"+ "---\nInstructions\n",+ encoding = "utf-8",+ )+ from routes.inference import _invalidate_agent_skills_cache++ _invalidate_agent_skills_cache()+ return {"name": SKILL_NAME}++CORE_FACTORIES = {"routes.chat_history:GET:/threads/{thread_id}": Factory("chat", fragment = SENTINEL),"routes.chat_history:PATCH:/threads/{thread_id}": Factory(@@ -128,6 +153,9 @@ CORE_FACTORIES = {"mcp", {"display_name": EDITED}, fragment = EDITED),"routes.mcp_servers:DELETE:/{server_id}": Factory("mcp", success = 204),+ "routes.skills:PUT:/{name}/enabled": Factory(+ "skill", {"enabled": False}, fragment = SKILL_NAME, absent = SENTINEL+ ),}diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex 3b52f722d5e..c57a6d53008 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -550,6 +550,22 @@ class TestToolActionNudge:def test_balanced_nudge_empty_without_known_tool_categories(self):assert _build_tool_action_nudge(tools = [], model_name = "Llama-3.1-8B-Instruct") == ""+ def test_read_skill_only_nudge_does_not_advertise_create_skill(self, monkeypatch):+ import routes.inference as inference_routes++ monkeypatch.setattr(+ inference_routes,+ "_enabled_agent_skills",+ lambda: [{"name": "guided", "description": "Guide this task."}],+ )+ nudge = _build_tool_action_nudge(+ tools = [{"type": "function", "function": {"name": "read_skill"}}],+ model_name = "test",+ )++ assert "- guided: Guide this task." in nudge+ assert "create_skill" not in nudge+# =====================================================================# Pydantic model tests@@ -1235,6 +1251,28 @@ class TestAnthropicToolsToOpenAI:assert [tool["function"]["name"] for tool in result] == ["web_search", "python"]+ @pytest.mark.parametrize(+ ("requested_studio_tools", "enabled_tools"),+ [({"web_search"}, None), (set(), ["web_search"])],+ )+ def test_explicit_server_tool_selection_does_not_add_read_skill(+ self, monkeypatch, requested_studio_tools, enabled_tools+ ):+ import routes.inference as inference_routes++ monkeypatch.setattr(+ inference_routes,+ "_enabled_agent_skills",+ lambda: [{"name": "guided", "description": "Guide this task."}],+ )+ result = _select_anthropic_server_tools(+ [{"type": "function", "function": {"name": "web_search"}}],+ requested_studio_tools = requested_studio_tools,+ enabled_tools = enabled_tools,+ )++ assert [tool["function"]["name"] for tool in result] == ["web_search"]+def test_pydantic_model_input(self):tool = AnthropicTool(name = "test", description = "desc", input_schema = {"type": "object"})result = anthropic_tools_to_openai([tool])@@ -2345,6 +2383,14 @@ class TestAnthropicRequestedStudioTools:tools = [{"type": "web_search_20250305", "name": "web_search"}]assert _anthropic_requested_studio_tools(tools) == {"web_search"}+ def test_recognizes_read_skill_server_tool_by_type(self):+ tools = [{"type": "read_skill", "name": "read_skill"}]+ assert _anthropic_requested_studio_tools(tools) == {"read_skill"}++ def test_create_skill_is_not_available_without_a_confirmation_channel(self):+ tools = [{"type": "create_skill", "name": "create_skill"}]+ assert _anthropic_requested_studio_tools(tools) == set()+def test_bare_name_without_type_is_not_treated_as_server_tool(self):# Anthropic dispatches server tools by `type`; bare-name matching# would let a malformed client tool (missing input_schema) silently@@ -3325,6 +3371,14 @@ class TestAnthropicMessagesToolRouting:assert backend.calls == []def test_permission_mode_gating_for_server_tools(self, monkeypatch):+ import routes.inference as inf_mod++ # An Anthropic web-search request must not inherit the confirmation-gated create_skill tool.+ monkeypatch.setattr(+ inf_mod,+ "_enabled_agent_skills",+ lambda: [{"name": "skill-creator", "description": "Create a skill."}],+ )# ask is a request for a per-call pause this channel cannot honor, so it is# always rejected, even for a safe-only server tool (web_search).safe_tools = [{"type": "web_search_20250305", "name": "web_search"}]diff --git a/studio/backend/tests/test_external_hosted_tool_passthrough.py b/studio/backend/tests/test_external_hosted_tool_passthrough.pyindex 8e0f98e1c16..36d8f9ae1c7 100644--- a/studio/backend/tests/test_external_hosted_tool_passthrough.py+++ b/studio/backend/tests/test_external_hosted_tool_passthrough.py@@ -720,3 +720,15 @@ def test_b_a_credential_reading_python_call_is_gated(monkeypatch):)assert [s["awaiting_confirmation"] for s in starts] == [True]assert executed == []+++def test_a_request_without_tools_never_scans_the_skill_roots(monkeypatch):+ inf = _install(monkeypatch, "openai")++ def _scan():+ raise AssertionError("skill roots scanned for a request that asked for no tools")++ monkeypatch.setattr(inf, "_enabled_agent_skills", _scan)+ chunks = _run(inf, _payload(enable_tools = False))+ assert FakeExternalClient.last["passthrough"] is not None+ assert any("hi" in chunk for chunk in chunks)diff --git a/studio/backend/tests/test_skills.py b/studio/backend/tests/test_skills.pynew file mode 100644index 00000000000..a149af9a0f2--- /dev/null+++ b/studio/backend/tests/test_skills.py@@ -0,0 +1,943 @@+# 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 json+import os+import sys+import threading+from pathlib import Path++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+++def _write_skill(+ home: Path,+ source: str,+ name: str,+ *,+ description: str = "Use this skill for testing.",+ frontmatter: str = "",+ body: str = "Instructions",+) -> Path:+ root = home / (".agents" if source == "agents" else ".claude") / "skills" / name+ root.mkdir(parents = True)+ extra = f"\n{frontmatter.rstrip()}" if frontmatter else ""+ (root / "SKILL.md").write_text(+ f"---\nname: {name}\ndescription: {description}{extra}\n---\n{body}",+ encoding = "utf-8",+ )+ return root++[email protected](autouse = True)+def _reset_tool_request_budget():+ # execute_tool never resets these, so the pagination test's tight budget must not leak.+ from core.inference import tools++ context_token = tools._REQUEST_CONTEXT_TOKENS.set(tools._UNSET_CONTEXT_TOKENS)+ budget_token = tools._REQUEST_RESULT_BUDGET.set(None)+ yield+ tools._REQUEST_CONTEXT_TOKENS.reset(context_token)+ tools._REQUEST_RESULT_BUDGET.reset(budget_token)+++def isolated_skills(tmp_path, monkeypatch):+ home = tmp_path / "home"+ studio = tmp_path / "studio"+ home.mkdir()+ monkeypatch.setattr(skills, "studio_root", lambda: studio)+ return home, studio+++def test_enabled_skill_cache_is_fresh_after_slow_discovery(monkeypatch):+ from routes import inference as inference_routes++ scans = 0++ def discover():+ nonlocal scans+ scans += 1+ return [{"name": "cached"}]++ clock = iter((10.0, 12.0, 12.5))+ monkeypatch.setattr(skills, "enabled_skills", discover)+ monkeypatch.setattr(inference_routes.time, "monotonic", lambda: next(clock))+ monkeypatch.setattr(inference_routes, "_AGENT_SKILLS_CACHE", {})++ assert inference_routes._enabled_agent_skills() == [{"name": "cached"}]+ assert inference_routes._enabled_agent_skills() == [{"name": "cached"}]+ assert scans == 1+++def test_discovers_both_roots_with_agents_precedence(isolated_skills):+ home, _ = isolated_skills+ _write_skill(home, "agents", "shared", description = "Agent copy")+ _write_skill(home, "claude", "claude-only")+ _write_skill(home, "claude", "shared", description = "Claude copy")++ records = skills.list_skills(home = home)++ assert [(item["name"], item["source"], item["shadowed"]) for item in records] == [+ ("shared", "agents", False),+ ("claude-only", "claude", False),+ ("shared", "claude", True),+ ]+ assert records[0]["description"] == "Agent copy"+ assert records[0]["enabled"] is True+ assert records[2]["shadowed_by"] == "agents"+++def test_bundled_skill_creator_is_enabled_and_user_override_wins(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ 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)++ creator = next(record for record in skills.list_skills() if record["name"] == "skill-creator")+ assert creator["source"] == "bundled"+ # Bundled skills ship disabled: a fresh install must not carry skill tools into every chat.+ assert creator["enabled"] is False+ assert skills.enabled_skills() == []+ with pytest.raises(skills.SkillError, match = "disabled"):+ skills.read_skill_resource("skill-creator")+ # Enabling one is an explicit override that survives a re-list; disabling clears it again.+ assert skills.set_skill_enabled("skill-creator", True)["enabled"] is True+ assert skills._load_overrides() == {"skill-creator": True}+ assert "create_skill" in skills.read_skill_resource("skill-creator")+ assert skills.set_skill_enabled("skill-creator", False)["enabled"] is False+ assert skills._load_overrides() == {}++ _write_skill(home, "agents", "skill-creator", description = "User override")+ records = [record for record in skills.list_skills() if record["name"] == "skill-creator"]+ assert [(record["source"], record["shadowed"]) for record in records] == [+ ("agents", False),+ ("bundled", True),+ ]+++ "directory,manifest",+ [+ ("wrong-dir", "---\nname: other\ndescription: valid\n---\n"),+ ("BadName", "---\nname: BadName\ndescription: valid\n---\n"),+ (+ "bad-metadata",+ "---\nname: bad-metadata\ndescription: valid\nmetadata:\n version: 1\n---\n",+ ),+ ("no-description", "---\nname: no-description\n---\n"),+ ],+)+def test_invalid_skill_is_reported_without_hiding_valid_skills(+ isolated_skills, directory, manifest+):+ home, _ = isolated_skills+ invalid = home / ".agents" / "skills" / directory+ invalid.mkdir(parents = True)+ (invalid / "SKILL.md").write_text(manifest, encoding = "utf-8")+ _write_skill(home, "agents", "valid")++ records = skills.list_skills(home = home)++ invalid_record = next(item for item in records if item["name"] == directory)+ assert invalid_record["valid"] is False+ assert invalid_record["error"]+ assert next(item for item in records if item["name"] == "valid")["valid"] is True+++ os.name == "nt" or sys.platform == "darwin",+ reason = "Windows has no surrogate-escaped filenames and APFS rejects non-UTF-8 names",+)+def test_non_utf8_directory_name_does_not_hide_valid_skills(isolated_skills):+ home, _ = isolated_skills+ root = home / ".agents" / "skills"+ root.mkdir(parents = True)+ os.mkdir(os.fsencode(root) + b"/bad-\xff")+ _write_skill(home, "agents", "valid")++ records = skills.list_skills(home = home)++ assert [record["name"] for record in records] == ["valid"]+ json.dumps(records, ensure_ascii = False).encode("utf-8")+++def test_disable_override_persists_without_touching_or_falling_through(isolated_skills):+ home, studio = isolated_skills+ winner = _write_skill(home, "agents", "shared", body = "winner")+ _write_skill(home, "claude", "shared", body = "shadowed")+ before = (winner / "SKILL.md").read_bytes()++ updated = skills.set_skill_enabled("shared", False, home = home)++ assert updated["enabled"] is False+ assert skills.enabled_skills(home = home) == []+ assert json.loads((studio / "skill-overrides.json").read_text()) == {"shared": False}+ assert (winner / "SKILL.md").read_bytes() == before+ skills.set_skill_enabled("shared", True, home = home)+ assert json.loads((studio / "skill-overrides.json").read_text()) == {}+++def test_read_resource_is_contained_utf8_and_paginated(isolated_skills):+ home, _ = isolated_skills+ root = _write_skill(home, "agents", "reader")+ resource = root / "references" / "guide.md"+ resource.parent.mkdir()+ resource.write_text("abcdef", encoding = "utf-8")++ page = skills.read_skill_resource("reader", "references/guide.md", 1, page_chars = 3, home = home)++ assert "Characters: 1-4 of 6" in page+ assert "\nbcd\n" in page+ assert "offset=4" in page+ skills.set_skill_enabled("reader", False, home = home)+ with pytest.raises(skills.SkillError, match = "disabled"):+ skills.read_skill_resource("reader", home = home)+++ not hasattr(os, "mkfifo"), reason = "POSIX FIFOs are unavailable on this platform"+)+def test_read_resource_rejects_fifo_without_blocking(isolated_skills):+ home, _ = isolated_skills+ root = _write_skill(home, "agents", "reader")+ pipe = root / "pipe"+ os.mkfifo(pipe)+ finished = threading.Event()+ errors = []++ def read_pipe():+ try:+ skills.read_skill_resource("reader", "pipe", home = home)+ except Exception as exc:+ errors.append(exc)+ finally:+ finished.set()++ worker = threading.Thread(target = read_pipe, daemon = True)+ worker.start()+ completed_without_writer = finished.wait(1)+ if not completed_without_writer:+ with pipe.open("wb"):+ pass+ worker.join(1)++ assert completed_without_writer, "reading a FIFO waited for a writer"+ assert errors and isinstance(errors[0], skills.SkillError)+ assert "regular file" in str(errors[0])+++def test_read_resource_rejects_escaping_symlink(isolated_skills):+ home, _ = isolated_skills+ root = _write_skill(home, "agents", "reader")+ outside = home / "secret.txt"+ outside.write_text("secret", encoding = "utf-8")+ try:+ (root / "link.txt").symlink_to(outside)+ except (OSError, NotImplementedError):+ # Reason: Windows may deny symlink creation without Developer Mode.+ pytest.skip("symlinks are unavailable on this platform")++ with pytest.raises(skills.SkillError, match = "symbolic links"):+ skills.read_skill_resource("reader", "link.txt", home = home)+ with pytest.raises(skills.SkillError, match = "stay inside"):+ skills.read_skill_resource("reader", "../secret.txt", home = home)+++def test_read_resource_rejects_link_swapped_during_open(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ root = _write_skill(home, "agents", "reader")+ resource = root / "guide.md"+ resource.write_text("safe", encoding = "utf-8")+ outside = home / "secret.txt"+ outside.write_text("secret", encoding = "utf-8")+ original_open = os.open+ swapped = False++ def replacing_open(path, *args, **kwargs):+ nonlocal swapped+ # The descriptor-relative walk opens the bare component name against a dir_fd.+ if path in (resource, resource.name) and not swapped:+ swapped = True+ resource.unlink()+ try:+ resource.symlink_to(outside)+ except (OSError, NotImplementedError):+ # Reason: Windows may deny symlink creation without Developer Mode.+ pytest.skip("symlinks are unavailable on this platform")+ return original_open(path, *args, **kwargs)++ monkeypatch.setattr(os, "open", replacing_open)+ with pytest.raises(skills.SkillError, match = "symbolic links"):+ skills.read_skill_resource("reader", "guide.md", home = home)+++def test_read_resource_rejects_skill_root_swapped_after_selection(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ root = _write_skill(home, "agents", "reader")+ (root / "guide.md").write_text("safe", encoding = "utf-8")+ outside = home / "outside"+ outside.mkdir()+ (outside / "guide.md").write_text("secret", encoding = "utf-8")+ original_root = home / "original-reader"+ original_selected_skill = skills._selected_skill++ def replacing_selected_skill(name, *, home = None):+ record, path, identity = original_selected_skill(name, home = home)+ root.rename(original_root)+ try:+ root.symlink_to(outside, target_is_directory = True)+ except (OSError, NotImplementedError):+ # Reason: Windows may deny symlink creation without Developer Mode.+ pytest.skip("symlinks are unavailable on this platform")+ return record, path, identity++ monkeypatch.setattr(skills, "_selected_skill", replacing_selected_skill)+ with pytest.raises(skills.SkillError, match = "symbolic links"):+ skills.read_skill_resource("reader", "guide.md", home = home)+++def test_skill_directory_name_must_match_exactly(isolated_skills):+ home, _ = isolated_skills+ root = home / ".agents" / "skills" / "skill"+ root.mkdir(parents = True)+ (root / "SKILL.md").write_text(+ "---\nname: skill\ndescription: test\n---\n",+ encoding = "utf-8",+ )++ record = skills.list_skills(home = home)[0]++ assert record["valid"] is False+ assert "match its parent directory" in record["error"]+++def test_create_skill_writes_valid_manifest_without_overwriting(isolated_skills):+ home, _ = isolated_skills++ record = skills.create_skill(+ "release-notes",+ "Draft concise release notes.",+ "# Workflow\n\n1. Inspect the diff.\n2. Summarize user-visible changes.",+ home = home,+ )++ assert record["name"] == "release-notes"+ assert record["source"] == "agents"+ created = home / ".agents" / "skills" / "release-notes" / "SKILL.md"+ metadata, real_dir = skills._validate_skill_dir(created.parent)+ assert metadata["description"] == "Draft concise release notes."+ assert real_dir == created.parent+ with pytest.raises(skills.SkillError, match = "already exists"):+ skills.create_skill("release-notes", "Different", "Do something else.", home = home)+ assert "Different" not in created.read_text(encoding = "utf-8")++[email protected]("name", ("../escape", "Bad Name", "con"))+def test_create_skill_rejects_unsafe_names(isolated_skills, name):+ home, _ = isolated_skills+ with pytest.raises(skills.SkillError):+ skills.create_skill(name, "Description", "Instructions", home = home)+++def test_create_skill_rejects_a_linked_agents_ancestor(isolated_skills):+ home, _ = isolated_skills+ outside = home.parent / "outside"+ outside.mkdir()+ try:+ (home / ".agents").symlink_to(outside, target_is_directory = True)+ except (OSError, NotImplementedError):+ pytest.skip("symlinks are unavailable on this platform")++ with pytest.raises(skills.SkillError, match = "unsafe"):+ skills.create_skill("escaped", "Description", "Instructions", home = home)++ assert not (outside / "skills").exists()+++def test_create_skill_tool_invalidates_the_inference_cache(isolated_skills, monkeypatch):+ from core.inference import tools as tools_module+ from routes import inference as inference_routes++ home, _ = isolated_skills+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setattr(+ inference_routes, "_AGENT_SKILLS_CACHE", {None: (float("inf"), [{"name": "stale"}])}+ )++ result = tools_module.execute_tool(+ "create_skill",+ {"name": "fresh", "description": "Description", "instructions": "Instructions"},+ )++ assert "Created Agent Skill 'fresh'" in result+ assert inference_routes._AGENT_SKILLS_CACHE == {}+++def test_create_skill_tool_does_not_commit_when_override_clear_fails(isolated_skills, monkeypatch):+ from core.inference import tools as tools_module++ home, studio = isolated_skills+ studio.mkdir()+ (studio / "skill-overrides.json").write_text('{"blocked":false}', encoding = "utf-8")+ monkeypatch.setenv("HOME", str(home))++ def deny_override_write(_overrides):+ raise PermissionError("read-only overrides")++ monkeypatch.setattr(skills, "_save_overrides", deny_override_write)+ result = tools_module.execute_tool(+ "create_skill",+ {"name": "blocked", "description": "Description", "instructions": "Instructions"},+ )++ assert result.startswith("Error:")+ assert not (home / ".agents" / "skills" / "blocked").exists()+++def test_catalog_is_bounded_at_complete_entries():+ candidates = [{"name": f"skill-{index}", "description": "x" * 300} for index in range(20)]++ catalog = skills.format_skill_catalog(candidates)++ *listed, marker = catalog.splitlines()+ assert len("\n".join(listed).encode("utf-8")) <= skills.MAX_SKILL_CATALOG_BYTES+ assert all(line.startswith("- skill-") for line in listed)+ assert (+ marker+ == f"- {20 - len(listed)} more enabled skills not listed; mention one as @skill-name."+ )+ large = skills.format_skill_catalog(candidates, budget = skills.LARGE_SKILL_CATALOG_BYTES)+ assert len(large.splitlines()) > len(listed)+ assert "more enabled skills" not in skills.format_skill_catalog(candidates[:2])+++def test_linked_skill_directory_is_followed_once_and_pinned(isolated_skills, tmp_path):+ home, _ = isolated_skills+ real = tmp_path / "dotfiles" / "skills" / "linked"+ real.mkdir(parents = True)+ (real / "SKILL.md").write_text(+ "---\nname: linked\ndescription: Linked in.\n---\nREAL", encoding = "utf-8"+ )+ root = home / ".agents" / "skills"+ root.mkdir(parents = True)+ try:+ (root / "linked").symlink_to(real, target_is_directory = True)+ (root / "dangling").symlink_to(tmp_path / "gone", target_is_directory = True)+ (root / "to-file").symlink_to(real / "SKILL.md")+ (real / "escape.md").symlink_to(tmp_path / "dotfiles")+ except (OSError, NotImplementedError):+ # Reason: Windows may deny symlink creation without Developer Mode.+ pytest.skip("symlinks are unavailable on this platform")++ records = {record["name"]: record for record in skills.list_skills(home = home)}++ assert records["linked"]["valid"] is True+ assert records["dangling"]["valid"] is False and records["to-file"]["valid"] is False+ assert skills.read_skill_resource("linked", home = home).endswith("REAL")+ with pytest.raises(skills.SkillError, match = "symbolic links"):+ skills.read_skill_resource("linked", "escape.md", home = home)+++def test_catalog_skips_an_oversized_entry_without_hiding_later_skills():+ candidates = [+ {"name": "oversized", "description": "界" * 600},+ {"name": "usable", "description": "Use this skill."},+ ]++ catalog = skills.format_skill_catalog(candidates)++ assert "oversized" not in catalog+ assert catalog.splitlines() == [+ "- usable: Use this skill.",+ "- 1 more enabled skills not listed; mention one as @skill-name.",+ ]+++def test_authenticated_list_and_toggle_routes(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ _write_skill(home, "agents", "api-skill")+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)++ app = FastAPI()+ app.include_router(router, prefix = "/api/skills")+ assert TestClient(app).get("/api/skills").status_code in (401, 403)+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ client = TestClient(app)++ from routes import inference as inference_routes++ monkeypatch.setattr(inference_routes, "_AGENT_SKILLS_CACHE", {None: (float("inf"), [])})+ response = client.get("/api/skills")+ assert response.status_code == 200+ assert response.json()[0]["name"] == "api-skill"+ assert inference_routes._AGENT_SKILLS_CACHE == {}+ response = client.put("/api/skills/api-skill/enabled", json = {"enabled": False})+ assert response.status_code == 200+ assert response.json()["enabled"] is False++ monkeypatch.setattr(+ inference_routes, "_AGENT_SKILLS_CACHE", {None: (float("inf"), [{"name": "stale"}])}+ )+ response = client.put("/api/skills/api-skill/enabled", json = {"enabled": True})+ assert response.status_code == 200+ assert inference_routes._AGENT_SKILLS_CACHE == {}+ assert client.put("/api/skills/api-skill/enabled", json = {"enabled": "false"}).status_code == 422+++def test_skill_tool_selection_honors_explicit_allowlist(isolated_skills, monkeypatch):+ import asyncio++ from models.inference import ChatCompletionRequest+ from routes import inference as inference_routes++ home, _ = isolated_skills+ _write_skill(home, "agents", "guided")+ _write_skill(home, "agents", "skill-creator")+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)+ monkeypatch.setattr(inference_routes, "_enabled_agent_skills", skills.enabled_skills)+ read_only = ChatCompletionRequest(+ model = "test",+ messages = [{"role": "user", "content": "hello"}],+ enable_tools = True,+ enabled_tools = ["read_skill"],+ permission_mode = "auto",+ stream = True,+ )++ selected = asyncio.run(+ inference_routes._select_request_tools(read_only, tools_on = True, mcp_allowed = False)+ )+ names = [tool["function"]["name"] for tool in selected]+ inference_routes._reject_confirm_gate_without_channel(+ read_only, ui_events = False, selected_names = set(names)+ )+ assert names == ["read_skill"]++ local_default = read_only.model_copy(update = {"enabled_tools": ["read_skill", "create_skill"]})+ selected = asyncio.run(+ inference_routes._select_request_tools(local_default, tools_on = True, mcp_allowed = False)+ )+ assert [tool["function"]["name"] for tool in selected] == ["read_skill", "create_skill"]+++def test_skill_tools_registration_selection_and_prompt(isolated_skills, monkeypatch):+ import asyncio++ from core.inference import tools as tools_module+ from models.inference import ChatCompletionRequest+ from routes import inference as inference_routes++ home, _ = isolated_skills+ _write_skill(home, "agents", "guided", description = "Guide this task")+ _write_skill(home, "agents", "skill-creator")+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)+ monkeypatch.setattr(inference_routes, "_enabled_agent_skills", skills.enabled_skills)+ payload = ChatCompletionRequest(+ model = "test",+ messages = [{"role": "user", "content": "hello"}],+ enabled_tools = ["read_skill", "create_skill"],+ )++ selected = asyncio.run(+ inference_routes._select_request_tools(payload, tools_on = True, mcp_allowed = False)+ )+ assert [tool["function"]["name"] for tool in selected] == ["read_skill", "create_skill"]+ assert tools_module.is_always_safe_tool("read_skill") is True+ assert tools_module.is_high_risk_tool_call("create_skill", {}) is True+ result = tools_module.execute_tool("read_skill", {"name": "guided"})+ assert "Skill: guided" in result+ nudge = inference_routes._build_tool_action_nudge(tools = selected, model_name = "test")+ assert "- guided: Guide this task" in nudge+ assert "@skill-name" in nudge+ assert "create_skill" in nudge+ # Codex and external paths skip the general nudge but keep the catalog for @mentions.+ narrow = inference_routes._build_tool_action_nudge(+ tools = [*selected, tools_module.WEB_SEARCH_TOOL],+ model_name = "test",+ full_access_only = True,+ )+ assert "- guided: Guide this task" in narrow+ assert inference_routes._TOOL_BASE_NUDGE not in narrow+ assert "web_search" not in narrow++ skills.set_skill_enabled("skill-creator", False, home = home)+ selected = asyncio.run(+ inference_routes._select_request_tools(payload, tools_on = True, mcp_allowed = False)+ )+ assert [tool["function"]["name"] for tool in selected] == ["read_skill"]+ assert "create_skill" not in inference_routes._build_tool_action_nudge(+ tools = selected, model_name = "test"+ )+ with pytest.raises(skills.SkillError, match = "disabled"):+ skills.read_skill_resource("skill-creator", home = home)++ skills.set_skill_enabled("guided", False, home = home)+ selected = asyncio.run(+ inference_routes._select_request_tools(payload, tools_on = True, mcp_allowed = False)+ )+ assert selected == []+++def test_read_skill_tool_keeps_pagination_consistent_with_tight_room(isolated_skills, monkeypatch):+ from core.inference import tools as tools_module++ home, _ = isolated_skills+ _write_skill(home, "agents", "paged", body = "x" * 12_000)+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)++ result = tools_module.execute_tool(+ "read_skill",+ {"name": "paged"},+ context_tokens = 4096,+ result_budget_tokens = 300,+ )++ assert "Resource continues. Call read_skill again" in result+ header = next(line for line in result.splitlines() if line.startswith("Characters:"))+ end = int(header.split("-")[1].split()[0])+ assert f"offset={end}." in result+ assert "truncated to" not in result+++# Account scoping: the owner keeps the home folders, a managed account gets its own workspace.++_ALICE_ID = "a" * 32+_BOB_ID = "b" * 32+++def managed_accounts(isolated_skills, monkeypatch):+ from utils.account_context import AccountContext++ home, studio = isolated_skills+ monkeypatch.setattr(skills, "_owner_home", lambda: home)+ monkeypatch.setattr(+ skills, "_BUNDLED_ROOT", ("bundled", Path(skills.__file__).with_name("bundled_skills"))+ )+ monkeypatch.setattr(skills, "workspace_root", lambda: studio / "accounts" / _account_id())+ return home, studio, AccountContext(_ALICE_ID, "alice"), AccountContext(_BOB_ID, "bob")+++def _account_id() -> str:+ from utils.account_context import current_account_id+ return current_account_id()+++def _account_skill(studio: Path, account_id: str, name: str, description: str) -> None:+ root = studio / "accounts" / account_id / "skills" / name+ root.mkdir(parents = True)+ (root / "SKILL.md").write_text(+ f"---\nname: {name}\ndescription: {description}\n---\nBody", encoding = "utf-8"+ )+++def test_managed_account_never_sees_the_owners_home_skills(managed_accounts):+ from utils.account_context import run_as++ home, studio, alice, bob = managed_accounts+ _write_skill(home, "agents", "owner-only", description = "OWNER_PRIVATE")+ _write_skill(home, "claude", "owner-claude", description = "OWNER_PRIVATE")+ _account_skill(studio, _ALICE_ID, "alice-skill", "ALICE_PRIVATE")++ owner_names = [record["name"] for record in skills.list_skills()]+ assert owner_names == ["owner-only", "owner-claude", "skill-creator"]++ alice_records = run_as(alice, skills.list_skills)+ assert [(r["name"], r["source"]) for r in alice_records] == [+ ("alice-skill", "agents"),+ ("skill-creator", "bundled"),+ ]+ assert run_as(bob, skills.list_skills)[0]["name"] == "skill-creator"+ assert "ALICE_PRIVATE" not in str(run_as(bob, skills.list_skills))++ with pytest.raises(skills.SkillNotFoundError):+ run_as(alice, skills.read_skill_resource, "owner-only")+ with pytest.raises(skills.SkillNotFoundError):+ run_as(bob, skills.read_skill_resource, "alice-skill")+ assert "Body" in run_as(alice, skills.read_skill_resource, "alice-skill")+++def test_managed_account_overrides_and_creation_stay_in_its_workspace(managed_accounts):+ from utils.account_context import run_as++ home, studio, alice, bob = managed_accounts+ _write_skill(home, "agents", "shared-name", description = "owner copy")+ _account_skill(studio, _ALICE_ID, "shared-name", "alice copy")++ # Alice disabling her copy leaves the owner's enabled and writes only her overrides file.+ assert run_as(alice, skills.set_skill_enabled, "shared-name", False)["enabled"] is False+ assert (studio / "accounts" / _ALICE_ID / "skill-overrides.json").is_file()+ assert not (studio / "skill-overrides.json").exists()+ assert next(r for r in skills.list_skills() if r["name"] == "shared-name")["enabled"] is True+ assert run_as(bob, skills.enabled_skills) == []++ # Bob toggling a skill he cannot see is a not-found, not a write into Alice's file.+ with pytest.raises(skills.SkillNotFoundError):+ run_as(bob, skills.set_skill_enabled, "shared-name", False)+ assert not (studio / "accounts" / _BOB_ID / "skill-overrides.json").exists()++ # create_skill lands in the caller's own workspace, never in the owner's home.+ record = run_as(bob, skills.create_skill, "bob-made", "Bob's skill", "Instructions")+ assert record["path"] == "skills/bob-made/SKILL.md"+ assert (studio / "accounts" / _BOB_ID / "skills" / "bob-made" / "SKILL.md").is_file()+ assert not (home / ".agents" / "skills" / "bob-made").exists()+ assert [r["name"] for r in run_as(bob, skills.enabled_skills)] == ["bob-made"]+ assert "bob-made" not in [r["name"] for r in skills.list_skills()]++ owner_record = skills.create_skill("owner-made", "Owner's skill", "Instructions")+ assert owner_record["path"] == "~/.agents/skills/owner-made/SKILL.md"+ assert (home / ".agents" / "skills" / "owner-made" / "SKILL.md").is_file()+++def test_inference_catalog_cache_is_per_account(managed_accounts, monkeypatch):+ import asyncio++ from routes import inference as inference_routes+ from utils.account_context import run_as++ home, studio, alice, bob = managed_accounts+ _write_skill(home, "agents", "owner-only", description = "OWNER_PRIVATE")+ _account_skill(studio, _ALICE_ID, "alice-skill", "ALICE_PRIVATE")+ monkeypatch.setattr(inference_routes, "_AGENT_SKILLS_CACHE", {})++ assert [s["name"] for s in inference_routes._enabled_agent_skills()] == ["owner-only"]+ assert [s["name"] for s in run_as(alice, inference_routes._enabled_agent_skills)] == [+ "alice-skill"+ ]+ assert run_as(bob, inference_routes._enabled_agent_skills) == []+ assert set(inference_routes._AGENT_SKILLS_CACHE) == {None, _ALICE_ID, _BOB_ID}++ # The catalog a request is built from follows the acting account.+ from models.inference import ChatCompletionRequest++ payload = ChatCompletionRequest(+ model = "test", messages = [{"role": "user", "content": "hi"}], enable_tools = True+ )++ def select():+ return asyncio.run(+ inference_routes._select_request_tools(payload, tools_on = True, mcp_allowed = False)+ )++ assert "read_skill" in [t["function"]["name"] for t in run_as(alice, select)]+ assert [+ t["function"]["name"] for t in run_as(bob, select) if "skill" in t["function"]["name"]+ ] == []+ nudge = run_as(+ alice,+ lambda: inference_routes._build_tool_action_nudge(+ tools = run_as(alice, select), model_name = "test"+ ),+ )+ assert "ALICE_PRIVATE" in nudge and "OWNER_PRIVATE" not in nudge++ inference_routes._invalidate_agent_skills_cache()+ assert inference_routes._AGENT_SKILLS_CACHE == {}+++def test_read_skill_page_floor_reports_no_room_instead_of_slivers(isolated_skills, monkeypatch):+ from core.inference import tools as tools_module++ home, _ = isolated_skills+ monkeypatch.setattr(skills, "_owner_home", lambda: home)+ _write_skill(home, "agents", "long", body = "x" * 12_000)+ # Whatever the room, a page smaller than the floor is not worth a round trip.+ monkeypatch.setattr(tools_module, "_fit_result_to_room", lambda result, name: result[:40])+ result = tools_module.execute_tool("read_skill", {"name": "long"})+ assert result.startswith("Error: Not enough context room")+++def test_read_resource_rejects_ancestor_swapped_after_selection(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ root = _write_skill(home, "agents", "reader")+ (root / "guide.md").write_text("safe", encoding = "utf-8")+ skills_root = root.parent+ outside = home / "outside"+ _write_skill(outside, "agents", "reader")+ (outside / ".agents" / "skills" / "reader" / "guide.md").write_text("secret", encoding = "utf-8")+ original_selected_skill = skills._selected_skill++ def replacing_selected_skill(name, *, home = None):+ selection = original_selected_skill(name, home = home)+ # The skill directory itself stays a real directory; only its parent is swapped.+ skills_root.rename(home / "original-skills")+ try:+ skills_root.symlink_to(outside / ".agents" / "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")+ return selection++ monkeypatch.setattr(skills, "_selected_skill", replacing_selected_skill)+ with pytest.raises(skills.SkillError, match = "changed after it was selected"):+ skills.read_skill_resource("reader", "guide.md", home = home)+++ os.name == "nt",+ reason = "Windows sharing semantics refuse to replace a manifest that is still open for writing",+)+def test_failed_create_keeps_a_manifest_another_writer_replaced(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ manifest = home / ".agents" / "skills" / "racer" / "SKILL.md"+ original_fsync = os.fsync++ def replacing_fsync(descriptor):+ original_fsync(descriptor)+ replacement = manifest.with_name("SKILL.md.new")+ replacement.write_text(+ "---\nname: racer\ndescription: Theirs.\n---\nTHEIRS", encoding = "utf-8"+ )+ os.replace(replacement, manifest)++ monkeypatch.setattr(os, "fsync", replacing_fsync)+ with pytest.raises(skills.SkillError, match = "changed while the manifest was being written"):+ skills.create_skill("racer", "Mine.", "MINE", home = home)++ assert manifest.read_text(encoding = "utf-8").endswith("THEIRS")+++def test_unreadable_root_reports_itself_without_hiding_other_roots(isolated_skills):+ if os.name == "nt" or os.geteuid() == 0:+ pytest.skip("permission bits are not enforced for this user")+ home, _ = isolated_skills+ _write_skill(home, "claude", "visible")+ unreadable = home / ".agents" / "skills"+ unreadable.mkdir(parents = True)+ unreadable.chmod(0)+ try:+ records = skills.list_skills(home = home)+ finally:+ unreadable.chmod(0o700)++ assert next(item for item in records if item["name"] == "visible")["valid"] is True+ failed = next(item for item in records if item["source"] == "agents")+ assert failed["valid"] is False+ assert "scan" in failed["error"]+++def test_root_entry_limit_ignores_hidden_and_regular_files(isolated_skills):+ home, _ = isolated_skills+ root = _write_skill(home, "agents", "counted").parent+ for index in range(skills.MAX_SKILLS_PER_ROOT):+ (root / f".hidden-{index}").write_text("", encoding = "utf-8")+ (root / "README.md").write_text("about these skills", encoding = "utf-8")++ records = skills.list_skills(home = home)++ assert [item["name"] for item in records] == ["counted"]+++def test_corrupt_overrides_are_ignored_and_repaired_by_the_next_toggle(isolated_skills):+ home, studio = isolated_skills+ _write_skill(home, "agents", "sturdy")+ studio.mkdir()+ (studio / "skill-overrides.json").write_text("{not json", encoding = "utf-8")++ assert next(item for item in skills.list_skills(home = home) if item["name"] == "sturdy")[+ "enabled"+ ]+ skills.set_skill_enabled("sturdy", False, home = home)++ assert json.loads((studio / "skill-overrides.json").read_text(encoding = "utf-8")) == {+ "sturdy": False+ }+ (studio / "skill-overrides.json").write_text(+ '{"sturdy": "no", "Bad Name": false, "other": true}', encoding = "utf-8"+ )+ assert next(item for item in skills.list_skills(home = home) if item["name"] == "sturdy")[+ "enabled"+ ]+++def test_indented_separator_inside_a_block_scalar_stays_in_the_frontmatter(isolated_skills):+ home, _ = isolated_skills+ _write_skill(+ home,+ "agents",+ "divided",+ description = "|\n Use for reports.\n ---\n Also for summaries.",+ )++ record = next(item for item in skills.list_skills(home = home) if item["name"] == "divided")++ assert record["valid"] is True+ assert record["description"] == "Use for reports.\n---\nAlso for summaries."+++def test_read_skill_tool_applies_defaults_for_null_arguments(isolated_skills, monkeypatch):+ from core.inference import tools as tools_module++ home, _ = isolated_skills+ _write_skill(home, "agents", "nullable", body = "Body text")+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)++ result = tools_module.execute_tool(+ "read_skill", {"name": "nullable", "resource": None, "offset": None}+ )++ assert "Body text" in result+++def test_reserved_device_name_resource_gets_its_own_message(isolated_skills):+ home, _ = isolated_skills+ _write_skill(home, "agents", "reserved")++ with pytest.raises(skills.SkillError, match = "reserved device name"):+ skills.read_skill_resource("reserved", "con.md", home = home)+++def test_aliased_metadata_cannot_expand_past_the_manifest_limit(isolated_skills):+ home, _ = isolated_skills+ big = "x" * (4 * 1024)+ aliases = "\n".join(f" k{i}: *big" for i in range(8))+ _write_skill(+ home,+ "agents",+ "aliased",+ frontmatter = f"big: &big {big}\nmetadata:\n{aliases}",+ )++ record = next(r for r in skills.list_skills(home = home) if r["name"] == "aliased")++ assert record["valid"] is False and "16 KB" in record["error"]++[email protected]("field", ["allowed-tools", "license"])+def test_oversized_scalar_fields_are_rejected(isolated_skills, field):+ home, _ = isolated_skills+ _write_skill(home, "agents", "wide", frontmatter = f"{field}: {'x' * 2000}")++ 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"]diff --git a/studio/frontend/src/components/assistant-ui/skill-mentions.tsx b/studio/frontend/src/components/assistant-ui/skill-mentions.tsxnew file mode 100644index 00000000000..7b9449cccb7--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/skill-mentions.tsx@@ -0,0 +1,391 @@+// 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 {+ SKILL_MENTION_PATTERN,+ type SkillRecord,+ refreshSkillsCatalog,+ useSkillsCatalog,+} from "@/features/chat";+import { useT } from "@/i18n";+import type {+ Unstable_DirectiveFormatter,+ Unstable_DirectiveSegment,+} from "@assistant-ui/core";+import {+ ComposerPrimitive,+ unstable_useMentionAdapter,+} from "@assistant-ui/react";+import { BookOpen01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import {+ type KeyboardEvent,+ type MutableRefObject,+ type ReactElement,+ type RefObject,+ useCallback,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";++function enabled(records: readonly SkillRecord[]): readonly SkillRecord[] {+ return records.filter(+ (skill) => skill.valid && !skill.shadowed && skill.enabled,+ );+}++// The catalog allows 1,000 skills per root; a keystroke must not render them all.+const MAX_MENTION_RESULTS = 50;++const skillMentionFormatter: Unstable_DirectiveFormatter = {+ serialize: (item) => `@${item.label}`,+ parse(text) {+ const segments: Unstable_DirectiveSegment[] = [];+ let lastIndex = 0;++ // Same pattern as the send path, so a chip and a catalog lookup agree on what a mention is.+ for (const match of text.matchAll(SKILL_MENTION_PATTERN)) {+ const whitespace = match[1] ?? "";+ const mentionStart = match.index + whitespace.length;+ if (mentionStart > lastIndex) {+ segments.push({+ kind: "text",+ text: text.slice(lastIndex, mentionStart),+ });+ }+ const label = match[2] ?? "";+ segments.push({+ kind: "mention",+ type: "skill",+ label,+ id: label,+ });+ lastIndex = match.index + match[0].length;+ }++ if (lastIndex < text.length) {+ segments.push({ kind: "text", text: text.slice(lastIndex) });+ }+ return segments;+ },+};++function useHighlightedItemScroll(root: HTMLElement | null) {+ useEffect(() => {+ if (!root) return;+ const scroll = () => {+ root+ .querySelector<HTMLElement>("[data-highlighted]")+ ?.scrollIntoView({ block: "nearest" });+ };+ const observer = new MutationObserver(scroll);+ observer.observe(root, {+ subtree: true,+ attributes: true,+ attributeFilter: ["data-highlighted"],+ });+ scroll();+ return () => observer.disconnect();+ }, [root]);+}++// Mounted inside the results list; reports whether Enter would pick a row rather than send.+function MentionEnterSignal({+ onChange,+ active,+}: {+ onChange?: (consumesEnter: boolean) => void;+ active: boolean;+}): null {+ useEffect(() => {+ if (!onChange) return;+ onChange(active);+ return () => onChange(false);+ }, [active, onChange]);+ return null;+}++export function SkillMentionPopover({+ enabled: mentionsEnabled,+ onConsumesEnterChange,+}: {+ enabled: boolean;+ onConsumesEnterChange?: (consumesEnter: boolean) => void;+}): ReactElement | null {+ const t = useT();+ const { skills } = useSkillsCatalog();+ const [listElement, setListElement] = useState<HTMLDivElement | null>(null);+ const available = mentionsEnabled ? enabled(skills) : [];+ const items = useMemo(+ () =>+ available.map((skill) => ({+ id: skill.name,+ type: "skill",+ label: skill.name,+ description: skill.description,+ })),+ [available],+ );+ const mention = unstable_useMentionAdapter({+ items,+ includeModelContextTools: false,+ formatter: skillMentionFormatter,+ });+ // Cap the search itself: the popover navigates and inserts from these results, not the rendered rows.+ const adapter = useMemo(+ () => ({+ ...mention.adapter,+ search: (query: string) =>+ (mention.adapter.search?.(query) ?? []).slice(0, MAX_MENTION_RESULTS),+ }),+ [mention.adapter],+ );+ useHighlightedItemScroll(listElement);+ if (items.length === 0) return null;++ return (+ <ComposerPrimitive.Unstable_TriggerPopover+ char="@"+ adapter={adapter}+ aria-label={t("skills.mentions")}+ className="data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 absolute bottom-[calc(100%+8px)] left-3 z-40 w-[min(360px,calc(100%-24px))] overflow-hidden rounded-lg border border-border/60 bg-popover p-1 text-popover-foreground shadow-border duration-100"+ >+ <ComposerPrimitive.Unstable_TriggerPopover.Directive+ {...mention.directive}+ />+ <ComposerPrimitive.Unstable_TriggerPopoverItems>+ {(results) => (+ <>+ <MentionEnterSignal+ onChange={onConsumesEnterChange}+ active={results.length > 0}+ />+ <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">+ {t("skills.mentions")}+ </div>+ <div ref={setListElement} className="max-h-64 overflow-y-auto">+ {results.map((item, index) => (+ <ComposerPrimitive.Unstable_TriggerPopoverItem+ key={item.id}+ item={item}+ index={index}+ 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+ icon={BookOpen01Icon}+ strokeWidth={1.75}+ className="mt-0.5 size-4 shrink-0 text-primary"+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium">+ {item.label}+ </span>+ {item.description ? (+ <span className="line-clamp-2 max-h-8 overflow-hidden break-words text-xs leading-4 text-muted-foreground">+ {item.description}+ </span>+ ) : null}+ </span>+ </ComposerPrimitive.Unstable_TriggerPopoverItem>+ ))}+ </div>+ </>+ )}+ </ComposerPrimitive.Unstable_TriggerPopoverItems>+ </ComposerPrimitive.Unstable_TriggerPopover>+ );+}++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] ?? "" };+}++export function useTextareaSkillMentions({+ text,+ setText,+ inputRef,+ composingRef,+ enabled: mentionsEnabled,+}: {+ text: string;+ setText: (text: string) => void;+ inputRef: RefObject<HTMLTextAreaElement | null>;+ composingRef: MutableRefObject<boolean>;+ enabled: boolean;+}) {+ const t = useT();+ const { skills } = useSkillsCatalog();+ const [range, setRange] = useState<MentionRange>(null);+ const listboxId = useId();+ const [highlighted, setHighlighted] = useState(0);+ const results = useMemo(() => {+ if (!range) return [];+ const query = range.query.toLowerCase();+ if (!mentionsEnabled) return [];+ const matches: SkillRecord[] = [];+ for (const skill of enabled(skills)) {+ if (+ skill.name.toLowerCase().includes(query) ||+ skill.description.toLowerCase().includes(query)+ ) {+ matches.push(skill);+ if (matches.length === MAX_MENTION_RESULTS) break;+ }+ }+ return matches;+ }, [mentionsEnabled, range, skills]);++ const open = range !== null && results.length > 0;+ const activeOptionId = open+ ? `${listboxId}-option-${highlighted}`+ : undefined;+ useEffect(() => {+ if (+ !mentionsEnabled ||+ (range &&+ (text.length < range.end ||+ !text.slice(range.start, range.end).startsWith("@")))+ ) {+ setRange(null);+ }+ }, [mentionsEnabled, range, text]);++ const resultsRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!range) return;+ resultsRef.current+ ?.querySelector<HTMLElement>(`[data-mention-index="${highlighted}"]`)+ ?.scrollIntoView({ block: "nearest" });+ }, [highlighted, range]);++ const update = useCallback(+ (nextText: string, caret: number) => {+ if (composingRef.current) {+ setRange(null);+ return;+ }+ const next = mentionAtCaret(nextText, caret);+ // A fresh @ re-reads the folders, so a skill written since page load is offered.+ if (next?.query === "") refreshSkillsCatalog();+ setRange(next);+ setHighlighted(0);+ },+ [composingRef],+ );++ const insert = useCallback(+ (skill: SkillRecord) => {+ if (!range) return;+ const directive = skillMentionFormatter.serialize({+ id: skill.name,+ 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);+ setRange(null);+ requestAnimationFrame(() => {+ inputRef.current?.focus();+ inputRef.current?.setSelectionRange(caret, caret);+ });+ },+ [inputRef, range, setText, text],+ );++ const onKeyDown = useCallback(+ (event: KeyboardEvent<HTMLTextAreaElement>): boolean => {+ if (!range || composingRef.current || results.length === 0) return false;+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ const direction = event.key === "ArrowDown" ? 1 : -1;+ setHighlighted(+ (index) => (index + direction + results.length) % results.length,+ );+ return true;+ }+ if ((event.key === "Enter" && !event.shiftKey) || event.key === "Tab") {+ event.preventDefault();+ insert(results[highlighted] ?? results[0]);+ return true;+ }+ if (event.key === "Escape") {+ event.preventDefault();+ setRange(null);+ return true;+ }+ return false;+ },+ [composingRef, highlighted, insert, range, results],+ );++ const popover = open ? (+ <div className="animate-in fade-in-0 zoom-in-95 absolute bottom-[calc(100%+8px)] left-3 z-40 w-[min(360px,calc(100%-24px))] overflow-hidden rounded-lg border border-border/60 bg-popover p-1 text-popover-foreground shadow-border duration-100">+ <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">+ {t("skills.mentions")}+ </div>+ <div+ ref={resultsRef}+ id={listboxId}+ role="listbox"+ aria-label={t("skills.mentions")}+ className="max-h-64 overflow-y-auto"+ >+ {results.map((skill, index) => (+ <button+ key={`${skill.source}:${skill.name}`}+ type="button"+ id={`${listboxId}-option-${index}`}+ role="option"+ aria-selected={index === highlighted}+ tabIndex={-1}+ data-mention-index={index}+ data-highlighted={index === highlighted}+ 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=true]:bg-accent data-[highlighted=true]:text-accent-foreground"+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => insert(skill)}+ onMouseEnter={() => setHighlighted(index)}+ >+ <HugeiconsIcon+ icon={BookOpen01Icon}+ strokeWidth={1.75}+ className="mt-0.5 size-4 shrink-0 text-primary"+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium">+ {skill.name}+ </span>+ <span className="line-clamp-2 max-h-8 overflow-hidden break-words text-xs leading-4 text-muted-foreground">+ {skill.description}+ </span>+ </span>+ </button>+ ))}+ </div>+ </div>+ ) : null;++ return {+ update,+ onKeyDown,+ popover,+ close: () => setRange(null),+ inputProps: {+ role: "combobox" as const,+ "aria-autocomplete": "list" as const,+ "aria-expanded": open,+ "aria-controls": open ? listboxId : undefined,+ "aria-activedescendant": activeOptionId,+ },+ };+}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex dd2e6a02db7..6e7fedf801b 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -43,12 +43,16 @@ import { ToolGroup } from "@/components/assistant-ui/tool-group";import { CodeExecutionToolUI } from "@/components/assistant-ui/tool-ui-code-execution";import { ImageGenerationToolUI } from "@/components/assistant-ui/tool-ui-image-generation";import { KnowledgeBaseToolUI } from "@/components/assistant-ui/tool-ui-knowledge-base";+import { ReadSkillToolUI } from "@/components/assistant-ui/tool-ui-read-skill";+import { SkillMentionPopover } from "@/components/assistant-ui/skill-mentions";import { RenderHtmlToolUI } from "@/components/assistant-ui/tool-ui-render-html";import { PythonToolUI } from "@/components/assistant-ui/tool-ui-python";import { TerminalToolUI } from "@/components/assistant-ui/tool-ui-terminal";import { WebSearchToolUI } from "@/components/assistant-ui/tool-ui-web-search";import { ChatDictationBar } from "@/components/assistant-ui/chat-dictation-bar";import {+ ChatSkillsDialog,+PROMPT_QUEUE_DRAG_TYPE,attachmentsPastedText,hasPendingPromptQueueStart,@@ -69,6 +73,7 @@ import {stripSearchImageTokens,useChatActive,useInComparePane,+ refreshSkillsCatalog,} from "@/features/chat";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";import {@@ -2365,6 +2370,8 @@ const Composer: FC<{(s) => s.setImageToolsEnabled,);const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled);++ const supportsTools = useChatRuntimeStore((s) => s.supportsTools);const codeToolsEnabled = useChatRuntimeStore((s) => s.codeToolsEnabled);const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);const supportsBuiltinImageGeneration = useChatRuntimeStore(@@ -2460,9 +2467,15 @@ const Composer: FC<{// Thread on screen, so the guard can tell whether a write belongs to the// thread that sent. Kept in step by the effect alongside pasteDraftKeyRef.const draftKeyRef = useRef<string | null>(null);+ // True while the @skill picker has a row to pick, so Enter selects it instead of sending.+ const mentionConsumesEnterRef = useRef(false);+ const setMentionConsumesEnter = useCallback((consumesEnter: boolean) => {+ mentionConsumesEnterRef.current = consumesEnter;+ }, []);const { inputProps, isComposing, isComposingRef } =useImeComposerInputHandlers({submitOnEnter: true,+ skipEnterRef: mentionConsumesEnterRef,onModEnter: queueOnModEnter,justSentRef,draftKeyRef,@@ -2481,6 +2494,8 @@ const Composer: FC<{plainPasteAtRef.current = isPlainPasteChord(event)? performance.now(): 0;+ // A fresh @ re-reads the skill folders, so a skill written since page load is offered.+ if (event.key === "@") refreshSkillsCatalog();},[],);@@ -4959,6 +4974,11 @@ const Composer: FC<{return (<PromptQueueContext.Provider value={queueContextValue}>+ <ComposerPrimitive.Unstable_TriggerPopoverRoot>+ <SkillMentionPopover+ enabled={supportsTools}+ onConsumesEnterChange={setMentionConsumesEnter}+ /><ComposerPrimitive.Rootref={attachComposer}// Out of find-in-page's reach: the draft itself lives in a textarea the index cannot read, so@@ -5015,6 +5035,7 @@ const Composer: FC<{</ComposerPrimitive.AttachmentDropzone>)}</ComposerPrimitive.Root>+ </ComposerPrimitive.Unstable_TriggerPopoverRoot></PromptQueueContext.Provider>);};@@ -5071,11 +5092,14 @@ const IME_STUCK_TIMEOUT_MS = 2500;function useImeComposerInputHandlers({submitOnEnter = false,+ skipEnterRef,onModEnter,justSentRef,draftKeyRef,}: {submitOnEnter?: boolean;+ /** Set while a composer popover will consume plain Enter itself. */+ skipEnterRef?: RefObject<boolean>;/** Cmd/Ctrl+Enter without Shift, claimed before the plain-Enter submit. */onModEnter?: (event: KeyboardEvent<HTMLTextAreaElement>) => void;// Guard armed by the last send or queue. See setComposerText below.@@ -5236,7 +5260,12 @@ function useImeComposerInputHandlers({onModEnter(e);return;}- if (submitOnEnter && e.key === "Enter" && !e.shiftKey) {+ if (+ submitOnEnter &&+ e.key === "Enter" &&+ !e.shiftKey &&+ !skipEnterRef?.current+ ) {e.preventDefault();e.currentTarget.form?.requestSubmit();}@@ -5246,6 +5275,7 @@ function useImeComposerInputHandlers({onModEnter,refreshStuckTimer,setCompositionState,+ skipEnterRef,submitOnEnter,],);@@ -5971,6 +6001,7 @@ const ComposerToolsMenu: FC<{}, [navigate]);const [newProjectOpen, setNewProjectOpen] = useState(false);+ const [skillsOpen, setSkillsOpen] = useState(false);const [promptStorageOpen, setPromptStorageOpen] = useState(false);const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);const aui = useAui();@@ -6081,6 +6112,12 @@ const ComposerToolsMenu: FC<{) : null}</DropdownMenuItem>),+ skills: (+ <DropdownMenuItem onSelect={() => setSkillsOpen(true)}>+ <HugeiconsIcon icon={BookOpen01Icon} strokeWidth={2} />+ Agent Skills+ </DropdownMenuItem>+ ),savedPrompts: (<DropdownMenuSub><DropdownMenuSubTrigger>@@ -6225,6 +6262,7 @@ const ComposerToolsMenu: FC<{return (<>+ <ChatSkillsDialog open={skillsOpen} onOpenChange={setSkillsOpen} /><PromptStorageDialogopen={promptStorageOpen}onOpenChange={setPromptStorageOpen}@@ -7251,6 +7289,10 @@ const ImageGenerationToolUIConfirmable = withToolConfirmation(ImageGenerationToolUI,);const RenderHtmlToolUIConfirmable = withToolConfirmation(RenderHtmlToolUI);+// Read at render time, not module scope: the skill modules reach the chat barrel.+const ReadSkillToolUIConfirmable = withToolConfirmation((props) => (+ <ReadSkillToolUI {...props} />+));const ToolFallbackConfirmable = withToolConfirmation(ToolFallback);/**@@ -7272,6 +7314,7 @@ const ASSISTANT_PART_COMPONENTS = {by_name: {web_search: WebSearchToolUIConfirmable,search_knowledge_base: KnowledgeBaseToolUIConfirmable,+ read_skill: ReadSkillToolUIConfirmable,python: PythonToolUIConfirmable,terminal: TerminalToolUIConfirmable,code_execution: CodeExecutionToolUIConfirmable,@@ -7282,6 +7325,7 @@ const ASSISTANT_PART_COMPONENTS = {},} as const;+// Live in-place denoising canvas for DiffusionGemma: while generating, render the// latest per-step canvas snapshot in the bubble so the user watches the answer resolve// out of noise. Transient (store-only, cleared on run end), so the finished messagediff --git a/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsxnew file mode 100644index 00000000000..c119065bd5b--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx@@ -0,0 +1,77 @@+// 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 { Spinner } from "@/components/ui/spinner";+import { useToolAwaitingApproval } from "@/features/chat/tool-approval";+import { stringifyToolResult } from "@/lib/strip-ansi";+import {+ type ToolCallMessagePartComponent,+ useAuiState,+} from "@assistant-ui/react";+import { BookOpenIcon } from "lucide-react";+import { memo } from "react";+import { toolArgText } from "./tool-arg-text";+import {+ ToolFallbackContent,+ ToolFallbackRoot,+ ToolFallbackTrigger,+} from "./tool-fallback";+import { useToolActivityOpen } from "./use-tool-activity-open";++const ReadSkillToolUIImpl: ToolCallMessagePartComponent = ({+ args,+ result,+ status,+ toolCallId,+}) => {+ const name = toolArgText((args as { name?: unknown })?.name) || "skill";+ const resource =+ toolArgText((args as { resource?: unknown })?.resource) || "SKILL.md";+ const isRunning = status?.type === "running";+ const resultText = result == null ? "" : stringifyToolResult(result);+ const hasText = useAuiState(({ message }) =>+ message.content.some(+ (part) =>+ part.type === "text" &&+ "text" in part &&+ (part as { text: string }).text.length > 0,+ ),+ );+ const awaitingApproval = useToolAwaitingApproval(toolCallId);+ const [open, setOpen] = useToolActivityOpen(isRunning, hasText);++ return (+ <ToolFallbackRoot+ open={open}+ onOpenChange={setOpen}+ awaitingApproval={awaitingApproval}+ >+ <ToolFallbackTrigger+ toolName={isRunning ? `Reading ${name}…` : `Read ${name} · ${resource}`}+ status={status}+ icon={BookOpenIcon}+ />+ <ToolFallbackContent>+ {isRunning ? (+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <Spinner className="size-3.5" />+ <span>Reading {name}…</span>+ </div>+ ) : resultText ? (+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">+ {resultText}+ </pre>+ ) : (+ <div className="text-sm text-muted-foreground">+ Loaded {resource}.+ </div>+ )}+ </ToolFallbackContent>+ </ToolFallbackRoot>+ );+};++export const ReadSkillToolUI = memo(+ ReadSkillToolUIImpl,+) as unknown as ToolCallMessagePartComponent;+ReadSkillToolUI.displayName = "ReadSkillToolUI";diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 8de48344672..7754c8230e1 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -39,6 +39,28 @@ import { loadManagedLlamaFlags } from "@/features/model-picker/api/llama-flags";import { fetchLoadExtraArgs } from "@/features/model-picker/api/model-overrides";import { sanitizeStoredExtraArgs } from "@/features/model-picker/model-config/llama-extra-args";import { usePlatformStore } from "@/config/env";++import { getSkillsSnapshot, settleSkillsForText } from "./skills-api";++function lastUserText(+ messages: readonly { role?: string; content?: unknown }[],+): string {+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (message?.role !== "user") continue;+ const content = message.content;+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content+ .map((part) =>+ part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string"+ ? (part as { text: string }).text+ : "",+ )+ .join(" ");+ }+ return "";+}import { projectHasSources } from "@/features/rag/api/rag-api";import {IMAGE_SENTINEL_TOOLS,@@ -1804,13 +1826,19 @@ export async function buildLocalTokenCountExtras(? await projectHasSources(ragProjectId): false;const ragOn = ragEnabled || projectRagEnabled;++ await settleSkillsForText("");+ const hasEnabledSkills = getSkillsSnapshot().skills.some(+ (skill) => skill.valid && !skill.shadowed && skill.enabled,+ );if (!toolsEnabled &&!codeToolsEnabled &&!artifactsEnabled &&!mcpEnabledForChat &&!ragOn &&- !deepResearchEnabled+ !deepResearchEnabled &&+ !hasEnabledSkills) {// Explicit false, not omission: the server defaults tools on. The permission level rides// along because `--enable-tools` still outranks that false in _effective_enable_tools.@@ -1834,6 +1862,8 @@ export async function buildLocalTokenCountExtras(...(toolsEnabled ? ["web_search"] : []),...(codeToolsEnabled ? ["python", "terminal", "edit_file"] : []),...(artifactsEnabled ? ["render_html"] : []),+ // Same gate as the request: with no enabled skill neither tool is sent, so neither is priced.+ ...(hasEnabledSkills ? ["read_skill", "create_skill"] : []),],mcp_enabled: mcpEnabledForChat,// Top level, not inside rag_scope: an archived thread puts search_conversation and its@@ -5754,6 +5784,12 @@ export function createOpenAIStreamAdapter(const buildRequestPayload = async (forceRefreshPublicKey = false,): Promise<OpenAIChatCompletionsRequest> => {+ if (supportsStudioToolsForThisTurn) {+ await settleSkillsForText(lastUserText(outboundMessages));+ }+ const hasEnabledSkills = getSkillsSnapshot().skills.some(+ (skill) => skill.valid && !skill.shadowed && skill.enabled,+ );if (externalSelection && externalProvider) {// Per-thread container reuse; empty falls back to container_auto. Anthropic uses its own key.// Anthropic uses anthropicCodeExecContainerId.@@ -5911,6 +5947,7 @@ export function createOpenAIStreamAdapter(mcpEnabledForChat ||ragEnabled ||projectRagEnabled ||+ hasEnabledSkills ||// Armed research needs Studio's loop: deep_research is appended past every tool filter, but// only for a request that asked for the loop at all.deepResearchArmed)@@ -5921,6 +5958,9 @@ export function createOpenAIStreamAdapter(? ["search_knowledge_base"]: []),...(toolsEnabled ? ["web_search"] : []),+ ...(hasEnabledSkills+ ? ["read_skill", "create_skill"]+ : []),...studioLocalCodeTools,// Hosted tools with no local stand-in; their pills stay lit regardless, so listing only local// names dropped Images/Fetch whenever another tool selected this branch. Search is excluded@@ -6146,13 +6186,14 @@ export function createOpenAIStreamAdapter(bypass_permissions: bypassPermissions,...(deepResearchArmed ? { deep_research_armed: true } : {}),...(supportsTools &&- (toolsEnabled ||- codeToolsEnabled ||- renderHtmlToolEnabledForThisTurn ||- mcpEnabledForChat ||- ragEnabled ||- projectRagEnabled ||- deepResearchArmed)+ (toolsEnabled ||+ codeToolsEnabled ||+ renderHtmlToolEnabledForThisTurn ||+ mcpEnabledForChat ||+ ragEnabled ||+ projectRagEnabled ||+ hasEnabledSkills ||+ deepResearchArmed)? {enable_tools: true,enabled_tools: [@@ -6161,6 +6202,9 @@ export function createOpenAIStreamAdapter(? ["search_knowledge_base"]: []),...(toolsEnabled ? ["web_search"] : []),+ ...(hasEnabledSkills+ ? ["read_skill", "create_skill"]+ : []),...(codeToolsEnabled? ["python", "terminal", "edit_file"]: []),@@ -6211,7 +6255,8 @@ export function createOpenAIStreamAdapter(return mins >= 9999 ? 9999 : mins * 60;})(),}- : // Explicit false, not omission: the server defaults tools on for a request that never mentions them.+ : // Explicit false keeps UI-off tools disabled; --enable-tools still overrides it+ // and sees no exhaustive enabled_tools list, so it can supply the default catalog.{ enable_tools: false }),};};diff --git a/studio/frontend/src/features/chat/api/skills-api.ts b/studio/frontend/src/features/chat/api/skills-api.tsnew file mode 100644index 00000000000..b47d55e25c2--- /dev/null+++ b/studio/frontend/src/features/chat/api/skills-api.ts@@ -0,0 +1,210 @@+// 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 { authFetch } from "@/features/auth";+import { AUTH_SESSION_CLEARED_EVENT } from "@/features/auth/session";+import { useEffect, useSyncExternalStore } from "react";++export type SkillRecord = {+ name: string;+ description: string;+ source: "agents" | "claude" | "bundled";+ enabled: boolean;+ valid: boolean;+ shadowed: 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;+};++type SkillsSnapshot = {+ skills: readonly SkillRecord[];+ loading: boolean;+ initialized: boolean;+ error: string | null;+};++const EMPTY_SNAPSHOT: SkillsSnapshot = {+ skills: [],+ loading: false,+ initialized: false,+ error: null,+};+let snapshot = EMPTY_SNAPSHOT;+let requestGeneration = 0;+let lastFetchedAt = 0;+let pending: Promise<readonly SkillRecord[]> | null = null;+const listeners = new Set<() => void>();+const channel =+ typeof BroadcastChannel === "undefined"+ ? null+ : new BroadcastChannel("unsloth-agent-skills");++function publish(next: SkillsSnapshot): void {+ snapshot = next;+ for (const listener of listeners) listener();+}++async function parseResponse<T>(response: Response): Promise<T> {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ const detail =+ body && typeof body === "object" && "detail" in body+ ? String(body.detail)+ : `Request failed (${response.status})`;+ throw new Error(detail);+ }+ return body as T;+}++export function subscribeSkills(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++export function getSkillsSnapshot(): SkillsSnapshot {+ return snapshot;+}++export function listSkills(force = false): Promise<readonly SkillRecord[]> {+ if (pending && !force) return pending;+ const generation = ++requestGeneration;+ publish({ ...snapshot, loading: true, error: null });+ const request = authFetch("/api/skills")+ .then((response) => parseResponse<SkillRecord[]>(response))+ .then((skills) => {+ if (!Array.isArray(skills)) {+ throw new Error("Could not load Agent Skills.");+ }+ return skills;+ })+ .then((skills) => {+ if (generation === requestGeneration) {+ lastFetchedAt = Date.now();+ publish({ skills, loading: false, initialized: true, error: null });+ }+ return skills;+ })+ .catch((error: unknown) => {+ if (generation === requestGeneration) {+ lastFetchedAt = Date.now();+ publish({+ ...snapshot,+ loading: false,+ initialized: true,+ error:+ error instanceof Error+ ? error.message+ : "Could not load Agent Skills.",+ });+ }+ throw error;+ })+ .finally(() => {+ if (pending === request) pending = null;+ });+ pending = request;+ return request;+}++export async function setSkillEnabled(+ name: string,+ enabled: boolean,+): Promise<SkillRecord> {+ const response = await authFetch(+ `/api/skills/${encodeURIComponent(name)}/enabled`,+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled }),+ },+ );+ const updated = await parseResponse<SkillRecord>(response);+ requestGeneration += 1;+ publish({+ skills: snapshot.skills.map((skill) =>+ skill.name === updated.name && !skill.shadowed+ ? { ...skill, enabled: updated.enabled }+ : skill,+ ),+ loading: false,+ initialized: true,+ error: null,+ });+ channel?.postMessage("changed");+ void import("../utils/refresh-context-usage").then(+ ({ refreshContextUsage }) => refreshContextUsage({ invalidate: true }),+ );+ return updated;+}++// 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;++// authFetch has no deadline, so a hung /api/skills must not stall the send.+const SETTLE_TIMEOUT_MS = 3000;++// Finish any in-flight fetch and re-read when the text names an unknown skill (pasted @mentions never refreshed).+export async function settleSkillsForText(text: string): Promise<void> {+ const deadline = new Promise<void>((resolve) =>+ setTimeout(resolve, SETTLE_TIMEOUT_MS),+ );+ if (pending) await Promise.race([pending.catch(() => undefined), deadline]);+ // Usable entries only: an invalid, shadowed or disabled one may have been fixed since.+ const known = new Set(+ snapshot.skills+ .filter((skill) => skill.valid && !skill.shadowed && skill.enabled)+ .map((skill) => skill.name),+ );+ let stale = !snapshot.initialized;+ for (const match of text.matchAll(SKILL_MENTION_PATTERN)) {+ const name = match[2] ?? "";+ if (!known.has(name)) {+ stale = true;+ break;+ }+ }+ if (stale) {+ await Promise.race([listSkills(true).catch(() => undefined), deadline]);+ }+}++// Skills are edited while Studio is open, so the dialog and @ re-read; throttled to one request per burst.+export function refreshSkillsCatalog(maxAgeMs = 1500): void {+ if (pending || Date.now() - lastFetchedAt < maxAgeMs) return;+ void listSkills(true).catch(() => undefined);+}++export function useSkillsCatalog(): SkillsSnapshot {+ const value = useSyncExternalStore(+ subscribeSkills,+ getSkillsSnapshot,+ () => EMPTY_SNAPSHOT,+ );+ useEffect(() => {+ if (!value.initialized && !value.loading)+ void listSkills().catch(() => undefined);+ }, [value.initialized, value.loading]);+ return value;+}++// The snapshot is module state, so a sign-out must drop it or the next account inherits it.+if (typeof window !== "undefined") {+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {+ requestGeneration += 1;+ pending = null;+ lastFetchedAt = 0;+ publish(EMPTY_SNAPSHOT);+ });+}++channel?.addEventListener("message", () => {+ void listSkills(true).catch(() => undefined);+ void import("../utils/refresh-context-usage").then(+ ({ refreshContextUsage }) => refreshContextUsage({ invalidate: true }),+ );+});diff --git a/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsxnew file mode 100644index 00000000000..92afa5ab1c8--- /dev/null+++ b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx@@ -0,0 +1,163 @@+// 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 { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Spinner } from "@/components/ui/spinner";+import { Switch } from "@/components/ui/switch";+import { useT } from "@/i18n";+import { toast } from "@/lib/toast";+import { BookOpen01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { RefreshCwIcon } from "lucide-react";+import { type ReactElement, useEffect, useState } from "react";+import {+ listSkills,+ setSkillEnabled,+ useSkillsCatalog,+} from "../api/skills-api";++export function ChatSkillsDialog({+ open,+ onOpenChange,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}): ReactElement {+ const t = useT();+ const { skills, loading, error } = useSkillsCatalog();+ const [changing, setChanging] = useState<string | null>(null);+ const sourceLabel = (source: "agents" | "claude" | "bundled") =>+ 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.+ useEffect(() => {+ if (open) void listSkills(true).catch(() => undefined);+ }, [open]);++ 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,+ });+ } finally {+ setChanging(null);+ }+ };++ 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={BookOpen01Icon}+ 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>++ <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>+ ) : 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>+ ) : 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-white/[0.06]"+ >+ <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}+ </div>+ <Switch+ aria-label={t(skill.enabled ? "skills.disable" : "skills.enable", {+ name: skill.name,+ })}+ checked={selectable && skill.enabled}+ disabled={!selectable || changing === skill.name}+ onCheckedChange={(checked) =>+ void toggle(skill.name, checked)+ }+ />+ </div>+ </div>+ );+ })}+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex ade81dea8b0..14ad50ca4ac 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -376,3 +376,13 @@ export {generateStudioTtsAudio,releaseTtsAudioUrl,} from "./adapters/studio-speech-synthesis-adapter";+export { ChatSkillsDialog } from "./components/chat-skills-dialog";+export {+ SKILL_MENTION_PATTERN,+ listSkills,+ refreshSkillsCatalog,+ setSkillEnabled,+ settleSkillsForText,+ useSkillsCatalog,+ type SkillRecord,+} from "./api/skills-api";diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 3a5e98a0307..aece9a16ff5 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -8,6 +8,7 @@ import {serverTuningLoadPayload,} from "./lib/server-tuning-fields";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";+import { useTextareaSkillMentions } from "@/components/assistant-ui/skill-mentions";import {thinkEffortAriaLabel,thinkToggleAriaLabel,@@ -69,6 +70,7 @@ import type { ModelLifecycleLease } from "./utils/model-lifecycle-gate";import { useAui } from "@assistant-ui/react";import {ArrowUpIcon,+ BookOpenIcon,ChevronDownIcon,Columns2Icon,GlobeIcon,@@ -109,6 +111,7 @@ import { PermissionModeComposerPill } from "./permission-mode-select";import { reasoningCapsFromLoad } from "./lib/apply-inference-status-to-store";import { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";import { NewProjectDialog } from "./components/new-project-dialog";+import { ChatSkillsDialog } from "./components/chat-skills-dialog";import { useChatProjects } from "./hooks/use-chat-projects";import { confirmRemoteCodeIfNeeded } from "@/features/security";import {@@ -581,6 +584,7 @@ export function SharedComposer({const [dragging, setDragging] = useState(false);const [isComposing, setIsComposing] = useState(false);const [newProjectOpen, setNewProjectOpen] = useState(false);+ const [skillsOpen, setSkillsOpen] = useState(false);const [promptStorageOpen, setPromptStorageOpen] = useState(false);const [recentPrompts, setRecentPrompts] = useState<PromptEntry[]>([]);const refreshRecentPrompts = useCallback(async () => {@@ -650,6 +654,14 @@ export function SharedComposer({const preserveThinking = useChatRuntimeStore((s) => s.preserveThinking);const setPreserveThinking = useChatRuntimeStore((s) => s.setPreserveThinking);const supportsTools = useChatRuntimeStore((s) => s.supportsTools);++ const skillMentions = useTextareaSkillMentions({+ text,+ setText,+ inputRef: textareaRef,+ composingRef,+ enabled: supportsTools,+ });const supportsBuiltinWebSearch = useChatRuntimeStore((s) => s.supportsBuiltinWebSearch,);@@ -1981,6 +1993,12 @@ export function SharedComposer({) : null}</DropdownMenuItem>),+ skills: (+ <DropdownMenuItem onSelect={() => setSkillsOpen(true)}>+ <BookOpenIcon />+ Agent Skills+ </DropdownMenuItem>+ ),savedPrompts: (<DropdownMenuSub><DropdownMenuSubTrigger>@@ -2132,6 +2150,8 @@ export function SharedComposer({void addFiles(e.dataTransfer.files);}}>+ <ChatSkillsDialog open={skillsOpen} onOpenChange={setSkillsOpen} />+<PromptStorageDialogopen={promptStorageOpen}onOpenChange={setPromptStorageOpen}@@ -2208,7 +2228,10 @@ export function SharedComposer({)}</div>)}+ {skillMentions.popover}+<textarea+ {...skillMentions.inputProps}ref={textareaRef}value={text}onChange={(e) => {@@ -2217,6 +2240,18 @@ export function SharedComposer({// to the stored value mid-composition, wiping the preedit (#5318).setCompositionState(isNativeComposing(e.nativeEvent));setText(e.target.value);+ skillMentions.update(+ e.target.value,+ e.target.selectionStart ?? e.target.value.length,+ );+ }}++ onSelect={(event) => {+ skillMentions.update(+ event.currentTarget.value,+ event.currentTarget.selectionStart ??+ event.currentTarget.value.length,+ );}}onCompositionStart={() => {setCompositionState(true);@@ -2228,12 +2263,16 @@ export function SharedComposer({setCompositionState(false);setText(e.currentTarget.value);}}- onKeyDown={onKeyDown}+ onKeyDown={(event) => {+ if (!skillMentions.onKeyDown(event)) onKeyDown(event);+ }}onPaste={handleFilePaste}onBlur={() => {// Mac: switching input methods can fire compositionstart without a matching compositionend,// leaving composingRef pinned. The OS always commits or cancels before focus is lost.setCompositionState(false);++ skillMentions.close();}}placeholder="Send to both models..."// dir="auto" detects RTL from the first strong character; no effect on LTR scripts. Kept next todiff --git a/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.ts b/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.tsindex 7c679c3bbf7..73f0b0cd5c7 100644--- a/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.ts+++ b/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.ts@@ -9,6 +9,7 @@ import { persist } from "zustand/middleware";export type PlusMenuItemId =| "chatWithFiles"| "mcp"+ | "skills"| "savedPrompts"| "compareChat"| "exportChat"@@ -21,6 +22,7 @@ export type PlusMenuItemId =export const PLUS_MENU_ORDER: PlusMenuItemId[] = ["chatWithFiles","mcp",+ "skills","savedPrompts","compareChat","exportChat",@@ -34,6 +36,7 @@ export const PLUS_MENU_ORDER: PlusMenuItemId[] = [const DEFAULT_PINS: Record<PlusMenuItemId, boolean> = {chatWithFiles: true,mcp: true,+ skills: true,projects: true,savedPrompts: false,compareChat: false,diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsxindex ffc34e84c5e..cb5d79b9ef1 100644--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx@@ -30,6 +30,7 @@ import { type TranslationKey, useT } from "@/i18n";import { toast } from "@/lib/toast";import {Bookmark02Icon,+ BookOpen01Icon,Download01Icon,FileDatabaseIcon,Folder01Icon,@@ -80,6 +81,17 @@ const PLUS_MENU_SETTINGS: {/>),},+ {+ id: "skills",+ labelKey: "settings.chat.menu.skills",+ icon: (+ <HugeiconsIcon+ icon={BookOpen01Icon}+ strokeWidth={2}+ className={PLUS_MENU_ICON_CLASS}+ />+ ),+ },{id: "savedPrompts",labelKey: "settings.chat.menu.savedPrompts",diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex bc4f04d789b..0cc21fc2b30 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1421,6 +1421,7 @@ export const ar = {"ثبّت العناصر في القائمة الجانبية لعلامة + في المحادثة. تنتقل العناصر الأخرى إلى «المزيد».",chatWithFiles: "المحادثة مع الملفات (RAG)",mcp: "MCP",+ skills: "مهارات الوكلاء",savedPrompts: "الموجّهات المحفوظة",compareChat: "مقارنة المحادثات",exportChat: "تصدير المحادثة",@@ -2480,4 +2481,22 @@ export const ar = {oomLikely: "مع الإعدادات الحالية يُرجَّح نفاد الذاكرة",tooLarge: "أكبر من ذاكرة الرسوميات، وسيُفرَّغ جزء منه إلى المعالج. التكميم الأصغر أسرع",},+ skills: {+ title: "مهارات الوكلاء",+ description: "تُكتشف المهارات من مجلدات الوكلاء القياسية. فعّلها هنا ثم اكتب @ في الدردشة لذكر إحداها.",+ precedence: "~/.agents/skills له الأولوية على ~/.claude/skills.",+ refresh: "تحديث",+ empty: "لم يُعثر على مهارات. أضف مجلدًا يحتوي على SKILL.md ضمن ~/.agents/skills أو ~/.claude/skills ثم حدّث.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "مضمّنة",+ shadowed: "محجوبة",+ invalid: "غير صالحة",+ compatibility: "التوافق: {value}",+ shadowedBy: "مهارة أخرى ({source}) بالاسم نفسه لها الأولوية.",+ enable: "تفعيل {name}",+ disable: "تعطيل {name}",+ updateError: "تعذّر تحديث مهارة الوكيل",+ mentions: "مهارات الوكلاء",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 396058cb508..0830cab27ab 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1457,6 +1457,7 @@ export const de = {"Elemente im seitlichen Plus-Menü des Chats anheften. Die übrigen werden unter „Mehr“ angezeigt.",chatWithFiles: "Chat mit Dateien (RAG)",mcp: "MCP",+ skills: "Agentenfähigkeiten",savedPrompts: "Gespeicherte Prompts",compareChat: "Chats vergleichen",exportChat: "Chat exportieren",@@ -2551,4 +2552,22 @@ export const de = {oomLikely: "Mit den aktuellen Einstellungen ist ein Speicherüberlauf wahrscheinlich",tooLarge: "Größer als der VRAM, wird auf die CPU ausgelagert. Eine kleinere Quantisierung läuft schneller",},+ skills: {+ title: "Agentenfähigkeiten",+ description: "Fähigkeiten werden aus deinen Standard-Agentenordnern erkannt. Aktiviere sie hier und tippe dann @ im Chat, um eine zu erwähnen.",+ precedence: "~/.agents/skills hat Vorrang vor ~/.claude/skills.",+ refresh: "Aktualisieren",+ empty: "Keine Agentenfähigkeiten gefunden. Lege einen SKILL.md-Ordner unter ~/.agents/skills oder ~/.claude/skills an und aktualisiere dann.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "Mitgeliefert",+ shadowed: "Überdeckt",+ invalid: "Ungültig",+ compatibility: "Kompatibilität: {value}",+ shadowedBy: "Eine andere Fähigkeit ({source}) mit diesem Namen hat Vorrang.",+ enable: "{name} aktivieren",+ disable: "{name} deaktivieren",+ updateError: "Agentenfähigkeit konnte nicht aktualisiert werden",+ mentions: "Agentenfähigkeiten",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 198aca96171..7da35f076d2 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1414,6 +1414,7 @@ export const en = {"Pin items to chat's + side menu. Others move into “More”.",chatWithFiles: "Chat with Files (RAG)",mcp: "MCP",+ skills: "Agent Skills",savedPrompts: "Saved prompts",compareChat: "Compare chat",exportChat: "Export chat",@@ -2463,4 +2464,22 @@ export const en = {oomLikely: "With current settings OOM likely",tooLarge: "Larger than VRAM, will offload to CPU. A smaller quantization runs faster",},+ skills: {+ title: "Agent Skills",+ description: "Skills are discovered from your standard agent folders. Enable them here, then type @ in chat to mention one.",+ precedence: "~/.agents/skills takes precedence over ~/.claude/skills.",+ refresh: "Refresh",+ empty: "No Agent Skills found. Add a SKILL.md folder under ~/.agents/skills or ~/.claude/skills, then refresh.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "Bundled",+ shadowed: "Shadowed",+ invalid: "Invalid",+ compatibility: "Compatibility: {value}",+ shadowedBy: "Another {source} skill with this name takes precedence.",+ enable: "Enable {name}",+ disable: "Disable {name}",+ updateError: "Could not update Agent Skill",+ mentions: "Agent Skills",+ },} as const;diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 89bfdf1f7f9..45cb06835d7 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1448,6 +1448,7 @@ export const es = {"Fija elementos en el menú lateral «+» del chat. Los demás pasarán a «Más».",chatWithFiles: "Chat con archivos (RAG)",mcp: "MCP",+ skills: "Habilidades de agentes",savedPrompts: "Prompts guardados",compareChat: "Comparar chats",exportChat: "Exportar chat",@@ -2548,4 +2549,22 @@ export const es = {oomLikely: "Con la configuración actual es probable un error de memoria",tooLarge: "Más grande que la VRAM, se descargará a la CPU. Una cuantización más pequeña es más rápida",},+ skills: {+ title: "Habilidades de agentes",+ description: "Las habilidades se detectan en tus carpetas de agentes estándar. Actívalas aquí y luego escribe @ en el chat para mencionar una.",+ precedence: "~/.agents/skills tiene prioridad sobre ~/.claude/skills.",+ refresh: "Actualizar",+ empty: "No se encontraron habilidades de agentes. Añade una carpeta con SKILL.md en ~/.agents/skills o ~/.claude/skills y actualiza.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "Incluida",+ shadowed: "Oculta",+ invalid: "No válida",+ compatibility: "Compatibilidad: {value}",+ shadowedBy: "Otra habilidad ({source}) con este nombre tiene prioridad.",+ enable: "Activar {name}",+ disable: "Desactivar {name}",+ updateError: "No se pudo actualizar la habilidad de agente",+ mentions: "Habilidades de agentes",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex f7eb4ee4e59..c60412dd8a0 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1454,6 +1454,7 @@ export const fr = {"Épinglez des éléments dans le menu latéral + du chat. Les autres seront placés dans « Plus ».",chatWithFiles: "Discuter avec des fichiers (RAG)",mcp: "MCP",+ skills: "Compétences des agents",savedPrompts: "Invites enregistrées",compareChat: "Comparer le chat",exportChat: "Exporter le chat",@@ -2560,4 +2561,22 @@ export const fr = {oomLikely: "Avec les réglages actuels, un dépassement de mémoire est probable",tooLarge: "Plus volumineux que la VRAM, sera déchargé sur le CPU. Une quantification plus petite est plus rapide",},+ skills: {+ title: "Compétences des agents",+ description: "Les compétences sont détectées dans vos dossiers d'agents standard. Activez-les ici, puis tapez @ dans le chat pour en mentionner une.",+ precedence: "~/.agents/skills est prioritaire par rapport à ~/.claude/skills.",+ refresh: "Actualiser",+ empty: "Aucune compétence d'agent trouvée. Ajoutez un dossier SKILL.md dans ~/.agents/skills ou ~/.claude/skills, puis actualisez.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "Intégrée",+ shadowed: "Masquée",+ invalid: "Non valide",+ compatibility: "Compatibilité : {value}",+ shadowedBy: "Une autre compétence ({source}) portant ce nom est prioritaire.",+ enable: "Activer {name}",+ disable: "Désactiver {name}",+ updateError: "Impossible de mettre à jour la compétence d'agent",+ mentions: "Compétences des agents",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 8e152c7c544..e75463a1a05 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1427,6 +1427,7 @@ export const hi = {"आइटम को चैट के + साइड मेन्यू में पिन करें। बाकी आइटम “More” में चले जाएँगे।",chatWithFiles: "फ़ाइलों के साथ चैट (RAG)",mcp: "MCP",+ skills: "एजेंट कौशल",savedPrompts: "सहेजे गए प्रॉम्प्ट",compareChat: "चैट की तुलना करें",exportChat: "चैट एक्सपोर्ट करें",@@ -2487,4 +2488,22 @@ export const hi = {oomLikely: "मौजूदा सेटिंग्स के साथ मेमोरी कम पड़ सकती है",tooLarge: "VRAM से बड़ा है, CPU पर ऑफ़लोड होगा। छोटा क्वांटाइज़ेशन तेज़ चलता है",},+ skills: {+ title: "एजेंट कौशल",+ description: "कौशल आपके मानक एजेंट फ़ोल्डरों से खोजे जाते हैं। उन्हें यहाँ सक्षम करें, फिर चैट में @ टाइप करके किसी का उल्लेख करें।",+ precedence: "~/.agents/skills को ~/.claude/skills पर प्राथमिकता मिलती है।",+ refresh: "रीफ़्रेश",+ empty: "कोई एजेंट कौशल नहीं मिला। ~/.agents/skills या ~/.claude/skills में SKILL.md फ़ोल्डर जोड़ें, फिर रीफ़्रेश करें।",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "बंडल्ड",+ shadowed: "छिपा हुआ",+ invalid: "अमान्य",+ compatibility: "संगतता: {value}",+ shadowedBy: "इसी नाम का एक और कौशल ({source}) प्राथमिकता लेता है।",+ enable: "{name} सक्षम करें",+ disable: "{name} अक्षम करें",+ updateError: "एजेंट कौशल अपडेट नहीं हो सका",+ mentions: "एजेंट कौशल",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex f82d5433dcb..d27ca1dcec0 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1422,6 +1422,7 @@ export const it = {"Fissa le voci nel menu laterale «+» della chat. Le altre verranno spostate in «Altro».",chatWithFiles: "Chat con file (RAG)",mcp: "MCP",+ skills: "Competenze degli agenti",savedPrompts: "Prompt salvati",compareChat: "Confronta chat",exportChat: "Esporta chat",@@ -2549,4 +2550,22 @@ export const it = {oomLikely: "Con le impostazioni attuali è probabile un errore di memoria",tooLarge: "Più grande della VRAM, verrà scaricato sulla CPU. Una quantizzazione più piccola è più veloce",},+ skills: {+ title: "Competenze degli agenti",+ description: "Le competenze vengono rilevate nelle cartelle standard degli agenti. Attivale qui, poi digita @ nella chat per menzionarne una.",+ precedence: "~/.agents/skills ha la precedenza rispetto a ~/.claude/skills.",+ refresh: "Aggiorna",+ empty: "Nessuna competenza trovata. Aggiungi una cartella SKILL.md in ~/.agents/skills o ~/.claude/skills, poi aggiorna.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "Inclusa",+ shadowed: "Oscurata",+ invalid: "Non valida",+ compatibility: "Compatibilità: {value}",+ shadowedBy: "Un'altra competenza ({source}) con questo nome ha la precedenza.",+ enable: "Attiva {name}",+ disable: "Disattiva {name}",+ updateError: "Impossibile aggiornare la competenza",+ mentions: "Competenze degli agenti",+ },} as const;diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 82dab7a1b6a..d85de906fde 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1409,6 +1409,7 @@ export const ja = {"項目をチャットの「+」サイドメニューに固定します。その他の項目は「More」に移動します。",chatWithFiles: "ファイルとチャット (RAG)",mcp: "MCP",+ skills: "エージェントスキル",savedPrompts: "保存済みプロンプト",compareChat: "チャットを比較",exportChat: "チャットをエクスポート",@@ -2433,4 +2434,22 @@ export const ja = {oomLikely: "現在の設定ではメモリ不足になる可能性があります",tooLarge: "VRAM を超えるため CPU にオフロードされます。より小さい量子化の方が高速です",},+ skills: {+ title: "エージェントスキル",+ description: "スキルは標準のエージェントフォルダーから検出されます。ここで有効にし、チャットで @ を入力して呼び出します。",+ precedence: "~/.agents/skills は ~/.claude/skills より優先されます。",+ refresh: "更新",+ empty: "エージェントスキルが見つかりません。~/.agents/skills または ~/.claude/skills に SKILL.md のフォルダーを追加して更新してください。",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "同梱",+ shadowed: "上書き",+ invalid: "無効",+ compatibility: "互換性: {value}",+ shadowedBy: "同名の別のスキル ({source}) が優先されます。",+ enable: "{name} を有効化",+ disable: "{name} を無効化",+ updateError: "エージェントスキルを更新できませんでした",+ mentions: "エージェントスキル",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex bfb3923165a..c988d168da2 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1418,6 +1418,7 @@ export const ko = {"채팅의 + 사이드 메뉴에 항목을 고정합니다. 나머지 항목은 ‘더 보기’로 이동합니다.",chatWithFiles: "파일과 채팅(RAG)",mcp: "MCP",+ skills: "에이전트 스킬",savedPrompts: "저장된 프롬프트",compareChat: "채팅 비교",exportChat: "채팅 내보내기",@@ -2478,4 +2479,22 @@ export const ko = {oomLikely: "현재 설정에서는 메모리 부족이 발생할 수 있습니다",tooLarge: "VRAM보다 커서 CPU로 오프로드됩니다. 더 작은 양자화가 더 빠릅니다",},+ skills: {+ title: "에이전트 스킬",+ description: "스킬은 표준 에이전트 폴더에서 찾습니다. 여기서 활성화한 뒤 채팅에서 @를 입력해 언급하세요.",+ precedence: "~/.agents/skills가 ~/.claude/skills보다 우선합니다.",+ refresh: "새로 고침",+ empty: "에이전트 스킬이 없습니다. ~/.agents/skills 또는 ~/.claude/skills에 SKILL.md 폴더를 추가한 뒤 새로 고침하세요.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "기본 제공",+ shadowed: "가려짐",+ invalid: "잘못됨",+ compatibility: "호환성: {value}",+ shadowedBy: "같은 이름의 다른 스킬({source})이 우선합니다.",+ enable: "{name} 활성화",+ disable: "{name} 비활성화",+ updateError: "에이전트 스킬을 업데이트할 수 없습니다",+ mentions: "에이전트 스킬",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 4d110da488a..de863512535 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1436,6 +1436,7 @@ export const ptBR = {"Fixe itens no menu lateral do botão + do chat. Os demais ficam em “Mais”.",chatWithFiles: "Chat com arquivos (RAG)",mcp: "MCP",+ skills: "Habilidades de agentes",savedPrompts: "Prompts salvos",compareChat: "Comparar chats",exportChat: "Exportar chat",@@ -2511,4 +2512,22 @@ export const ptBR = {oomLikely: "Com as configurações atuais, é provável um erro de memória",tooLarge: "Maior que a VRAM, será descarregado para a CPU. Uma quantização menor roda mais rápido",},+ skills: {+ title: "Habilidades de agentes",+ description: "As habilidades são descobertas nas suas pastas padrão de agentes. Ative-as aqui e digite @ no chat para mencionar uma.",+ precedence: "~/.agents/skills tem precedência sobre ~/.claude/skills.",+ refresh: "Atualizar",+ empty: "Nenhuma habilidade encontrada. Adicione uma pasta com SKILL.md em ~/.agents/skills ou ~/.claude/skills e atualize.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "Incluída",+ shadowed: "Ocultada",+ invalid: "Inválida",+ compatibility: "Compatibilidade: {value}",+ shadowedBy: "Outra habilidade ({source}) com este nome tem precedência.",+ enable: "Ativar {name}",+ disable: "Desativar {name}",+ updateError: "Não foi possível atualizar a habilidade",+ mentions: "Habilidades de agentes",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex a98c7abc5ae..281e4caf801 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1433,6 +1433,7 @@ export const ru = {"Закрепляйте пункты в боковом меню «+» чата. Остальные будут доступны в разделе «Ещё».",chatWithFiles: "Чат с файлами (RAG)",mcp: "MCP",+ skills: "Навыки агентов",savedPrompts: "Сохранённые промпты",compareChat: "Сравнить чаты",exportChat: "Экспортировать чат",@@ -2511,4 +2512,22 @@ export const ru = {oomLikely: "При текущих настройках вероятна нехватка памяти",tooLarge: "Больше объёма VRAM, часть уйдёт на CPU. Меньшая квантизация работает быстрее",},+ skills: {+ title: "Навыки агентов",+ description: "Навыки находятся в стандартных папках агентов. Включите их здесь, затем введите @ в чате, чтобы упомянуть навык.",+ precedence: "~/.agents/skills имеет приоритет над ~/.claude/skills.",+ refresh: "Обновить",+ empty: "Навыки не найдены. Добавьте папку с SKILL.md в ~/.agents/skills или ~/.claude/skills и обновите.",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "Встроенный",+ shadowed: "Перекрыт",+ invalid: "Недействителен",+ compatibility: "Совместимость: {value}",+ shadowedBy: "Другой навык ({source}) с таким именем имеет приоритет.",+ enable: "Включить {name}",+ disable: "Отключить {name}",+ updateError: "Не удалось обновить навык агента",+ mentions: "Навыки агентов",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 2166294c2aa..5008cd67692 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1390,6 +1390,7 @@ export const zhCN = {"将条目固定到聊天中的“+”侧边菜单,其他条目会移到“更多”中。",chatWithFiles: "与文件聊天(RAG)",mcp: "MCP",+ skills: "代理技能",savedPrompts: "已保存的提示词",compareChat: "对比聊天",exportChat: "导出聊天",@@ -2398,4 +2399,22 @@ export const zhCN = {oomLikely: "按当前设置可能显存不足",tooLarge: "超出显存,将卸载到 CPU 运行。更小的量化版本速度更快",},+ skills: {+ title: "代理技能",+ description: "技能会从标准的代理文件夹中发现。在此启用后,在聊天中输入 @ 即可提及。",+ precedence: "~/.agents/skills 优先于 ~/.claude/skills。",+ refresh: "刷新",+ empty: "未找到代理技能。请在 ~/.agents/skills 或 ~/.claude/skills 下添加包含 SKILL.md 的文件夹,然后刷新。",+ sourceAgents: "Agents",+ sourceClaude: "Claude",+ sourceBundled: "内置",+ shadowed: "被覆盖",+ invalid: "无效",+ compatibility: "兼容性:{value}",+ shadowedBy: "另一个同名技能({source})优先。",+ enable: "启用 {name}",+ disable: "禁用 {name}",+ updateError: "无法更新代理技能",+ mentions: "代理技能",+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/tests/skill-mention-accessibility.test.ts b/studio/frontend/tests/skill-mention-accessibility.test.tsnew file mode 100644index 00000000000..2bb3a8878b4--- /dev/null+++ b/studio/frontend/tests/skill-mention-accessibility.test.ts@@ -0,0 +1,36 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++const mentionsSource = readFileSync(+ new URL("../src/components/assistant-ui/skill-mentions.tsx", import.meta.url),+ "utf8",+);+const composerSource = readFileSync(+ new URL("../src/features/chat/shared-composer.tsx", import.meta.url),+ "utf8",+);++test("the compare composer exposes its skill suggestions as a linked combobox", () => {+ assert.ok(composerSource.includes("{...skillMentions.inputProps}"));+ for (const semantic of [+ 'role: "combobox"',+ '"aria-controls": open ? listboxId : undefined',+ '"aria-activedescendant": activeOptionId',+ 'role="listbox"',+ 'role="option"',+ "aria-selected={index === highlighted}",+ ]) {+ assert.ok(mentionsSource.includes(semantic), semantic);+ }+});++test("the popover caps the adapter search, so navigation never leaves the rendered rows", () => {+ assert.ok(+ mentionsSource.includes("(mention.adapter.search?.(query) ?? []).slice(0, MAX_MENTION_RESULTS)"),+ );+ assert.ok(!mentionsSource.includes("results.slice(0, MAX_MENTION_RESULTS)"));+});diff --git a/studio/frontend/tests/skill-mention-pattern.test.ts b/studio/frontend/tests/skill-mention-pattern.test.tsnew file mode 100644index 00000000000..eae8e29332e--- /dev/null+++ b/studio/frontend/tests/skill-mention-pattern.test.ts@@ -0,0 +1,59 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++// The module imports the auth layer, so the pattern is lifted from source; the assertion keeps the copy honest.+const SKILLS_API_SOURCE = readFileSync(+ new URL("../src/features/chat/api/skills-api.ts", import.meta.url),+ "utf8",+);+const declaration = /export const SKILL_MENTION_PATTERN =\s*(\/.*\/g);/.exec(+ SKILLS_API_SOURCE,+);+assert.ok(declaration, "SKILL_MENTION_PATTERN declaration not found");+const SKILL_MENTION_PATTERN = new RegExp(+ declaration[1].slice(1, declaration[1].lastIndexOf("/")),+ "g",+);++const names = (text: string): string[] =>+ [...text.matchAll(SKILL_MENTION_PATTERN)].map((match) => match[2] ?? "");++test("spec-shaped names at a word boundary are mentions", () => {+ assert.deepEqual(names("@probe-alpha"), ["probe-alpha"]);+ assert.deepEqual(names("use @probe-alpha."), ["probe-alpha"]);+ // No whitespace before the first @, so only the second one is a mention.+ assert.deepEqual(names("(@probe-alpha), then @beta2!"), ["beta2"]);+ assert.deepEqual(names("@a @b9 x"), ["a", "b9"]);+ assert.deepEqual(names(`say "@probe-alpha"`), []);+ assert.deepEqual(names("first line\n@probe-alpha\tnext"), ["probe-alpha"]);+});++test("emails, underscores, uppercase and dangling hyphens are not mentions", () => {+ assert.deepEqual(names("mail [email protected]"), []);+ assert.deepEqual(names("@example.com please"), []);+ // Digit-led names are valid per spec, so `@3pm` stays a candidate; the send path re-reads under a deadline.+ assert.deepEqual(names("meet @3pm"), ["3pm"]);+ assert.deepEqual(names("@probe_alpha"), []);+ assert.deepEqual(names("@Probe-Alpha"), []);+ assert.deepEqual(names("@probe-alpha-"), []);+ assert.deepEqual(names("@-probe"), []);+});++test("a name is at most 64 characters", () => {+ const sixtyFour = "a".repeat(64);+ assert.deepEqual(names(`@${sixtyFour}`), [sixtyFour]);+ assert.deepEqual(names(`@${sixtyFour}a`), []);+});++test("the picker formatter and the send path share one pattern", () => {+ const mentions = readFileSync(+ new URL("../src/components/assistant-ui/skill-mentions.tsx", import.meta.url),+ "utf8",+ );+ assert.match(mentions, /text\.matchAll\(SKILL_MENTION_PATTERN\)/);+ assert.doesNotMatch(mentions, /const MENTION_PATTERN =/);+});diff --git a/studio/frontend/tests/skills-token-count-discovery.test.ts b/studio/frontend/tests/skills-token-count-discovery.test.tsnew file mode 100644index 00000000000..17f53b7c0e3--- /dev/null+++ b/studio/frontend/tests/skills-token-count-discovery.test.ts@@ -0,0 +1,80 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++const SKILLS_API_SOURCE = readFileSync(+ new URL("../src/features/chat/api/skills-api.ts", import.meta.url),+ "utf8",+);+const CHAT_ADAPTER_SOURCE = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+);++test("token counting waits for the initial skills discovery", () => {+ assert.match(SKILLS_API_SOURCE, /initialized: boolean;/);+ assert.match(SKILLS_API_SOURCE, /initialized: false,/);+ assert.match(SKILLS_API_SOURCE, /initialized: true,/);+ assert.match(+ SKILLS_API_SOURCE,+ /if \(pending\) await Promise\.race\(\[pending\.catch\(\(\) => undefined\), deadline\]\);/,+ );+ assert.match(SKILLS_API_SOURCE, /let stale = !snapshot\.initialized;/);+ assert.match(CHAT_ADAPTER_SOURCE, /await settleSkillsForText\(""\);/);+ assert.match(+ CHAT_ADAPTER_SOURCE,+ /const hasEnabledSkills = getSkillsSnapshot\(\)\.skills\.some\(/,+ );+});++test("a pre-send catalog re-read cannot hold the request past the settle deadline", () => {+ assert.match(SKILLS_API_SOURCE, /const SETTLE_TIMEOUT_MS = 3000;/);+ assert.match(+ SKILLS_API_SOURCE,+ /await Promise\.race\(\[listSkills\(true\)\.catch\(\(\) => undefined\), deadline\]\);/,+ );+});++test("token counting lists the skill tools only when the completion would", () => {+ const countExtras = CHAT_ADAPTER_SOURCE.slice(+ CHAT_ADAPTER_SOURCE.indexOf("export async function buildLocalTokenCountExtras"),+ CHAT_ADAPTER_SOURCE.indexOf("mcp_enabled: mcpEnabledForChat"),+ );+ assert.match(+ countExtras,+ /\.\.\.\(hasEnabledSkills \? \["read_skill", "create_skill"\] : \[\]\),/,+ );+ assert.doesNotMatch(countExtras, /^\s*"read_skill",$/m);+ assert.doesNotMatch(countExtras, /^\s*"create_skill",$/m);+});++test("request building waits for skills and preserves the launcher tool catalog", () => {+ const payloadBuilder = CHAT_ADAPTER_SOURCE.slice(+ CHAT_ADAPTER_SOURCE.indexOf("const buildRequestPayload = async"),+ CHAT_ADAPTER_SOURCE.indexOf(+ "while (true)",+ CHAT_ADAPTER_SOURCE.indexOf("const buildRequestPayload = async"),+ ),+ );+ assert.match(+ payloadBuilder,+ /if \(supportsStudioToolsForThisTurn\) \{\s*await settleSkillsForText\(lastUserText\(outboundMessages\)\);/,+ );+ assert.match(+ payloadBuilder,+ /supportsTools &&\s*\([\s\S]*hasEnabledSkills[\s\S]*\)\s*\? \{\s*enable_tools: true/,+ );+ const localToolCatalog = payloadBuilder.slice(+ payloadBuilder.indexOf("// Sent for every local chat"),+ );+ assert.doesNotMatch(localToolCatalog, /^\s*"read_skill",$/m);+ assert.doesNotMatch(localToolCatalog, /^\s*"create_skill",$/m);+});++test("a sign-out drops the module-level skills snapshot", () => {+ assert.ok(SKILLS_API_SOURCE.includes("window.addEventListener(AUTH_SESSION_CLEARED_EVENT"));+ assert.ok(SKILLS_API_SOURCE.includes("publish(EMPTY_SNAPSHOT)"));+});diff --git a/studio/frontend/tests/tool-card-arg-coercion.test.ts b/studio/frontend/tests/tool-card-arg-coercion.test.tsindex d7bfee6cddb..2edf2f0c33b 100644--- a/studio/frontend/tests/tool-card-arg-coercion.test.ts+++ b/studio/frontend/tests/tool-card-arg-coercion.test.ts@@ -157,6 +157,7 @@ const COERCED: ReadonlyArray<["tool-ui-python.tsx", "PythonToolUIImpl", ["code"]],["tool-ui-terminal.tsx", "TerminalToolUIImpl", ["command"]],["tool-ui-knowledge-base.tsx", "KnowledgeBaseToolUIImpl", ["query"]],+ ["tool-ui-read-skill.tsx", "ReadSkillToolUIImpl", ["name", "resource"]],["tool-ui-web-search.tsx", "WebSearchToolUIImpl", ["query", "url"]],["tool-ui-code-execution.tsx",