From fe70685d68b0283bdad256f77df4b3f55c010d97 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Mon, 6 Jul 2026 17:53:58 -0500 Subject: [PATCH] refac --- cptr/frontend/src/lib/apis/skills.ts | 1 + .../src/lib/components/chat/ChatInput.svelte | 57 +++++++ .../src/lib/components/chat/ChatPanel.svelte | 29 ++++ .../lib/components/chat/SkillsModal.svelte | 55 ++++++ cptr/routers/skills.py | 2 + cptr/utils/chat_task.py | 100 +++++++++++ cptr/utils/skills.py | 158 +++++++++++++++--- cptr/utils/tools.py | 38 +++++ 8 files changed, 421 insertions(+), 19 deletions(-) create mode 100644 cptr/frontend/src/lib/components/chat/SkillsModal.svelte diff --git a/cptr/frontend/src/lib/apis/skills.ts b/cptr/frontend/src/lib/apis/skills.ts index 82025c1..4bdc386 100644 --- a/cptr/frontend/src/lib/apis/skills.ts +++ b/cptr/frontend/src/lib/apis/skills.ts @@ -10,6 +10,7 @@ export interface SkillInfo { source: string; // "workspace" | "global" license?: string; compatibility?: string; + managed?: boolean; } export const getSkills = (workspace: string) => diff --git a/cptr/frontend/src/lib/components/chat/ChatInput.svelte b/cptr/frontend/src/lib/components/chat/ChatInput.svelte index 83374e6..4dfa105 100644 --- a/cptr/frontend/src/lib/components/chat/ChatInput.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatInput.svelte @@ -73,6 +73,7 @@ oncompact?: () => void; onplan?: () => void; onstatus?: () => void; + onskillslist?: () => void; oncancel?: () => void; onqueuesendnow?: (id: string) => void; onqueueedit?: (id: string) => void; @@ -91,6 +92,7 @@ oncompact, onplan, onstatus, + onskillslist, oncancel, onqueuesendnow, onqueueedit, @@ -927,6 +929,8 @@ if (oncompact && '/compact'.startsWith(slashCommandQuery)) ids.push('compact'); if (onplan && '/plan'.startsWith(slashCommandQuery)) ids.push('plan'); if (onstatus && '/status'.startsWith(slashCommandQuery)) ids.push('status'); + if (onskillslist && '/skills:list'.startsWith(slashCommandQuery)) ids.push('skills:list'); + if ('/skills:create'.startsWith(slashCommandQuery)) ids.push('skills:create'); return ids; }); const showSlashCommands = $derived(slashCommandIds.length > 0); @@ -955,6 +959,15 @@ onstatus(); return; } + if (commandId === 'skills:list' && onskillslist) { + inputText = ''; + onskillslist(); + return; + } + if (commandId === 'skills:create') { + inputText = '/skills:create '; + return; + } onsend(); } @@ -1123,6 +1136,50 @@ {/if} + {#if slashCommandIds.includes('skills:list')} + + {/if} + {#if slashCommandIds.includes('skills:create')} + + {/if} {/if} diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index 7e813ce..dd2fb3c 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -53,7 +53,9 @@ import AssistantMessage from './AssistantMessage.svelte'; import ChatHistory from './ChatHistory.svelte'; import StatusModal from './StatusModal.svelte'; + import SkillsModal from './SkillsModal.svelte'; import { listCommandSessions, type CommandSession } from '$lib/apis/terminal'; + import { getSkills, type SkillInfo } from '$lib/apis/skills'; import Spinner from '../common/Spinner.svelte'; import Icon from '../Icon.svelte'; import { toast } from 'svelte-sonner'; @@ -79,6 +81,8 @@ let currentMessageId = $state(null); let contextUsage = $state(null); let showStatusModal = $state(false); + let showSkillsModal = $state(false); + let skillsModalList = $state([]); let commandSessions = $state([]); let initialCommandSessionId = $state(null); let previousChats = $state([]); @@ -686,6 +690,11 @@ inputText = ''; return; } + if (text === '/skills:list') { + await handleSkillsListCommand(); + inputText = ''; + return; + } stopTtsPlayback(); if (shouldStreamTts()) void unlockTtsAudioPlayback(); sending = true; @@ -865,6 +874,15 @@ refreshCommandSessions(); } + async function handleSkillsListCommand() { + try { + skillsModalList = await getSkills(workspace); + showSkillsModal = true; + } catch (err: any) { + toast.error(err?.message || 'Failed to load skills'); + } + } + async function refreshCommandSessions() { const currentChatId = chatId; if (!currentChatId) { @@ -1576,6 +1594,7 @@ oncompact={handleManualCompact} onplan={handlePlanCommand} onstatus={handleStatusCommand} + onskillslist={handleSkillsListCommand} oncancel={handleCancel} {queuedMessages} onqueuesendnow={handleQueueSendNow} @@ -1601,3 +1620,13 @@ }} /> {/if} + +{#if showSkillsModal} + { + showSkillsModal = false; + skillsModalList = []; + }} + /> +{/if} diff --git a/cptr/frontend/src/lib/components/chat/SkillsModal.svelte b/cptr/frontend/src/lib/components/chat/SkillsModal.svelte new file mode 100644 index 0000000..d550b47 --- /dev/null +++ b/cptr/frontend/src/lib/components/chat/SkillsModal.svelte @@ -0,0 +1,55 @@ + + + +
+ +
+ Skills +
+
+ +
+ {#if skills.length} +
+ {#each skills as item} +
+
+
+ {item.name} +
+
+ {item.managed ? 'managed' : 'read-only'} +
+
+
+ {item.description} +
+
+ {/each} +
+ {:else} +
No skills found
+ {/if} +
+
diff --git a/cptr/routers/skills.py b/cptr/routers/skills.py index 72546f7..5780b11 100644 --- a/cptr/routers/skills.py +++ b/cptr/routers/skills.py @@ -18,6 +18,7 @@ class SkillResponse(BaseModel): source: str # "workspace" or "global" license: Optional[str] = None compatibility: Optional[str] = None + managed: bool = False @router.get("", response_model=list[SkillResponse]) @@ -34,6 +35,7 @@ async def list_skills(workspace: str = Query(..., description="Workspace path")) source=s.source, license=s.license, compatibility=s.compatibility, + managed=s.managed, ) for s in skills ] diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 27a0961..f7cacf7 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -50,6 +50,104 @@ PLAN_MODE_PROMPT = ( "tools or implementing." ) +SKILLS_CREATE_RE = re.compile(r"^/skills:create(?:\s+(.*))?$", re.IGNORECASE | re.DOTALL) + +COMPUTER_SKILL_AUTHORING_STANDARDS = """\ +Follow the Computer skill-authoring standards: + +Frontmatter: +- name: lowercase-hyphenated, <=64 chars, no spaces. +- description: one sentence, <=60 characters, ends with a period. State the + capability, not the implementation. Do not repeat the skill name. Avoid + marketing words like powerful, comprehensive, seamless, advanced, or robust. + Count the characters before saving. +- version: 0.1.0. +- platforms: declare [macos], [linux], or [windows] only when the skill uses + OS-bound primitives. Omit it for portable skills. + +Body section order: +1. "# " plus a short intro covering what it does, what it does not + do, and important dependency assumptions. +2. "## When to Use" with concrete trigger phrases. +3. "## Prerequisites" with exact env vars, credentials, install steps, or "None". +4. "## How to Run" with the canonical workflow framed through Computer tools. +5. "## Quick Reference" with flat commands, routes, files, or APIs. +6. "## Procedure" with numbered, copy-paste-exact steps. +7. "## Pitfalls" with known limits and failure modes. +8. "## Verification" with one focused check that proves the skill works. + +Computer-tool framing: +- Reference Computer tools by name in backticks: `read_file`, `list_directory`, + `search_files`, `web_search`, `read_url`, `run_command`, `view_skill`, + and `manage_skill`. +- Frame shell work as "run through `run_command`". +- Prefer Computer tools in prose over raw shell utilities when a tool exists: + say `read_file` instead of cat/head/tail, `search_files` instead of grep/rg/find, + and `read_url` instead of curl-to-scrape. +- Third-party CLIs are fine inside procedures or scripts, but explain that the + agent invokes them through `run_command`. + +Quality bar: +- Prefer exact commands, routes, file paths, function names, config keys, and + error text found verbatim in the sources. Do not invent flags, paths, APIs, + or behavior. +- Keep SKILL.md tight and scannable: about 100 lines for a simple workflow, + about 200 for a complex one. +- Do not create a router/index/hub skill that only points at other skills. +- Put larger reusable scripts in `scripts/`, detailed docs in `references/`, + reusable outputs in `templates/`, and binary or visual assets in `assets/`. +- New skills default to workspace scope. Do not use scope="global" unless the + user explicitly asks for a global skill.""" + + +def _build_skill_create_prompt(user_request: str) -> str: + req = (user_request or "").strip() + if not req: + req = ( + "the workflow we just went through in this conversation - review the " + "steps taken and distill them into a reusable skill" + ) + return ( + "[/skills:create] The user wants you to create a reusable Computer skill " + "from the request below and save it.\n\n" + f"THE REQUEST:\n{req}\n\n" + "The request is open-ended and may mix SOURCES to gather (directories, " + "file paths, URLs, what we just did, pasted notes) and REQUIREMENTS that " + "shape the skill (focus, exclusions, scope, naming, style, constraints). " + "Treat every part of the request as load-bearing. Prose after a path or " + "URL is not incidental; it is authoring guidance. Never fetch the first " + "source and ignore the rest.\n\n" + "Do this:\n" + "1. Gather every source the user named with the tools you already have: " + "`read_file`/`search_files`/`list_directory` for local files or directories, " + "`web_search`/`read_url` for web sources, the current conversation if they " + "refer to what just happened, and pasted text as-is. If scope is ambiguous, " + "make a reasonable choice and note it; do not stall.\n" + "2. Apply every requirement, focus, and constraint in the request to what " + "the skill covers and emphasizes.\n" + "3. Author one SKILL.md using the standards below.\n" + '4. Save it with manage_skill(action="create", name=..., content=...). ' + "If the skill needs supporting files, add them after the create with " + 'manage_skill(action="write_file", name=..., file_path=..., ' + "file_content=...).\n\n" + f"{COMPUTER_SKILL_AUTHORING_STANDARDS}\n\n" + "When done, tell the user the skill name, location, and one-line summary." + ) + + +def _apply_skills_create_prompt(messages: list[dict]) -> bool: + for message in reversed(messages): + if message.get("role") != "user": + continue + text = _plain_message_text(message.get("content")) + match = SKILLS_CREATE_RE.match(text.strip()) + if not match: + return False + message["content"] = _build_skill_create_prompt(match.group(1) or "") + return True + return False + + # ── Task registry ─────────────────────────────────────────── _tasks: dict[str, asyncio.Task] = {} # message_id → asyncio.Task @@ -1284,6 +1382,7 @@ async def run_chat_task( chat_obj = await Chat.get_by_id(chat_id) chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {} messages, loaded_summary = await _load_message_history(chat_id, message_id) + _apply_skills_create_prompt(messages) memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt) system = await _load_system_prompt( workspace, @@ -1545,6 +1644,7 @@ async def run_chat_task( chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {} configured_model = (msg.model if msg else None) or model messages, loaded_summary = await _load_message_history(chat_id, message_id) + _apply_skills_create_prompt(messages) memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt) system = await _load_system_prompt( workspace, diff --git a/cptr/utils/skills.py b/cptr/utils/skills.py index a9a6a28..3fa9259 100644 --- a/cptr/utils/skills.py +++ b/cptr/utils/skills.py @@ -17,6 +17,7 @@ from __future__ import annotations import logging import re from dataclasses import dataclass, field +from typing import Literal from pathlib import Path import yaml @@ -39,6 +40,10 @@ GLOBAL_SKILL_DIRS = [ str(Path.home() / ".cptr" / "skills"), ] +MANAGED_WORKSPACE_SKILL_DIR = ".cptr/skills" +MANAGED_GLOBAL_SKILL_DIR = Path.home() / ".cptr" / "skills" +ALLOWED_BUNDLE_DIRS = {"references", "templates", "scripts", "assets"} + # Directories to skip during scanning _SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"} @@ -53,21 +58,25 @@ _MAX_SCAN_DIRS = 2000 @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" + 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 + managed: bool = False @dataclass class SkillContent(SkillMeta): """Tier 2: full instructions + resource listing.""" - body: str = "" # markdown body after frontmatter + + content: str = "" # full SKILL.md, including frontmatter + body: str = "" # markdown body after frontmatter resources: list[str] = field(default_factory=list) # relative paths of bundled files @@ -108,7 +117,7 @@ def parse_frontmatter(text: str) -> tuple[dict, str]: # 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}\"") + fixed_lines.append(f'{" " * indent}{key_part.strip()}: "{val}"') continue fixed_lines.append(line) @@ -149,7 +158,9 @@ def validate_name(name: str, parent_dir: str) -> list[str]: 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)") + warnings.append( + f"name '{name}' contains invalid characters (must be lowercase alphanumeric + hyphens)" + ) if "--" in name: warnings.append(f"name '{name}' contains consecutive hyphens") @@ -163,7 +174,22 @@ def validate_name(name: str, parent_dir: str) -> list[str]: # ── Discovery ─────────────────────────────────────────────── -def _scan_skills_dir(skills_dir: Path, source: str) -> list[SkillMeta]: +def _is_managed_skill(skill_md: Path, workspace: str = "") -> bool: + try: + skill_dir = skill_md.parent.resolve() + global_root = MANAGED_GLOBAL_SKILL_DIR.expanduser().resolve() + if skill_dir.is_relative_to(global_root): + return True + if workspace: + workspace_root = (Path(workspace) / MANAGED_WORKSPACE_SKILL_DIR).resolve() + if skill_dir.is_relative_to(workspace_root): + return True + except OSError: + pass + return False + + +def _scan_skills_dir(skills_dir: Path, source: str, workspace: str = "") -> list[SkillMeta]: """Scan a single skills directory for skill folders containing SKILL.md.""" results: list[SkillMeta] = [] @@ -211,16 +237,19 @@ def _scan_skills_dir(skills_dir: Path, source: str) -> list[SkillMeta]: 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"), - )) + 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"), + managed=_is_managed_skill(skill_md, workspace), + ) + ) except PermissionError: logger.debug("[skills] Permission denied scanning %s", skills_dir) @@ -245,20 +274,21 @@ def discover_skills(workspace: str) -> list[SkillMeta]: 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"): + for skill in _scan_skills_dir(skills_dir, source="workspace", workspace=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, + 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"): + for skill in _scan_skills_dir(skills_dir, source="global", workspace=workspace): if skill.name not in seen_names: seen_names.add(skill.name) all_skills.append(skill) @@ -337,11 +367,101 @@ def load_skill(workspace: str, skill_name: str) -> SkillContent | None: compatibility=meta.compatibility, metadata=meta.metadata, allowed_tools=meta.allowed_tools, + managed=meta.managed, + content=text, body=body, resources=resources, ) +def _managed_root(workspace: str, scope: Literal["workspace", "global"]) -> Path: + if scope == "global": + return MANAGED_GLOBAL_SKILL_DIR.expanduser() + if not workspace: + raise ValueError("workspace is required for workspace skills") + return Path(workspace).expanduser().resolve() / MANAGED_WORKSPACE_SKILL_DIR + + +def _validate_skill_name(name: str) -> str: + normalized = (name or "").strip() + warnings = validate_name(normalized, normalized) + if warnings: + raise ValueError("; ".join(warnings)) + return normalized + + +def _validate_skill_content(name: str, content: str) -> tuple[dict, str]: + if not content or not content.strip(): + raise ValueError("content is required") + fm, body = parse_frontmatter(content) + skill_name = str(fm.get("name", "")).strip() + description = str(fm.get("description", "")).strip() + if skill_name != name: + raise ValueError("frontmatter name must match skill name") + if not description: + raise ValueError("frontmatter description is required") + if not body: + raise ValueError("skill body is required") + return fm, body + + +def _write_text_atomic(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f".{path.name}.tmp") + tmp.write_text(content, encoding="utf-8") + tmp.replace(path) + + +def create_managed_skill( + workspace: str, + name: str, + content: str, + scope: Literal["workspace", "global"] = "workspace", +) -> dict: + name = _validate_skill_name(name) + _validate_skill_content(name, content) + if any(skill.name == name for skill in discover_skills(workspace)): + raise ValueError(f"skill '{name}' already exists") + skill_dir = _managed_root(workspace, scope) / name + skill_md = skill_dir / "SKILL.md" + if skill_md.exists(): + raise ValueError(f"skill '{name}' already exists") + _write_text_atomic(skill_md, content.strip() + "\n") + return {"success": True, "name": name, "location": str(skill_md.resolve())} + + +def _managed_skill_dir(workspace: str, name: str) -> Path: + name = _validate_skill_name(name) + skill = next((s for s in discover_skills(workspace) if s.name == name), None) + if not skill: + raise ValueError(f"skill '{name}' not found") + if not skill.managed: + raise ValueError(f"skill '{name}' is read-only in Computer") + return Path(skill.location).parent.resolve() + + +def write_managed_skill_file( + workspace: str, name: str, file_path: str, file_content: str | None +) -> dict: + if file_content is None: + raise ValueError("file_content is required") + rel = Path(file_path or "") + if not rel.parts: + raise ValueError("file_path is required") + if rel.is_absolute() or ".." in rel.parts: + raise ValueError("file_path must stay inside the skill") + if rel.parts[0] not in ALLOWED_BUNDLE_DIRS: + raise ValueError("file_path must start with references/, templates/, scripts/, or assets/") + if any(part.startswith(".") for part in rel.parts): + raise ValueError("dot paths are not allowed") + skill_dir = _managed_skill_dir(workspace, name) + target = (skill_dir / rel).resolve() + if not target.is_relative_to(skill_dir): + raise ValueError("file_path escapes the skill") + _write_text_atomic(target, file_content) + return {"success": True, "name": name, "location": str(target)} + + # ── Catalog & structured output ───────────────────────────── diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index 62f3cd2..026a5f2 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -1421,6 +1421,43 @@ async def view_skill( return format_skill_content(skill) +async def manage_skill( + action: Literal["create", "write_file"], + name: str, + content: Optional[str] = None, + scope: Literal["workspace", "global"] = "workspace", + file_path: Optional[str] = None, + file_content: Optional[str] = None, + *, + __context__: dict, +) -> str: + """Create Computer-managed skills and supporting bundle files. + + Use this only when the user asks to create a reusable skill. New skills + default to the current workspace. For supporting files, write only under + references/, templates/, scripts/, or assets/. + :param action: "create" to write SKILL.md, or "write_file" to add a bundle file. + :param name: Lowercase hyphenated skill name. + :param content: Full SKILL.md content for action="create". + :param scope: "workspace" for .cptr/skills, or "global" for ~/.cptr/skills. + :param file_path: Relative bundle path for action="write_file". + :param file_content: File content for action="write_file". + """ + from cptr.utils.skills import create_managed_skill, write_managed_skill_file + + workspace = __context__.get("workspace", "") + try: + if action == "create": + result = create_managed_skill(workspace, name, content or "", scope) + elif action == "write_file": + result = write_managed_skill_file(workspace, name, file_path or "", file_content) + else: + result = {"success": False, "error": f"unsupported action '{action}'"} + except Exception as e: + result = {"success": False, "error": str(e)} + return json.dumps(result, ensure_ascii=False) + + # ── Browser tools ──────────────────────────────────────────── @@ -1934,6 +1971,7 @@ TOOLS: dict[str, dict] = { "delete_automation": {"fn": delete_automation, "auto": False}, "notify": {"fn": notify, "auto": False}, "image_generate": {"fn": image_generate, "auto": False}, + "manage_skill": {"fn": manage_skill, "auto": False}, "update_memory": {"fn": update_memory, "auto": True}, }