Skip to content

Agent Zero AI framework

- Added a new Skills section in settings with import functionality - Introduced Skills tab in the web UI for better user interaction

TerminallyLazy3d348c0ed552
diff --git a/prompts/agent.system.skills.md b/prompts/agent.system.skills.md
new file mode 100644
index 000000000..ae4f59f62
--- /dev/null
+++ b/prompts/agent.system.skills.md
@@ -0,0 +1,5 @@
+# Relevant Skills (SKILL.md)
+- The following Skills may be useful for the current task.
+- Use `skills_tool` to list/search/load skills and progressively read supporting files/scripts.
+
+{{skills}}
diff --git a/python/api/skills_import.py b/python/api/skills_import.py
new file mode 100644
index 000000000..4b0ce5238
--- /dev/null
+++ b/python/api/skills_import.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+import os
+import time
+import uuid
+from pathlib import Path
+
+from python.helpers.api import ApiHandler, Request, Response
+from python.helpers import files
+from python.helpers.skills_import import import_skills
+from werkzeug.datastructures import FileStorage
+from werkzeug.utils import secure_filename
+
+
+class SkillsImport(ApiHandler):
+ """
+ Import an external skills pack (.zip) into skills/shared/<namespace>/...
+ Performs the actual import (not dry-run).
+ """
+
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ if "skills_file" not in request.files:
+ return {"success": False, "error": "No skills file provided"}
+
+ skills_file: FileStorage = request.files["skills_file"]
+ if not skills_file.filename:
+ return {"success": False, "error": "No file selected"}
+
+ ctxid = request.form.get("ctxid", "")
+ if not ctxid:
+ return {"success": False, "error": "No context id provided"}
+ _context = self.use_context(ctxid)
+
+ dest = (request.form.get("dest", "shared") or "shared").strip().lower()
+ if dest not in ("shared", "custom", "project"):
+ dest = "shared"
+
+ conflict = (request.form.get("conflict", "skip") or "skip").strip().lower()
+ if conflict not in ("skip", "overwrite", "rename"):
+ conflict = "skip"
+
+ namespace = (request.form.get("namespace", "") or "").strip() or None
+ project_name = (request.form.get("project_name", "") or "").strip() or None
+
+ # If dest is "project", project_name is required
+ if dest == "project" and not project_name:
+ return {"success": False, "error": "project_name is required when dest is 'project'"}
+
+ # Save upload to a temp file so we can pass a filesystem path to the importer
+ tmp_dir = Path(files.get_abs_path("tmp", "uploads"))
+ tmp_dir.mkdir(parents=True, exist_ok=True)
+ base = secure_filename(skills_file.filename) # type: ignore[arg-type]
+ if not base.lower().endswith(".zip"):
+ base = f"{base}.zip"
+ unique = uuid.uuid4().hex[:8]
+ stamp = time.strftime("%Y%m%d_%H%M%S")
+ tmp_path = tmp_dir / f"skills_import_{stamp}_{unique}_{base}"
+ skills_file.save(str(tmp_path))
+
+ try:
+ result = import_skills(
+ str(tmp_path),
+ dest_subdir=dest, # type: ignore[arg-type]
+ namespace=namespace,
+ conflict=conflict, # type: ignore[arg-type]
+ dry_run=False, # Actual import, not preview
+ project_name=project_name,
+ )
+
+ imported = [files.deabsolute_path(str(p)) for p in result.imported]
+ skipped = [files.deabsolute_path(str(p)) for p in result.skipped]
+ dest_root = files.deabsolute_path(str(result.destination_root / result.namespace))
+
+ return {
+ "success": True,
+ "namespace": result.namespace,
+ "destination": dest_root,
+ "imported": imported,
+ "skipped": skipped,
+ "imported_count": len(imported),
+ "skipped_count": len(skipped),
+ "conflict_policy": conflict,
+ }
+ finally:
+ try:
+ tmp_path.unlink(missing_ok=True) # type: ignore[arg-type]
+ except Exception:
+ pass
diff --git a/python/api/skills_import_preview.py b/python/api/skills_import_preview.py
new file mode 100644
index 000000000..e12262e73
--- /dev/null
+++ b/python/api/skills_import_preview.py
@@ -0,0 +1,89 @@
+from __future__ import annotations
+
+import os
+import time
+import uuid
+from pathlib import Path
+
+from python.helpers.api import ApiHandler, Request, Response
+from python.helpers import files
+from python.helpers.skills_import import import_skills
+from werkzeug.datastructures import FileStorage
+from werkzeug.utils import secure_filename
+
+
+class SkillsImportPreview(ApiHandler):
+ """
+ Preview importing an external skills pack (.zip) into skills/shared/<namespace>/...
+ Uses dry-run (no copying).
+ """
+
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ if "skills_file" not in request.files:
+ return {"success": False, "error": "No skills file provided"}
+
+ skills_file: FileStorage = request.files["skills_file"]
+ if not skills_file.filename:
+ return {"success": False, "error": "No file selected"}
+
+ ctxid = request.form.get("ctxid", "")
+ if not ctxid:
+ return {"success": False, "error": "No context id provided"}
+ _context = self.use_context(ctxid)
+
+ dest = (request.form.get("dest", "shared") or "shared").strip().lower()
+ if dest not in ("shared", "custom", "project"):
+ dest = "shared"
+
+ conflict = (request.form.get("conflict", "skip") or "skip").strip().lower()
+ if conflict not in ("skip", "overwrite", "rename"):
+ conflict = "skip"
+
+ namespace = (request.form.get("namespace", "") or "").strip() or None
+ project_name = (request.form.get("project_name", "") or "").strip() or None
+
+ # If dest is "project", project_name is required
+ if dest == "project" and not project_name:
+ return {"success": False, "error": "project_name is required when dest is 'project'"}
+
+ # Save upload to a temp file so we can pass a filesystem path to the importer
+ tmp_dir = Path(files.get_abs_path("tmp", "uploads"))
+ tmp_dir.mkdir(parents=True, exist_ok=True)
+ base = secure_filename(skills_file.filename) # type: ignore[arg-type]
+ if not base.lower().endswith(".zip"):
+ base = f"{base}.zip"
+ unique = uuid.uuid4().hex[:8]
+ stamp = time.strftime("%Y%m%d_%H%M%S")
+ tmp_path = tmp_dir / f"skills_import_preview_{stamp}_{unique}_{base}"
+ skills_file.save(str(tmp_path))
+
+ try:
+ result = import_skills(
+ str(tmp_path),
+ dest_subdir=dest, # type: ignore[arg-type]
+ namespace=namespace,
+ conflict=conflict, # type: ignore[arg-type]
+ dry_run=True,
+ project_name=project_name,
+ )
+
+ imported = [files.deabsolute_path(str(p)) for p in result.imported]
+ skipped = [files.deabsolute_path(str(p)) for p in result.skipped]
+ dest_root = files.deabsolute_path(str(result.destination_root / result.namespace))
+
+ return {
+ "success": True,
+ "namespace": result.namespace,
+ "destination": dest_root,
+ "imported": imported,
+ "skipped": skipped,
+ "imported_count": len(imported),
+ "skipped_count": len(skipped),
+ "conflict_policy": conflict,
+ }
+ finally:
+ try:
+ tmp_path.unlink(missing_ok=True) # type: ignore[arg-type]
+ except Exception:
+ pass
+
diff --git a/python/extensions/message_loop_prompts_after/_55_recall_skills.py b/python/extensions/message_loop_prompts_after/_55_recall_skills.py
new file mode 100644
index 000000000..67bf4a62e
--- /dev/null
+++ b/python/extensions/message_loop_prompts_after/_55_recall_skills.py
@@ -0,0 +1,109 @@
+import os
+from pathlib import Path
+
+from python.helpers.extension import Extension
+from agent import LoopData
+from python.helpers.memory import Memory
+from python.helpers import files
+from python.helpers import skills as skills_helper
+
+
+class RecallSkills(Extension):
+ """
+ Surface relevant SKILL.md-based Skills into the prompt (token-efficient).
+
+ The Memory subsystem already indexes `skills/**/SKILL.md` into area "skills".
+ This extension does a lightweight similarity lookup and injects a small
+ "relevant skills" list into extras for the current user message.
+ """
+
+ async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
+ # Only on the first iteration of the message loop (new user instruction)
+ if loop_data.iteration != 0:
+ return
+
+ # Determine query from current user message
+ user_instruction = (
+ loop_data.user_message.output_text() if loop_data.user_message else ""
+ ).strip()
+ if not user_instruction or len(user_instruction) < 8:
+ return
+
+ try:
+ db = await Memory.get(self.agent)
+ docs = await db.search_similarity_threshold(
+ query=user_instruction,
+ limit=12,
+ threshold=0.55,
+ filter=f"area == '{Memory.Area.SKILLS.value}'",
+ )
+ except Exception:
+ docs = []
+
+ # Fallback: simple keyword search over discovered skills if vector recall yields nothing
+ recalled = []
+ if docs:
+ seen = set()
+ for doc in docs:
+ src = (doc.metadata or {}).get("source_path") or ""
+ if not src:
+ continue
+ if src in seen:
+ continue
+ seen.add(src)
+ recalled.append(src)
+ if len(recalled) >= 6:
+ break
+
+ if not recalled:
+ # cheap lexical fallback
+ matches = skills_helper.search_skills(user_instruction, limit=6)
+ for s in matches:
+ recalled.append(str(s.skill_md_path))
+
+ if not recalled:
+ return
+
+ # Build compact metadata list
+ base_skills_dir = Path(files.get_abs_path("skills")).resolve()
+ lines = []
+ for src_path in recalled[:6]:
+ try:
+ p = Path(src_path)
+ # Some docs may store /a0/... paths; map to dev path when needed
+ abs_path = Path(files.fix_dev_path(str(p)))
+ text = abs_path.read_text(encoding="utf-8", errors="replace")
+ fm, body = skills_helper.split_frontmatter(text)
+
+ # Infer source if possible (custom/builtin/shared), else "unknown"
+ source = "unknown"
+ try:
+ rel = abs_path.resolve().relative_to(base_skills_dir)
+ if rel.parts and rel.parts[0] in ("custom", "builtin", "shared"):
+ source = rel.parts[0]
+ except Exception:
+ pass
+
+ name = str(fm.get("name") or abs_path.parent.name).strip()
+ desc = str(fm.get("description") or "").strip()
+ if not desc:
+ # fallback to first non-empty line of body
+ for line in (body or "").splitlines():
+ if line.strip():
+ desc = line.strip()
+ break
+ if len(desc) > 220:
+ desc = desc[:220].rstrip() + "…"
+
+ lines.append(f"- {name} [{source}]: {desc}")
+ except Exception:
+ continue
+
+ if not lines:
+ return
+
+ skills_block = "\n".join(lines)
+ loop_data.extras_temporary["skills"] = self.agent.parse_prompt(
+ "agent.system.skills.md", skills=skills_block
+ )
+
diff --git a/python/helpers/mcp_server.py b/python/helpers/mcp_server.py
index 2c3a6c221..43cd1c3c3 100644
--- a/python/helpers/mcp_server.py
+++ b/python/helpers/mcp_server.py
@@ -318,15 +318,20 @@ class DynamicMcpProxy:
http_path = f"/t-{self.token}/http"
message_path = f"/t-{self.token}/messages/"
+ # Update settings in the MCP server instance if provided
+ mcp_server.settings.message_path = message_path
+ mcp_server.settings.sse_path = sse_path
+
# Create new MCP apps with updated settings
with self._lock:
self.sse_app = create_sse_app(
server=mcp_server,
- message_path=message_path,
- sse_path=sse_path,
- auth=None, # No auth configured
- debug=False,
- routes=[],
+ message_path=mcp_server.settings.message_path,
+ sse_path=mcp_server.settings.sse_path,
+ auth_server_provider=mcp_server._auth_server_provider,
+ auth_settings=mcp_server.settings.auth,
+ debug=mcp_server.settings.debug,
+ routes=mcp_server._additional_http_routes,
middleware=[Middleware(BaseHTTPMiddleware, dispatch=mcp_middleware)],
)
@@ -334,12 +339,13 @@ class DynamicMcpProxy:
# doesn't work properly in our Flask/Werkzeug environment
self.http_app = self._create_custom_http_app(
http_path,
- None, # No auth configured
- False,
- [],
+ mcp_server._auth_server_provider,
+ mcp_server.settings.auth,
+ mcp_server.settings.debug,
+ mcp_server._additional_http_routes,
)
- def _create_custom_http_app(self, streamable_http_path, auth, debug, routes):
+ def _create_custom_http_app(self, streamable_http_path, auth_server_provider, auth_settings, debug, routes):
"""Create a custom HTTP app that manages the session manager manually."""
from fastmcp.server.http import setup_auth_middleware_and_routes, create_base_app # type: ignore
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager # type: ignore
@@ -352,6 +358,7 @@ class DynamicMcpProxy:
self.http_session_task_group = None
+
# Create session manager
self.http_session_manager = StreamableHTTPSessionManager(
app=mcp_server._mcp_server,
@@ -360,6 +367,7 @@ class DynamicMcpProxy:
stateless=False,
)
+
# Custom ASGI handler that ensures task group is initialized
async def handle_streamable_http(scope, receive, send):
# Lazy initialization of task group
@@ -372,14 +380,30 @@ class DynamicMcpProxy:
if self.http_session_manager:
await self.http_session_manager.handle_request(scope, receive, send)
- # Add StreamableHTTP route (no auth)
- server_routes.append(
- Mount(
- streamable_http_path,
- app=handle_streamable_http,
- )
+ # Get auth middleware and routes
+ auth_middleware, auth_routes, required_scopes = setup_auth_middleware_and_routes(
+ auth_server_provider, auth_settings
)
+ server_routes.extend(auth_routes)
+ server_middleware.extend(auth_middleware)
+
+ # Add StreamableHTTP routes with or without auth
+ if auth_server_provider:
+ server_routes.append(
+ Mount(
+ streamable_http_path,
+ app=RequireAuthMiddleware(handle_streamable_http, required_scopes),
+ )
+ )
+ else:
+ server_routes.append(
+ Mount(
+ streamable_http_path,
+ app=handle_streamable_http,
+ )
+ )
+
# Add custom routes with lowest precedence
if routes:
server_routes.extend(routes)
@@ -460,4 +484,4 @@ async def mcp_middleware(request: Request, call_next):
status_code=403, detail="MCP server is disabled in settings."
)
- return await call_next(request)
+ return await call_next(request)
\ No newline at end of file
diff --git a/python/helpers/settings.py b/python/helpers/settings.py
index f09124bd7..9e13f6083 100644
--- a/python/helpers/settings.py
+++ b/python/helpers/settings.py
@@ -1275,6 +1275,28 @@ def convert_out(settings: Settings) -> SettingsOutput:
"tab": "external",
}
+ # Skills section (UI-friendly import)
+ skills_fields: list[SettingsField] = []
+ skills_fields.append(
+ {
+ "id": "skills_import",
+ "title": "Import Skills",
+ "description": "Import a Skills pack (.zip) into <code>skills/shared/&lt;namespace&gt;/...</code> "
+ "using the open Agent Skills (SKILL.md) standard.",
+ "type": "button",
+ "value": "Import Skills",
+ }
+ )
+
+ skills_section: SettingsSection = {
+ "id": "skills",
+ "title": "Skills",
+ "description": "Skills are portable bundles of instructions, scripts, and resources that agents can discover and load on demand. "
+ "See the spec at <code>agentskills.io</code>.",
+ "fields": skills_fields,
+ "tab": "agent",
+ }
+
# Backup & Restore section
backup_fields: list[SettingsField] = []
diff --git a/python/helpers/skills.py b/python/helpers/skills.py
new file mode 100644
index 000000000..0ea94765d
--- /dev/null
+++ b/python/helpers/skills.py
@@ -0,0 +1,340 @@
+from __future__ import annotations
+
+import os
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple
+
+from python.helpers import files
+
+try:
+ import yaml # type: ignore
+except Exception: # pragma: no cover
+ yaml = None # type: ignore
+
+
+SkillSource = Literal["custom", "builtin", "shared"]
+
+
+@dataclass(slots=True)
+class Skill:
+ name: str
+ description: str
+ path: Path
+ skill_md_path: Path
+ source: SkillSource
+
+ version: str = ""
+ author: str = ""
+ tags: List[str] = field(default_factory=list)
+ triggers: List[str] = field(default_factory=list)
+ allowed_tools: List[str] = field(default_factory=list)
+ license: str = ""
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+ # Optional heavy fields (only set when requested)
+ content: str = "" # body content (markdown without frontmatter)
+ raw_frontmatter: Dict[str, Any] = field(default_factory=dict)
+
+
+def get_skills_base_dir() -> Path:
+ return Path(files.get_abs_path("skills"))
+
+
+def get_skill_roots(order: Optional[List[SkillSource]] = None) -> List[Tuple[SkillSource, Path]]:
+ base = get_skills_base_dir()
+ order = order or ["custom", "builtin", "shared"]
+ return [(src, base / src) for src in order]
+
+
+def _is_hidden_path(path: Path) -> bool:
+ return any(part.startswith(".") for part in path.parts)
+
+
+def discover_skill_md_files(root: Path) -> List[Path]:
+ """
+ Recursively discover SKILL.md files under a root directory.
+ Hidden folders/files are ignored.
+ """
+ if not root.exists():
+ return []
+
+ results: List[Path] = []
+ for p in root.rglob("SKILL.md"):
+ try:
+ if not p.is_file():
+ continue
+ if _is_hidden_path(p.relative_to(root)):
+ continue
+ results.append(p)
+ except Exception:
+ # If relative_to fails (weird symlink), fall back to conservative checks
+ if p.is_file() and ".git" not in str(p):
+ results.append(p)
+ results.sort(key=lambda x: str(x))
+ return results
+
+
+def _coerce_list(value: Any) -> List[str]:
+ if value is None:
+ return []
+ if isinstance(value, list):
+ return [str(v).strip() for v in value if str(v).strip()]
+ if isinstance(value, tuple):
+ return [str(v).strip() for v in list(value) if str(v).strip()]
+ if isinstance(value, str):
+ # Support comma-separated strings
+ parts = [p.strip() for p in value.split(",")]
+ return [p for p in parts if p]
+ return [str(value).strip()] if str(value).strip() else []
+
+
+def _normalize_name(name: str) -> str:
+ return re.sub(r"\s+", "-", (name or "").strip().lower())
+
+
+def _read_text(path: Path) -> str:
+ return path.read_text(encoding="utf-8", errors="replace")
+
+
+def split_frontmatter(markdown: str) -> Tuple[Dict[str, Any], str]:
+ """
+ Splits a SKILL.md into (frontmatter_dict, body_text).
+
+ If no YAML frontmatter is present, returns ({}, full_text).
+ """
+ text = markdown or ""
+ if not text.lstrip().startswith("---"):
+ return {}, text.strip()
+
+ # We require frontmatter fence at the start (allow leading whitespace/newlines).
+ lines = text.splitlines()
+ # find first '---' line
+ start_idx = None
+ for i, line in enumerate(lines):
+ if line.strip() == "---":
+ start_idx = i
+ break
+ if line.strip(): # non-empty before fence => not frontmatter
+ return {}, text.strip()
+
+ if start_idx is None:
+ return {}, text.strip()
+
+ end_idx = None
+ for j in range(start_idx + 1, len(lines)):
+ if lines[j].strip() == "---":
+ end_idx = j
+ break
+
+ if end_idx is None:
+ return {}, text.strip()
+
+ fm_text = "\n".join(lines[start_idx + 1 : end_idx]).strip()
+ body = "\n".join(lines[end_idx + 1 :]).strip()
+ fm = parse_frontmatter(fm_text)
+ return fm, body
+
+
+def parse_frontmatter(frontmatter_text: str) -> Dict[str, Any]:
+ """
+ Parse YAML frontmatter. Uses PyYAML if available, otherwise a minimal fallback parser.
+ """
+ if not frontmatter_text.strip():
+ return {}
+
+ if yaml is not None:
+ try:
+ parsed = yaml.safe_load(frontmatter_text) # type: ignore[attr-defined]
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception:
+ return {}
+
+ # Fallback: very small YAML subset (key: value, lists with '- item')
+ data: Dict[str, Any] = {}
+ current_key: Optional[str] = None
+ for raw in frontmatter_text.splitlines():
+ line = raw.rstrip()
+ if not line.strip() or line.strip().startswith("#"):
+ continue
+
+ m = re.match(r"^([A-Za-z0-9_.-]+)\s*:\s*(.*)$", line)
+ if m:
+ key = m.group(1)
+ val = m.group(2).strip()
+ current_key = key
+ if val == "":
+ data[key] = []
+ else:
+ # strip surrounding quotes
+ if (val.startswith('"') and val.endswith('"')) or (
+ val.startswith("'") and val.endswith("'")
+ ):
+ val = val[1:-1]
+ data[key] = val
+ continue
+
+ m_list = re.match(r"^\s*-\s*(.*)$", line)
+ if m_list and current_key:
+ item = m_list.group(1).strip()
+ if (item.startswith('"') and item.endswith('"')) or (
+ item.startswith("'") and item.endswith("'")
+ ):
+ item = item[1:-1]
+ if not isinstance(data.get(current_key), list):
+ data[current_key] = []
+ data[current_key].append(item)
+ continue
+
+ return data
+
+
+def skill_from_markdown(
+ skill_md_path: Path,
+ source: SkillSource,
+ *,
+ include_content: bool = False,
+) -> Optional[Skill]:
+ try:
+ text = _read_text(skill_md_path)
+ except Exception:
+ return None
+
+ fm, body = split_frontmatter(text)
+ skill_dir = skill_md_path.parent
+
+ name = str(fm.get("name") or fm.get("skill") or skill_dir.name).strip()
+ description = str(
+ fm.get("description") or fm.get("when_to_use") or fm.get("summary") or ""
+ ).strip()
+
+ # Cross-platform aliases:
+ # - Claude Code leans on description (triggers may be embedded there)
+ # - Some repos use triggers/trigger_patterns
+ triggers = _coerce_list(
+ fm.get("triggers")
+ or fm.get("trigger_patterns")
+ or fm.get("trigger")
+ or fm.get("activation")
+ )
+
+ tags = _coerce_list(fm.get("tags") or fm.get("tag"))
+ allowed_tools = _coerce_list(fm.get("allowed_tools") or fm.get("tools"))
+
+ version = str(fm.get("version") or "").strip()
+ author = str(fm.get("author") or "").strip()
+ license_ = str(fm.get("license") or "").strip()
+
+ meta = fm.get("metadata")
+ if not isinstance(meta, dict):
+ meta = {}
+
+ skill = Skill(
+ name=name,
+ description=description,
+ path=skill_dir,
+ skill_md_path=skill_md_path,
+ source=source,
+ version=version,
+ author=author,
+ tags=tags,
+ triggers=triggers,
+ allowed_tools=allowed_tools,
+ license=license_,
+ metadata=dict(meta),
+ raw_frontmatter=fm if include_content else {},
+ content=body if include_content else "",
+ )
+ return skill
+
+
+def list_skills(
+ *,
+ include_content: bool = False,
+ dedupe: bool = True,
+ root_order: Optional[List[SkillSource]] = None,
+) -> List[Skill]:
+ skills: List[Skill] = []
+
+ roots = get_skill_roots(order=root_order)
+ for source, root in roots:
+ for skill_md in discover_skill_md_files(root):
+ s = skill_from_markdown(skill_md, source, include_content=include_content)
+ if s:
+ skills.append(s)
+
+ if not dedupe:
+ return skills
+
+ # Dedupe by normalized name, preserving root_order priority (earlier wins)
+ by_name: Dict[str, Skill] = {}
+ for s in skills:
+ key = _normalize_name(s.name) or _normalize_name(s.path.name)
+ if key and key not in by_name:
+ by_name[key] = s
+ return list(by_name.values())
+
+
+def find_skill(
+ skill_name: str,
+ *,
+ include_content: bool = False,
+ root_order: Optional[List[SkillSource]] = None,
+) -> Optional[Skill]:
+ target = _normalize_name(skill_name)
+ if not target:
+ return None
+
+ roots = get_skill_roots(order=root_order)
+ for source, root in roots:
+ for skill_md in discover_skill_md_files(root):
+ s = skill_from_markdown(skill_md, source, include_content=include_content)
+ if not s:
+ continue
+ if _normalize_name(s.name) == target or _normalize_name(s.path.name) == target:
+ return s
+ return None
+
+
+def search_skills(query: str, *, limit: int = 25) -> List[Skill]:
+ q = (query or "").strip().lower()
+ if not q:
+ return []
+
+ terms = [t for t in re.split(r"\s+", q) if t]
+ candidates = list_skills(include_content=False, dedupe=True)
+
+ scored: List[Tuple[int, Skill]] = []
+ for s in candidates:
+ name = s.name.lower()
+ desc = (s.description or "").lower()
+ tags = [t.lower() for t in s.tags]
+
+ score = 0
+ for term in terms:
+ if term in name:
+ score += 3
+ if term in desc:
+ score += 2
+ if any(term in tag for tag in tags):
+ score += 1
+
+ if score > 0:
+ scored.append((score, s))
+
+ scored.sort(key=lambda pair: (-pair[0], pair[1].name))
+ return [s for _score, s in scored[:limit]]
+
+
+def safe_path_within_dir(base_dir: Path, rel_path: str) -> Path:
+ """
+ Resolve rel_path inside base_dir, preventing directory traversal.
+ """
+ base = base_dir.resolve()
+ candidate = (base / rel_path).resolve()
+ if os.path.commonpath([str(candidate), str(base)]) != str(base):
+ raise ValueError("Path escapes skill directory")
+ return candidate
+
+
diff --git a/python/helpers/skills_import.py b/python/helpers/skills_import.py
new file mode 100644
index 000000000..89b407fe2
--- /dev/null
+++ b/python/helpers/skills_import.py
@@ -0,0 +1,251 @@
+from __future__ import annotations
+
+import os
+import shutil
+import tempfile
+import time
+import zipfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Iterable, List, Literal, Optional, Tuple
+
+from python.helpers import files
+from python.helpers.skills import discover_skill_md_files
+
+
+ConflictPolicy = Literal["skip", "overwrite", "rename"]
+DestSubdir = Literal["shared", "custom", "project"]
+
+# Project skills folder name (inside .a0proj)
+PROJECT_SKILLS_DIR = "skills"
+
+
+@dataclass(slots=True)
+class ImportPlanItem:
+ src_root: Path
+ src_skill_dir: Path
+ dest_skill_dir: Path
+
+
+@dataclass(slots=True)
+class ImportResult:
+ imported: List[Path]
+ skipped: List[Path]
+ source_root: Path
+ destination_root: Path
+ namespace: str
+
+
+def _is_within(child: Path, parent: Path) -> bool:
+ try:
+ child.resolve().relative_to(parent.resolve())
+ return True
+ except Exception:
+ return False
+
+
+def _derive_namespace(source: Path) -> str:
+ # Use stem for zip, name for directory
+ return (source.stem or source.name or "import").strip()
+
+
+def _candidate_skill_roots(source_dir: Path) -> List[Path]:
+ """
+ Heuristics to find likely skill roots inside a repo/pack:
+ - <source>/skills
+ - <source>/plugins/*/skills (Claude Code style)
+ - fallback: <source>
+ """
+ candidates: List[Path] = []
+
+ direct = source_dir / "skills"
+ if direct.is_dir() and discover_skill_md_files(direct):
+ candidates.append(direct)
+
+ plugins = source_dir / "plugins"
+ if plugins.is_dir():
+ for child in plugins.iterdir():
+ if not child.is_dir():
+ continue
+ skills_dir = child / "skills"
+ if skills_dir.is_dir() and discover_skill_md_files(skills_dir):
+ candidates.append(skills_dir)
+
+ # Deduplicate while preserving order
+ unique: List[Path] = []
+ seen = set()
+ for c in candidates:
+ key = str(c.resolve())
+ if key not in seen:
+ seen.add(key)
+ unique.append(c)
+
+ return unique or [source_dir]
+
+
+def _unzip_to_temp_dir(zip_path: Path) -> Path:
+ """
+ Extract a zip into a temp folder under tmp/skill_imports (inside Agent Zero base dir).
+ Returns the extraction root folder.
+ """
+ base_tmp = Path(files.get_abs_path("tmp", "skill_imports"))
+ base_tmp.mkdir(parents=True, exist_ok=True)
+ stamp = time.strftime("%Y%m%d_%H%M%S")
+ target = base_tmp / f"import_{zip_path.stem}_{stamp}"
+ target.mkdir(parents=True, exist_ok=True)
+
+ with zipfile.ZipFile(zip_path, "r") as z:
+ z.extractall(target)
+
+ # If zip contains a single top-level folder, treat that as the root
+ children = [p for p in target.iterdir()]
+ if len(children) == 1 and children[0].is_dir():
+ return children[0]
+ return target
+
+
+def build_import_plan(
+ source: Path,
+ dest_root: Path,
+ *,
+ namespace: Optional[str] = None,
+) -> Tuple[List[ImportPlanItem], Path]:
+ """
+ Build a copy plan for importing skills from a source folder.
+
+ Returns: (plan_items, source_root_dir_used_for_scan)
+ """
+ source_dir = source
+ roots = _candidate_skill_roots(source_dir)
+ plan: List[ImportPlanItem] = []
+ ns = (namespace or _derive_namespace(source)).strip()
+ dest_ns_root = dest_root / ns
+
+ for root in roots:
+ for skill_md in discover_skill_md_files(root):
+ skill_dir = skill_md.parent
+ # Skip if the skill dir is already inside destination (prevents recursive import)
+ if _is_within(skill_dir, dest_root):
+ continue
+ try:
+ rel = skill_dir.resolve().relative_to(root.resolve())
+ except Exception:
+ # If relative fails due to symlink oddities, just use leaf folder name
+ rel = Path(skill_dir.name)
+ dest_dir = dest_ns_root / rel
+ plan.append(ImportPlanItem(src_root=root, src_skill_dir=skill_dir, dest_skill_dir=dest_dir))
+
+ # Deduplicate by destination path (keep first occurrence)
+ seen_dest = set()
+ deduped: List[ImportPlanItem] = []
+ for item in plan:
+ key = str(item.dest_skill_dir.resolve())
+ if key in seen_dest:
+ continue
+ seen_dest.add(key)
+ deduped.append(item)
+
+ return deduped, roots[0]
+
+
+def _resolve_conflict(dest: Path, policy: ConflictPolicy) -> Tuple[Path, bool]:
+ """
+ Returns (final_dest_path, should_copy).
+ """
+ if not dest.exists():
+ return dest, True
+
+ if policy == "skip":
+ return dest, False
+
+ if policy == "overwrite":
+ shutil.rmtree(dest)
+ return dest, True
+
+ # rename
+ i = 2
+ while True:
+ candidate = dest.with_name(f"{dest.name}_{i}")
+ if not candidate.exists():
+ return candidate, True
+ i += 1
+
+
+def get_project_skills_folder(project_name: str) -> Path:
+ """Get the skills folder path for a project."""
+ from python.helpers.projects import get_project_meta_folder
+ return Path(get_project_meta_folder(project_name, PROJECT_SKILLS_DIR))
+
+
+def import_skills(
+ source_path: str,
+ *,
+ dest_subdir: DestSubdir = "shared",
+ namespace: Optional[str] = None,
+ conflict: ConflictPolicy = "skip",
+ dry_run: bool = False,
+ project_name: Optional[str] = None,
+) -> ImportResult:
+ """
+ Import external Skills into skills/<dest_subdir>/<namespace>/...
+
+ If dest_subdir is "project", imports into the project's .a0proj/skills/ folder.
+
+ - source_path can be a directory or a .zip file
+ - Uses heuristics to detect the Skills root(s)
+ - Copies each skill folder (parent of SKILL.md) as-is
+ """
+ src = Path(source_path).expanduser()
+ if not src.is_absolute():
+ src = (Path.cwd() / src).resolve()
+
+ if not src.exists():
+ raise FileNotFoundError(f"Source not found: {src}")
+
+ # Determine destination root based on dest_subdir
+ if dest_subdir == "project":
+ if not project_name:
+ raise ValueError("project_name is required when dest_subdir is 'project'")
+ dest_root = get_project_skills_folder(project_name)
+ else:
+ dest_root = Path(files.get_abs_path("skills", dest_subdir))
+ dest_root.mkdir(parents=True, exist_ok=True)
+
+ extracted_root: Optional[Path] = None
+ source_dir: Path
+ if src.is_file() and src.suffix.lower() == ".zip":
+ extracted_root = _unzip_to_temp_dir(src)
+ source_dir = extracted_root
+ elif src.is_dir():
+ source_dir = src
+ else:
+ raise ValueError("Source must be a directory or a .zip file")
+
+ ns = (namespace or _derive_namespace(src)).strip()
+ if not ns:
+ ns = "import"
+
+ plan, root_used = build_import_plan(source_dir, dest_root, namespace=ns)
+ imported: List[Path] = []
+ skipped: List[Path] = []
+
+ for item in plan:
+ final_dest, should_copy = _resolve_conflict(item.dest_skill_dir, conflict)
+ if not should_copy:
+ skipped.append(item.dest_skill_dir)
+ continue
+ if dry_run:
+ imported.append(final_dest)
+ continue
+ final_dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copytree(item.src_skill_dir, final_dest)
+ imported.append(final_dest)
+
+ return ImportResult(
+ imported=imported,
+ skipped=skipped,
+ source_root=root_used,
+ destination_root=dest_root,
+ namespace=ns,
+ )
+
diff --git a/python/tools/skills_tool.py b/python/tools/skills_tool.py
new file mode 100644
index 000000000..35890da8d
--- /dev/null
+++ b/python/tools/skills_tool.py
@@ -0,0 +1,351 @@
+from __future__ import annotations
+
+import json
+import re
+import shlex
+from pathlib import Path
+from typing import Any, Dict, List
+
+from python.helpers.tool import Tool, Response
+from python.helpers import files
+from python.helpers import skills as skills_helper
+
+
+class SkillsTool(Tool):
+ """
+ Manage and use SKILL.md-based Skills (Anthropic open standard).
+
+ Methods (tool_args.method):
+ - list
+ - search (query)
+ - load (skill_name)
+ - read_file (skill_name, file_path)
+ - execute_script (skill_name, script_path, script_args)
+ """
+
+ async def execute(self, **kwargs) -> Response:
+ method = (
+ (kwargs.get("method") or self.args.get("method") or self.method or "")
+ .strip()
+ .lower()
+ )
+
+ try:
+ if method == "list":
+ return Response(message=self._list(), break_loop=False)
+ if method == "search":
+ query = str(kwargs.get("query") or "").strip()
+ return Response(message=self._search(query), break_loop=False)
+ if method == "load":
+ skill_name = str(kwargs.get("skill_name") or "").strip()
+ return Response(message=self._load(skill_name), break_loop=False)
+ if method == "read_file":
+ skill_name = str(kwargs.get("skill_name") or "").strip()
+ file_path = str(kwargs.get("file_path") or "").strip()
+ return Response(message=self._read_file(skill_name, file_path), break_loop=False)
+ if method == "execute_script":
+ skill_name = str(kwargs.get("skill_name") or "").strip()
+ script_path = str(kwargs.get("script_path") or "").strip()
+ script_args = kwargs.get("script_args") or {}
+ if not isinstance(script_args, dict):
+ script_args = {}
+ return await self._execute_script(skill_name, script_path, script_args)
+
+ return Response(
+ message=(
+ "Error: missing/invalid 'method'. Supported methods: "
+ "list, search, load, read_file, execute_script."
+ ),
+ break_loop=False,
+ )
+ except Exception as e: # keep tool robust; return error instead of crashing loop
+ return Response(message=f"Error in skills_tool: {e}", break_loop=False)
+
+ def _list(self) -> str:
+ skills = skills_helper.list_skills(include_content=False, dedupe=True)
+ if not skills:
+ return "No skills found. Expected SKILL.md files under: skills/{custom,builtin,shared}."
+
+ # Stable output: sort by name
+ skills_sorted = sorted(skills, key=lambda s: (s.name.lower(), s.source))
+
+ lines: List[str] = []
+ lines.append(f"Available skills ({len(skills_sorted)}):")
+ for s in skills_sorted:
+ tags = f" tags={','.join(s.tags)}" if s.tags else ""
+ ver = f" v{s.version}" if s.version else ""
+ desc = (s.description or "").strip()
+ if len(desc) > 200:
+ desc = desc[:200].rstrip() + "…"
+ lines.append(f"- {s.name}{ver} [{s.source}]{tags}: {desc}")
+ lines.append("")
+ lines.append("Tip: use skills_tool method=search or method=load for details.")
+ return "\n".join(lines)
+
+ def _search(self, query: str) -> str:
+ if not query:
+ return "Error: 'query' is required for method=search."
+
+ results = skills_helper.search_skills(query, limit=25)
+ if not results:
+ return f"No skills matched query: {query!r}"
+
+ lines: List[str] = []
+ lines.append(f"Skills matching {query!r} ({len(results)}):")
+ for s in results:
+ desc = (s.description or "").strip()
+ if len(desc) > 200:
+ desc = desc[:200].rstrip() + "…"
+ lines.append(f"- {s.name} [{s.source}]: {desc}")
+ lines.append("")
+ lines.append("Tip: use skills_tool method=load skill_name=<name> to load full instructions.")
+ return "\n".join(lines)
+
+ def _load(self, skill_name: str) -> str:
+ if not skill_name:
+ return "Error: 'skill_name' is required for method=load."
+
+ skill = skills_helper.find_skill(skill_name, include_content=True)
+ if not skill:
+ return f"Error: skill not found: {skill_name!r}. Try skills_tool method=list or method=search."
+
+ # Enumerate files under the skill directory for progressive disclosure
+ referenced_files = self._list_skill_files(skill.path, max_files=80)
+ rel_skill_dir = Path(files.deabsolute_path(str(skill.path)))
+
+ lines: List[str] = []
+ lines.append(f"Skill: {skill.name}")
+ lines.append(f"Source: {skill.source}")
+ lines.append(f"Path: {rel_skill_dir}")
+ if skill.version:
+ lines.append(f"Version: {skill.version}")
+ if skill.author:
+ lines.append(f"Author: {skill.author}")
+ if skill.license:
+ lines.append(f"License: {skill.license}")
+ if skill.tags:
+ lines.append(f"Tags: {', '.join(skill.tags)}")
+ if skill.allowed_tools:
+ lines.append(f"Allowed tools: {', '.join(skill.allowed_tools)}")
+ if skill.triggers:
+ lines.append(f"Triggers: {', '.join(skill.triggers)}")
+
+ lines.append("")
+ if skill.description:
+ lines.append("Description:")
+ lines.append(skill.description.strip())
+ lines.append("")
+
+ lines.append("Content (SKILL.md body):")
+ lines.append(skill.content.strip() or "(empty)")
+ lines.append("")
+
+ if referenced_files:
+ lines.append("Files in skill directory (use skills_tool method=read_file to open):")
+ for p in referenced_files:
+ lines.append(f"- {p}")
+ else:
+ lines.append("No additional files found in skill directory.")
+
+ return "\n".join(lines)
+
+ def _read_file(self, skill_name: str, file_path: str) -> str:
+ if not skill_name:
+ return "Error: 'skill_name' is required for method=read_file."
+ if not file_path:
+ return "Error: 'file_path' is required for method=read_file."
+
+ skill = skills_helper.find_skill(skill_name, include_content=False)
+ if not skill:
+ return f"Error: skill not found: {skill_name!r}."
+
+ try:
+ target = skills_helper.safe_path_within_dir(skill.path, file_path)
+ except Exception as e:
+ return f"Error: invalid file_path: {e}"
+
+ if not target.exists() or not target.is_file():
+ return f"Error: file not found: {file_path!r} (within skill {skill.name})"
+
+ # Basic binary guard: if null byte present, do not dump
+ content = target.read_bytes()
+ if b"\x00" in content[:4096]:
+ return f"Error: file appears to be binary; refusing to print raw bytes ({file_path})."
+
+ text = content.decode("utf-8", errors="replace")
+ return f"File: {file_path}\n\n{text}"
+
+ async def _execute_script(
+ self, skill_name: str, script_path: str, script_args: Dict[str, Any]
+ ) -> Response:
+ if not skill_name:
+ return Response(message="Error: 'skill_name' is required for method=execute_script.", break_loop=False)
+ if not script_path:
+ return Response(message="Error: 'script_path' is required for method=execute_script.", break_loop=False)
+
+ skill = skills_helper.find_skill(skill_name, include_content=False)
+ if not skill:
+ return Response(message=f"Error: skill not found: {skill_name!r}.", break_loop=False)
+
+ try:
+ script_abs = skills_helper.safe_path_within_dir(skill.path, script_path)
+ except Exception as e:
+ return Response(message=f"Error: invalid script_path: {e}", break_loop=False)
+
+ if not script_abs.exists() or not script_abs.is_file():
+ return Response(message=f"Error: script not found: {script_path!r} (within skill {skill.name})", break_loop=False)
+
+ ext = script_abs.suffix.lower()
+ runtime: str
+ code: str
+
+ # Use /a0 paths for remote (SSH) execution inside the container; use local absolute paths otherwise.
+ if self.agent.config.code_exec_ssh_enabled:
+ script_runtime_path = files.normalize_a0_path(str(script_abs))
+ script_runtime_dir = files.normalize_a0_path(str(script_abs.parent))
+ else:
+ script_runtime_path = str(script_abs)
+ script_runtime_dir = str(script_abs.parent)
+
+ # Normalize args once for injection
+ args_json = json.dumps(script_args, ensure_ascii=False)
+
+ if ext == ".py":
+ runtime = "python"
+ code = (
+ "import json, os, runpy\n"
+ f"os.chdir({json.dumps(script_runtime_dir)})\n"
+ f"_skill_args = json.loads({json.dumps(args_json)})\n"
+ f"runpy.run_path({json.dumps(script_runtime_path)}, run_name='__main__', init_globals={{'_skill_args': _skill_args}})\n"
+ )
+ elif ext == ".js":
+ runtime = "nodejs"
+ code = (
+ "const fs = require('fs');\n"
+ "const path = require('path');\n"
+ f"process.chdir({json.dumps(script_runtime_dir)});\n"
+ f"const _skill_args = JSON.parse({json.dumps(args_json)});\n"
+ f"const __skill_script = fs.readFileSync({json.dumps(script_runtime_path)}, 'utf8');\n"
+ "eval(__skill_script);\n"
+ )
+ elif ext == ".sh":
+ runtime = "terminal"
+ env_parts: List[str] = []
+ for k, v in (script_args or {}).items():
+ key = re.sub(r"[^A-Za-z0-9_]", "_", str(k).upper())
+ if not key:
+ continue
+ env_key = f"SKILL_ARG_{key}"
+ env_parts.append(f"{env_key}={shlex.quote(str(v))}")
+ env_prefix = " ".join(env_parts)
+ cd_cmd = f"cd {shlex.quote(script_runtime_dir)}"
+ run_cmd = f"bash {shlex.quote(script_runtime_path)}"
+ if env_prefix:
+ code = f"{cd_cmd} && {env_prefix} {run_cmd}"
+ else:
+ code = f"{cd_cmd} && {run_cmd}"
+ else:
+ return Response(
+ message=f"Error: unsupported script type {ext!r}. Supported: .py, .js, .sh",
+ break_loop=False,
+ )
+
+ # Delegate actual execution to code_execution_tool (sandboxed)
+ from python.tools.code_execution_tool import CodeExecution
+
+ cet = CodeExecution(
+ agent=self.agent,
+ name="code_execution_tool",
+ method=None,
+ args={
+ "runtime": runtime,
+ "code": code,
+ "session": int(self.args.get("session", 0) or 0),
+ },
+ message=self.message,
+ loop_data=self.loop_data,
+ )
+
+ resp = await cet.execute(**cet.args)
+ # Wrap result to make it clear it was a skill script
+ wrapped = (
+ f"Executed script: {skill.name}/{script_path}\n"
+ f"Runtime: {runtime}\n\n"
+ f"{resp.message}"
+ )
+ return Response(message=wrapped, break_loop=False)
+
+ def _list_skill_files(self, skill_dir: Path, *, max_files: int = 80) -> List[str]:
+ if not skill_dir.exists():
+ return []
+
+ results: List[str] = []
+
+ preferred_dirs = ["scripts", "references", "assets", "templates", "docs"]
+
+ # 1) Root-level files (excluding SKILL.md)
+ try:
+ for p in sorted(skill_dir.iterdir(), key=lambda x: x.name):
+ if len(results) >= max_files:
+ return results
+ if p.name.startswith("."):
+ continue
+ if p.is_file():
+ if p.name == "SKILL.md":
+ continue
+ results.append(p.name)
+ except Exception:
+ pass
+
+ # 2) Preferred optional directories (one level deep)
+ for dname in preferred_dirs:
+ dpath = skill_dir / dname
+ if not dpath.exists() or not dpath.is_dir():
+ continue
+ try:
+ for p in sorted(dpath.iterdir(), key=lambda x: x.name):
+ if len(results) >= max_files:
+ return results
+ if p.name.startswith("."):
+ continue
+ if p.is_file():
+ results.append(f"{dname}/{p.name}")
+ elif p.is_dir():
+ # Show one nested level (common in assets/templates/*)
+ nested_added = False
+ try:
+ for sub in sorted(p.iterdir(), key=lambda x: x.name):
+ if sub.name.startswith("."):
+ continue
+ if sub.is_file():
+ results.append(f"{dname}/{p.name}/{sub.name}")
+ nested_added = True
+ break
+ except Exception:
+ pass
+ if not nested_added:
+ results.append(f"{dname}/{p.name}/")
+ except Exception:
+ continue
+
+ # 3) Other directories (one level deep)
+ try:
+ for p in sorted(skill_dir.iterdir(), key=lambda x: x.name):
+ if len(results) >= max_files:
+ return results
+ if p.name.startswith(".") or p.name in preferred_dirs:
+ continue
+ if p.is_dir():
+ for sub in sorted(p.iterdir(), key=lambda x: x.name):
+ if len(results) >= max_files:
+ return results
+ if sub.name.startswith("."):
+ continue
+ if sub.is_file():
+ results.append(f"{p.name}/{sub.name}")
+ except Exception:
+ pass
+
+ return results
+
+
diff --git a/requirements.txt b/requirements.txt
index 34592991c..665854cc2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -4,7 +4,7 @@ browser-use==0.5.11
docker==7.1.0
duckduckgo-search==6.1.12
faiss-cpu==1.11.0
-fastmcp==2.11.0
+fastmcp==2.3.4
fasta2a==0.5.0
flask[async]==3.0.3
flask-basicauth==0.2.0
@@ -19,7 +19,7 @@ langchain-unstructured[all-docs]==0.1.6
openai-whisper==20240930
lxml_html_clean==0.3.1
markdown==3.7
-mcp==1.12.4
+mcp==1.13.1
newspaper3k==0.2.8
paramiko==3.5.0
playwright==1.52.0
diff --git a/skills/shared/.gitkeep b/skills/shared/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/skills/shared/claude-code-skill-factory-dev/generated-skills/prompt-factory/outputs/.gitkeep b/skills/shared/claude-code-skill-factory-dev/generated-skills/prompt-factory/outputs/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/webui/components/projects/project-edit-skills.html b/webui/components/projects/project-edit-skills.html
new file mode 100644
index 000000000..87579df2e
--- /dev/null
+++ b/webui/components/projects/project-edit-skills.html
@@ -0,0 +1,92 @@
+<html>
+<head>
+ <title>Project Skills</title>
+ <script type="module">
+ import { store } from "/components/projects/projects-store.js";
+ import { store as skillsStore } from "/components/settings/skills/skills-import-store.js";
+ </script>
+</head>
+<body>
+ <div x-data="{
+ openSkillsImport() {
+ // Pre-configure the skills import for this project
+ if ($store.skillsImportStore) {
+ $store.skillsImportStore.dest = 'project';
+ $store.skillsImportStore.projectName = $store.projects.selectedProject.name;
+ }
+ openModal('settings/skills/import.html');
+ }
+ }">
+ <template x-if="$store.projects && $store.projects.selectedProject">
+ <div class="project-skills-section">
+ <p class="skills-description">
+ Import skills specific to this project. Project skills are stored in the project's
+ <code>.a0proj/skills/</code> folder and are only available when this project is active.
+ </p>
+
+ <div class="skills-actions">
+ <button type="button" class="button" @click="openSkillsImport()">
+ Import Skills
+ </button>
+ </div>
+
+ <div class="skills-info">
+ <p>
+ <strong>Project Skills Location:</strong><br>
+ <code x-text="'usr/projects/' + $store.projects.selectedProject.name + '/.a0proj/skills/'"></code>
+ </p>
+ <p class="skills-note">
+ Use the global Settings &gt; Skills tab for shared skills available to all projects.
+ </p>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <style>
+ .project-skills-section {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ }
+
+ .skills-description {
+ color: var(--color-text-secondary);
+ font-size: 0.9rem;
+ margin: 0;
+ }
+
+ .skills-actions {
+ display: flex;
+ gap: 0.5rem;
+ }
+
+ .skills-info {
+ background: var(--color-bg-secondary);
+ padding: 0.75rem;
+ border-radius: 4px;
+ font-size: 0.85rem;
+ }
+
+ .skills-info p {
+ margin: 0 0 0.5rem 0;
+ }
+
+ .skills-info p:last-child {
+ margin-bottom: 0;
+ }
+
+ .skills-note {
+ color: var(--color-text-secondary);
+ font-style: italic;
+ }
+
+ .skills-info code {
+ background: var(--color-bg-tertiary);
+ padding: 0.1rem 0.3rem;
+ border-radius: 3px;
+ font-size: 0.85em;
+ }
+ </style>
+</body>
+</html>
diff --git a/webui/components/projects/project-edit.html b/webui/components/projects/project-edit.html
index ad04b446b..0a2cd29f2 100644
--- a/webui/components/projects/project-edit.html
+++ b/webui/components/projects/project-edit.html
@@ -66,6 +66,14 @@
</x-component>
</div>
+ <div class="project-detail">
+ <div class="project-detail-header">
+ <span class="projects-project-card-title">Skills</span>
+ </div>
+ <x-component path="projects/project-edit-skills.html">
+ </x-component>
+ </div>
+
<div class="buttons-container" style="margin: var(--spacing-md) var(--spacing-sm) var(--spacing-lg) var(--spacing-sm);">
<div class="buttons-left">
<button type="button" class="button cancel"
diff --git a/webui/components/settings/skills/import.html b/webui/components/settings/skills/import.html
new file mode 100644
index 000000000..1c4b1f634
--- /dev/null
+++ b/webui/components/settings/skills/import.html
@@ -0,0 +1,221 @@
+<html>
+<head>
+ <title>Import Skills</title>
+ <script type="module">
+ import { store } from "/components/settings/skills/skills-import-store.js";
+ </script>
+</head>
+<body>
+ <div x-data>
+ <template x-if="$store.skillsImportStore">
+ <div x-init="$store.skillsImportStore.init()" x-destroy="$store.skillsImportStore.onClose()">
+
+ <h3>Import Skills (SKILL.md)</h3>
+
+ <div class="upload-section">
+ <label for="skills-file" class="upload-label">
+ Select Skills Pack (.zip)
+ </label>
+ <input type="file" id="skills-file" accept=".zip"
+ @change="$store.skillsImportStore.handleFileUpload($event)">
+ <div class="upload-hint">
+ Upload a repository/archive that contains SKILL.md skill folders (see agentskills.io).
+ </div>
+ </div>
+
+ <div class="options" x-show="$store.skillsImportStore.skillsFile">
+ <label class="policy-label">
+ <span class="policy-label-text">Destination:</span>
+ <select x-model="$store.skillsImportStore.dest" class="policy-dropdown"
+ @change="$store.skillsImportStore.previewImport()">
+ <option value="shared">Shared (recommended)</option>
+ <option value="custom">Custom</option>
+ <option value="project">Project</option>
+ </select>
+ </label>
+
+ <label class="policy-label" x-show="$store.skillsImportStore.dest === 'project'">
+ <span class="policy-label-text">Project:</span>
+ <select x-model="$store.skillsImportStore.projectName" class="policy-dropdown"
+ @change="$store.skillsImportStore.previewImport()">
+ <option value="">Select a project...</option>
+ <template x-for="project in $store.skillsImportStore.projects" :key="project.name">
+ <option :value="project.name" x-text="project.title || project.name"></option>
+ </template>
+ </select>
+ </label>
+
+ <label class="policy-label">
+ <span class="policy-label-text">Namespace:</span>
+ <input class="text-input" type="text" placeholder="e.g. my-pack"
+ x-model="$store.skillsImportStore.namespace"
+ @change="$store.skillsImportStore.previewImport()">
+ </label>
+
+ <label class="policy-label">
+ <span class="policy-label-text">Conflict policy:</span>
+ <select x-model="$store.skillsImportStore.conflict" class="policy-dropdown"
+ @change="$store.skillsImportStore.previewImport()">
+ <option value="skip">Skip existing</option>
+ <option value="rename">Rename (add _2, _3...)</option>
+ <option value="overwrite">Overwrite existing</option>
+ </select>
+ </label>
+
+ <div class="buttons">
+ <button class="btn slim" @click="$store.skillsImportStore.previewImport()"
+ :disabled="$store.skillsImportStore.loading">Preview</button>
+ <button class="btn slim primary" @click="$store.skillsImportStore.performImport()"
+ :disabled="$store.skillsImportStore.loading">Import</button>
+ </div>
+ </div>
+
+ <div x-show="$store.skillsImportStore.loading" class="loading">
+ <span x-text="$store.skillsImportStore.loadingMessage || 'Processing...'"></span>
+ </div>
+
+ <div x-show="$store.skillsImportStore.error" class="error">
+ <span x-text="$store.skillsImportStore.error"></span>
+ </div>
+
+ <div x-show="$store.skillsImportStore.preview" class="preview">
+ <h4>Preview</h4>
+ <div class="preview-meta">
+ <div>Destination: <code x-text="$store.skillsImportStore.preview?.destination"></code></div>
+ <div>Namespace: <code x-text="$store.skillsImportStore.preview?.namespace"></code></div>
+ <div>Would import: <span x-text="$store.skillsImportStore.preview?.imported_count || 0"></span></div>
+ <div>Would skip: <span x-text="$store.skillsImportStore.preview?.skipped_count || 0"></span></div>
+ </div>
+
+ <textarea class="preview-list" readonly
+ x-text="($store.skillsImportStore.preview?.imported || []).join('\n')"></textarea>
+ </div>
+
+ <div x-show="$store.skillsImportStore.result" class="result">
+ <h4>Import Complete</h4>
+ <div class="preview-meta">
+ <div>Imported: <span x-text="$store.skillsImportStore.result?.imported_count || 0"></span></div>
+ <div>Skipped: <span x-text="$store.skillsImportStore.result?.skipped_count || 0"></span></div>
+ </div>
+ <div class="note">
+ Skills are indexed automatically. If you don’t see them immediately, use the Restart button in the left pane.
+ </div>
+ </div>
+
+ </div>
+ </template>
+ </div>
+
+ <style>
+ .upload-section {
+ margin-bottom: 1rem;
+ padding: 1rem;
+ border: 2px dashed var(--color-border);
+ border-radius: 4px;
+ text-align: center;
+ }
+
+ .upload-label {
+ display: block;
+ margin-bottom: 0.5rem;
+ font-weight: 600;
+ }
+
+ .upload-hint {
+ margin-top: 0.5rem;
+ font-size: 0.85rem;
+ color: var(--color-secondary);
+ }
+
+ .options {
+ margin: 1rem 0;
+ padding: 0.75rem;
+ background: var(--color-input);
+ border: 1px solid var(--color-border);
+ border-radius: 4px;
+ }
+
+ .policy-label {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin: 0.5rem 0;
+ }
+
+ .policy-label-text {
+ font-weight: 600;
+ white-space: nowrap;
+ width: 9rem;
+ }
+
+ .policy-dropdown, .text-input {
+ flex: 1;
+ padding: 0.5rem;
+ border: 1px solid var(--color-border);
+ border-radius: 4px;
+ background: var(--color-bg-primary);
+ color: var(--color-text-primary);
+ font-size: 0.9rem;
+ }
+
+ .buttons {
+ margin-top: 0.75rem;
+ display: flex;
+ gap: 0.5rem;
+ }
+
+ .loading {
+ width: 100%;
+ text-align: center;
+ margin-top: 1rem;
+ margin-bottom: 1rem;
+ color: var(--color-secondary);
+ }
+
+ .error {
+ color: var(--color-error);
+ margin: 0.5rem 0;
+ padding: 0.5rem;
+ background: var(--color-error-bg);
+ border-radius: 4px;
+ }
+
+ .preview, .result {
+ margin-top: 1rem;
+ padding: 0.75rem;
+ background: var(--color-bg-primary);
+ border: 1px solid var(--color-border);
+ border-radius: 4px;
+ }
+
+ .preview-meta {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.25rem 1rem;
+ margin-bottom: 0.5rem;
+ color: var(--color-text-secondary);
+ font-size: 0.9rem;
+ }
+
+ .preview-list {
+ width: 100%;
+ height: 12em;
+ font-family: monospace;
+ font-size: 0.85em;
+ background: var(--color-bg-primary);
+ color: var(--color-text-primary);
+ border: 1px solid var(--color-border);
+ border-radius: 4px;
+ padding: 0.5em;
+ resize: vertical;
+ }
+
+ .note {
+ margin-top: 0.5rem;
+ font-size: 0.9rem;
+ color: var(--color-text-secondary);
+ }
+ </style>
+</body>
+</html>
+
diff --git a/webui/components/settings/skills/skills-import-store.js b/webui/components/settings/skills/skills-import-store.js
new file mode 100644
index 000000000..d5d6c021d
--- /dev/null
+++ b/webui/components/settings/skills/skills-import-store.js
@@ -0,0 +1,180 @@
+import { createStore } from "/js/AlpineStore.js";
+
+const fetchApi = globalThis.fetchApi;
+
+function sanitizeNamespace(text) {
+ if (!text) return "";
+ return String(text)
+ .trim()
+ .replace(/[^a-zA-Z0-9._-]+/g, "_")
+ .replace(/^_+|_+$/g, "");
+}
+
+const model = {
+ loading: false,
+ loadingMessage: "",
+ error: "",
+
+ skillsFile: null,
+ dest: "shared", // shared|custom|project
+ namespace: "",
+ conflict: "skip", // skip|overwrite|rename
+ projectName: "", // selected project name when dest is "project"
+ projects: [], // available projects list
+
+ preview: null,
+ result: null,
+
+ init() {
+ this.resetState();
+ this.loadProjects();
+ },
+
+ resetState() {
+ this.loading = false;
+ this.loadingMessage = "";
+ this.error = "";
+ this.preview = null;
+ this.result = null;
+ },
+
+ onClose() {
+ this.resetState();
+ this.skillsFile = null;
+ },
+
+ async loadProjects() {
+ try {
+ const response = await fetchApi("/projects", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ action: "list" }),
+ });
+ const data = await response.json();
+ this.projects = data.ok ? (data.data || []) : [];
+ } catch (e) {
+ console.error("Failed to load projects:", e);
+ this.projects = [];
+ }
+ },
+
+ async handleFileUpload(event) {
+ const file = event.target.files[0];
+ if (!file) return;
+
+ this.skillsFile = file;
+ this.error = "";
+ this.result = null;
+ this.preview = null;
+
+ // default namespace from file name (minus .zip)
+ const base = file.name.replace(/\.zip$/i, "");
+ if (!this.namespace) {
+ this.namespace = sanitizeNamespace(base);
+ } else {
+ this.namespace = sanitizeNamespace(this.namespace);
+ }
+
+ await this.previewImport();
+ },
+
+ buildFormData() {
+ const formData = new FormData();
+ formData.append("skills_file", this.skillsFile);
+ formData.append("ctxid", globalThis.getContext ? globalThis.getContext() : "");
+ formData.append("dest", this.dest);
+ formData.append("namespace", sanitizeNamespace(this.namespace));
+ formData.append("conflict", this.conflict);
+ if (this.dest === "project" && this.projectName) {
+ formData.append("project_name", this.projectName);
+ }
+ return formData;
+ },
+
+ async previewImport() {
+ if (!this.skillsFile) {
+ this.error = "Please select a skills .zip file first";
+ return;
+ }
+
+ if (this.dest === "project" && !this.projectName) {
+ this.error = "Please select a project";
+ return;
+ }
+
+ try {
+ this.loading = true;
+ this.loadingMessage = "Previewing skills import...";
+ this.error = "";
+ this.preview = null;
+
+ const response = await fetchApi("/skills_import_preview", {
+ method: "POST",
+ body: this.buildFormData(),
+ });
+
+ const result = await response.json();
+ if (!result.success) {
+ this.error = result.error || "Preview failed";
+ return;
+ }
+
+ this.preview = result;
+ // normalize namespace (server may sanitize)
+ if (result.namespace) this.namespace = result.namespace;
+ } catch (e) {
+ this.error = `Preview error: ${e.message}`;
+ } finally {
+ this.loading = false;
+ this.loadingMessage = "";
+ }
+ },
+
+ async performImport() {
+ if (!this.skillsFile) {
+ this.error = "Please select a skills .zip file first";
+ return;
+ }
+
+ if (this.dest === "project" && !this.projectName) {
+ this.error = "Please select a project";
+ return;
+ }
+
+ try {
+ this.loading = true;
+ this.loadingMessage = "Importing skills...";
+ this.error = "";
+ this.result = null;
+
+ const response = await fetchApi("/skills_import", {
+ method: "POST",
+ body: this.buildFormData(),
+ });
+
+ const result = await response.json();
+ if (!result.success) {
+ this.error = result.error || "Import failed";
+ return;
+ }
+
+ this.result = result;
+ this.preview = result; // keep last info visible
+ if (window.toastFrontendInfo) {
+ window.toastFrontendInfo(
+ `Imported ${result.imported_count} skill folder(s)`,
+ "Skills Import"
+ );
+ }
+ } catch (e) {
+ this.error = `Import error: ${e.message}`;
+ } finally {
+ this.loading = false;
+ this.loadingMessage = "";
+ }
+ },
+};
+
+const store = createStore("skillsImportStore", model);
+export { store };
+
diff --git a/webui/index.html b/webui/index.html
index 82abf4b59..c0ec596f0 100644
--- a/webui/index.html
+++ b/webui/index.html
@@ -142,7 +142,6 @@
<div class="sidebar-overlay" :class="{'visible': $store.sidebar.isOpen && $store.sidebar.isMobile()}" @click="$store.sidebar.close()"></div>
</template>
</div>
- </template>
<!-- Left Sidebar (Header Icons, Quick Actions, Tabs, Chats, Tasks) -->
<x-component path="sidebar/left-sidebar.html"></x-component>
@@ -206,13 +205,15 @@
@click="switchTab('developer')" title="Developer">Developer</div>
<div class="settings-tab" :class="{'active': activeTab === 'scheduler'}"
@click="switchTab('scheduler')" title="Task Scheduler">Task Scheduler</div>
+ <div class="settings-tab" :class="{'active': activeTab === 'skills'}"
+ @click="switchTab('skills')" title="Skills">Skills</div>
<div class="settings-tab" :class="{'active': activeTab === 'backup'}"
@click="switchTab('backup')" title="Backup & Restore">Backup & Restore</div>
</div>
</div>
<!-- Display settings sections for agent, external, developer, mcp, backup tabs -->
- <div id="settings-sections" x-show="activeTab !== 'scheduler'">
+ <div id="settings-sections" x-show="activeTab !== 'scheduler' && activeTab !== 'skills'">
<nav>
<ul>
<template x-for="(section, index) in filteredSections" :key="section.title">
@@ -1218,6 +1219,24 @@
</div>
</div>
</div>
+
+ <!-- Skills Tab Content -->
+ <div id="skills-tab-content" x-show="activeTab === 'skills'" x-cloak>
+ <nav>
+ <ul>
+ <li>
+ <a href="#section-skills-import">
+ <img src="/public/skills.svg" alt="Skills">
+ <span>Import Skills</span>
+ </a>
+ </li>
+ </ul>
+ </nav>
+
+ <div id="section-skills-import" class="section">
+ <x-component path="settings/skills/import.html" />
+ </div>
+ </div>
</div>
<div class="modal-footer">
diff --git a/webui/js/settings.js b/webui/js/settings.js
index 059d64541..a0a9b8a86 100644
--- a/webui/js/settings.js
+++ b/webui/js/settings.js
@@ -283,6 +283,8 @@ const settingsModalProxy = {
openModal("settings/external/api-examples.html");
} else if (field.id === "memory_dashboard") {
openModal("settings/memory/memory-dashboard.html");
+ } else if (field.id === "skills_import") {
+ openModal("settings/skills/import.html");
}
}
};
diff --git a/webui/public/skills.svg b/webui/public/skills.svg
new file mode 100644
index 000000000..8ca3877c2
--- /dev/null
+++ b/webui/public/skills.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
+ <path d="M7 7h10M7 11h10M7 15h6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
+ <path d="M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z" stroke="currentColor" stroke-width="2"/>
+</svg>
\ No newline at end of file