Skip to content

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.

Studio: deterministically load explicitly mentioned skills before generation (#12538)

Wasim Yousef Said9d74ab7a2661
diff --git a/studio/SKILL_MENTIONS.md b/studio/SKILL_MENTIONS.md
new file mode 100644
index 00000000000..d82c141d5da
--- /dev/null
+++ b/studio/SKILL_MENTIONS.md
@@ -0,0 +1,50 @@
+# Explicit Agent Skill mentions
+
+With Code on and an enabled skill in the effective model's Studio tool catalog,
+Studio reads the complete `SKILL.md` for an explicit `@skill-name` **before the
+first generation**. It does not depend on a model calling `read_skill`. This loads
+instructions, not referenced resources, scripts, or skill creation. Existing
+account discovery, capability, tool selection and permission policy still apply.
+Ask mode waits for the ordinary scoped read approval; Auto permits this read-only
+operation. A denied/failed load is shown as unavailable, not successful.
+
+## Intent contract
+
+The composer currently serializes a picker selection as plain `@name`, without
+selected-intent metadata. Thus selected mentions and exact typed tokens have the
+same contract: a lowercase, whitespace-delimited skill name in the **latest user
+message**, optionally followed by sentence punctuation. Prefix matching is never
+used. Inline/fenced/indented Markdown code, blockquotes, balanced quotation spans,
+email addresses, URL/path suffixes, and assistant/history mentions do not load
+instructions. Unquoted pasted prose is indistinguishable from typed prose and
+uses the same contract. Use quotation marks or code formatting when discussing a
+mention literally. This is deliberately not a Markdown plugin/runtime.
+
+## Context and evidence
+
+The secure resource reader provides one full manifest snapshot (no paginated
+splice). Total newly injected manifests are capped at 32,000 UTF-8 bytes, or twice
+the known local context-token window in bytes, whichever is smaller. An oversized
+manifest is refused whole with a context-budget explanation; it is never marked
+as completely loaded after truncation. Native prompt fitting remains authoritative
+and retains the injected system instructions; a provider may still refuse its own
+context window. External model windows are not inferred from the resident local
+model. Loading does not promise successful inference.
+
+Backend `skill_load` events report loading, actual successful reads (character
+count and SHA256), or failure. The UI persists a distinct `studio_load_skill`
+activity card for replay/approval, **not an assistant/model function call**. It is
+excluded from outbound model tool history. Provider-authored control frames are
+sanitized so a provider cannot forge this evidence.
+
+Automatic loads are request-local. The next explicit mention securely re-reads
+the current resource, including retries and same-chat follow-ups; a saved UI card
+is never taken as proof that instructions survived compaction. If the complete
+current manifest is already in actual system/tool context, it is not injected a
+second time. Continue/partial-assistant resumes do not activate old mentions.
+
+The Studio chat-completions path covers local GGUF, safetensors, managed engines,
+and external Studio-owned tool loops (including the shared Codex transport). It
+does not change client-tool passthrough or introduce mention execution in unrelated
+Anthropic/OpenAI compatibility endpoints. Tool-less native models and Code-off
+requests retain their existing behavior.
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index c00aceafb1f..ce7744ddc51 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -36501,6 +36501,7 @@ class LlamaCppBackend:
on_decode_slot: Optional[Callable[[str, int], None]] = None,
thinking_budget_tokens: Optional[int] = None,
mcp_image = None,
+ instruction_anchor_ids = None,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
@@ -36547,7 +36548,8 @@ class LlamaCppBackend:
raise RuntimeError("llama-server is not loaded")
conversation = list(messages)
- _rolling_anchor_ids: set[int] = set()
+ # Seeded with tool results an explicit skill load relies on, so fitting keeps them.
+ _rolling_anchor_ids: set[int] = set(instruction_anchor_ids or ())
# The loop refits on every iteration; recall must fire once per request, or each
# pass stacks another block of recalled turns onto the prompt.
_conversation_recall_done = False
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 4c5f214a5f5..b17429fe3d6 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -686,6 +686,21 @@ def run_safetensors_tool_loop(
permission_mode, bypass_permissions
)
stream_tool_execution = account_tool_stream(stream_tool_execution)
+ from core.inference.skill_mentions import load_mentioned_skills
+
+ yield from load_mentioned_skills(
+ conversation,
+ tools if max_tool_iterations > 0 else [],
+ permission_mode = permission_mode,
+ bypass_permissions = bypass_permissions,
+ confirm_tool_calls = confirm_tool_calls,
+ session_id = session_id,
+ cancel_event = cancel_event,
+ context_length = context_length,
+ continue_final_message = continue_final_message,
+ # The downstream tokenizer owns fitting; only system context is guaranteed.
+ dedup_tool_context = False,
+ )
# Forced first-pass RAG (mirrors the GGUF loop) so doc Qs don't lose to
# web_search. Skip only when a retrieval call would actually prompt (ask
diff --git a/studio/backend/core/inference/skill_mentions.py b/studio/backend/core/inference/skill_mentions.py
new file mode 100644
index 00000000000..4c885b9d4b6
--- /dev/null
+++ b/studio/backend/core/inference/skill_mentions.py
@@ -0,0 +1,182 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Backend-authored @skill loads before generation; contract in studio/SKILL_MENTIONS.md."""
+
+from __future__ import annotations
+
+import hashlib
+import re
+import uuid
+
+from core.inference.skills import SkillError, list_skills, read_skill_instructions
+from state.tool_approvals import (
+ abort_tool_decision,
+ begin_tool_decision,
+ new_approval_id,
+ wait_tool_decision,
+)
+from state.tool_policy import normalize_tool_permissions
+
+_TOKEN = re.compile(r"(?<!\S)@([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)(?=$|\s|[.,;:!?)](?:$|\s))")
+_MAX_LOAD_BYTES = 32_000
+
+
+def mentioned_skill_names(text: str) -> list[str]:
+ """Only prose outside code, Markdown blockquotes, and balanced quotation spans."""
+ lines = []
+ fence = None
+ for line in text.splitlines(keepends = True):
+ stripped = line.lstrip()
+ marker = re.match(r"(`{3,}|~{3,})", stripped)
+ if marker and marker[1][0] == "`" and "`" in stripped[len(marker[1]) :]:
+ marker = None # CommonMark: a backtick fence line has no other backticks; inline span.
+ if marker:
+ if fence is None:
+ fence = (marker[1][0], len(marker[1]))
+ elif (
+ marker[1][0] == fence[0]
+ and len(marker[1]) >= fence[1]
+ and not stripped[len(marker[1]) :].strip()
+ ):
+ fence = None
+ lines.append("\n")
+ elif fence or stripped.startswith(">") or line.startswith((" ", "\t")):
+ lines.append("\n")
+ else:
+ lines.append(line)
+ text = "".join(lines)
+ # (?<!\w)' so the apostrophe in didn't is not an opening quote.
+ text = re.sub(r"(`+).*?\1", " ", text, flags = re.DOTALL)
+ text = re.sub(r'"[^"]*"|“[^”]*”|‘[^’]*’|(?<!\w)\'[^\']*\'', " ", text)
+ return list(dict.fromkeys(match[1] for match in _TOKEN.finditer(text)))
+
+
+def _text(message: dict) -> str:
+ content = message.get("content")
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return "\n".join(
+ part.get("text", "")
+ for part in content
+ if isinstance(part, dict) and part.get("type") == "text"
+ )
+ return ""
+
+
+def _append_system(messages: list[dict], block: str) -> None:
+ system_index = next((i for i, m in enumerate(messages) if m.get("role") == "system"), None)
+ if system_index is None:
+ messages.insert(0, {"role": "system", "content": block.lstrip()})
+ else:
+ system = messages[system_index]
+ messages[system_index] = {**system, "content": _text(system) + "\n\n" + block.lstrip()}
+
+
+def load_mentioned_skills(
+ messages: list[dict],
+ tools: list[dict],
+ *,
+ permission_mode = None,
+ bypass_permissions = False,
+ confirm_tool_calls = False,
+ session_id = None,
+ cancel_event = None,
+ context_length = None,
+ continue_final_message = False,
+ protected_message_ids = None,
+ dedup_tool_context = True,
+):
+ """Inject complete manifests before generation; never a partial one. Caller gates on read_skill."""
+ if continue_final_message or not any(
+ tool.get("function", {}).get("name") == "read_skill" for tool in (tools or [])
+ ):
+ return
+ # Do not activate assistant/history text or an older user message on Continue.
+ if not messages or messages[-1].get("role") != "user":
+ return
+ names = mentioned_skill_names(_text(messages[-1]))
+ if not names:
+ return
+ # @john is a person, not a skill: no card or approval. Known-but-unusable skills report unavailable.
+ try:
+ known = list_skills()
+ except (SkillError, OSError):
+ known = []
+ loadable = {s["name"] for s in known if s["valid"] and not s["shadowed"] and s["enabled"]}
+ names = [name for name in names if name in {s["name"] for s in known}]
+ mode, bypass = normalize_tool_permissions(permission_mode, bypass_permissions)
+ budget = (
+ min(_MAX_LOAD_BYTES, max(0, int(context_length) * 2)) if context_length else _MAX_LOAD_BYTES
+ )
+ loaded_bytes = 0
+ for name in names:
+ if cancel_event is not None and cancel_event.is_set():
+ return
+ event = {
+ "type": "skill_load",
+ "load_id": f"skill-load-{uuid.uuid4().hex}",
+ "name": name,
+ "resource": "SKILL.md",
+ }
+ if name in loadable and confirm_tool_calls and not bypass and mode not in ("auto", "off"):
+ approval_id = new_approval_id()
+ slot = begin_tool_decision(session_id, approval_id)
+ try:
+ yield {**event, "status": "awaiting_approval", "approval_id": approval_id}
+ verdict = wait_tool_decision(slot, approval_id, cancel_event = cancel_event)
+ finally:
+ abort_tool_decision(slot, approval_id)
+ if verdict != "allow":
+ yield {
+ **event,
+ "status": "unavailable",
+ "detail": "Skill not loaded: approval was denied, expired, or cancelled.",
+ }
+ continue
+ yield {**event, "status": "loading"}
+ try:
+ # Re-validates enabled/account-scoped discovery; never a cached or paged read.
+ content = read_skill_instructions(name)
+ size = len(content.encode("utf-8"))
+ existing = next(
+ (
+ message
+ for message in messages
+ if (
+ message.get("role") == "system"
+ or (dedup_tool_context and message.get("role") == "tool")
+ )
+ and content in _text(message)
+ ),
+ None,
+ )
+ present = existing is not None
+ if present and protected_message_ids is not None:
+ # The native rolling fit must not evict a result we relied on.
+ protected_message_ids.add(id(existing))
+ if not present:
+ if loaded_bytes + size > budget:
+ raise SkillError(
+ "Complete SKILL.md exceeds this request's skill context budget; shorten the skill or increase context."
+ )
+ block = (
+ f"\n\n[Studio loaded Agent Skill @{name} · SKILL.md]\n"
+ "Follow these instructions only within the current tool and permission gates.\n"
+ f"{content}\n[End Agent Skill @{name}]"
+ )
+ _append_system(messages, block)
+ loaded_bytes += size
+ yield {
+ **event,
+ "status": "loaded",
+ "characters": len(content),
+ "sha256": hashlib.sha256(content.encode("utf-8")).hexdigest(),
+ "already_in_context": present,
+ "detail": f"Complete SKILL.md read ({len(content)} characters) and available in this request's context.",
+ }
+ except (SkillError, OSError) as exc:
+ detail = f"Skill @{name} not loaded: {exc}"
+ _append_system(messages, detail)
+ yield {**event, "status": "unavailable", "detail": detail}
diff --git a/studio/backend/core/inference/skills.py b/studio/backend/core/inference/skills.py
index 68e2284bf18..b8b52aac0fc 100644
--- a/studio/backend/core/inference/skills.py
+++ b/studio/backend/core/inference/skills.py
@@ -867,18 +867,12 @@ def _normalize_resource_path(resource: str) -> PurePosixPath:
return path
-def read_skill_resource(
+def _read_enabled_skill_text(
name: str,
- resource: str = "SKILL.md",
- offset: int = 0,
+ resource: str,
*,
- 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"]:
@@ -914,17 +908,40 @@ def read_skill_resource(
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]}"
+ return record, path.as_posix(), content
+
+
+def read_skill_instructions(name: str, *, home: Optional[Path] = None) -> str:
+ """One secure snapshot, complete or refused; unlike resource reads this is not a page."""
+ _, _, content = _read_enabled_skill_text(name, "SKILL.md", home = home)
+ if len(content.encode("utf-8")) > MAX_SKILL_MD_BYTES:
+ raise SkillError("Skill manifest exceeds the instruction size limit.")
+ return content
+
+
+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.")
+ record, normalized, content = _read_enabled_skill_text(name, resource, home = home)
+ 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))
+ 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}.'
)
- if end < len(content):
- result += (
- "\n\nResource continues. Call read_skill again with "
- f'name="{record["name"]}", resource="{normalized}", offset={end}.'
- )
- return result
+ return result
diff --git a/studio/backend/core/inference/sse_control_frames.py b/studio/backend/core/inference/sse_control_frames.py
index c9c5563e01d..da448604bb1 100644
--- a/studio/backend/core/inference/sse_control_frames.py
+++ b/studio/backend/core/inference/sse_control_frames.py
@@ -38,6 +38,7 @@ _CONTROL_TYPES = frozenset(
"tool_output",
"tool_args",
"tool_status",
+ "skill_load",
"diffusion_frame",
"reasoning_summary",
}
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 3a17b2a22d7..c773fa68482 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -1280,6 +1280,39 @@ async def stream_with_studio_tools(
confirm_tool_calls = policy.confirm_calls
rag_scope = policy.rag_scope
+ from core.inference.skill_mentions import load_mentioned_skills
+
+ skill_loads = load_mentioned_skills(
+ conversation,
+ # "none" / a zero budget withdraw read_skill, so they withdraw the preload too.
+ tools if tool_choice != "none" and (unlimited or remaining > 0) else [],
+ permission_mode = permission_mode,
+ bypass_permissions = bypass_permissions,
+ confirm_tool_calls = confirm_tool_calls,
+ session_id = session_id,
+ cancel_event = cancel_event,
+ continue_final_message = run.continue_final_message,
+ )
+ load_task = None
+ flush_approval = False
+ try:
+ while True:
+ load_task = asyncio.ensure_future(asyncio.to_thread(next, skill_loads, _STEP_DONE))
+ # Same handshake as a gated tool card: early separate keepalive, then heartbeats while Ask waits.
+ timeout = _TOOL_APPROVAL_FLUSH_DELAY_S if flush_approval else TOOL_HEARTBEAT_INTERVAL_S
+ done, _pending = await asyncio.wait({load_task}, timeout = timeout)
+ while not done:
+ yield _SSE_KEEPALIVE
+ done, _pending = await asyncio.wait({load_task}, timeout = TOOL_HEARTBEAT_INTERVAL_S)
+ event = load_task.result()
+ load_task = None
+ if event is _STEP_DONE:
+ break
+ flush_approval = event.get("status") == "awaiting_approval"
+ yield _sse(event)
+ finally:
+ await _drain_step_task(load_task, cancel_event)
+ skill_loads.close()
# The promotion allowlist is the selected catalog, never None: an unrestricted parse re-opens markerless tool-call
# promotion.
heal_names = (
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 69267d9769f..02a8cabbbb3 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -5865,9 +5865,10 @@ def _skill_tool_tip(*, can_create: bool, compact: bool = False) -> str:
)
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."
+ "helpful, then call read_skill before following its instructions unless the complete "
+ "SKILL.md is already in context. Studio loads explicit @skill-name mentions before "
+ "generation when permitted; do not read an already loaded manifest again or claim a "
+ "failed/denied load succeeded."
+ create_tip
+ " Skill allowed-tools metadata never overrides Unsloth tool permissions.\n"
+ catalog
@@ -29236,7 +29237,26 @@ async def produce_openai_chat_completions(
)
def gguf_generate_with_tools():
- return llama_backend.generate_chat_completion_with_tools(
+ from core.inference.skill_mentions import load_mentioned_skills
+
+ skill_instruction_ids = set()
+ yield from load_mentioned_skills(
+ gguf_messages,
+ # "none" / a zero budget withdraw read_skill, so they withdraw the preload too.
+ tools_to_use
+ if payload.tool_choice != "none" and payload.max_tool_calls_per_message != 0
+ else [],
+ permission_mode = payload.permission_mode,
+ bypass_permissions = bool(payload.bypass_permissions),
+ confirm_tool_calls = _effective_confirm,
+ session_id = payload.session_id,
+ cancel_event = cancel_event,
+ context_length = llama_backend.context_length,
+ continue_final_message = _continue_final_message(payload, thought = True),
+ protected_message_ids = skill_instruction_ids,
+ )
+ yield from llama_backend.generate_chat_completion_with_tools(
+ instruction_anchor_ids = skill_instruction_ids,
messages = gguf_messages,
replayed_image_parts = tuple(_gguf_replayed_image_parts),
tools = tools_to_use,
@@ -29521,7 +29541,11 @@ async def produce_openai_chat_completions(
# Anything after the gated tool_start means the user answered.
if not (
- event["type"] == "tool_start" and event.get("awaiting_confirmation")
+ (event["type"] == "tool_start" and event.get("awaiting_confirmation"))
+ or (
+ event["type"] == "skill_load"
+ and event.get("status") == "awaiting_approval"
+ )
):
await _park_admission(False)
@@ -29530,7 +29554,13 @@ async def produce_openai_chat_completions(
yield _OPENAI_TOOL_HEARTBEAT_SSE
continue
- if event["type"] in ("tool_output", "tool_args"):
+ if event["type"] in ("tool_output", "tool_args", "skill_load"):
+ if (
+ event["type"] == "skill_load"
+ and event.get("status") == "awaiting_approval"
+ ):
+ await _park_admission(True)
+ approval_flush_pending = True
# Live stdout/stderr or tool-call arguments, forwarded
# verbatim for the UI. Final result still arrives in tool_end.
if _ui_events:
@@ -31491,6 +31521,13 @@ async def produce_openai_chat_completions(
yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
+ if event["type"] == "skill_load":
+ approval_flush_pending = event.get("status") == "awaiting_approval"
+ if _ui_events:
+ yield f"data: {json.dumps(event)}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
if event["type"] in ("tool_start", "tool_end"):
if event["type"] == "tool_start":
# Same as the GGUF loop, gated with the card for the same reason:
diff --git a/studio/backend/tests/test_explicit_skill_loading.py b/studio/backend/tests/test_explicit_skill_loading.py
new file mode 100644
index 00000000000..285508092cc
--- /dev/null
+++ b/studio/backend/tests/test_explicit_skill_loading.py
@@ -0,0 +1,119 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The reporter's mention must reach generation even when the model calls no tools."""
+
+import json
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import get_current_subject
+from core.inference import skills
+from core.inference.tools import READ_SKILL_TOOL
+from routes import inference as api
+from .llama_backend_double import FakeLlamaCppBackend
+
+
+class CapturingBackend(FakeLlamaCppBackend):
+ supports_tools = True
+ context_length = 8192
+
+ def __init__(self):
+ self.requests = []
+
+ def count_chat_tokens(self, *args, **kwargs):
+ return 100
+
+ def generate_chat_completion_with_tools(self, **kwargs):
+ self.requests.append(kwargs)
+ yield {"type": "content", "text": "No model read call."}
+ yield {"type": "metadata", "finish_reason": "stop"}
+
+ def generate_chat_completion(self, **kwargs):
+ self.requests.append(kwargs)
+ yield "No model read call."
+ yield {"type": "metadata", "finish_reason": "stop"}
+
+
+def mention_client(tmp_path, monkeypatch):
+ root = tmp_path / "skills"
+ manifest = root / "skill-creator" / "SKILL.md"
+ manifest.parent.mkdir(parents = True)
+ manifest.write_text(
+ "---\nname: skill-creator\ndescription: Test instructions.\n---\n"
+ "Complete manifest sentinel: do not execute or create anything.\n",
+ encoding = "utf-8",
+ )
+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: (("agents", root),))
+ monkeypatch.setattr(skills, "studio_root", lambda: tmp_path / "studio")
+ monkeypatch.setattr(api, "_AGENT_SKILLS_CACHE", {})
+ backend = CapturingBackend()
+ monkeypatch.setattr(api, "get_llama_cpp_backend", lambda: backend)
+ app = FastAPI()
+ app.include_router(api.router)
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ return TestClient(app), backend, manifest
+
+
+ "prompt",
+ [
+ "@skill-creator what did i just paste?",
+ "wait so @skill-creator didnt load it for you?",
+ ],
+)
+def test_reporter_manifest_is_in_first_generation_without_model_read(mention_client, prompt):
+ client, backend, manifest = mention_client
+ response = client.post(
+ "/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": prompt}],
+ "stream": True,
+ "enable_tools": True,
+ "enabled_tools": ["read_skill"],
+ "permission_mode": "auto",
+ "max_tokens": 256,
+ },
+ headers = {"X-Unsloth-Events": "1"},
+ )
+ assert response.status_code == 200, response.text
+ assert backend.requests, response.text
+ first_context = json.dumps(backend.requests[0]["messages"], ensure_ascii = False)
+ assert manifest.read_text() in "\n".join(
+ message.get("content", "") for message in backend.requests[0]["messages"]
+ ), f"complete SKILL.md absent from first generation: {first_context}"
+ assert '"type": "skill_load"' in response.text
+ assert '"status": "loaded"' in response.text
+ assert '"type": "tool_start"' not in response.text
+ assert [t["function"]["name"] for t in backend.requests[0]["tools"]] == [
+ READ_SKILL_TOOL["function"]["name"]
+ ]
+
+
[email protected]("gate", ["code_off", "unsupported", "disabled"])
+def test_actual_local_request_gates_do_not_load(mention_client, gate):
+ client, backend, manifest = mention_client
+ if gate == "unsupported":
+ backend.supports_tools = False
+ if gate == "disabled":
+ skills.set_skill_enabled("skill-creator", False)
+ response = client.post(
+ "/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": "@skill-creator what did i just paste?"}],
+ "stream": True,
+ "enable_tools": gate != "code_off",
+ "enabled_tools": [] if gate == "code_off" else ["read_skill"],
+ "permission_mode": "auto",
+ },
+ headers = {"X-Unsloth-Events": "1"},
+ )
+ assert response.status_code == 200, response.text
+ assert backend.requests
+ assert manifest.read_text() not in "\n".join(
+ m.get("content", "") for m in backend.requests[0]["messages"]
+ )
+ assert '"status": "loaded"' not in response.text
diff --git a/studio/backend/tests/test_skill_mention_semantics.py b/studio/backend/tests/test_skill_mention_semantics.py
new file mode 100644
index 00000000000..49c543bdb08
--- /dev/null
+++ b/studio/backend/tests/test_skill_mention_semantics.py
@@ -0,0 +1,425 @@
+# 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 asyncio
+import json
+import threading
+
+import pytest
+
+from core.inference import skill_mentions as mentions, skills
+from core.inference.tools import READ_SKILL_TOOL
+from .test_explicit_skill_loading import mention_client # noqa: F401 -- shared isolated fixture
+
+
+ "text, expected",
+ [
+ ("@skill-creator what did i just paste?", ["skill-creator"]),
+ ("wait so @skill-creator didnt load it for you?", ["skill-creator"]),
+ ("@skill-creator @another @skill-creator", ["skill-creator", "another"]),
+ ("@skill-creator-extra @skill", ["skill-creator-extra", "skill"]),
+ ("foo@skill-creator https://example/@skill-creator @skill-creator.com", []),
+ ("He said \"@skill-creator\" and '@skill-creator'", []),
+ ("“@skill-creator” ‘@skill-creator’", []),
+ ("`@skill-creator` `` @skill-creator ``", []),
+ ("```python\n@skill-creator\n```\n@another", ["another"]),
+ ("~~~\n@skill-creator\n~~~", []),
+ ('"quoted\n@skill-creator\n"', []),
+ ("````\n```\n@skill-creator\n````", []),
+ ("> @skill-creator\n @skill-creator\n\t@skill-creator", []),
+ ("@Skill-creator @skill-creator/README.md @skill-creator_foo", []),
+ ("@skill-creator, please", ["skill-creator"]),
+ ("```@literal```\n@skill-creator", ["skill-creator"]),
+ ("````\n````python\n@skill-creator\n````\n@another", ["another"]),
+ ("```\n```x```\n@skill-creator\n```\n@another", ["another"]),
+ ],
+)
+def test_plain_text_intent_contract(text, expected):
+ assert mentions.mentioned_skill_names(text) == expected
+
+
+def _load(
+ text = "@skill-creator",
+ *,
+ messages = None,
+ tools = None,
+ **kwargs,
+):
+ messages = messages if messages is not None else [{"role": "user", "content": text}]
+ events = list(
+ mentions.load_mentioned_skills(
+ messages, [READ_SKILL_TOOL] if tools is None else tools, **kwargs
+ )
+ )
+ return messages, events
+
+
+def test_duplicates_and_multiple_skills_are_complete(mention_client):
+ _, _, path = mention_client
+ other = path.parent.parent / "another" / "SKILL.md"
+ other.parent.mkdir()
+ other.write_text("---\nname: another\ndescription: Another.\n---\nSecond body.\n")
+ messages, events = _load("@skill-creator @another @skill-creator")
+ assert [e["name"] for e in events if e["status"] == "loaded"] == ["skill-creator", "another"]
+ assert messages[0]["content"].count(path.read_text()) == 1
+ assert other.read_text() in messages[0]["content"]
+
+
[email protected]("failure", ["disabled", "symlink", "invalid"])
+def test_secure_discovery_failures_are_not_success(mention_client, failure):
+ _, _, path = mention_client
+ if failure == "disabled":
+ skills.set_skill_enabled("skill-creator", False)
+ elif failure == "symlink":
+ old = path.read_text()
+ target = path.parent / "other.md"
+ target.write_text(old)
+ path.unlink()
+ path.symlink_to(target)
+ elif failure == "invalid":
+ path.write_text("no frontmatter")
+ messages, events = _load("@skill-creator")
+ assert events[-1]["status"] == "unavailable"
+ assert "not loaded" in events[-1]["detail"]
+ assert not any(e["status"] == "loaded" for e in events)
+ assert "Complete manifest sentinel" not in messages[0]["content"]
+
+
+def test_complete_snapshot_larger_than_resource_page(mention_client):
+ _, _, path = mention_client
+ path.write_text(path.read_text() + "Instruction.\n" * 1000)
+ assert "Resource continues" in skills.read_skill_resource("skill-creator")
+ messages, events = _load(context_length = 16384)
+ assert events[-1]["status"] == "loaded"
+ assert events[-1]["characters"] == len(path.read_text())
+ assert path.read_text() in messages[0]["content"]
+
+
+def test_budget_refuses_whole_manifest_not_a_truncated_success(mention_client):
+ _, _, path = mention_client
+ messages, events = _load(context_length = 16)
+ assert events[-1]["status"] == "unavailable"
+ assert "budget" in events[-1]["detail"]
+ assert path.read_text() not in messages[0]["content"]
+
+
+def test_existing_actual_instructions_deduplicate_but_changed_resources_reload(mention_client):
+ _, _, path = mention_client
+ original = path.read_text()
+ history = [{"role": "tool", "content": original}, {"role": "user", "content": "@skill-creator"}]
+ messages, events = _load(messages = history)
+ assert events[-1]["already_in_context"] is True
+ assert len(messages) == 2
+ path.write_text(original + "Changed resource.\n")
+ messages, events = _load(messages = history)
+ assert events[-1]["already_in_context"] is False
+ assert path.read_text() in messages[0]["content"]
+
+
+def test_retry_without_instructions_reloads_and_old_mentions_never_activate(mention_client):
+ _, _, path = mention_client
+ for _ in range(2):
+ messages, events = _load()
+ assert path.read_text() in messages[0]["content"]
+ assert events[-1]["already_in_context"] is False
+ for history in [
+ [{"role": "assistant", "content": "@skill-creator"}],
+ [{"role": "user", "content": "@skill-creator"}, {"role": "user", "content": "hello"}],
+ [{"role": "system", "content": "@skill-creator"}, {"role": "user", "content": "hello"}],
+ ]:
+ assert _load(messages = history)[1] == []
+ assert _load(continue_final_message = True)[1] == []
+
+
+def test_deduplicated_native_result_is_protected_through_context_fitting(mention_client):
+ from core.inference.context_window import truncate_oldest_messages
+
+ _, _, path = mention_client
+ manifest = path.read_text()
+ history = [
+ {"role": "user", "content": "earlier task"},
+ {"role": "assistant", "content": "earlier reply"},
+ {"role": "tool", "content": manifest},
+ {"role": "user", "content": "another task"},
+ {"role": "assistant", "content": "another reply"},
+ {"role": "user", "content": "@skill-creator"},
+ ]
+ pins = set()
+ messages, events = _load(messages = history, protected_message_ids = pins)
+ assert events[-1]["already_in_context"] is True
+ assert id(history[2]) in pins
+ fitted, _ = truncate_oldest_messages(messages, keep_ratio = 0.1, protected_message_ids = pins)
+ assert any(manifest in message.get("content", "") for message in fitted)
+
+
+def test_mentions_that_are_not_skills_are_silent(mention_client, monkeypatch):
+ monkeypatch.setattr(mentions, "begin_tool_decision", lambda *a: pytest.fail("no approval"))
+ text = "ask @john and @everyone about it"
+ messages, events = _load(text, permission_mode = "ask", confirm_tool_calls = True)
+ assert events == []
+ assert messages == [{"role": "user", "content": text}]
+
+
+def test_disabled_skill_reports_unavailable_without_asking_approval(mention_client, monkeypatch):
+ skills.set_skill_enabled("skill-creator", False)
+ monkeypatch.setattr(mentions, "begin_tool_decision", lambda *a: pytest.fail("no approval"))
+ _, events = _load(permission_mode = "ask", confirm_tool_calls = True)
+ assert events[-1]["status"] == "unavailable"
+
+
+def test_read_error_preserves_a_single_system_message_and_original_history(mention_client):
+ _, _, path = mention_client
+ path.write_text("no frontmatter")
+ system = {"role": "system", "content": "Standing instructions."}
+ messages, events = _load(
+ "@skill-creator", messages = [system, {"role": "user", "content": "@skill-creator"}]
+ )
+ assert events[-1]["status"] == "unavailable"
+ assert [m["role"] for m in messages] == ["system", "user"]
+ assert system["content"] == "Standing instructions."
+ assert "Standing instructions." in messages[0]["content"]
+
+
+def test_code_or_capability_gate_cannot_be_bypassed_by_a_mention(mention_client, monkeypatch):
+ monkeypatch.setattr(
+ mentions, "read_skill_instructions", lambda name: pytest.fail("must not read")
+ )
+ assert _load(tools = [])[1] == []
+ assert _load(tools = [{"function": {"name": "terminal"}}])[1] == []
+
+
[email protected]("verdict", ["allow", "deny"])
+def test_ask_requires_actual_scoped_approval_before_read(mention_client, monkeypatch, verdict):
+ _, _, path = mention_client
+ messages = [{"role": "user", "content": "@skill-creator"}]
+ gen = mentions.load_mentioned_skills(
+ messages,
+ [READ_SKILL_TOOL],
+ permission_mode = "ask",
+ confirm_tool_calls = True,
+ session_id = "isolated-session",
+ )
+ event = next(gen)
+ assert event["status"] == "awaiting_approval"
+ assert len(messages) == 1
+ from state.tool_approvals import resolve_tool_decision, tool_decision_is_pending
+
+ assert not resolve_tool_decision(event["approval_id"], verdict, session_id = "wrong-session")
+ assert resolve_tool_decision(event["approval_id"], verdict, session_id = "isolated-session")
+ events = list(gen)
+ assert not tool_decision_is_pending(event["approval_id"])
+ assert events[-1]["status"] == ("loaded" if verdict == "allow" else "unavailable")
+ assert (path.read_text() in json.dumps(messages).replace("\\n", "\n")) == (verdict == "allow")
+
+
+def test_closing_parked_preload_cleans_approval_slot(mention_client):
+ from state.tool_approvals import tool_decision_is_pending
+
+ gen = mentions.load_mentioned_skills(
+ [{"role": "user", "content": "@skill-creator"}],
+ [READ_SKILL_TOOL],
+ permission_mode = "ask",
+ confirm_tool_calls = True,
+ )
+ event = next(gen)
+ assert tool_decision_is_pending(event["approval_id"])
+ gen.close()
+ assert not tool_decision_is_pending(event["approval_id"])
+
+
+def test_provider_cannot_forge_successful_load_status():
+ from core.inference.sse_control_frames import sanitize_provider_sse_line
+ assert sanitize_provider_sse_line('data: {"type":"skill_load","status":"loaded"}') is None
+
+
+def test_external_transport_gets_manifest_before_first_request(mention_client):
+ from core.inference.studio_tool_loop import (
+ ToolLoopRun,
+ ToolLoopPolicy,
+ stream_with_studio_tools,
+ )
+
+ _, _, path = mention_client
+ captured = []
+
+ class Transport:
+ heals_text_tool_calls = False
+ sanitizes_provider_frames = False
+
+ async def stream(self, **kwargs):
+ captured.append(kwargs)
+ yield 'data: {"choices":[{"delta":{"content":"No tool call."},"finish_reason":"stop"}]}'
+ yield "data: [DONE]"
+
+ async def drive():
+ return [
+ event
+ async for event in stream_with_studio_tools(
+ Transport(),
+ run = ToolLoopRun(
+ messages = [{"role": "user", "content": "@skill-creator what did i just paste?"}]
+ ),
+ policy = ToolLoopPolicy(
+ tools = [READ_SKILL_TOOL],
+ max_calls = 1,
+ timeout = 30,
+ permission_mode = "auto",
+ confirm_calls = False,
+ bypass_permissions = False,
+ rag_scope = None,
+ nudge_tool_calls = False,
+ ),
+ cancel_event = threading.Event(),
+ )
+ ]
+
+ events = asyncio.run(drive())
+ assert path.read_text() in captured[0]["messages"][0]["content"]
+ assert any('"type":"skill_load"' in event and '"status":"loaded"' in event for event in events)
+ assert not any('"type":"tool_start"' in event for event in events)
+
+
+def test_safetensors_gets_complete_manifest_before_first_turn(mention_client):
+ from core.inference.safetensors_agentic import run_safetensors_tool_loop
+
+ _, _, path = mention_client
+ captured = []
+
+ def single_turn(messages):
+ captured.append(messages)
+ yield "No tool call."
+
+ events = list(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "@skill-creator"}],
+ tools = [READ_SKILL_TOOL],
+ execute_tool = lambda *args, **kwargs: pytest.fail("no script/tool execution"),
+ nudge_tool_calls = False,
+ permission_mode = "auto",
+ context_length = 8192,
+ )
+ )
+ assert path.read_text() in captured[0][0]["content"]
+ assert any(event["type"] == "skill_load" and event["status"] == "loaded" for event in events)
+
+
+def test_external_ask_flushes_skill_approval_before_waiting(mention_client, monkeypatch):
+ from core.inference.studio_tool_loop import (
+ ToolLoopRun,
+ ToolLoopPolicy,
+ stream_with_studio_tools,
+ )
+
+ def slow_allow(*args, **kwargs):
+ import time
+ time.sleep(0.3)
+ return "allow"
+
+ monkeypatch.setattr(mentions, "wait_tool_decision", slow_allow)
+
+ class Transport:
+ heals_text_tool_calls = False
+ sanitizes_provider_frames = False
+
+ async def stream(self, **kwargs):
+ yield 'data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}'
+ yield "data: [DONE]"
+
+ async def drive():
+ return [
+ event
+ async for event in stream_with_studio_tools(
+ Transport(),
+ run = ToolLoopRun(
+ messages = [{"role": "user", "content": "@skill-creator"}], session_id = "s"
+ ),
+ policy = ToolLoopPolicy(
+ tools = [READ_SKILL_TOOL],
+ max_calls = 1,
+ timeout = 30,
+ permission_mode = "ask",
+ confirm_calls = True,
+ bypass_permissions = False,
+ rag_scope = None,
+ nudge_tool_calls = False,
+ ),
+ cancel_event = threading.Event(),
+ )
+ ]
+
+ events = asyncio.run(drive())
+ gate = next(i for i, e in enumerate(events) if '"status":"awaiting_approval"' in e)
+ # The Allow / Deny card must be followed by its own keepalive write while Ask waits.
+ assert events[gate + 1].startswith(":"), events[gate : gate + 2]
+ assert any('"status":"loaded"' in e for e in events)
+
+
[email protected]("tool_choice, max_calls", [("none", 5), ("auto", 0)])
+def test_external_withdrawn_tools_skip_preload(mention_client, tool_choice, max_calls):
+ from core.inference.studio_tool_loop import (
+ ToolLoopRun,
+ ToolLoopPolicy,
+ stream_with_studio_tools,
+ )
+
+ _, _, path = mention_client
+ captured = []
+
+ class Transport:
+ heals_text_tool_calls = False
+ sanitizes_provider_frames = False
+
+ async def stream(self, **kwargs):
+ captured.append(kwargs)
+ yield 'data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}'
+ yield "data: [DONE]"
+
+ async def drive():
+ return [
+ event
+ async for event in stream_with_studio_tools(
+ Transport(),
+ run = ToolLoopRun(
+ messages = [{"role": "user", "content": "@skill-creator"}],
+ tool_choice = tool_choice,
+ ),
+ policy = ToolLoopPolicy(
+ tools = [READ_SKILL_TOOL],
+ max_calls = max_calls,
+ timeout = 30,
+ permission_mode = "auto",
+ confirm_calls = False,
+ bypass_permissions = False,
+ rag_scope = None,
+ nudge_tool_calls = False,
+ ),
+ cancel_event = threading.Event(),
+ )
+ ]
+
+ events = asyncio.run(drive())
+ assert path.read_text() not in json.dumps([c.get("messages") for c in captured])
+ assert not any('"type":"skill_load"' in event for event in events)
+
+
[email protected]("extra", [{"tool_choice": "none"}, {"max_tool_calls_per_message": 0}])
+def test_local_withdrawn_tools_skip_preload(mention_client, extra):
+ client, backend, manifest = mention_client
+ response = client.post(
+ "/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": "@skill-creator hi"}],
+ "stream": True,
+ "enable_tools": True,
+ "enabled_tools": ["read_skill"],
+ "permission_mode": "auto",
+ **extra,
+ },
+ headers = {"X-Unsloth-Events": "1"},
+ )
+ assert response.status_code == 200, response.text
+ assert backend.requests, response.text
+ assert manifest.read_text() not in json.dumps(backend.requests[0]["messages"])
+ assert '"type": "skill_load"' not in response.text
diff --git a/studio/backend/tests/test_skills.py b/studio/backend/tests/test_skills.py
index d58b936788d..814c38a8943 100644
--- a/studio/backend/tests/test_skills.py
+++ b/studio/backend/tests/test_skills.py
@@ -1157,3 +1157,26 @@ def test_managed_account_edits_and_deletes_only_its_own_skills(managed_accounts)
run_as(bob, skills.delete_skill, "bob-made")
assert not (studio / "accounts" / _BOB_ID / "skills" / "bob-made").exists()
assert owner_manifest.is_file()
+
+
+def test_explicit_manifest_loading_uses_current_account_discovery(managed_accounts):
+ from core.inference.skill_mentions import load_mentioned_skills
+ from core.inference.tools import READ_SKILL_TOOL
+ from utils.account_context import run_as
+
+ home, studio, alice, bob = managed_accounts
+ _write_skill(home, "agents", "owner-only", body = "OWNER_ONLY_INSTRUCTIONS")
+ _account_skill(studio, _ALICE_ID, "alice-only", "ALICE_ONLY_INSTRUCTIONS")
+
+ def load(prompt):
+ messages = [{"role": "user", "content": prompt}]
+ events = list(load_mentioned_skills(messages, [READ_SKILL_TOOL]))
+ return messages, events
+
+ alice_messages, alice_events = run_as(alice, load, "@alice-only @owner-only")
+ assert [e["name"] for e in alice_events if e["status"] == "loaded"] == ["alice-only"]
+ assert "OWNER_ONLY_INSTRUCTIONS" not in str(alice_messages)
+ bob_messages, bob_events = run_as(bob, load, "@alice-only @owner-only")
+ assert not any(e["status"] == "loaded" for e in bob_events)
+ assert "ALICE_ONLY_INSTRUCTIONS" not in str(bob_messages)
+ assert "OWNER_ONLY_INSTRUCTIONS" not in str(bob_messages)
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 09b47416d45..f9a9dcfb234 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -2670,6 +2670,8 @@ const Composer: FC<{
const supportsTools = useChatRuntimeStore((s) => s.supportsTools);
const codeToolsEnabled = useChatRuntimeStore((s) => s.codeToolsEnabled);
+ // Effective Code (Full Access implies it), the same gate the request uses to offer read_skill.
+ const codeToolsEffective = useChatRuntimeStore(codeToolsOn);
const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);
const supportsBuiltinImageGeneration = useChatRuntimeStore(
(s) => s.supportsBuiltinImageGeneration,
@@ -5503,7 +5505,7 @@ const Composer: FC<{
<PromptQueueContext.Provider value={queueContextValue}>
<ComposerPrimitive.Unstable_TriggerPopoverRoot>
<SkillMentionPopover
- enabled={supportsTools}
+ enabled={supportsTools && codeToolsEffective}
onConsumesEnterChange={setMentionConsumesEnter}
onOpenChange={setMentionOpen}
/>
@@ -7755,6 +7757,7 @@ const ASSISTANT_PART_COMPONENTS = {
web_search: WebSearchToolUIConfirmable,
search_knowledge_base: KnowledgeBaseToolUIConfirmable,
read_skill: ReadSkillToolUIConfirmable,
+ studio_load_skill: ReadSkillToolUIConfirmable,
python: PythonToolUIConfirmable,
terminal: TerminalToolUIConfirmable,
code_execution: CodeExecutionToolUIConfirmable,
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx
index fa459bc4a46..398d7468f3c 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx
@@ -40,6 +40,17 @@ const ReadSkillToolUIImpl: ToolCallMessagePartComponent = ({
toolArgText((args as { resource?: unknown })?.resource) || "SKILL.md";
const isRunning = status?.type === "running";
const resultText = result == null ? "" : stringifyToolResult(result);
+ const isPreload = (args as { _studio_skill_load?: unknown })?._studio_skill_load === true;
+ const preloadLoaded = resultText.startsWith("Complete SKILL.md read");
+ const label = isPreload
+ ? isRunning
+ ? `Loading ${name}…`
+ : preloadLoaded
+ ? `Loaded ${name} · ${resource}`
+ : `Skill not loaded · ${name}`
+ : isRunning
+ ? `Reading ${name}…`
+ : `Read ${name} · ${resource}`;
const hasText = useAuiState(({ message }) =>
message.content.some(
(part) =>
@@ -58,7 +69,7 @@ const ReadSkillToolUIImpl: ToolCallMessagePartComponent = ({
awaitingApproval={awaitingApproval}
>
<ToolFallbackTrigger
- toolName={isRunning ? `Reading ${name}…` : `Read ${name} · ${resource}`}
+ toolName={label}
status={status}
icon={SkillIcon}
/>
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 50cd1f00712..f18251f0dfd 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1421,6 +1421,8 @@ function serializeAssistantReplayMessages(
if (part.type === "tool-call") {
const toolPart = part as ToolCallMessagePart;
+ // Backend preload card is UI evidence, not a model function call.
+ if (toolPart.toolName === "studio_load_skill") continue;
const toolCall = serializeAssistantToolCallPart(toolPart);
if (!toolCall) continue;
@@ -6976,7 +6978,7 @@ export function createOpenAIStreamAdapter(
if (toolEvent !== undefined) {
// Unsloth's own tool events end the turn that asked for them; finish_reason alone is not
// enough, since a hosted tool runs INSIDE the turn and rides a whole chunk.
- if (!chunk.choices) {
+ if (!chunk.choices && toolEvent.tool_name !== "studio_load_skill") {
endProviderTurn();
}
// Deep Research is an ordinary tool to every loop that runs it, so the handoff is read off the
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index eaece2b1500..40672059457 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1,6 +1,7 @@
// 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 { skillLoadCardEvent } from "./skill-load-event";
import { authFetch, getAuthSessionEpoch } from "@/features/auth";
import { prepareHfTokenForUse } from "@/features/hf-auth";
// These helpers are deliberately API-layer-only, not part of their features' public barrels.
@@ -1764,6 +1765,11 @@ export async function* streamChatCompletions(
if ("error" in parsed && parsed.error) {
throw new Error(parsed.error.message || "Stream error");
}
+ if ("type" in parsed && parsed.type === "skill_load") {
+ yield { _toolEvent: skillLoadCardEvent(parsed) } as unknown as OpenAIChatChunk;
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
+ }
// Tool status events are custom SSE payloads, not OpenAI chunks
if ("type" in parsed && parsed.type === "tool_status") {
yield {
diff --git a/studio/frontend/src/features/chat/api/chat-generation-api.ts b/studio/frontend/src/features/chat/api/chat-generation-api.ts
index fd88c25d7ec..eb9cf013c34 100644
--- a/studio/frontend/src/features/chat/api/chat-generation-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-generation-api.ts
@@ -8,6 +8,7 @@ import type {
OpenAIChatCompletionsRequest,
} from "../types/api";
+import { skillLoadCardEvent } from "./skill-load-event";
export type ChatGenerationStatus =
| "queued"
| "running"
@@ -62,6 +63,9 @@ export function normalizeChatGenerationChunkPayload(
): OpenAIChatChunk | Record<string, unknown> {
if (payload !== null && typeof payload === "object" && "type" in payload) {
const frameType = (payload as { type?: unknown }).type;
+ if (frameType === "skill_load") {
+ return { _toolEvent: skillLoadCardEvent(payload) } as unknown as OpenAIChatChunk;
+ }
// Relay server-side reasoning duration.
if (frameType === "reasoning_summary") {
return {
diff --git a/studio/frontend/src/features/chat/api/skill-load-event.ts b/studio/frontend/src/features/chat/api/skill-load-event.ts
new file mode 100644
index 00000000000..d77e2e559cc
--- /dev/null
+++ b/studio/frontend/src/features/chat/api/skill-load-event.ts
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** UI-only card for a backend skill load; excluded from model history, provider frames sanitized. */
+export function skillLoadCardEvent(
+ event: Record<string, unknown>,
+): Record<string, unknown> {
+ const pending =
+ event.status === "loading" || event.status === "awaiting_approval";
+ return {
+ type: pending ? "tool_start" : "tool_end",
+ tool_name: "studio_load_skill",
+ tool_call_id: event.load_id,
+ arguments: {
+ name: event.name,
+ resource: "SKILL.md",
+ _studio_skill_load: true,
+ },
+ ...(event.status === "awaiting_approval"
+ ? { awaiting_confirmation: true, approval_id: event.approval_id }
+ : {}),
+ ...(pending
+ ? {}
+ : { result: event.detail ?? "Skill loading unavailable." }),
+ };
+}
diff --git a/studio/frontend/tests/chat-save-conflict-detail.test.ts b/studio/frontend/tests/chat-save-conflict-detail.test.ts
index df1ad9ae229..c881a700b36 100644
--- a/studio/frontend/tests/chat-save-conflict-detail.test.ts
+++ b/studio/frontend/tests/chat-save-conflict-detail.test.ts
@@ -8,6 +8,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { loadWithStubs } from "./helpers/module-stubs.ts";
+import { skillLoadCardEvent } from "../src/features/chat/api/skill-load-event.ts";
type Module = {
saveChatMessage: (
@@ -47,6 +48,7 @@ function harness(response: ReturnType<typeof jsonResponse>) {
const module = loadWithStubs<Module>(
new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
{
+ "./skill-load-event": { skillLoadCardEvent },
"@/features/auth": {
authFetch: async (url: string, init?: RequestInit) => {
requests.push({ url, init });
diff --git a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts b/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
index e914fcd5cf8..b664382f3b2 100644
--- a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
+++ b/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
@@ -24,6 +24,7 @@ import test from "node:test";
import { readSrc } from "./helpers/kit.ts";
import { loadWithStubs } from "./helpers/module-stubs.ts";
+import { skillLoadCardEvent } from "../src/features/chat/api/skill-load-event.ts";
const paddedResponse = await import("../src/features/chat/api/padded-response.ts");
const { shouldRestorePreviousModel, loadOutcomeUnknown } = await import(
@@ -109,6 +110,7 @@ function realAuthFetch(port: number): AuthApi {
function realLoadModel(auth: AuthApi): ChatApi {
return loadWithStubs<ChatApi>(new URL("../src/features/chat/api/chat-api.ts", import.meta.url), {
+ "./skill-load-event": { skillLoadCardEvent },
"@/features/auth": { authFetch: auth.authFetch },
"./padded-response": paddedResponse,
"@/lib/format-fastapi-error": {
diff --git a/studio/frontend/tests/load-warning-toast.test.ts b/studio/frontend/tests/load-warning-toast.test.ts
index 01d011e124c..36a779dae07 100644
--- a/studio/frontend/tests/load-warning-toast.test.ts
+++ b/studio/frontend/tests/load-warning-toast.test.ts
@@ -7,6 +7,7 @@ import test from "node:test";
import { readSrc } from "./helpers/kit.ts";
import { loadWithStubs } from "./helpers/module-stubs.ts";
+import { skillLoadCardEvent } from "../src/features/chat/api/skill-load-event.ts";
register("./helpers/toast-resolver.mjs", import.meta.url);
@@ -29,6 +30,7 @@ function chatApi(body: Record<string, unknown>) {
const module = loadWithStubs<ChatApi>(
new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
{
+ "./skill-load-event": { skillLoadCardEvent },
"@/features/auth": {
authFetch: async () => ({
status: 200,
diff --git a/studio/frontend/tests/parallel-tool-call-arguments.test.ts b/studio/frontend/tests/parallel-tool-call-arguments.test.ts
index d68706c819d..e6eee1be81c 100644
--- a/studio/frontend/tests/parallel-tool-call-arguments.test.ts
+++ b/studio/frontend/tests/parallel-tool-call-arguments.test.ts
@@ -1356,13 +1356,33 @@ test("metadata from a resent name goes to the call that runs", () => {
test("a provider-hosted tool event does not end the provider turn", () => {
// Hosted events ride a whole chunk, `choices` and all, and leave the turn
- // open; Unsloth's are bare {"type": "tool_start"}.
+ // open; ordinary Unsloth tool events are bare {"type": "tool_start"}.
+ // A backend skill preload is also bare, but happens BEFORE the provider turn.
const guarded = liftBetween(
"the hosted-event guard",
"const toolEvent = (",
"// Deep Research is an ordinary tool",
);
- assert.match(guarded, /if \(!chunk\.choices\) \{\s*endProviderTurn\(\);/);
+ assert.match(
+ guarded,
+ /if \(!chunk\.choices && toolEvent\.tool_name !== "studio_load_skill"\) \{\s*endProviderTurn\(\);/,
+ );
+ // Execute the actual lifted guard, not a hand-written copy of its condition.
+ const js = ts.transpileModule(`${guarded}\n}`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ const applyGuard = new Function("chunk", "endProviderTurn", js);
+ for (const [chunk, expectedEnds] of [
+ [{ _toolEvent: { tool_name: "web_search" } }, 1],
+ [{ choices: [{}], _toolEvent: { tool_name: "web_search" } }, 0],
+ [{ _toolEvent: { tool_name: "studio_load_skill" } }, 0],
+ [{ choices: [{}], _toolEvent: { tool_name: "studio_load_skill" } }, 0],
+ [{ choices: [{}] }, 0],
+ ] as const) {
+ let ends = 0;
+ applyGuard(chunk, () => { ends += 1; });
+ assert.equal(ends, expectedEnds, JSON.stringify(chunk));
+ }
});
test("a late id does not rescue a fork whose object never closed", () => {
diff --git a/studio/frontend/tests/skill-load-event.test.ts b/studio/frontend/tests/skill-load-event.test.ts
new file mode 100644
index 00000000000..78718c86b5b
--- /dev/null
+++ b/studio/frontend/tests/skill-load-event.test.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { skillLoadCardEvent } from "../src/features/chat/api/skill-load-event.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const event = { type: "skill_load", load_id: "load-1", name: "skill-creator" };
+
+test("backend preload has a distinct UI-only card identity, not a model read_skill call", () => {
+ const start = skillLoadCardEvent({ ...event, status: "loading" });
+ assert.equal(start.tool_name, "studio_load_skill");
+ assert.equal(start.type, "tool_start");
+ assert.equal(start.tool_call_id, "load-1");
+ const loaded = skillLoadCardEvent({
+ ...event,
+ status: "loaded",
+ detail: "Complete SKILL.md read",
+ });
+ assert.equal(loaded.type, "tool_end");
+ assert.equal(loaded.result, "Complete SKILL.md read");
+ assert.equal(loaded.tool_call_id, start.tool_call_id);
+ const denied = skillLoadCardEvent({
+ ...event,
+ status: "unavailable",
+ detail: "Not loaded",
+ });
+ assert.equal(denied.result, "Not loaded");
+});
+
+test("Ask reuses the real scoped confirmation channel", () => {
+ const approval = skillLoadCardEvent({
+ ...event,
+ status: "awaiting_approval",
+ approval_id: "approval-1",
+ });
+ assert.equal(approval.awaiting_confirmation, true);
+ assert.equal(approval.approval_id, "approval-1");
+});
+
+test("legacy and durable streams normalize preload, and history omits UI evidence", () => {
+ const legacy = readSrc("features/chat/api/chat-api.ts");
+ const durable = readSrc("features/chat/api/chat-generation-api.ts");
+ assert.match(legacy, /parsed.type === "skill_load"/);
+ assert.match(durable, /frameType === "skill_load"/);
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ assert.match(
+ adapter,
+ /if \(toolPart.toolName === "studio_load_skill"\) continue;/,
+ );
+ assert.match(
+ adapter,
+ /!chunk.choices && toolEvent.tool_name !== "studio_load_skill"/,
+ );
+ const thread = readSrc("components/assistant-ui/thread.tsx");
+ assert.match(thread, /studio_load_skill: ReadSkillToolUIConfirmable/);
+ assert.match(thread, /enabled=\{supportsTools && codeToolsEffective\}/);
+ assert.match(thread, /const codeToolsEffective = useChatRuntimeStore\(codeToolsOn\);/);
+ const ui = readSrc("components/assistant-ui/tool-ui-read-skill.tsx");
+ assert.match(ui, /Skill not loaded/);
+ assert.match(ui, /Loaded \$\{name\}/);
+});
diff --git a/studio/frontend/tests/tool-approval-gone.test.ts b/studio/frontend/tests/tool-approval-gone.test.ts
index 7b608f49889..38e708a72f8 100644
--- a/studio/frontend/tests/tool-approval-gone.test.ts
+++ b/studio/frontend/tests/tool-approval-gone.test.ts
@@ -10,6 +10,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { loadWithStubs } from "./helpers/module-stubs.ts";
+import { skillLoadCardEvent } from "../src/features/chat/api/skill-load-event.ts";
type Module = {
resolveToolConfirmation: (
@@ -36,6 +37,7 @@ function harness(response: ReturnType<typeof jsonResponse>) {
const module = loadWithStubs<Module>(
new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
{
+ "./skill-load-event": { skillLoadCardEvent },
"@/features/auth": {
authFetch: async (url: string, init?: RequestInit) => {
requests.push({ url, init });