This commit is contained in:
Timothy Jaeryang Baek
2026-06-12 10:09:45 +01:00
Unverified
parent df8582f4fb
commit 71f23621bb
10 changed files with 836 additions and 3 deletions
+2
View File
@@ -15,6 +15,7 @@ from cptr.routers import (
git_router,
proxy_router,
search_router,
skills_router,
state_router,
terminal_router,
workspace_router,
@@ -192,6 +193,7 @@ app.include_router(files_router)
app.include_router(git_router)
app.include_router(proxy_router)
app.include_router(search_router)
app.include_router(skills_router)
app.include_router(state_router)
app.include_router(terminal_router)
app.include_router(workspace_router)
+16
View File
@@ -0,0 +1,16 @@
/**
* Skills API: list available skills for the $ mention picker.
*/
import { fetchJSON } from '$lib/apis';
export interface SkillInfo {
name: string;
description: string;
location: string;
source: string; // "workspace" | "global"
license?: string;
compatibility?: string;
}
export const getSkills = (workspace: string) =>
fetchJSON<SkillInfo[]>(`/api/skills?workspace=${encodeURIComponent(workspace)}`);
@@ -9,8 +9,11 @@
import { all, createLowlight } from 'lowlight';
import { createFileMention, extractMentionedFiles, type FileMentionAttrs } from './FileMention';
import { createSkillMention, extractMentionedSkills, type SkillMentionAttrs } from './SkillMention';
import FileSuggestionPopup from './FileSuggestionPopup.svelte';
import SkillSuggestionPopup from './SkillSuggestionPopup.svelte';
import { searchFiles } from '$lib/apis/files';
import { getSkills } from '$lib/apis/skills';
import { uploadFile } from '$lib/apis/files';
import ModelSelector from '../common/ModelSelector.svelte';
import SendButton from './SendButton.svelte';
@@ -265,6 +268,156 @@
}
}
// ── $skill mention suggestion ──────────────────────
let skillPopupEl: HTMLDivElement | null = null;
let skillPopupComponent: Record<string, any> | null = null;
let skillActiveClientRectFn: (() => DOMRect | null) | null = null;
let skillRepositionRafId: number | null = null;
let cachedSkills: SkillMentionAttrs[] | null = null;
async function fetchSkillSuggestions({ query }: { query: string }): Promise<SkillMentionAttrs[]> {
if (!workspace) return [];
try {
// Cache skills list (small, doesn't change during a session)
if (!cachedSkills) {
const data = await getSkills(workspace);
cachedSkills = data.map((s) => ({
id: s.name,
label: s.name,
description: s.description,
source: s.source,
}));
}
if (!query) return cachedSkills;
const q = query.toLowerCase();
return cachedSkills.filter(
(s) => s.label.toLowerCase().includes(q) || (s.description || '').toLowerCase().includes(q)
);
} catch {
return [];
}
}
function mountSkillPopup(
items: SkillMentionAttrs[],
selectedIdx: number,
onselect: (i: number) => void
) {
if (skillPopupComponent) {
try { unmount(skillPopupComponent); } catch {}
skillPopupComponent = null;
}
if (!skillPopupEl) {
skillPopupEl = document.createElement('div');
document.body.appendChild(skillPopupEl);
}
skillPopupComponent = mount(SkillSuggestionPopup, {
target: skillPopupEl,
props: { items, selectedIndex: selectedIdx, onselect }
});
}
function startSkillRepositionLoop() {
stopSkillRepositionLoop();
function tick() {
if (skillActiveClientRectFn) {
updateSkillPopupPosition(skillActiveClientRectFn());
skillRepositionRafId = requestAnimationFrame(tick);
}
}
skillRepositionRafId = requestAnimationFrame(tick);
}
function stopSkillRepositionLoop() {
if (skillRepositionRafId !== null) {
cancelAnimationFrame(skillRepositionRafId);
skillRepositionRafId = null;
}
}
function createSkillSuggestionRenderer() {
let selectedIndex = 0;
let currentItems: SkillMentionAttrs[] = [];
let command: ((attrs: SkillMentionAttrs) => void) | null = null;
function doSelect(index: number) {
const item = currentItems[index];
if (item && command) command(item);
}
function remount() {
mountSkillPopup(currentItems, selectedIndex, doSelect);
}
return {
onStart(props: any) {
command = props.command;
currentItems = props.items;
selectedIndex = 0;
skillActiveClientRectFn = props.clientRect ?? null;
remount();
updateSkillPopupPosition(props.clientRect?.());
startSkillRepositionLoop();
},
onUpdate(props: any) {
command = props.command;
currentItems = props.items;
selectedIndex = 0;
skillActiveClientRectFn = props.clientRect ?? null;
remount();
updateSkillPopupPosition(props.clientRect?.());
},
onKeyDown({ event }: { event: KeyboardEvent }) {
if (event.key === 'ArrowDown') {
selectedIndex = (selectedIndex + 1) % Math.max(currentItems.length, 1);
remount();
return true;
}
if (event.key === 'ArrowUp') {
selectedIndex = (selectedIndex - 1 + currentItems.length) % Math.max(currentItems.length, 1);
remount();
return true;
}
if (event.key === 'Enter') {
const item = currentItems[selectedIndex];
if (item && command) command(item);
return true;
}
if (event.key === 'Escape') {
destroySkillPopup();
return true;
}
return false;
},
onExit() {
destroySkillPopup();
}
};
}
function updateSkillPopupPosition(rect: DOMRect | null) {
if (!skillPopupEl || !rect) return;
const child = skillPopupEl.firstElementChild as HTMLElement | null;
if (!child) return;
const popupHeight = child.offsetHeight || 200;
child.style.position = 'fixed';
child.style.left = `${Math.max(8, Math.min(rect.left, window.innerWidth - 340))}px`;
child.style.top = `${rect.top - popupHeight - 8}px`;
}
function destroySkillPopup() {
stopSkillRepositionLoop();
skillActiveClientRectFn = null;
if (skillPopupComponent) {
try { unmount(skillPopupComponent); } catch {}
skillPopupComponent = null;
}
if (skillPopupEl) {
skillPopupEl.remove();
skillPopupEl = null;
}
}
// ── Editor lifecycle ────────────────────────────
onMount(() => {
if (!editorEl) return;
@@ -274,6 +427,11 @@
render: createSuggestionRenderer
});
const skillMention = createSkillMention({
items: fetchSkillSuggestions,
render: createSkillSuggestionRenderer
});
editor = new Editor({
element: editorEl,
extensions: [
@@ -284,7 +442,8 @@
Markdown,
Placeholder.configure({ placeholder }),
CodeBlockLowlight.configure({ lowlight }),
fileMention
fileMention,
skillMention
],
content: inputText || '',
contentType: inputText ? 'markdown' : undefined,
@@ -297,7 +456,7 @@
handleKeyDown: (view, event) => {
if (event.key === 'Enter' && !event.shiftKey) {
// Don't send while suggestion popup is open — let it confirm selection
if (popupComponent) return false;
if (popupComponent || skillPopupComponent) return false;
const { state } = view;
const head = state.selection.$head;
@@ -326,6 +485,7 @@
onDestroy(() => {
destroyPopup();
destroySkillPopup();
editor?.destroy();
editor = null;
});
@@ -359,6 +519,11 @@
attachedUploads = [];
}
export function getSkillIds(): string[] {
if (!editor) return [];
return extractMentionedSkills(editor.getJSON());
}
// Allow sending during streaming (message will be enqueued server-side)
const canSend = $derived(inputText.trim() && selectedModel && !sending);
</script>
@@ -0,0 +1,64 @@
/**
* TipTap Mention extension configured for $skill mentions.
*
* Similar to FileMention but uses '$' as the trigger character
* and wired to the skills API for suggestions.
*/
import Mention from '@tiptap/extension-mention';
export interface SkillMentionAttrs {
id: string; // skill name
label: string; // display name
description?: string; // skill description (for popup)
source?: string; // "workspace" | "global" (for popup badge)
}
/**
* Create the configured Mention extension for skills.
* Uses '$' as the trigger character.
*/
export function createSkillMention(suggestionOptions: {
items: (props: { query: string }) => Promise<SkillMentionAttrs[]> | SkillMentionAttrs[];
render: () => {
onStart: (props: any) => void;
onUpdate: (props: any) => void;
onKeyDown: (props: any) => boolean;
onExit: () => void;
};
}) {
return Mention.extend({ name: 'skillMention' }).configure({
HTMLAttributes: {
class: 'bg-purple-500/10 text-purple-400 rounded px-1 py-px text-xs font-mono'
},
renderText({ node }) {
return `$${node.attrs.label ?? node.attrs.id}`;
},
suggestion: {
char: '$',
allowSpaces: false,
...suggestionOptions
}
});
}
/**
* Extract all skill mention names from a TipTap editor JSON doc.
*/
export function extractMentionedSkills(doc: any): string[] {
const skills: string[] = [];
function walk(node: any) {
if (node.type === 'skillMention' && node.attrs?.id) {
skills.push(node.attrs.id);
}
if (node.content) {
for (const child of node.content) {
walk(child);
}
}
}
if (doc) walk(doc);
return [...new Set(skills)];
}
@@ -0,0 +1,74 @@
<script lang="ts">
import Icon from '../Icon.svelte';
interface SuggestionItem {
id: string;
label: string;
description?: string;
source?: string;
}
interface Props {
items: SuggestionItem[];
selectedIndex: number;
onselect: (index: number) => void;
}
let { items, selectedIndex, onselect }: Props = $props();
let listEl: HTMLDivElement | undefined = $state();
// Scroll selected item into view
$effect(() => {
if (listEl && selectedIndex >= 0) {
const el = listEl.children[selectedIndex] as HTMLElement | undefined;
el?.scrollIntoView({ block: 'nearest' });
}
});
</script>
<div
class="fixed z-50 w-72 max-h-48 overflow-y-auto rounded-xl bg-white dark:bg-[#1a1a1a] border border-gray-150 dark:border-white/6 shadow-xl p-0.5"
>
{#if items.length === 0}
<div class="px-3 py-2 text-xs text-gray-400 dark:text-gray-600">No skills found</div>
{:else}
<div class="text-[10px] text-gray-400 dark:text-gray-600 px-2.5 pt-1.5 pb-0.5">
Skills
</div>
<div bind:this={listEl}>
{#each items as item, i (item.id)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<button
class="flex items-start gap-2 w-full px-2 py-1.5 rounded-xl text-xs text-left transition-colors duration-75
{i === selectedIndex
? 'bg-gray-50 dark:bg-white/5 text-gray-900 dark:text-white'
: 'text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 hover:text-gray-900 dark:hover:text-white'}"
onmousedown={(e) => {
e.preventDefault();
onselect(i);
}}
onmouseenter={() => (selectedIndex = i)}
>
<span
class="flex items-center justify-center w-4 shrink-0 mt-0.5 text-purple-400 dark:text-purple-400"
>
<svg viewBox="0 0 16 16" fill="currentColor" class="size-3.5">
<path d="M8.75 1a.75.75 0 0 0-1.5 0v1.249c-1.373.158-2.476.682-3.33 1.536C3.066 4.639 2.5 5.77 2.5 7.25c0 1.296-.266 2.193-.613 2.852-.35.663-.83 1.132-1.268 1.507a.75.75 0 0 0 .494 1.315h3.137a3.75 3.75 0 0 0 7.5 0h3.137a.75.75 0 0 0 .494-1.315c-.438-.375-.919-.844-1.268-1.507-.347-.659-.613-1.556-.613-2.852 0-1.48-.566-2.611-1.42-3.465-.854-.854-1.957-1.378-3.33-1.536V1ZM6.5 12.924a2.25 2.25 0 0 0 3 0h-3Z" />
</svg>
</span>
<span class="flex-1 min-w-0 flex flex-col overflow-hidden">
<span class="flex items-center gap-1.5">
<span class="truncate font-medium">{item.label}</span>
{#if item.source && item.source !== 'workspace'}
<span class="text-[9px] text-gray-400 dark:text-gray-600 bg-gray-100 dark:bg-white/5 rounded px-1 shrink-0">{item.source}</span>
{/if}
</span>
{#if item.description}
<span class="text-[10px] text-gray-400 dark:text-gray-600 truncate">{item.description}</span>
{/if}
</span>
</button>
{/each}
</div>
{/if}
</div>
+2
View File
@@ -9,6 +9,7 @@ from cptr.routers.files import router as files_router
from cptr.routers.git import router as git_router
from cptr.routers.proxy import router as proxy_router
from cptr.routers.search import router as search_router
from cptr.routers.skills import router as skills_router
from cptr.routers.state import router as state_router
from cptr.routers.terminal import router as terminal_router
from cptr.routers.workspace import router as workspace_router
@@ -23,6 +24,7 @@ __all__ = [
"git_router",
"proxy_router",
"search_router",
"skills_router",
"state_router",
"terminal_router",
"workspace_router",
+39
View File
@@ -0,0 +1,39 @@
"""Skills API: lightweight read-only endpoint for the $ mention picker."""
from __future__ import annotations
import asyncio
from typing import Optional
from fastapi import APIRouter, Query
from pydantic import BaseModel
router = APIRouter(prefix="/api/skills", tags=["skills"])
class SkillResponse(BaseModel):
name: str
description: str
location: str
source: str # "workspace" or "global"
license: Optional[str] = None
compatibility: Optional[str] = None
@router.get("", response_model=list[SkillResponse])
async def list_skills(workspace: str = Query(..., description="Workspace path")):
"""List available skills (frontmatter only) for the $ mention picker."""
from cptr.utils.skills import discover_skills
skills = await asyncio.to_thread(discover_skills, workspace)
return [
SkillResponse(
name=s.name,
description=s.description,
location=s.location,
source=s.source,
license=s.license,
compatibility=s.compatibility,
)
for s in skills
]
+41 -1
View File
@@ -13,6 +13,7 @@ from pathlib import Path
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_MAX_CHARS
from cptr.utils.context import should_compact
from cptr.utils.skills import discover_skills, load_skill, build_catalog_xml, format_skill_content
from cptr.utils.summarize import summarize_messages
from cptr.models import Chat, ChatMessage, Config
from cptr.socket.main import emit_to_user
@@ -320,6 +321,7 @@ DEFAULT_SYSTEM_PROMPT = (
"For complex tasks, create an implementation plan first using "
"create_artifact, then wait for approval before coding."
"\n\n{{INSTRUCTIONS}}"
"\n\n{{SKILLS}}"
"\n\nWorkspace: {{WORKSPACE_NAME}}"
"\nFiles:\n{{FILE_TREE}}"
)
@@ -361,11 +363,16 @@ def _build_template_variables(workspace: str, model: str = "") -> dict[str, str]
else:
instructions_block = ""
# Build skills catalog
skills = discover_skills(workspace)
skills_block = build_catalog_xml(skills)
return {
"WORKSPACE_NAME": ws_path.name if ws_path.is_dir() else "",
"WORKSPACE_PATH": str(ws_path),
"FILE_TREE": _get_file_tree(workspace),
"INSTRUCTIONS": instructions_block,
"SKILLS": skills_block,
"OS": platform.system().replace("Darwin", "macOS"),
"DATE": date.today().isoformat(),
"MODEL": model,
@@ -793,9 +800,33 @@ async def run_chat_task(
messages.append({"role": "user", "content": regeneration_prompt})
tools = get_tool_list()
# Load chat params for approval mode
# Remove view_skill tool if no skills are available
skills = discover_skills(workspace)
if not skills:
tools = [t for t in tools if t["name"] != "view_skill"]
# Parse $skill-name mentions from the user message to auto-activate skills
chat_obj = await Chat.get_by_id(chat_id)
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
attached_skill_ids: list[str] = []
if skills and messages:
# Find the last user message
last_user = next((m for m in reversed(messages) if m["role"] == "user"), None)
if last_user:
import re as _re
mentioned = _re.findall(r'\$([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)', last_user["content"])
skill_names = {s.name for s in skills}
attached_skill_ids = [m for m in mentioned if m in skill_names]
if attached_skill_ids:
from cptr.utils.tools import _activated_skills
skill_blocks = []
for sid in attached_skill_ids:
skill = load_skill(workspace, sid)
if skill:
skill_blocks.append(format_skill_content(skill))
_activated_skills.add(sid) # mark as activated for dedup
if skill_blocks:
system += "\n\n" + "\n\n".join(skill_blocks)
# Plan mode: strip write tools, inject prompt as user message (not system, to preserve cache)
plan_mode = chat_params.get("plan_mode", False)
@@ -853,6 +884,15 @@ async def run_chat_task(
# Append summary to system prompt (works for all providers)
system = await _load_system_prompt(workspace, model)
system += f"\n\n[CONVERSATION SUMMARY]\n{summary}"
# Re-inject attached skills after compaction (protect from pruning)
if attached_skill_ids:
skill_blocks = []
for sid in attached_skill_ids:
skill = load_skill(workspace, sid)
if skill:
skill_blocks.append(format_skill_content(skill))
if skill_blocks:
system += "\n\n" + "\n\n".join(skill_blocks)
messages = keep_zone
last_usage = None # reset after compaction
new_messages_since = 0
+402
View File
@@ -0,0 +1,402 @@
"""Agent Skills support following the agentskills.io specification.
Skills are folders containing a SKILL.md file with YAML frontmatter
(name + description) and markdown instructions. Optional subdirectories
include scripts/, references/, and assets/.
Discovery follows progressive disclosure:
1. Catalog (startup): name + description only (~50-100 tokens/skill)
2. Instructions (activation): full SKILL.md body (<5000 tokens recommended)
3. Resources (on-demand): scripts, references, assets loaded individually
See: https://agentskills.io/specification
"""
from __future__ import annotations
import logging
import re
from dataclasses import dataclass, field
from pathlib import Path
import yaml
logger = logging.getLogger(__name__)
# ── Discovery paths ─────────────────────────────────────────
# Workspace-level: scan client-specific + cross-client convention paths.
# First match on skill name wins within the same scope.
WORKSPACE_SKILL_DIRS = [
".cptr/skills",
".agents/skills",
".claude/skills",
".codex/skills",
]
# Global (user-level): only our own directory
GLOBAL_SKILL_DIRS = [
str(Path.home() / ".cptr" / "skills"),
]
# Directories to skip during scanning
_SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"}
# Max scan limits (per spec recommendation)
_MAX_SCAN_DEPTH = 4
_MAX_SCAN_DIRS = 2000
# ── Data classes ────────────────────────────────────────────
@dataclass
class SkillMeta:
"""Tier 1: lightweight metadata for the catalog."""
name: str
description: str
location: str # absolute path to SKILL.md
source: str # "workspace" or "global"
# Optional spec fields
license: str | None = None
compatibility: str | None = None
metadata: dict | None = None
allowed_tools: str | None = None
@dataclass
class SkillContent(SkillMeta):
"""Tier 2: full instructions + resource listing."""
body: str = "" # markdown body after frontmatter
resources: list[str] = field(default_factory=list) # relative paths of bundled files
# ── Frontmatter parsing ────────────────────────────────────
_FRONTMATTER_RE = re.compile(r"\A---\s*\n(.*?)\n---\s*\n?(.*)", re.DOTALL)
def parse_frontmatter(text: str) -> tuple[dict, str]:
"""Split SKILL.md into (frontmatter_dict, body_string).
Handles malformed YAML (unquoted colons) with a fallback retry.
Returns ({}, body) if frontmatter is missing or unparseable.
"""
match = _FRONTMATTER_RE.match(text)
if not match:
return {}, text.strip()
yaml_block = match.group(1)
body = match.group(2).strip()
# Try parsing YAML
try:
fm = yaml.safe_load(yaml_block)
if isinstance(fm, dict):
return fm, body
return {}, body
except yaml.YAMLError:
pass
# Fallback: try wrapping problematic values in quotes
# Common issue: unquoted colons in description values
fixed_lines = []
for line in yaml_block.splitlines():
if ":" in line and not line.strip().startswith("#"):
key_part, _, val_part = line.partition(":")
val = val_part.strip()
# If value contains a colon and isn't already quoted
if ":" in val and not (val.startswith('"') or val.startswith("'")):
indent = len(line) - len(line.lstrip())
fixed_lines.append(f"{' ' * indent}{key_part.strip()}: \"{val}\"")
continue
fixed_lines.append(line)
try:
fm = yaml.safe_load("\n".join(fixed_lines))
if isinstance(fm, dict):
logger.debug("[skills] Parsed frontmatter with colon-quoting fallback")
return fm, body
except yaml.YAMLError:
pass
logger.warning("[skills] Unparseable YAML frontmatter")
return {}, body
# ── Name validation ─────────────────────────────────────────
_NAME_RE = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$")
def validate_name(name: str, parent_dir: str) -> list[str]:
"""Validate skill name per spec. Returns list of warnings (lenient).
Spec constraints:
- 1-64 characters
- Lowercase letters, numbers, and hyphens only
- Must not start or end with a hyphen
- Must not contain consecutive hyphens
- Must match the parent directory name
"""
warnings: list[str] = []
if not name:
warnings.append("name is empty")
return warnings
if len(name) > 64:
warnings.append(f"name exceeds 64 characters ({len(name)})")
if not _NAME_RE.match(name):
warnings.append(f"name '{name}' contains invalid characters (must be lowercase alphanumeric + hyphens)")
if "--" in name:
warnings.append(f"name '{name}' contains consecutive hyphens")
if name != parent_dir:
warnings.append(f"name '{name}' doesn't match parent directory '{parent_dir}'")
return warnings
# ── Discovery ───────────────────────────────────────────────
def _scan_skills_dir(skills_dir: Path, source: str) -> list[SkillMeta]:
"""Scan a single skills directory for skill folders containing SKILL.md."""
results: list[SkillMeta] = []
if not skills_dir.is_dir():
return results
dirs_scanned = 0
try:
for item in sorted(skills_dir.iterdir()):
if dirs_scanned >= _MAX_SCAN_DIRS:
logger.warning("[skills] Hit max scan limit (%d dirs)", _MAX_SCAN_DIRS)
break
if not item.is_dir() or item.name in _SKIP_DIRS or item.name.startswith("."):
continue
dirs_scanned += 1
skill_md = item / "SKILL.md"
if not skill_md.is_file():
continue
try:
text = skill_md.read_text(errors="replace")
except OSError:
logger.debug("[skills] Failed to read %s", skill_md)
continue
fm, _body = parse_frontmatter(text)
name = str(fm.get("name", "")).strip()
description = str(fm.get("description", "")).strip()
# Skip if description is missing (per spec: essential for disclosure)
if not description:
logger.warning("[skills] Skipping %s: missing description", skill_md)
continue
# Use folder name as fallback if name is missing
if not name:
name = item.name
logger.debug("[skills] Using folder name as skill name: %s", name)
# Lenient validation: warn but load
warnings = validate_name(name, item.name)
for w in warnings:
logger.warning("[skills] %s: %s", skill_md, w)
results.append(SkillMeta(
name=name,
description=description[:1024],
location=str(skill_md.resolve()),
source=source,
license=fm.get("license"),
compatibility=fm.get("compatibility"),
metadata=fm.get("metadata") if isinstance(fm.get("metadata"), dict) else None,
allowed_tools=fm.get("allowed-tools"),
))
except PermissionError:
logger.debug("[skills] Permission denied scanning %s", skills_dir)
return results
def discover_skills(workspace: str) -> list[SkillMeta]:
"""Discover all available skills from workspace + global directories.
Scans workspace-level dirs first, then global. Deduplicates by name:
workspace skills take precedence over global skills.
Returns list of SkillMeta (frontmatter only, no body content).
"""
seen_names: set[str] = set()
all_skills: list[SkillMeta] = []
ws = Path(workspace)
# 1. Workspace-level skills (project-specific, git-trackable)
if ws.is_dir():
for rel_dir in WORKSPACE_SKILL_DIRS:
skills_dir = ws / rel_dir
for skill in _scan_skills_dir(skills_dir, source="workspace"):
if skill.name not in seen_names:
seen_names.add(skill.name)
all_skills.append(skill)
else:
logger.debug(
"[skills] Skipping duplicate '%s' from %s (already found)",
skill.name, skill.location,
)
# 2. Global skills (user-level, available across all workspaces)
for dir_path in GLOBAL_SKILL_DIRS:
skills_dir = Path(dir_path).expanduser()
for skill in _scan_skills_dir(skills_dir, source="global"):
if skill.name not in seen_names:
seen_names.add(skill.name)
all_skills.append(skill)
else:
logger.debug(
"[skills] Global skill '%s' shadowed by workspace skill",
skill.name,
)
if all_skills:
logger.info(
"[skills] Discovered %d skills (%d workspace, %d global)",
len(all_skills),
sum(1 for s in all_skills if s.source == "workspace"),
sum(1 for s in all_skills if s.source == "global"),
)
return all_skills
# ── Loading (tier 2) ────────────────────────────────────────
def _enumerate_resources(skill_dir: Path) -> list[str]:
"""List all files in a skill folder (relative paths), excluding SKILL.md."""
resources: list[str] = []
def _walk(directory: Path, prefix: str = "", depth: int = 0):
if depth >= _MAX_SCAN_DEPTH:
return
try:
for item in sorted(directory.iterdir()):
if item.name in _SKIP_DIRS:
continue
rel = f"{prefix}{item.name}" if not prefix else f"{prefix}/{item.name}"
if item.is_file() and item.name != "SKILL.md":
resources.append(rel)
elif item.is_dir():
_walk(item, rel, depth + 1)
except PermissionError:
pass
_walk(skill_dir)
return resources
def load_skill(workspace: str, skill_name: str) -> SkillContent | None:
"""Load full skill content (tier 2): body + resource listing.
Finds the skill by name using the same discovery order,
reads the full SKILL.md, and enumerates bundled files.
"""
# Find the skill's location
skills = discover_skills(workspace)
meta = next((s for s in skills if s.name == skill_name), None)
if not meta:
return None
skill_md = Path(meta.location)
try:
text = skill_md.read_text(errors="replace")
except OSError:
logger.error("[skills] Failed to read %s", skill_md)
return None
fm, body = parse_frontmatter(text)
skill_dir = skill_md.parent
resources = _enumerate_resources(skill_dir)
return SkillContent(
name=meta.name,
description=meta.description,
location=meta.location,
source=meta.source,
license=meta.license,
compatibility=meta.compatibility,
metadata=meta.metadata,
allowed_tools=meta.allowed_tools,
body=body,
resources=resources,
)
# ── Catalog & structured output ─────────────────────────────
def build_catalog_xml(skills: list[SkillMeta]) -> str:
"""Build the <available_skills> XML catalog for the system prompt.
Includes behavioral instructions telling the model how to use skills.
Returns empty string if no skills.
"""
if not skills:
return ""
lines = [
"The following skills provide specialized instructions for specific tasks.",
"When a task matches a skill's description, call the view_skill tool",
"with the skill's name to load its full instructions.",
"",
"<available_skills>",
]
for s in skills:
lines.append("<skill>")
lines.append(f" <name>{s.name}</name>")
lines.append(f" <description>{s.description}</description>")
lines.append(f" <location>{s.location}</location>")
lines.append("</skill>")
lines.append("</available_skills>")
return "\n".join(lines)
def format_skill_content(skill: SkillContent) -> str:
"""Format loaded skill content with structured wrapping (per spec).
Wraps in <skill_content> tags with <skill_resources> listing
so the model can identify skill instructions and available files.
"""
skill_dir = str(Path(skill.location).parent)
parts = [
f'<skill_content name="{skill.name}">',
skill.body,
"",
f"Skill directory: {skill_dir}",
"Relative paths in this skill are relative to the skill directory.",
]
if skill.resources:
parts.append("")
parts.append("<skill_resources>")
for r in skill.resources[:50]: # cap listing for large dirs
parts.append(f" <file>{r}</file>")
if len(skill.resources) > 50:
parts.append(f" <!-- ... and {len(skill.resources) - 50} more files -->")
parts.append("</skill_resources>")
parts.append("</skill_content>")
return "\n".join(parts)
+29
View File
@@ -910,6 +910,34 @@ async def delete_automation(
return json.dumps({"error": str(e)})
# ── Skill tools ─────────────────────────────────────────────
# Track activated skills per session (cleared on import)
_activated_skills: set[str] = set()
async def view_skill(
skill_name: str,
*,
workspace: str,
) -> str:
"""Load the full instructions and resource listing for an available skill.
:param skill_name: The name of the skill to load (from the <available_skills> catalog).
"""
from cptr.utils.skills import load_skill, format_skill_content
# Deduplication: if already activated, return short notice
if skill_name in _activated_skills:
return f"Skill '{skill_name}' is already loaded in this session. Refer to the existing <skill_content> above."
skill = load_skill(workspace, skill_name)
if not skill:
return f"Error: skill '{skill_name}' not found. Check <available_skills> for valid names."
_activated_skills.add(skill_name)
return format_skill_content(skill)
# ── Registry ────────────────────────────────────────────────
TOOLS: dict[str, dict] = {
@@ -921,6 +949,7 @@ TOOLS: dict[str, dict] = {
"web_search": {"fn": web_search, "auto": True},
"read_url": {"fn": read_url, "auto": True},
"list_automations": {"fn": list_automations, "auto": True},
"view_skill": {"fn": view_skill, "auto": True},
# Write / mutate (require approval unless auto_approve_all)
"create_file": {"fn": create_file, "auto": False},
"edit_file": {"fn": edit_file, "auto": False},