Skip to content

Agent Zero AI framework

Improve active skills management and simplify Skills UI

Alessandro79f948b0769c
diff --git a/helpers/skills.py b/helpers/skills.py
index bf3b624d9..ab713f5ac 100644
--- a/helpers/skills.py
+++ b/helpers/skills.py
@@ -4,9 +4,10 @@ import os
import re
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, TYPE_CHECKING
+from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, TYPE_CHECKING, TypedDict
from helpers import files, subagents, projects, file_tree, runtime
+from helpers import plugins as plugin_helpers
if TYPE_CHECKING:
from agent import Agent
@@ -17,6 +18,24 @@ except Exception: # pragma: no cover
yaml = None # type: ignore
+MAX_ACTIVE_SKILLS = 20
+ACTIVE_SKILLS_PLUGIN_NAME = "_skills"
+CONTEXT_DATA_NAME_CHAT_ACTIVE_SKILLS = "skills_chat_active"
+CONTEXT_DATA_NAME_CHAT_DISABLED_SKILLS = "skills_chat_disabled"
+
+
+class ActiveSkillEntry(TypedDict, total=False):
+ name: str
+ path: str
+
+
+class CatalogSkill(TypedDict):
+ name: str
+ description: str
+ path: str
+ origin: str
+
+
@dataclass(slots=True)
class Skill:
name: str
@@ -544,3 +563,464 @@ def validate_skill_md(skill_md_path: Path) -> List[str]:
if not skill:
return ["Unable to parse SKILL.md frontmatter"]
return validate_skill(skill)
+
+
+def get_max_active_skills() -> int:
+ return MAX_ACTIVE_SKILLS
+
+
+def normalize_skills_config(config: dict[str, Any] | None) -> dict[str, Any]:
+ normalized = dict(config or {})
+ normalized["active_skills"] = normalize_active_skills(
+ normalized.get("active_skills")
+ )
+ return normalized
+
+
+def normalize_active_skills(raw: Any) -> list[ActiveSkillEntry]:
+ if not isinstance(raw, list):
+ return []
+
+ normalized: list[ActiveSkillEntry] = []
+ seen: set[str] = set()
+
+ for item in raw:
+ entry = _normalize_active_skill_entry(item)
+ if not entry:
+ continue
+
+ key = _entry_key(entry)
+ if not key or key in seen:
+ continue
+
+ seen.add(key)
+ normalized.append(entry)
+ if len(normalized) >= get_max_active_skills():
+ break
+
+ return normalized
+
+
+def list_skill_catalog(
+ project_name: str = "",
+ agent: Agent | None = None,
+) -> list[CatalogSkill]:
+ if not project_name:
+ project_name = _get_agent_project_name(agent)
+
+ catalog: list[CatalogSkill] = []
+ seen_paths: set[str] = set()
+
+ for root in _get_catalog_roots(project_name=project_name, agent=agent):
+ root_path = Path(root)
+ for skill_md in discover_skill_md_files(root_path):
+ skill = skill_from_markdown(skill_md, include_content=False)
+ if not skill:
+ continue
+
+ runtime_path = files.normalize_a0_path(str(skill.path))
+ if runtime_path in seen_paths:
+ continue
+
+ seen_paths.add(runtime_path)
+ catalog.append(
+ {
+ "name": skill.name or skill.path.name,
+ "description": skill.description or "",
+ "path": runtime_path,
+ "origin": _get_skill_origin(
+ runtime_path,
+ project_name=project_name,
+ ),
+ }
+ )
+
+ catalog.sort(key=lambda item: (item["name"].lower(), item["path"]))
+ return catalog
+
+
+def get_scope_active_skills(agent: Agent | None) -> list[ActiveSkillEntry]:
+ if not agent:
+ return []
+
+ project_name = _get_agent_project_name(agent)
+ config = (
+ plugin_helpers.get_plugin_config(
+ ACTIVE_SKILLS_PLUGIN_NAME,
+ agent=agent,
+ project_name=project_name,
+ agent_profile="",
+ )
+ or {}
+ )
+ return normalize_active_skills(config.get("active_skills"))
+
+
+def get_chat_active_skills(context: Any | None) -> list[ActiveSkillEntry]:
+ if not context:
+ return []
+ return normalize_active_skills(context.get_data(CONTEXT_DATA_NAME_CHAT_ACTIVE_SKILLS))
+
+
+def get_chat_disabled_skills(context: Any | None) -> list[ActiveSkillEntry]:
+ if not context:
+ return []
+ return normalize_active_skills(
+ context.get_data(CONTEXT_DATA_NAME_CHAT_DISABLED_SKILLS)
+ )
+
+
+def _build_active_skills(
+ agent: Agent | None,
+ *,
+ chat_entries: list[ActiveSkillEntry] | None = None,
+ disabled_entries: list[ActiveSkillEntry] | None = None,
+ limit: int | None = None,
+) -> list[ActiveSkillEntry]:
+ if not agent:
+ return []
+
+ context = getattr(agent, "context", None)
+ effective_limit = get_max_active_skills() if limit is None else limit
+ scope_entries = get_scope_active_skills(agent)
+ current_chat_entries = list(
+ chat_entries if chat_entries is not None else get_chat_active_skills(context)
+ )
+ current_disabled_entries = list(
+ disabled_entries
+ if disabled_entries is not None
+ else get_chat_disabled_skills(context)
+ )
+ return _merge_active_skill_entries(
+ scope_entries,
+ current_chat_entries,
+ current_disabled_entries,
+ limit=effective_limit,
+ )
+
+
+def get_active_skills(agent: Agent | None) -> list[ActiveSkillEntry]:
+ return _build_active_skills(agent, limit=get_max_active_skills())
+
+
+def activate_chat_skill(agent: Agent, entry: Any) -> list[ActiveSkillEntry]:
+ normalized = _normalize_active_skill_entry(entry)
+ if not normalized:
+ raise ValueError("A skill name or path is required.")
+
+ context = getattr(agent, "context", None)
+ if not context:
+ raise ValueError("A chat context is required.")
+
+ key = _entry_key(normalized)
+ scope_entries = get_scope_active_skills(agent)
+ chat_entries = [
+ item for item in get_chat_active_skills(context) if _entry_key(item) != key
+ ]
+ disabled_entries = [
+ item
+ for item in get_chat_disabled_skills(context)
+ if _entry_key(item) != key
+ ]
+
+ if not any(_entry_key(item) == key for item in scope_entries):
+ chat_entries.append(normalized)
+
+ merged_entries = _build_active_skills(
+ agent,
+ chat_entries=chat_entries,
+ disabled_entries=disabled_entries,
+ limit=-1,
+ )
+ if len(merged_entries) > get_max_active_skills():
+ raise ValueError(
+ f"You can activate at most {get_max_active_skills()} skills."
+ )
+
+ _store_context_active_skill_entries(
+ context,
+ CONTEXT_DATA_NAME_CHAT_ACTIVE_SKILLS,
+ chat_entries,
+ )
+ _store_context_active_skill_entries(
+ context,
+ CONTEXT_DATA_NAME_CHAT_DISABLED_SKILLS,
+ disabled_entries,
+ )
+ return get_active_skills(agent)
+
+
+def deactivate_chat_skill(agent: Agent, entry: Any) -> list[ActiveSkillEntry]:
+ normalized = _normalize_active_skill_entry(entry)
+ if not normalized:
+ raise ValueError("A skill name or path is required.")
+
+ context = getattr(agent, "context", None)
+ if not context:
+ raise ValueError("A chat context is required.")
+
+ key = _entry_key(normalized)
+ chat_entries = [
+ item for item in get_chat_active_skills(context) if _entry_key(item) != key
+ ]
+ disabled_entries = [
+ item
+ for item in get_chat_disabled_skills(context)
+ if _entry_key(item) != key
+ ]
+
+ is_scope_default = any(
+ _entry_key(item) == key for item in get_scope_active_skills(agent)
+ )
+ if is_scope_default:
+ disabled_entries.append(normalized)
+
+ _store_context_active_skill_entries(
+ context,
+ CONTEXT_DATA_NAME_CHAT_ACTIVE_SKILLS,
+ chat_entries,
+ )
+ _store_context_active_skill_entries(
+ context,
+ CONTEXT_DATA_NAME_CHAT_DISABLED_SKILLS,
+ disabled_entries,
+ )
+ return get_active_skills(agent)
+
+
+def clear_chat_skill_overrides(agent: Agent) -> list[ActiveSkillEntry]:
+ context = getattr(agent, "context", None)
+ if not context:
+ raise ValueError("A chat context is required.")
+
+ _store_context_active_skill_entries(context, CONTEXT_DATA_NAME_CHAT_ACTIVE_SKILLS, [])
+ _store_context_active_skill_entries(context, CONTEXT_DATA_NAME_CHAT_DISABLED_SKILLS, [])
+ return get_active_skills(agent)
+
+
+def build_active_skills_prompt(agent: Agent | None) -> str:
+ items = _resolve_active_skill_entries(agent, get_active_skills(agent))
+ return "\n\n".join(item["content"] for item in items if item.get("content")).strip()
+
+
+def _format_skill_prompt(skill: Skill) -> str:
+ lines = [
+ f"Skill: {skill.name or skill.path.name}",
+ f"Path: {files.normalize_a0_path(str(skill.path))}",
+ ]
+
+ if skill.description:
+ lines.extend(["", "Description:", skill.description.strip()])
+
+ lines.extend(["", "Instructions:", (skill.content or "").strip() or "(empty)"])
+ return "\n".join(lines)
+
+
+def _get_skill_origin(skill_path: str, project_name: str = "") -> str:
+ abs_path = files.fix_dev_path(skill_path)
+
+ if project_name:
+ project_root = projects.get_project_meta(project_name, "skills")
+ if files.exists(project_root) and files.is_in_dir(abs_path, project_root):
+ return "Project"
+
+ user_root = files.get_abs_path("usr", "skills")
+ if files.exists(user_root) and files.is_in_dir(abs_path, user_root):
+ return "User"
+
+ normalized_path = files.normalize_a0_path(abs_path)
+ if "/usr/plugins/" in normalized_path:
+ return "Community plugin"
+ if "/plugins/" in normalized_path:
+ return "Built-in plugin"
+ return "Built-in"
+
+
+def _normalize_active_skill_entry(item: Any) -> ActiveSkillEntry | None:
+ if isinstance(item, str):
+ stripped = item.strip()
+ if not stripped:
+ return None
+ if "/" in stripped:
+ return {"path": _normalize_active_skill_path(stripped)}
+ return {"name": stripped}
+
+ if not isinstance(item, dict):
+ return None
+
+ name = str(item.get("name") or "").strip()
+ path = str(item.get("path") or "").strip()
+
+ if path:
+ path = _normalize_active_skill_path(path)
+ if not (path or name):
+ return None
+
+ entry: ActiveSkillEntry = {}
+ if name:
+ entry["name"] = name
+ if path:
+ entry["path"] = path
+ return entry
+
+
+def _normalize_active_skill_path(path: str) -> str:
+ fixed = path.strip().replace("\\", "/")
+ if fixed.startswith("/a0/"):
+ return fixed.rstrip("/")
+ if fixed.startswith("/"):
+ return files.normalize_a0_path(fixed).rstrip("/")
+ return files.normalize_a0_path(files.get_abs_path(fixed)).rstrip("/")
+
+
+def _entry_key(entry: ActiveSkillEntry) -> str:
+ return str(entry.get("path") or entry.get("name") or "").strip().lower()
+
+
+def _get_agent_project_name(agent: Agent | None) -> str:
+ context = getattr(agent, "context", None)
+ if not context:
+ return ""
+ return projects.get_context_project_name(context) or ""
+
+
+def _get_catalog_roots(
+ project_name: str = "",
+ agent: Agent | None = None,
+) -> list[str]:
+ roots: list[str] = []
+ seen: set[str] = set()
+
+ def add(path: str) -> None:
+ if not path:
+ return
+ fixed = files.fix_dev_path(path)
+ if not files.exists(fixed) or fixed in seen:
+ return
+ seen.add(fixed)
+ roots.append(fixed)
+
+ if agent is not None:
+ for path in get_skill_roots(agent):
+ add(path)
+ return roots
+
+ if project_name:
+ add(projects.get_project_meta(project_name, "skills"))
+
+ add(files.get_abs_path("usr", "skills"))
+ for path in plugin_helpers.get_enabled_plugin_paths(None, "skills"):
+ add(path)
+ add(files.get_abs_path("skills"))
+
+ return roots
+
+
+def _merge_active_skill_entries(
+ scope_entries: list[ActiveSkillEntry],
+ dynamic_entries: list[ActiveSkillEntry],
+ disabled_entries: list[ActiveSkillEntry],
+ *,
+ limit: int | None,
+) -> list[ActiveSkillEntry]:
+ merged: list[ActiveSkillEntry] = []
+ seen: set[str] = set()
+ disabled_keys = {_entry_key(entry) for entry in disabled_entries if _entry_key(entry)}
+
+ for entry in [*scope_entries, *dynamic_entries]:
+ key = _entry_key(entry)
+ if not key or key in seen or key in disabled_keys:
+ continue
+
+ seen.add(key)
+ merged.append(entry)
+ if limit is not None and limit >= 0 and len(merged) >= limit:
+ break
+
+ return merged
+
+
+def _store_context_active_skill_entries(
+ context: Any,
+ key: str,
+ entries: list[ActiveSkillEntry],
+) -> None:
+ normalized_entries = normalize_active_skills(entries)
+ context.set_data(key, normalized_entries or None)
+
+
+def _resolve_active_skill_entries(
+ agent: Agent | None,
+ entries: list[ActiveSkillEntry],
+) -> list[dict[str, str]]:
+ if not agent:
+ return []
+
+ visible_roots = [files.fix_dev_path(root) for root in get_skill_roots(agent)]
+ resolved: list[dict[str, str]] = []
+ seen_paths: set[str] = set()
+
+ for entry in entries:
+ skill = _resolve_active_skill_entry(entry, visible_roots)
+ if not skill:
+ continue
+
+ runtime_path = files.normalize_a0_path(str(skill.path))
+ if runtime_path in seen_paths:
+ continue
+
+ seen_paths.add(runtime_path)
+ resolved.append(
+ {
+ "name": skill.name or skill.path.name,
+ "path": runtime_path,
+ "content": _format_skill_prompt(skill),
+ }
+ )
+
+ return resolved
+
+
+def _resolve_active_skill_entry(
+ entry: ActiveSkillEntry,
+ visible_roots: list[str],
+) -> Skill | None:
+ skill_path = str(entry.get("path") or "").strip()
+ if skill_path:
+ skill = _load_skill_from_runtime_path(skill_path, visible_roots)
+ if skill:
+ return skill
+
+ skill_name = str(entry.get("name") or "").strip()
+ if not skill_name:
+ return None
+
+ target = skill_name.lower().strip()
+ for root in visible_roots:
+ for skill_md in discover_skill_md_files(Path(root)):
+ skill = skill_from_markdown(skill_md, include_content=True)
+ if not skill:
+ continue
+ candidates = {
+ (skill.name or "").strip().lower(),
+ skill.path.name.strip().lower(),
+ }
+ if target in candidates:
+ return skill
+
+ return None
+
+
+def _load_skill_from_runtime_path(
+ skill_path: str,
+ visible_roots: list[str],
+) -> Skill | None:
+ abs_path = files.fix_dev_path(skill_path)
+ if not any(files.is_in_dir(abs_path, root) for root in visible_roots):
+ return None
+
+ skill_md = Path(abs_path) / "SKILL.md"
+ if not skill_md.is_file():
+ return None
+
+ return skill_from_markdown(skill_md, include_content=True)
diff --git a/plugins/_skills/README.md b/plugins/_skills/README.md
index fdce59842..1aa304a24 100644
--- a/plugins/_skills/README.md
+++ b/plugins/_skills/README.md
@@ -1,11 +1,12 @@
# Skills
-Skills is a built-in Agent Zero plugin that lets you pin skills into prompt extras for a chosen scope.
+Skills is a built-in Agent Zero plugin that manages active skills across scope defaults and the current chat.
## What It Does
-- activates selected skills for the current plugin scope
-- injects those skills into prompt extras on every turn
+- pins default skills for the current plugin scope
+- injects the effective active skills into prompt extras on every turn
+- extends the same config screen with a current-chat mode so users can activate or hide skills live per conversation
- supports global and project scoped configurations without agent-profile variants
- links directly to the built-in Skills list
- links directly to the active project's Skills section when a project is active
@@ -15,10 +16,12 @@ Skills is a built-in Agent Zero plugin that lets you pin skills into prompt extr
Agent Zero already supports loading skills dynamically with `skills_tool`, and already has great built-in skill management surfaces. What it did not have was a lightweight way to make a few skills feel "always on" for a specific scope without modifying the core prompt system.
Skills fills that gap as a bundled built-in plugin.
+The shared active-skill state and prompt-resolution logic live in `helpers/skills.py`, and this plugin focuses on configuration, UI, and prompt injection.
## Notes
-- keep the active list short because every selected skill is injected into prompt extras every turn
-- this plugin enforces the same extras cap as the core `skills_tool`: at most 5 active skills
+- keep the active list short because every active skill is injected into prompt extras every turn
+- the framework-wide cap is 20 active skills
- selected skills are stored in normalized `/a0/...` form so configs stay portable across development and Docker-style layouts
+- scope defaults can be hidden or supplemented per chat without creating a new conversation
- if a configured skill is not visible in the current agent scope, it is skipped quietly instead of breaking the prompt build
diff --git a/plugins/_skills/api/skills_catalog.py b/plugins/_skills/api/skills_catalog.py
index 98ba393df..24d87b3dc 100644
--- a/plugins/_skills/api/skills_catalog.py
+++ b/plugins/_skills/api/skills_catalog.py
@@ -1,24 +1,263 @@
from __future__ import annotations
-from helpers.api import ApiHandler, Request, Response
+from pathlib import Path
+from typing import Any
-from plugins._skills.helpers.runtime import (
- get_max_active_skills,
- list_catalog,
-)
+from agent import AgentContext
+from helpers import files, projects, skills
+from helpers.api import ApiHandler, Request, Response
+from helpers.persist_chat import save_tmp_chat
class SkillsCatalog(ApiHandler):
async def process(self, input: dict, request: Request) -> dict | Response:
action = str(input.get("action", "list") or "list").strip().lower()
+ context_id = str(input.get("context_id", "") or "").strip()
+ project_name = str(input.get("project_name", "") or "").strip()
- if action != "list":
+ try:
+ if action == "list":
+ return self._build_state(context_id=context_id, project_name=project_name)
+ if action == "activate":
+ return self._activate(input, context_id=context_id)
+ if action == "deactivate":
+ return self._deactivate(input, context_id=context_id)
+ if action == "clear":
+ return self._clear(context_id=context_id)
+ if action == "get_doc":
+ return self._get_doc(input, context_id=context_id, project_name=project_name)
return {"ok": False, "error": f"Unknown action: {action}"}
+ except Exception as e:
+ return {"ok": False, "error": str(e)}
- project_name = str(input.get("project_name", "") or "").strip()
+ def _activate(self, input: dict, *, context_id: str) -> dict[str, Any]:
+ context = self._require_context(context_id)
+ skill_entry = self._require_skill_entry(input)
+ skills.activate_chat_skill(context.get_agent(), skill_entry)
+ save_tmp_chat(context)
+ return self._build_state(context_id=context.id)
+
+ def _deactivate(self, input: dict, *, context_id: str) -> dict[str, Any]:
+ context = self._require_context(context_id)
+ skill_entry = self._require_skill_entry(input)
+ skills.deactivate_chat_skill(context.get_agent(), skill_entry)
+ save_tmp_chat(context)
+ return self._build_state(context_id=context.id)
+
+ def _clear(self, *, context_id: str) -> dict[str, Any]:
+ context = self._require_context(context_id)
+ skills.clear_chat_skill_overrides(context.get_agent())
+ save_tmp_chat(context)
+ return self._build_state(context_id=context.id)
+
+ def _build_state(
+ self,
+ *,
+ context_id: str = "",
+ project_name: str = "",
+ ) -> dict[str, Any]:
+ context = AgentContext.get(context_id) if context_id else None
+ agent = context.get_agent() if context else None
+
+ if context and not project_name:
+ project_name = projects.get_context_project_name(context) or ""
+
+ catalog = skills.list_skill_catalog(project_name=project_name, agent=agent)
+ catalog_by_key = {self._entry_key(skill): skill for skill in catalog}
+ catalog_by_name = {
+ str(skill.get("name") or "").strip().lower(): skill for skill in catalog
+ }
+
+ scope_entries = skills.get_scope_active_skills(agent)
+ chat_entries = skills.get_chat_active_skills(context)
+ disabled_entries = skills.get_chat_disabled_skills(context)
+ active_entries = self._merge_entries(
+ skills.get_active_skills(agent),
+ self._get_loaded_skill_entries(agent),
+ )
+
+ scope_keys = {
+ self._entry_key(entry) for entry in scope_entries if self._entry_key(entry)
+ }
+ chat_keys = {
+ self._entry_key(entry) for entry in chat_entries if self._entry_key(entry)
+ }
+
+ return {
+ "ok": True,
+ "context_available": bool(context),
+ "context_id": context.id if context else "",
+ "project_name": project_name,
+ "skills": catalog,
+ "max_active_skills": skills.get_max_active_skills(),
+ "active_skills": [
+ self._serialize_entry(
+ entry,
+ catalog_by_key,
+ catalog_by_name,
+ state_source=(
+ "Pinned + chat"
+ if key in scope_keys and key in chat_keys
+ else "Pinned default"
+ if key in scope_keys
+ else "Chat"
+ ),
+ )
+ for entry in active_entries
+ if (key := self._entry_key(entry))
+ ],
+ "scope_skills": [
+ self._serialize_entry(
+ entry,
+ catalog_by_key,
+ catalog_by_name,
+ state_source="Pinned default",
+ )
+ for entry in scope_entries
+ ],
+ "chat_skills": [
+ self._serialize_entry(
+ entry,
+ catalog_by_key,
+ catalog_by_name,
+ state_source="Chat",
+ )
+ for entry in chat_entries
+ ],
+ "disabled_skills": [
+ self._serialize_entry(
+ entry,
+ catalog_by_key,
+ catalog_by_name,
+ state_source="Hidden in chat",
+ )
+ for entry in disabled_entries
+ ],
+ }
+
+ def _get_doc(
+ self,
+ input: dict,
+ *,
+ context_id: str = "",
+ project_name: str = "",
+ ) -> dict[str, Any]:
+ context = AgentContext.get(context_id) if context_id else None
+ agent = context.get_agent() if context else None
+
+ if context and not project_name:
+ project_name = projects.get_context_project_name(context) or ""
+
+ skill_entry = self._require_skill_entry(input)
+ requested_key = self._entry_key(skill_entry)
+ catalog = skills.list_skill_catalog(project_name=project_name, agent=agent)
+ skill = next(
+ (item for item in catalog if self._entry_key(item) == requested_key),
+ None,
+ )
+ if not skill and skill_entry.get("name"):
+ requested_name = str(skill_entry.get("name") or "").strip().lower()
+ skill = next(
+ (item for item in catalog if str(item.get("name") or "").strip().lower() == requested_name),
+ None,
+ )
+
+ if not skill:
+ raise ValueError("Skill not found in the current list")
+
+ skill_path = str(skill.get("path") or "").strip()
+ skill_md_path = Path(files.fix_dev_path(skill_path)) / "SKILL.md"
+ if not skill_md_path.is_file():
+ raise FileNotFoundError("SKILL.md not found")
return {
"ok": True,
- "skills": list_catalog(project_name=project_name),
- "max_active_skills": get_max_active_skills(),
+ "filename": f"{skill.get('name') or skill_md_path.parent.name} / SKILL.md",
+ "content": skill_md_path.read_text(encoding="utf-8", errors="replace"),
+ }
+
+ def _require_context(self, context_id: str) -> AgentContext:
+ if not context_id:
+ raise ValueError("context_id is required")
+
+ context = AgentContext.get(context_id)
+ if not context:
+ raise ValueError("Context not found")
+ return context
+
+ def _require_skill_entry(self, input: dict) -> dict[str, str]:
+ entries = skills.normalize_active_skills([input.get("skill")])
+ if not entries:
+ raise ValueError("skill is required")
+ return entries[0]
+
+ def _entry_key(self, entry: dict[str, Any]) -> str:
+ return str(entry.get("path") or entry.get("name") or "").strip().lower()
+
+ def _get_loaded_skill_entries(self, agent: Any | None) -> list[dict[str, str]]:
+ if not agent:
+ return []
+
+ loaded = getattr(agent, "data", {}).get("loaded_skills")
+ if not isinstance(loaded, list):
+ return []
+
+ return [
+ {"name": str(skill_name).strip()}
+ for skill_name in loaded
+ if str(skill_name).strip()
+ ]
+
+ def _merge_entries(
+ self,
+ *entry_groups: list[dict[str, Any]],
+ ) -> list[dict[str, Any]]:
+ merged: list[dict[str, Any]] = []
+ seen: set[str] = set()
+
+ for entries in entry_groups:
+ for entry in entries:
+ key = self._entry_key(entry)
+ if not key or key in seen:
+ continue
+ seen.add(key)
+ merged.append(entry)
+
+ return merged
+
+ def _serialize_entry(
+ self,
+ entry: dict[str, Any],
+ catalog_by_key: dict[str, dict[str, Any]],
+ catalog_by_name: dict[str, dict[str, Any]],
+ *,
+ state_source: str,
+ ) -> dict[str, Any]:
+ key = self._entry_key(entry)
+ match = catalog_by_key.get(key)
+
+ if not match:
+ name_key = str(entry.get("name") or "").strip().lower()
+ if name_key:
+ match = catalog_by_name.get(name_key)
+
+ if match:
+ return {
+ **match,
+ "state_source": state_source,
+ "missing": False,
+ }
+
+ path = str(entry.get("path") or "").strip()
+ fallback_name = str(entry.get("name") or "").strip()
+ if not fallback_name and path:
+ fallback_name = Path(path).name or path
+
+ return {
+ "name": fallback_name or "(unnamed skill)",
+ "description": "",
+ "path": path,
+ "origin": "Unavailable",
+ "state_source": state_source,
+ "missing": True,
}
diff --git a/plugins/_skills/extensions/python/message_loop_prompts_after/_66_include_active_skills.py b/plugins/_skills/extensions/python/message_loop_prompts_after/_66_include_active_skills.py
index 537dbca49..fc10cc0c8 100644
--- a/plugins/_skills/extensions/python/message_loop_prompts_after/_66_include_active_skills.py
+++ b/plugins/_skills/extensions/python/message_loop_prompts_after/_66_include_active_skills.py
@@ -1,36 +1,23 @@
from __future__ import annotations
+from helpers import skills
from agent import LoopData
-from helpers import plugins, projects
from helpers.extension import Extension
-from plugins._skills.helpers.runtime import PLUGIN_NAME, resolve_active_skills
-
class IncludeActiveSkills(Extension):
async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
if not self.agent:
return
- project_name = projects.get_context_project_name(self.agent.context) or ""
- config = (
- plugins.get_plugin_config(
- PLUGIN_NAME,
- agent=self.agent,
- project_name=project_name,
- agent_profile="",
- )
- or {}
- )
- active_skills = resolve_active_skills(self.agent, config.get("active_skills"))
- if not active_skills:
- return
+ extras = loop_data.extras_persistent
+ extras.pop("active_skills", None)
- content = "\n\n".join(item["content"] for item in active_skills if item.get("content")).strip()
+ content = skills.build_active_skills_prompt(self.agent)
if not content:
return
- loop_data.extras_persistent["active_skills"] = self.agent.read_prompt(
+ extras["active_skills"] = self.agent.read_prompt(
"agent.system.active_skills.md",
skills=content,
)
diff --git a/plugins/_skills/extensions/webui/initFw_end/skills-menu-injector.js b/plugins/_skills/extensions/webui/initFw_end/skills-menu-injector.js
index cb78e1695..fd4ddef13 100644
--- a/plugins/_skills/extensions/webui/initFw_end/skills-menu-injector.js
+++ b/plugins/_skills/extensions/webui/initFw_end/skills-menu-injector.js
@@ -1,6 +1,6 @@
import { store as pluginSettingsStore } from "/components/plugins/plugin-settings-store.js";
-import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";
import { store as chatInputStore } from "/components/chat/input/input-store.js";
+import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";
const MENU_SELECTOR = ".chat-bottom-actions-menu";
const BUTTON_ID = "skills-chat-more-item";
@@ -16,9 +16,9 @@ function buildButton() {
`;
button.addEventListener("click", async () => {
- const projectName = chatsStore.selectedContext?.project?.name || "";
chatInputStore.closeChatMoreMenu();
- await pluginSettingsStore.openConfig("_skills", projectName, "");
+ const projectName = chatsStore.selectedContext?.project?.name || "";
+ await pluginSettingsStore.openConfig("_skills", projectName, "", { focus: "chat" });
});
return button;
diff --git a/plugins/_skills/helpers/__init__.py b/plugins/_skills/helpers/__init__.py
index 7cf5673b4..636cdce97 100644
--- a/plugins/_skills/helpers/__init__.py
+++ b/plugins/_skills/helpers/__init__.py
@@ -1 +1 @@
-# Helpers for the Skill Switchboard plugin.
+# Plugin-local helpers for the Skills UI plugin.
diff --git a/plugins/_skills/helpers/runtime.py b/plugins/_skills/helpers/runtime.py
deleted file mode 100644
index be56a51c3..000000000
--- a/plugins/_skills/helpers/runtime.py
+++ /dev/null
@@ -1,255 +0,0 @@
-from __future__ import annotations
-
-from pathlib import Path
-from typing import Any, TypedDict
-
-from helpers import files, plugins as plugin_helpers, projects, skills
-
-
-PLUGIN_NAME = "_skills"
-DEFAULT_MAX_ACTIVE_SKILLS = 5
-
-
-class ActiveSkillEntry(TypedDict, total=False):
- name: str
- path: str
-
-
-class CatalogSkill(TypedDict):
- name: str
- description: str
- path: str
- origin: str
-
-
-def get_max_active_skills() -> int:
- try:
- from tools.skills_tool import max_loaded_skills
-
- value = int(max_loaded_skills())
- return value if value > 0 else DEFAULT_MAX_ACTIVE_SKILLS
- except Exception:
- return DEFAULT_MAX_ACTIVE_SKILLS
-
-
-def coerce_config(config: dict[str, Any] | None) -> dict[str, Any]:
- normalized = dict(config or {})
- normalized["active_skills"] = normalize_active_skills(normalized.get("active_skills"))
- return normalized
-
-
-def normalize_active_skills(raw: Any) -> list[ActiveSkillEntry]:
- if not isinstance(raw, list):
- return []
-
- limit = get_max_active_skills()
- normalized: list[ActiveSkillEntry] = []
- seen: set[str] = set()
-
- for item in raw:
- entry = _normalize_active_skill_entry(item)
- if not entry:
- continue
-
- key = _entry_key(entry)
- if not key or key in seen:
- continue
-
- seen.add(key)
- normalized.append(entry)
- if len(normalized) >= limit:
- break
-
- return normalized
-
-
-def list_catalog(project_name: str = "") -> list[CatalogSkill]:
- catalog: list[CatalogSkill] = []
- seen_paths: set[str] = set()
-
- for root in _get_catalog_roots(project_name=project_name):
- root_path = Path(root)
- for skill_md in skills.discover_skill_md_files(root_path):
- skill = skills.skill_from_markdown(skill_md, include_content=False)
- if not skill:
- continue
-
- runtime_path = files.normalize_a0_path(str(skill.path))
- if runtime_path in seen_paths:
- continue
-
- seen_paths.add(runtime_path)
- catalog.append(
- {
- "name": skill.name or skill.path.name,
- "description": skill.description or "",
- "path": runtime_path,
- "origin": classify_origin(runtime_path, project_name=project_name),
- }
- )
-
- catalog.sort(key=lambda item: (item["name"].lower(), item["path"]))
- return catalog
-
-
-def resolve_active_skills(agent: Any, raw_entries: Any) -> list[dict[str, str]]:
- visible_roots = [files.fix_dev_path(root) for root in skills.get_skill_roots(agent)]
- resolved: list[dict[str, str]] = []
- seen_paths: set[str] = set()
-
- for entry in normalize_active_skills(raw_entries):
- skill = _resolve_skill_entry(entry, visible_roots)
- if not skill:
- continue
-
- runtime_path = files.normalize_a0_path(str(skill.path))
- if runtime_path in seen_paths:
- continue
-
- seen_paths.add(runtime_path)
- resolved.append(
- {
- "name": skill.name or skill.path.name,
- "path": runtime_path,
- "content": format_skill_for_prompt(skill),
- }
- )
-
- return resolved
-
-
-def format_skill_for_prompt(skill: skills.Skill) -> str:
- lines = [
- f"Skill: {skill.name or skill.path.name}",
- f"Path: {files.normalize_a0_path(str(skill.path))}",
- ]
-
- if skill.description:
- lines.extend(["", "Description:", skill.description.strip()])
-
- lines.extend(["", "Instructions:", (skill.content or "").strip() or "(empty)"])
- return "\n".join(lines)
-
-
-def classify_origin(skill_path: str, project_name: str = "") -> str:
- abs_path = files.fix_dev_path(skill_path)
-
- if project_name:
- project_root = projects.get_project_meta(project_name, "skills")
- if files.exists(project_root) and files.is_in_dir(abs_path, project_root):
- return "Project"
-
- user_root = files.get_abs_path("usr", "skills")
- if files.exists(user_root) and files.is_in_dir(abs_path, user_root):
- return "User"
-
- normalized_path = files.normalize_a0_path(abs_path)
- if "/usr/plugins/" in normalized_path:
- return "Community plugin"
- if "/plugins/" in normalized_path:
- return "Built-in plugin"
- return "Built-in"
-
-
-def _entry_key(entry: ActiveSkillEntry) -> str:
- return str(entry.get("path") or entry.get("name") or "").strip().lower()
-
-
-def _normalize_active_skill_entry(item: Any) -> ActiveSkillEntry | None:
- if isinstance(item, str):
- stripped = item.strip()
- if not stripped:
- return None
- if "/" in stripped:
- return {"path": _normalize_skill_path(stripped)}
- return {"name": stripped}
-
- if not isinstance(item, dict):
- return None
-
- name = str(item.get("name") or "").strip()
- path = str(item.get("path") or "").strip()
-
- if path:
- path = _normalize_skill_path(path)
- if not (path or name):
- return None
-
- entry: ActiveSkillEntry = {}
- if name:
- entry["name"] = name
- if path:
- entry["path"] = path
- return entry
-
-
-def _normalize_skill_path(path: str) -> str:
- fixed = path.strip().replace("\\", "/")
- if fixed.startswith("/a0/"):
- return fixed.rstrip("/")
- if fixed.startswith("/"):
- return files.normalize_a0_path(fixed).rstrip("/")
- return files.normalize_a0_path(files.get_abs_path(fixed)).rstrip("/")
-
-
-def _get_catalog_roots(project_name: str = "") -> list[str]:
- roots: list[str] = []
- seen: set[str] = set()
-
- def add(path: str) -> None:
- if not path:
- return
- fixed = files.fix_dev_path(path)
- if not files.exists(fixed) or fixed in seen:
- return
- seen.add(fixed)
- roots.append(fixed)
-
- if project_name:
- add(projects.get_project_meta(project_name, "skills"))
-
- add(files.get_abs_path("usr", "skills"))
- for path in plugin_helpers.get_enabled_plugin_paths(None, "skills"):
- add(path)
- add(files.get_abs_path("skills"))
-
- return roots
-
-
-def _resolve_skill_entry(entry: ActiveSkillEntry, visible_roots: list[str]) -> skills.Skill | None:
- skill_path = str(entry.get("path") or "").strip()
- if skill_path:
- skill = _load_skill_from_path(skill_path, visible_roots)
- if skill:
- return skill
-
- skill_name = str(entry.get("name") or "").strip()
- if not skill_name:
- return None
-
- target = skill_name.lower().strip()
- for root in visible_roots:
- for skill_md in skills.discover_skill_md_files(Path(root)):
- skill = skills.skill_from_markdown(skill_md, include_content=True)
- if not skill:
- continue
- candidates = {
- (skill.name or "").strip().lower(),
- skill.path.name.strip().lower(),
- }
- if target in candidates:
- return skill
-
- return None
-
-
-def _load_skill_from_path(skill_path: str, visible_roots: list[str]) -> skills.Skill | None:
- abs_path = files.fix_dev_path(skill_path)
- if not any(files.is_in_dir(abs_path, root) for root in visible_roots):
- return None
-
- skill_md = Path(abs_path) / "SKILL.md"
- if not skill_md.is_file():
- return None
-
- return skills.skill_from_markdown(skill_md, include_content=True)
diff --git a/plugins/_skills/hooks.py b/plugins/_skills/hooks.py
index b69c5e6df..d291eae63 100644
--- a/plugins/_skills/hooks.py
+++ b/plugins/_skills/hooks.py
@@ -1,11 +1,11 @@
from __future__ import annotations
-from plugins._skills.helpers.runtime import coerce_config
+from helpers.skills import normalize_skills_config
def get_plugin_config(default=None, **kwargs):
- return coerce_config(default)
+ return normalize_skills_config(default)
def save_plugin_config(settings=None, **kwargs):
- return coerce_config(settings)
+ return normalize_skills_config(settings)
diff --git a/plugins/_skills/webui/config-store.js b/plugins/_skills/webui/config-store.js
index 9ce8dc070..aff60e46e 100644
--- a/plugins/_skills/webui/config-store.js
+++ b/plugins/_skills/webui/config-store.js
@@ -1,14 +1,13 @@
import * as API from "/js/api.js";
-import { store as settingsStore } from "/components/settings/settings-store.js";
+import { store as markdownModalStore } from "/components/modals/markdown/markdown-store.js";
import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";
-import { store as projectsStore } from "/components/projects/projects-store.js";
import {
toastFrontendError,
toastFrontendInfo,
} from "/components/notifications/notification-store.js";
const CATALOG_API = "/plugins/_skills/skills_catalog";
-const MAX_ACTIVE_SKILLS_FALLBACK = 5;
+const MAX_ACTIVE_SKILLS_FALLBACK = 20;
function normalizeEntry(entry) {
if (!entry) return null;
@@ -52,14 +51,28 @@ function ensureConfig(config) {
config.active_skills = normalized;
}
+function compactEntries(entries) {
+ return entries
+ .map((entry) => normalizeEntry(entry))
+ .filter(Boolean)
+ .map((entry) => ({
+ ...(entry.name ? { name: entry.name } : {}),
+ ...(entry.path ? { path: entry.path } : {}),
+ }));
+}
+
window.createSkillsConfigModel = (context, config) => ({
loadingCatalog: false,
+ mutatingChat: false,
catalog: [],
search: "",
maxActiveSkills: MAX_ACTIVE_SKILLS_FALLBACK,
+ selectedSkills: [],
+ chatContextAvailable: false,
initDefaults() {
ensureConfig(config);
+ this.selectedSkills = [...this.activeEntries];
},
get activeEntries() {
@@ -68,28 +81,13 @@ window.createSkillsConfigModel = (context, config) => ({
},
get selectedCount() {
- return this.activeEntries.length;
+ return this.selectedSkills.length;
},
get selectedCountLabel() {
return `${this.selectedCount} / ${this.maxActiveSkills}`;
},
- get limitDescription() {
- return `Max in extras: ${this.maxActiveSkills}`;
- },
-
- get activeProject() {
- return chatsStore.selectedContext?.project || null;
- },
-
- get scopeSummary() {
- if (context.projectName) {
- return `Project: ${context.projectLabel(context.projectName)}`;
- }
- return "Project: Global";
- },
-
get catalogMap() {
const byKey = new Map();
for (const skill of this.catalog) {
@@ -124,11 +122,11 @@ window.createSkillsConfigModel = (context, config) => ({
},
isSelected(skill) {
- return this.activeEntries.some((entry) => entryKey(entry) === entryKey(skill));
+ return this.selectedSkills.some((entry) => entryKey(entry) === entryKey(skill));
},
isCheckboxDisabled(skill) {
- return !this.isSelected(skill) && this.selectedCount >= this.maxActiveSkills;
+ return this.mutatingChat || (!this.isSelected(skill) && this.selectedCount >= this.maxActiveSkills);
},
isEntryMissing(entry) {
@@ -147,11 +145,9 @@ window.createSkillsConfigModel = (context, config) => ({
secondaryLabelForEntry(entry) {
const skill = this._resolveEntry(entry);
- if (skill) {
- return `${skill.origin} | ${skill.path}`;
- }
- if (entry?.path) return `Not visible in the current catalog | ${entry.path}`;
- return "Not visible in the current catalog";
+ if (skill) return `${skill.origin} | ${skill.path}`;
+ if (entry?.path) return `Not visible in the current list | ${entry.path}`;
+ return "Not visible in the current list";
},
_resolveEntry(entry) {
@@ -163,15 +159,31 @@ window.createSkillsConfigModel = (context, config) => ({
return name ? this.catalogMap.get(name) || null : null;
},
- toggleSkill(skill, selected) {
- ensureConfig(config);
+ _setSelectedSkills(entries) {
+ const normalized = [];
+ const seen = new Set();
+
+ for (const entry of entries) {
+ const item = normalizeEntry(entry);
+ const key = entryKey(item);
+ if (!item || !key || seen.has(key)) continue;
+ seen.add(key);
+ normalized.push(item);
+ if (normalized.length >= this.maxActiveSkills) break;
+ }
+
+ this.selectedSkills = normalized;
+ config.active_skills = compactEntries(normalized);
+ },
+
+ async toggleSkill(skill, selected) {
const key = entryKey(skill);
- const nextEntries = this.activeEntries.filter((entry) => entryKey(entry) !== key);
+ const nextEntries = this.selectedSkills.filter((entry) => entryKey(entry) !== key);
if (selected) {
- if (this.selectedCount >= this.maxActiveSkills) {
- void toastFrontendInfo(
- `You can activate at most ${this.maxActiveSkills} skills in extras.`,
+ if (this.selectedCount >= this.maxActiveSkills && !this.isSelected(skill)) {
+ await toastFrontendInfo(
+ `You can activate at most ${this.maxActiveSkills} skills.`,
"Skills"
);
return;
@@ -183,18 +195,32 @@ window.createSkillsConfigModel = (context, config) => ({
});
}
- config.active_skills = nextEntries;
+ this._setSelectedSkills(nextEntries);
+
+ if (this.chatContextAvailable) {
+ await this.submitChatAction(selected ? "activate" : "deactivate", skill);
+ }
},
- removeEntry(entry) {
- ensureConfig(config);
- const key = entryKey(entry);
- config.active_skills = this.activeEntries.filter((item) => entryKey(item) !== key);
+ async removeEntry(entry) {
+ await this.toggleSkill(entry, false);
},
- clearSelections() {
- ensureConfig(config);
- config.active_skills = [];
+ async clearSelections() {
+ const previous = [...this.selectedSkills];
+ this._setSelectedSkills([]);
+ if (this.chatContextAvailable) {
+ for (const entry of previous) {
+ await this.submitChatAction("deactivate", entry);
+ }
+ }
+ },
+
+ applyCatalogState(response) {
+ this.chatContextAvailable = !!response?.context_available;
+ const activeFromChat = Array.isArray(response?.active_skills) ? response.active_skills : null;
+ const activeFromConfig = this.activeEntries;
+ this._setSelectedSkills(activeFromChat || activeFromConfig);
},
async loadCatalog() {
@@ -203,67 +229,85 @@ window.createSkillsConfigModel = (context, config) => ({
const response = await API.callJsonApi(CATALOG_API, {
action: "list",
project_name: context.projectName || "",
+ context_id: chatsStore.selectedContext?.id || "",
});
if (!response?.ok) {
- throw new Error(response?.error || "Failed to load skills catalog");
+ throw new Error(response?.error || "Failed to load skills");
}
this.catalog = Array.isArray(response.skills) ? response.skills : [];
this.maxActiveSkills = Number(response.max_active_skills) || MAX_ACTIVE_SKILLS_FALLBACK;
+ this.applyCatalogState(response);
} catch (error) {
this.catalog = [];
this.maxActiveSkills = MAX_ACTIVE_SKILLS_FALLBACK;
- await toastFrontendError(error?.message || "Failed to load skills catalog", "Skills");
+ this.chatContextAvailable = false;
+ this._setSelectedSkills(this.activeEntries);
+ await toastFrontendError(error?.message || "Failed to load skills", "Skills");
} finally {
this.loadingCatalog = false;
}
},
- async navigateAway(callback) {
- if (context.hasUnsavedChanges && !context.confirmDiscardUnsavedChanges()) {
- return;
- }
-
- await window.closeModal?.();
- await callback();
- },
+ async submitChatAction(action, skill = null) {
+ this.mutatingChat = true;
+ try {
+ const response = await API.callJsonApi(CATALOG_API, {
+ action,
+ context_id: chatsStore.selectedContext?.id || "",
+ project_name: context.projectName || "",
+ ...(skill
+ ? {
+ skill: {
+ name: String(skill.name || "").trim(),
+ path: String(skill.path || "").trim(),
+ },
+ }
+ : {}),
+ });
- async openSettingsSkills() {
- await this.navigateAway(async () => {
- await settingsStore.open("skills");
- });
- },
+ if (!response?.ok) {
+ throw new Error(response?.error || "Failed to update skills");
+ }
- async openActiveProjectSkills() {
- const projectName = this.activeProject?.name;
- if (!projectName) {
- await toastFrontendInfo("No active project is selected in the current chat.", "Skills");
- return;
+ this.catalog = Array.isArray(response.skills) ? response.skills : this.catalog;
+ this.maxActiveSkills = Number(response.max_active_skills) || this.maxActiveSkills;
+ this.chatContextAvailable = !!response.context_available;
+ return true;
+ } catch (error) {
+ await toastFrontendError(error?.message || "Failed to update skills", "Skills");
+ return false;
+ } finally {
+ this.mutatingChat = false;
}
-
- await this.navigateAway(async () => {
- await projectsStore.openEditModal(projectName);
- this.scrollProjectSkillsSection();
- });
},
- scrollProjectSkillsSection(attempt = 0) {
- const headers = Array.from(
- document.querySelectorAll(".project-detail-header .projects-project-card-title")
- );
- const target = headers.find(
- (header) => header.textContent?.trim().toLowerCase() === "skills"
- );
- const section = target?.closest(".project-detail");
-
- if (section) {
- section.scrollIntoView({ behavior: "smooth", block: "start" });
- return;
- }
+ async openSkill(skill) {
+ try {
+ const response = await API.callJsonApi(CATALOG_API, {
+ action: "get_doc",
+ context_id: chatsStore.selectedContext?.id || "",
+ project_name: context.projectName || "",
+ skill: {
+ name: String(skill?.name || "").trim(),
+ path: String(skill?.path || "").trim(),
+ },
+ });
- if (attempt < 12) {
- window.setTimeout(() => this.scrollProjectSkillsSection(attempt + 1), 120);
+ if (!response?.ok) {
+ throw new Error(response?.error || "Failed to open skill");
+ }
+ if (!markdownModalStore?.open) {
+ throw new Error("Markdown viewer is unavailable");
+ }
+
+ markdownModalStore.open(response.filename || "SKILL.md", response.content || "", {
+ viewer: "ace",
+ });
+ window.openModal?.("components/modals/markdown/markdown-modal.html");
+ } catch (error) {
+ await toastFrontendError(error?.message || "Failed to open skill", "Skills");
}
},
});
diff --git a/plugins/_skills/webui/config.html b/plugins/_skills/webui/config.html
index 0b61ff64e..ea777e60e 100644
--- a/plugins/_skills/webui/config.html
+++ b/plugins/_skills/webui/config.html
@@ -12,117 +12,97 @@
$watch('context.projectName', async () => { await loadCatalog(); });
"
>
- <div class="ssb-layout">
+ <div class="skills-layout">
<div class="section-title">Skills</div>
- <div class="section-description">
- Pin skills for the selected project scope. Every active skill is injected into prompt extras on each turn, so keep this list lean and intentional.
- </div>
-
- <div class="ssb-link-row">
- <button type="button" class="button" @click="openSettingsSkills()">
- <span class="icon material-symbols-outlined">menu_book</span>
- Open Skills List
- </button>
- <button
- type="button"
- class="button"
- x-show="activeProject"
- @click="openActiveProjectSkills()"
- >
- <span class="icon material-symbols-outlined">snippet_folder</span>
- Open Active Project Skills
- </button>
- </div>
-
- <div class="ssb-summary-grid">
- <div class="ssb-summary-card">
- <span class="ssb-summary-label">Selected scope</span>
- <strong x-text="scopeSummary"></strong>
- </div>
- <div class="ssb-summary-card">
- <span class="ssb-summary-label">Active skills</span>
- <strong x-text="selectedCountLabel"></strong>
- </div>
- <div class="ssb-summary-card" x-show="activeProject">
- <span class="ssb-summary-label">Current chat project</span>
- <strong x-text="activeProject?.title || activeProject?.name || ''"></strong>
- </div>
- </div>
- <div class="ssb-controls">
- <label class="ssb-search">
+ <div class="skills-toolbar">
+ <label class="skills-search">
<span class="material-symbols-outlined">search</span>
<input
type="text"
x-model.trim="search"
- placeholder="Filter skills by name, description, path, or origin"
+ placeholder="Search skills"
>
</label>
- <div class="ssb-control-actions">
- <button type="button" class="button" @click="loadCatalog()" :disabled="loadingCatalog">
+ <div class="skills-actions">
+ <button type="button" class="button" @click="loadCatalog()" :disabled="loadingCatalog || mutatingChat">
<span class="icon material-symbols-outlined">refresh</span>
Refresh
</button>
- <button type="button" class="button cancel" @click="clearSelections()" :disabled="selectedCount === 0">
- <span class="icon material-symbols-outlined">ink_eraser</span>
- Clear
- </button>
</div>
</div>
- <div class="ssb-panel" x-show="activeEntries.length > 0">
- <div class="ssb-panel-title">Selected for this scope</div>
- <div class="ssb-selected-list">
- <template x-for="entry in activeEntries" :key="entryKey(entry)">
- <div class="ssb-selected-card" :class="{ 'is-missing': isEntryMissing(entry) }">
- <div class="ssb-selected-copy">
- <div class="ssb-selected-title" x-text="labelForEntry(entry)"></div>
- <div class="ssb-selected-meta" x-text="secondaryLabelForEntry(entry)"></div>
+ <div class="skills-panel" x-show="selectedSkills.length > 0">
+ <div class="skills-panel-title">Active skills</div>
+ <div class="skills-selected-list">
+ <template x-for="entry in selectedSkills" :key="entryKey(entry)">
+ <div class="skills-selected-card" :class="{ 'is-missing': isEntryMissing(entry) }">
+ <div class="skills-selected-copy">
+ <div class="skills-selected-title" x-text="labelForEntry(entry)"></div>
+ <div class="skills-selected-meta" x-text="secondaryLabelForEntry(entry)"></div>
+ </div>
+ <div class="skills-card-actions">
+ <button
+ type="button"
+ class="button icon-button"
+ title="Open skill"
+ aria-label="Open skill"
+ @click="openSkill(entry)"
+ >
+ <span class="icon material-symbols-outlined">article</span>
+ </button>
+ <button
+ type="button"
+ class="button cancel icon-button"
+ title="Remove"
+ aria-label="Remove skill"
+ @click="$confirmClick($event, () => removeEntry(entry))"
+ :disabled="mutatingChat"
+ >
+ <span class="icon material-symbols-outlined">close</span>
+ </button>
</div>
- <button type="button" class="button cancel icon-button" title="Remove" @click="removeEntry(entry)">
- <span class="icon material-symbols-outlined">close</span>
- </button>
</div>
</template>
</div>
</div>
- <div class="ssb-panel">
- <div class="ssb-panel-title">Available skills</div>
- <div class="ssb-panel-subtitle">
- The catalog below resolves for the currently selected plugin scope. Changing the project selector above refreshes the available set.
- </div>
- <div class="ssb-panel-subtitle" x-text="limitDescription"></div>
+ <div class="skills-panel">
+ <div class="skills-panel-title">Available skills</div>
+ <div class="skills-panel-subtitle">Check a skill to add it. Uncheck it to remove it.</div>
- <div class="ssb-loading" x-show="loadingCatalog">
+ <div class="skills-loading" x-show="loadingCatalog">
<span class="material-symbols-outlined spinning">progress_activity</span>
- <span>Loading skills catalog...</span>
+ <span>Loading skills...</span>
</div>
<template x-if="!loadingCatalog && filteredCatalog.length === 0">
- <div class="ssb-empty">No skills matched the current scope or filter.</div>
+ <div class="skills-empty">No skills matched your search.</div>
</template>
- <div class="ssb-skill-list">
+ <div class="skills-list">
<template x-for="skill in filteredCatalog" :key="skill.path">
- <label class="ssb-skill-card">
- <div class="ssb-skill-main">
- <input
- type="checkbox"
- :checked="isSelected(skill)"
- :disabled="isCheckboxDisabled(skill)"
- @change="toggleSkill(skill, $event.target.checked)"
- >
- <div class="ssb-skill-copy">
- <div class="ssb-skill-header">
- <div class="ssb-skill-title" x-text="skill.name || '(unnamed skill)'"></div>
- <span class="ssb-origin-pill" x-text="skill.origin"></span>
- </div>
- <div class="ssb-skill-description" x-text="skill.description || 'No description provided.'"></div>
- <code class="ssb-skill-path" x-text="skill.path"></code>
- </div>
+ <label class="skills-card" :class="{ 'is-selected': isSelected(skill) }">
+ <input
+ type="checkbox"
+ :checked="isSelected(skill)"
+ :disabled="isCheckboxDisabled(skill)"
+ @change="toggleSkill(skill, $event.target.checked)"
+ >
+ <div class="skills-card-copy">
+ <div class="skills-card-title" x-text="skill.name || '(unnamed skill)'"></div>
+ <div class="skills-card-description" x-text="skill.description || 'No description provided.'"></div>
</div>
+ <button
+ type="button"
+ class="button icon-button"
+ title="Open skill"
+ aria-label="Open skill"
+ @click.prevent.stop="openSkill(skill)"
+ >
+ <span class="icon material-symbols-outlined">article</span>
+ </button>
</label>
</template>
</div>
@@ -131,101 +111,82 @@
</div>
<style>
- .ssb-layout {
+ .skills-layout {
display: flex;
flex-direction: column;
gap: 1rem;
}
- .ssb-link-row {
- display: flex;
- gap: 0.75rem;
- flex-wrap: wrap;
- }
-
- .ssb-summary-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
- gap: 0.75rem;
- }
-
- .ssb-summary-card,
- .ssb-panel {
- border: 1px solid var(--color-border);
- border-radius: 0.75rem;
- background: var(--color-bg-secondary);
- padding: 0.9rem 1rem;
- }
-
- .ssb-summary-card {
- display: flex;
- flex-direction: column;
- gap: 0.25rem;
- }
-
- .ssb-summary-label,
- .ssb-panel-subtitle,
- .ssb-selected-meta,
- .ssb-skill-description,
- .ssb-skill-path {
- color: var(--color-text-secondary);
- font-size: var(--font-size-small);
- }
-
- .ssb-controls {
+ .skills-toolbar {
display: flex;
+ align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
- align-items: center;
}
- .ssb-search {
+ .skills-search {
flex: 1 1 18rem;
min-width: 14rem;
display: flex;
align-items: center;
gap: 0.65rem;
border: 1px solid var(--color-border);
- border-radius: 999px;
+ border-radius: 0.5rem;
background: var(--color-bg-primary);
- padding: 0.55rem 0.85rem;
+ padding: var(--spacing-xs) var(--spacing-sm);
}
- .ssb-search input {
+ .skills-search input {
width: 100%;
border: none;
background: transparent;
outline: none;
}
- .ssb-control-actions {
+ .skills-actions {
display: flex;
+ align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
margin-left: auto;
}
- .ssb-panel-title {
+ .skills-count {
+ color: var(--color-text-secondary);
+ font-size: var(--font-size-small);
+ font-weight: 600;
+ white-space: nowrap;
+ }
+
+ .skills-help,
+ .skills-panel-subtitle,
+ .skills-selected-meta,
+ .skills-card-description {
+ color: var(--color-text-secondary);
+ font-size: var(--font-size-small);
+ }
+
+ .skills-panel-title {
font-weight: 700;
margin-bottom: 0.3rem;
}
- .ssb-selected-list,
- .ssb-skill-list {
+ .skills-selected-list,
+ .skills-list {
display: flex;
flex-direction: column;
- gap: 0.75rem;
+ gap: 0.65rem;
margin-top: 0.75rem;
}
- .ssb-selected-card,
- .ssb-skill-card {
+ .skills-selected-card,
+ .skills-card {
border: 1px solid var(--color-border);
border-radius: 0.75rem;
background: var(--color-bg-primary);
}
- .ssb-selected-card {
+ .skills-selected-card {
display: flex;
align-items: center;
justify-content: space-between;
@@ -233,80 +194,90 @@
padding: 0.8rem 0.9rem;
}
- .ssb-selected-card.is-missing {
+ .skills-selected-card.is-missing {
border-style: dashed;
}
- .ssb-selected-copy {
+ .skills-selected-copy {
+ flex: 1 1 auto;
min-width: 0;
}
- .ssb-selected-title {
- font-weight: 600;
+ .skills-selected-title,
+ .skills-card-title {
+ font-weight: 650;
word-break: break-word;
}
- .ssb-skill-card {
- padding: 0.9rem;
- cursor: pointer;
+ .skills-selected-meta {
+ margin-top: 0.25rem;
+ word-break: break-all;
}
- .ssb-skill-main {
+ .skills-card {
display: flex;
align-items: flex-start;
- gap: 0.9rem;
+ gap: 0.85rem;
+ padding: 0.85rem;
+ cursor: pointer;
+ transition: border-color 0.15s ease, background-color 0.15s ease;
}
- .ssb-skill-copy {
- min-width: 0;
- flex: 1 1 auto;
- display: flex;
- flex-direction: column;
- gap: 0.35rem;
+ .skills-card.is-selected {
+ border-color: color-mix(in srgb, var(--color-primary) 45%, var(--color-border));
+ background: color-mix(in srgb, var(--color-primary) 8%, var(--color-bg-primary));
}
- .ssb-skill-header {
- display: flex;
- gap: 0.75rem;
- justify-content: space-between;
- align-items: flex-start;
- flex-wrap: wrap;
+ .skills-card input {
+ margin-top: 0.15rem;
}
- .ssb-skill-title {
- font-weight: 600;
- font-size: 1rem;
+ .skills-card-copy {
+ flex: 1 1 auto;
+ min-width: 0;
}
- .ssb-origin-pill {
- display: inline-flex;
+ .skills-card-actions {
+ display: flex;
align-items: center;
- border-radius: 999px;
- padding: 0.15rem 0.55rem;
- background: var(--color-bg-tertiary);
- color: var(--color-text-secondary);
- font-size: 0.78rem;
- white-space: nowrap;
+ gap: 0.5rem;
+ flex: 0 0 auto;
+ margin-left: auto;
}
- .ssb-skill-path {
- white-space: pre-wrap;
- word-break: break-word;
- overflow-wrap: anywhere;
+ .skills-card-description {
+ margin-top: 0.3rem;
+ line-height: 1.45;
}
- .ssb-empty,
- .ssb-loading {
+ .skills-loading {
display: flex;
align-items: center;
- justify-content: center;
- gap: 0.6rem;
+ gap: 0.5rem;
margin-top: 0.75rem;
- padding: 1rem;
+ color: var(--color-text-secondary);
+ }
+
+ .skills-empty {
border: 1px dashed var(--color-border);
border-radius: 0.75rem;
color: var(--color-text-secondary);
- text-align: center;
+ margin-top: 0.75rem;
+ padding: 1rem;
+ }
+
+ .button, .button.cancel {
+ padding: var(--spacing-sm) !important;
+ }
+
+ .icon-button {
+ flex: 0 0 auto;
+ width: 2.5rem;
+ min-width: 2.5rem;
+ padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
}
.spinning {
@@ -317,17 +288,6 @@
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
-
- @media (max-width: 640px) {
- .ssb-control-actions {
- margin-left: 0;
- width: 100%;
- }
-
- .ssb-control-actions .button {
- flex: 1 1 0;
- }
- }
</style>
</body>
</html>
diff --git a/skills/a0-development/SKILL.md b/skills/a0-development/SKILL.md
index 0aea9c173..eab9ca563 100644
--- a/skills/a0-development/SKILL.md
+++ b/skills/a0-development/SKILL.md
@@ -455,6 +455,8 @@ class MyEndpoint(ApiHandler):
Agent profiles define specialized subordinates with custom prompts and behaviors.
+> For a guided, step-by-step wizard (scope selection, `agent.yaml` schema, prompt overrides, tool/extension stubs, test checklist) use the dedicated `/a0/skills/a0-new-agent/SKILL.md` skill.
+
### Profile Directory Structure
```
diff --git a/skills/a0-new-agent/SKILL.md b/skills/a0-new-agent/SKILL.md
new file mode 100644
index 000000000..7bac36cdc
--- /dev/null
+++ b/skills/a0-new-agent/SKILL.md
@@ -0,0 +1,200 @@
+---
+name: a0-new-agent
+description: Create a new Agent Zero agent profile (subordinate). Covers where profiles live (user / plugin-distributed / project-scoped), the agent.yaml schema, the prompt inheritance & override model, and optional profile-specific tools and extensions. Use for any "create/add/new agent profile" request.
+version: 1.0.0
+tags: ["agents", "profile", "create", "new", "subordinate"]
+trigger_patterns:
+ - "create agent profile"
+ - "new agent profile"
+ - "add agent profile"
+ - "make agent profile"
+ - "new subordinate agent"
+ - "create subordinate"
+ - "agent profile template"
+ - "build agent profile"
+---
+
+# Create an Agent Zero Agent Profile
+
+> [!IMPORTANT]
+> Do **not** create new profiles in `/a0/agents/` — that directory is reserved for core framework profiles (`default`, `agent0`, `developer`, `hacker`, `researcher`, `_example`). User profiles belong in `/a0/usr/agents/<profile_name>/`.
+
+Related skills: `/a0/skills/a0-development/SKILL.md` (broader framework guide) | `/a0/skills/a0-create-plugin/SKILL.md` (bundle a profile inside a plugin).
+
+Primary references:
+- `/a0/agents/_example/` — the canonical reference profile (tool + extension + prompt overrides)
+- `/a0/agents/default/` — the base profile every other profile inherits from
+- `/a0/docs/agents/AGENTS.plugins.md` — plugin-distributed profiles + per-profile config
+
+---
+
+## Step 0: Ask First — Where should this profile live?
+
+Before creating anything, ask the user one question:
+
+> "Where should this profile live?
+> 1. **User profile** — `/a0/usr/agents/<name>/` (survives framework updates, this is the normal choice).
+> 2. **Plugin-distributed** — shipped with a plugin at `/a0/usr/plugins/<plugin>/agents/<name>/` (for reusable profiles tied to a plugin's tools).
+> 3. **Project-scoped** — `project/.a0proj/agents/<name>/` (only available inside that project)."
+
+Pick the path based on the answer. The rest of the skill uses `<PROFILE_ROOT>` for whichever was chosen.
+
+---
+
+## Step 1: Collect the four inputs
+
+Gather these before writing any files:
+
+| Input | Rule | Example |
+|---|---|---|
+| **name** (directory name) | lowercase letters, numbers, hyphens or underscores; must be unique across profile search paths | `data-analyst` |
+| **title** | human-readable display name shown in the UI | `Data Analyst` |
+| **description** | one-line specialization summary | `Agent specialized in data analysis, visualization, and statistical modeling.` |
+| **context** | instructions telling the *superior* agent when to delegate to this profile | `Use this agent for data analysis tasks, creating visualizations, statistical analysis, and working with datasets in Python.` |
+
+> [!NOTE]
+> `agent.yaml` has **only** these three content fields (`title`, `description`, `context`). There is no per-profile model, temperature, or `allowed_tools` setting — model config is handled by the `_model_config` plugin, and tool availability is controlled by plugin activation. Do not invent extra fields.
+
+---
+
+## Step 2: Create the directory and `agent.yaml`
+
+```
+<PROFILE_ROOT>/<name>/
+├── agent.yaml # Required
+├── prompts/ # Optional — prompt overrides
+├── tools/ # Optional — profile-specific tools
+└── extensions/ # Optional — profile-specific extensions
+```
+
+`agent.yaml`:
+
+```yaml
+title: Data Analyst
+description: Agent specialized in data analysis, visualization, and statistical modeling.
+context: Use this agent for data analysis tasks, creating visualizations, statistical
+ analysis, and working with datasets in Python.
+```
+
+A profile with only `agent.yaml` is valid — it inherits everything from `default/`. Add the sections below only when you need to change something.
+
+---
+
+## Step 3: Override prompts (the most common customization)
+
+Profiles inherit all prompts from `/a0/prompts/default/` and from `/a0/agents/default/prompts/`. To change behavior, drop a file with the **same filename** into `<PROFILE_ROOT>/<name>/prompts/`. The loader searches profile-specific prompts first, then falls back.
+
+The usual overrides:
+
+| File | What it controls |
+|---|---|
+| `agent.system.main.role.md` | The agent's role / identity (most common) |
+| `agent.system.main.specifics.md` | Specialized behavioral instructions for this profile |
+| `agent.system.main.communication.md` | Communication style / reply format |
+| `agent.system.main.environment.md` | Environment & tooling context (e.g. `hacker` uses this for Kali) |
+| `agent.system.tool.<name>.md` | Usage instructions for a profile-specific tool |
+
+Example `agent.system.main.role.md`:
+
+```markdown
+## Your role
+
+You are a specialized data analysis agent.
+Your expertise includes:
+- Python data analysis (pandas, numpy, scipy)
+- Data visualization (matplotlib, seaborn, plotly)
+- Statistical modeling and hypothesis testing
+- SQL queries and database analysis
+- Data cleaning and preprocessing
+```
+
+> [!TIP]
+> Only override what you need. Copying unchanged prompt files creates drift when the framework updates the originals.
+
+---
+
+## Step 4 (optional): Profile-specific tools
+
+Drop a Python tool class in `<PROFILE_ROOT>/<name>/tools/<tool_name>.py`:
+
+```python
+from helpers.tool import Tool, Response
+
+class ExampleTool(Tool):
+ async def execute(self, **kwargs):
+ test_input = kwargs.get("test_input", "")
+ return Response(
+ message=f"Example tool executed with test_input: {test_input}",
+ break_loop=False,
+ )
+```
+
+Two important rules:
+
+1. To make the tool visible in the system prompt, add `prompts/agent.system.tool.<tool_name>.md` describing its usage and JSON call schema. The prompt loader auto-includes every file matching `agent.system.tool.*.md`.
+2. Placing a file with the same name as a core tool (e.g. `tools/response.py`) **replaces** the core tool for this profile only. See `/a0/agents/_example/tools/response.py` for a redefinition example.
+
+---
+
+## Step 5 (optional): Profile-specific extensions
+
+Lifecycle hooks go in `<PROFILE_ROOT>/<name>/extensions/<hook_point>/_NN_<name>.py`. The `_NN_` prefix controls execution order.
+
+Example — rename the agent at init (`/a0/agents/_example/extensions/agent_init/_10_example_extension.py`):
+
+```python
+from helpers.extension import Extension
+
+class ExampleExtension(Extension):
+ async def execute(self, **kwargs):
+ self.agent.agent_name = "SuperAgent" + str(self.agent.number)
+```
+
+Available hook points mirror the framework's own `/a0/extensions/python/<point>/` directories — see `a0-development/SKILL.md` for the full list.
+
+---
+
+## Step 6: Test the new profile
+
+1. The profile is picked up on next agent initialization — no restart of individual conversations needed, but a fresh agent/subordinate spawn is required.
+2. From the superior agent, delegate to it via `call_subordinate` using the profile's **directory name** (not the title).
+3. Verify:
+ - Title appears correctly in the UI agent selector.
+ - Role override (if any) takes effect in the new agent's system prompt.
+ - Profile-specific tools are callable and their prompt files are included.
+
+If the profile does not appear, check:
+- Directory name matches the `^[a-z0-9_-]+$` pattern and is unique.
+- `agent.yaml` parses as valid YAML.
+- It is placed in one of the recognized search paths (see Step 0).
+
+---
+
+## Reference: Complete `_example` profile layout
+
+```
+/a0/agents/_example/
+├── agent.yaml
+├── prompts/
+│ ├── agent.system.main.specifics.md # role override
+│ └── agent.system.tool.example_tool.md # tool usage prompt
+├── tools/
+│ ├── example_tool.py # new tool
+│ └── response.py # redefines core response tool
+└── extensions/
+ └── agent_init/
+ └── _10_example_extension.py # init-time hook
+```
+
+Copy this shape when in doubt — it demonstrates every customization surface a profile supports.
+
+---
+
+## Quick checklist
+
+- [ ] Confirmed profile scope (user / plugin / project)
+- [ ] Directory name is unique and matches allowed characters
+- [ ] `agent.yaml` contains exactly `title`, `description`, `context`
+- [ ] Prompt overrides only include files that actually change behavior
+- [ ] Any new tool has a matching `agent.system.tool.<name>.md`
+- [ ] Profile tested via `call_subordinate` in a fresh conversation
diff --git a/tests/test_skills_runtime.py b/tests/test_skills_runtime.py
new file mode 100644
index 000000000..009d20803
--- /dev/null
+++ b/tests/test_skills_runtime.py
@@ -0,0 +1,171 @@
+import importlib.util
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+SKILLS_HELPER_PATH = PROJECT_ROOT / "helpers" / "skills.py"
+
+
+def _register_helpers_stubs():
+ helpers_pkg = types.ModuleType("helpers")
+ helpers_pkg.__path__ = []
+
+ files = types.ModuleType("helpers.files")
+ files.normalize_a0_path = lambda path: str(path).replace("\\", "/")
+ files.fix_dev_path = lambda path: str(path).replace("\\", "/")
+ files.get_abs_path = lambda *parts: "/" + "/".join(str(part).strip("/") for part in parts if part)
+ files.exists = lambda path: False
+ files.is_in_dir = lambda path, root: str(path).startswith(str(root))
+ files.find_existing_paths_by_pattern = lambda pattern: []
+ files.read_file = lambda path: ""
+
+ projects = types.ModuleType("helpers.projects")
+ projects.get_context_project_name = lambda context: context.get_data("project")
+ projects.get_project_meta = lambda project_name, *parts: (
+ f"/projects/{project_name}/" + "/".join(str(part).strip("/") for part in parts if part)
+ if project_name
+ else ""
+ )
+
+ plugins = types.ModuleType("helpers.plugins")
+ plugins.get_plugin_config = lambda *args, **kwargs: {}
+ plugins.get_enabled_plugin_paths = lambda *args, **kwargs: []
+
+ subagents = types.ModuleType("helpers.subagents")
+ subagents.get_paths = lambda agent, *parts: []
+
+ file_tree = types.ModuleType("helpers.file_tree")
+ file_tree.file_tree = lambda *args, **kwargs: ""
+
+ runtime = types.ModuleType("helpers.runtime")
+ runtime.is_development = lambda: False
+
+ helpers_pkg.files = files
+ helpers_pkg.projects = projects
+ helpers_pkg.plugins = plugins
+ helpers_pkg.subagents = subagents
+ helpers_pkg.file_tree = file_tree
+ helpers_pkg.runtime = runtime
+
+ sys.modules["helpers"] = helpers_pkg
+ sys.modules["helpers.files"] = files
+ sys.modules["helpers.projects"] = projects
+ sys.modules["helpers.plugins"] = plugins
+ sys.modules["helpers.subagents"] = subagents
+ sys.modules["helpers.file_tree"] = file_tree
+ sys.modules["helpers.runtime"] = runtime
+
+
+def _load_skills_helper_module():
+ _register_helpers_stubs()
+ spec = importlib.util.spec_from_file_location("test_skills_helper_module", SKILLS_HELPER_PATH)
+ module = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+runtime = _load_skills_helper_module()
+
+
+class DummyContext:
+ def __init__(self):
+ self.data = {}
+
+ def get_data(self, key, recursive=True):
+ return self.data.get(key)
+
+ def set_data(self, key, value, recursive=True):
+ self.data[key] = value
+
+
+class DummyAgent:
+ def __init__(self):
+ self.context = DummyContext()
+ self.data = {}
+
+
+def _scope_config(entries):
+ return {"active_skills": entries}
+
+
+def test_active_skills_cap_is_twenty():
+ assert runtime.MAX_ACTIVE_SKILLS == 20
+ assert runtime.get_max_active_skills() == 20
+
+
+def test_chat_activation_can_override_scope_defaults(monkeypatch):
+ monkeypatch.setattr(
+ runtime.plugin_helpers,
+ "get_plugin_config",
+ lambda *args, **kwargs: _scope_config([{"name": "Pinned"}]),
+ )
+ agent = DummyAgent()
+
+ assert [entry["name"] for entry in runtime.get_active_skills(agent)] == [
+ "Pinned"
+ ]
+
+ runtime.activate_chat_skill(agent, {"name": "Extra"})
+ assert [entry["name"] for entry in runtime.get_active_skills(agent)] == [
+ "Pinned",
+ "Extra",
+ ]
+ assert [entry["name"] for entry in runtime.get_chat_active_skills(agent.context)] == [
+ "Extra"
+ ]
+
+ runtime.deactivate_chat_skill(agent, {"name": "Pinned"})
+ assert [entry["name"] for entry in runtime.get_active_skills(agent)] == [
+ "Extra"
+ ]
+ assert [entry["name"] for entry in runtime.get_chat_disabled_skills(agent.context)] == [
+ "Pinned"
+ ]
+
+ runtime.activate_chat_skill(agent, {"name": "Pinned"})
+ assert [entry["name"] for entry in runtime.get_active_skills(agent)] == [
+ "Pinned",
+ "Extra",
+ ]
+ assert runtime.get_chat_disabled_skills(agent.context) == []
+
+
+def test_clearing_chat_overrides_restores_scope_defaults(monkeypatch):
+ monkeypatch.setattr(
+ runtime.plugin_helpers,
+ "get_plugin_config",
+ lambda *args, **kwargs: _scope_config([{"name": "Pinned"}]),
+ )
+ agent = DummyAgent()
+ runtime.activate_chat_skill(agent, {"name": "Extra"})
+ runtime.deactivate_chat_skill(agent, {"name": "Pinned"})
+
+ runtime.clear_chat_skill_overrides(agent)
+
+ assert [entry["name"] for entry in runtime.get_active_skills(agent)] == [
+ "Pinned"
+ ]
+ assert runtime.get_chat_active_skills(agent.context) == []
+ assert runtime.get_chat_disabled_skills(agent.context) == []
+
+
+def test_activating_new_skill_fails_once_limit_is_full(monkeypatch):
+ monkeypatch.setattr(
+ runtime.plugin_helpers,
+ "get_plugin_config",
+ lambda *args, **kwargs: _scope_config(
+ [{"name": f"Pinned {index}"} for index in range(20)]
+ ),
+ )
+ agent = DummyAgent()
+
+ with pytest.raises(ValueError, match="at most 20"):
+ runtime.activate_chat_skill(agent, {"name": "Overflow"})
+
+ assert len(runtime.get_active_skills(agent)) == 20
diff --git a/tools/skills_tool.py b/tools/skills_tool.py
index b3607a45d..8cee30443 100644
--- a/tools/skills_tool.py
+++ b/tools/skills_tool.py
@@ -1,11 +1,9 @@
from __future__ import annotations
-from pathlib import Path
from typing import List
from helpers.tool import Tool, Response
-from helpers import projects, files, file_tree
-from helpers import skills as skills_helper, runtime
+from helpers import skills as skills_helper
from helpers.print_style import PrintStyle
@@ -197,4 +195,4 @@ class SkillsTool(Tool):
def max_loaded_skills() -> int:
- return 5 # TODO move to settings
+ return skills_helper.MAX_ACTIVE_SKILLS
diff --git a/webui/components/modals/markdown/markdown-modal.html b/webui/components/modals/markdown/markdown-modal.html
index 7262672a7..b692e1515 100644
--- a/webui/components/modals/markdown/markdown-modal.html
+++ b/webui/components/modals/markdown/markdown-modal.html
@@ -9,6 +9,7 @@
<div x-data>
<template x-if="$store.markdownModal">
<div x-create="$el.closest('.modal')?.querySelector('.modal-title') && ($el.closest('.modal').querySelector('.modal-title').textContent = $store.markdownModal.title)"
+ x-init="$store.markdownModal.onOpen()"
x-destroy="$store.markdownModal.cleanup()"
class="md-modal-root">
@@ -18,9 +19,14 @@
</div>
<div class="md-modal-body msg-content"
- x-show="!$store.markdownModal.error"
+ x-show="!$store.markdownModal.error && !$store.markdownModal.isAce"
x-html="$store.markdownModal.renderedHtml">
</div>
+
+ <div id="markdown-ace-viewer-container"
+ class="md-modal-ace no-scrollbar"
+ x-show="!$store.markdownModal.error && $store.markdownModal.isAce">
+ </div>
</div>
</template>
</div>
@@ -42,6 +48,17 @@
max-height: 72vh;
}
+ .md-modal-ace {
+ width: 100%;
+ height: 72vh;
+ border-radius: 0.4rem;
+ overflow: auto;
+ }
+
+ .md-modal-root {
+ overflow: hidden;
+ }
+
.md-modal-error {
display: flex;
align-items: center;
diff --git a/webui/components/modals/markdown/markdown-store.js b/webui/components/modals/markdown/markdown-store.js
index 07e65e4bd..6de6f40e4 100644
--- a/webui/components/modals/markdown/markdown-store.js
+++ b/webui/components/modals/markdown/markdown-store.js
@@ -5,11 +5,15 @@ export const store = createStore("markdownModal", {
title: "",
content: "",
error: null,
+ viewer: "rendered",
+ editor: null,
- open(title, content) {
+ open(title, content, options = {}) {
this.title = title;
this.content = content;
this.error = null;
+ this.viewer = options.viewer || "rendered";
+ this.destroyEditor();
},
get renderedHtml() {
@@ -17,9 +21,63 @@ export const store = createStore("markdownModal", {
return renderSafeMarkdown(this.content);
},
+ get isAce() {
+ return this.viewer === "ace";
+ },
+
+ onOpen() {
+ if (this.isAce) {
+ this.scheduleEditorInit();
+ }
+ },
+
+ scheduleEditorInit() {
+ window.requestAnimationFrame(() => {
+ if (!this.isAce || this.error) return;
+ window.requestAnimationFrame(() => this.initEditor());
+ });
+ },
+
+ initEditor() {
+ const container = document.getElementById("markdown-ace-viewer-container");
+ if (!container) return;
+
+ this.destroyEditor();
+
+ if (!window.ace?.edit) {
+ this.error = "Editor library not loaded";
+ return;
+ }
+
+ const editor = window.ace.edit("markdown-ace-viewer-container");
+ if (!editor) {
+ this.error = "Failed to initialize editor";
+ return;
+ }
+
+ const darkMode = window.localStorage?.getItem("darkMode");
+ const theme = darkMode !== "false" ? "ace/theme/github_dark" : "ace/theme/tomorrow";
+
+ this.editor = editor;
+ this.editor.setTheme(theme);
+ this.editor.session.setMode("ace/mode/markdown");
+ this.editor.setValue(this.content || "", -1);
+ this.editor.setReadOnly(true);
+ this.editor.clearSelection();
+ },
+
+ destroyEditor() {
+ if (this.editor?.destroy) {
+ this.editor.destroy();
+ }
+ this.editor = null;
+ },
+
cleanup() {
+ this.destroyEditor();
this.title = "";
this.content = "";
this.error = null;
+ this.viewer = "rendered";
},
});