AI-native design editor. Open-source Figma alternative.
feat(ai): add Agent Skills to the AI chat and Settings › Skills (#1510)
Danila Poyarkov05a892992daa
diff --git a/bun.lock b/bun.lockindex 370169a31..2a940ba25 100644--- a/bun.lock+++ b/bun.lock@@ -101,6 +101,7 @@"vue-stream-markdown": "2.0.0-beta.5","y-indexeddb": "^9.0.12","y-protocols": "^1.0.7",+ "yaml": "^2.9.0","yjs": "^13.6.32","yoga-layout": "npm:@open-pencil/[email protected]","zod": "^4.6.5",diff --git a/changes/1510/added.md b/changes/1510/added.mdnew file mode 100644index 000000000..4ef2c0e7e--- /dev/null+++ b/changes/1510/added.md@@ -0,0 +1,2 @@+- The AI chat supports Agent Skills: SKILL.md folders it lists by name and description and loads when a request matches. **Settings › Skills** takes uploads as a ZIP or a SKILL.md, and in the desktop app also reads the skills folders next to the open document once you trust them, and the skills you pick from `~/.agents/skills` and `~/.claude/skills`, which AI setup offers one by one since most are coding workflows; each folder and skill can be switched on or off.+- Start a message with `/skill:name` to run a skill; Pi gets the enabled skills too.diff --git a/desktop/src/agents/mod.rs b/desktop/src/agents/mod.rsindex ad01953b0..512e6270f 100644--- a/desktop/src/agents/mod.rs+++ b/desktop/src/agents/mod.rs@@ -3,3 +3,4 @@pub mod lookup;pub mod mcp;pub mod path;+pub mod skills;diff --git a/desktop/src/agents/skills.rs b/desktop/src/agents/skills.rsnew file mode 100644index 000000000..d14085fa9--- /dev/null+++ b/desktop/src/agents/skills.rs@@ -0,0 +1,392 @@+//! Agent Skills folders the chat reads from the user's other agents (`~/.agents/skills`,+//! `~/.claude/skills`). Skills there are often symlinks into a checkout elsewhere, which the+//! fs plugin's scope judges by their real path, so reading goes through these commands instead:+//! they read only `.agents/skills` and `.claude/skills` folders, only the folders in them that+//! hold a SKILL.md, and only files inside those.++use std::fs;+use std::io::Read;+use std::path::{Component, Path, PathBuf};++const SKILL_FILE: &str = "SKILL.md";+/// The specification asks for a SKILL.md under 500 lines; this leaves room for long ones.+const MAX_SKILL_FILE_BYTES: u64 = 256 * 1024;+const MAX_FILE_BYTES: u64 = 1024 * 1024;+/// Bounds the listing of a skill that is a whole repository checkout.+const MAX_LISTED_FILES: usize = 200;+const MAX_DEPTH: usize = 4;++#[derive(Debug, serde::Serialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct SkillFolder {+ /// The folder's name, which the specification makes the skill's name.+ name: String,+ /// The folder inside the root, before following symlinks.+ path: String,+ skill_file: String,+ /// Files besides SKILL.md, relative to the folder, with `/` separators.+ files: Vec<String>,+}++/// A folder agents install skills into: `skills` inside `.agents` or `.claude`.+fn is_skills_root(root: &Path) -> bool {+ let mut names = root+ .components()+ .rev()+ .map(|component| component.as_os_str());+ names.next().is_some_and(|name| name == "skills")+ && names+ .next()+ .is_some_and(|name| name == ".agents" || name == ".claude")+}++fn is_listed_name(name: &str) -> bool {+ !name.starts_with('.') && name != "node_modules"+}++/// `path` with symlinks resolved, when that stays inside `skill` (itself resolved).+fn inside_skill(skill: &Path, path: &Path) -> Option<PathBuf> {+ let resolved = path.canonicalize().ok()?;+ resolved.starts_with(skill).then_some(resolved)+}++/// A regular file's text, refused past `limit`: a device or a FIFO would never end.+fn read_bounded(path: &Path, limit: u64) -> Result<String, String> {+ let metadata = fs::metadata(path).map_err(|_| "The file cannot be read.".to_owned())?;+ if !metadata.is_file() {+ return Err("The path is not a file.".to_owned());+ }+ if metadata.len() > limit {+ return Err(format!("The file is larger than {} KB.", limit / 1024));+ }+ let mut bytes = Vec::new();+ fs::File::open(path)+ .and_then(|file| file.take(limit + 1).read_to_end(&mut bytes))+ .map_err(|_| "The file cannot be read.".to_owned())?;+ if bytes.len() as u64 > limit {+ return Err(format!("The file is larger than {} KB.", limit / 1024));+ }+ String::from_utf8(bytes).map_err(|_| "The file is not text.".to_owned())+}++/// Lists the files under `dir` inside `skill`; symlinks are followed only while they stay inside.+fn list_files(skill: &Path, dir: &Path, prefix: &str, depth: usize, files: &mut Vec<String>) {+ let Ok(entries) = fs::read_dir(dir) else {+ return;+ };+ let mut entries: Vec<_> = entries.flatten().collect();+ entries.sort_by_key(|entry| entry.file_name());+ for entry in entries {+ if files.len() >= MAX_LISTED_FILES {+ return;+ }+ let Some(name) = entry.file_name().to_str().map(str::to_owned) else {+ continue;+ };+ if !is_listed_name(&name) || (depth == 0 && name == SKILL_FILE) {+ continue;+ }+ let relative = if prefix.is_empty() {+ name+ } else {+ format!("{prefix}/{name}")+ };+ let Some(resolved) = inside_skill(skill, &entry.path()) else {+ continue;+ };+ let Ok(metadata) = fs::metadata(&resolved) else {+ continue;+ };+ if metadata.is_dir() {+ if depth + 1 < MAX_DEPTH {+ list_files(skill, &resolved, &relative, depth + 1, files);+ }+ } else if metadata.is_file() {+ files.push(relative);+ }+ }+}++/// The skills directly inside `root`, each a folder with a SKILL.md; empty without the root.+pub fn read_skill_folders(root: &Path) -> Vec<SkillFolder> {+ if !is_skills_root(root) {+ return Vec::new();+ }+ let Ok(entries) = fs::read_dir(root) else {+ return Vec::new();+ };+ let mut folders: Vec<SkillFolder> = entries+ .flatten()+ .filter_map(|entry| {+ let name = entry.file_name().to_str()?.to_owned();+ if !is_listed_name(&name) {+ return None;+ }+ let dir = entry.path();+ // The folder itself may be a symlink into a checkout; nothing in it may lead out.+ let skill = dir.canonicalize().ok()?;+ let skill_path = inside_skill(&skill, &skill.join(SKILL_FILE))?;+ let skill_file = read_bounded(&skill_path, MAX_SKILL_FILE_BYTES).ok()?;+ let mut files = Vec::new();+ list_files(&skill, &skill, "", 0, &mut files);+ Some(SkillFolder {+ name,+ path: dir.to_string_lossy().into_owned(),+ skill_file,+ files,+ })+ })+ .collect();+ folders.sort_by(|a, b| a.name.cmp(&b.name));+ folders+}++/// A file inside a skill folder, by the relative path the listing gave it.+pub fn read_skill_folder_file(dir: &Path, path: &str) -> Result<String, String> {+ let relative = Path::new(path);+ let plain = relative.components().all(|component| {+ matches!(component, Component::Normal(name) if name.to_str().is_some_and(is_listed_name))+ });+ if path.is_empty() || !plain {+ return Err(format!("\"{path}\" is not a file in the skill."));+ }+ if !dir.parent().is_some_and(is_skills_root) || !dir.join(SKILL_FILE).is_file() {+ return Err("The folder is not a skill.".to_owned());+ }+ let skill = dir+ .canonicalize()+ .map_err(|_| "The folder is not a skill.".to_owned())?;+ // A symlink inside the skill must not lead out of it.+ let target = inside_skill(&skill, &skill.join(relative))+ .ok_or_else(|| format!("\"{path}\" is not a file in the skill."))?;+ read_bounded(&target, MAX_FILE_BYTES)+}++/// The skills folders a document's folder sees, nearest first: `.agents/skills` and+/// `.claude/skills` in it and each folder above, up to the repository root (the folder with+/// `.git`). The walk stops below `home`, whose own folders are read as the user's skills, and+/// at the file system's root.+pub fn project_skill_roots(dir: &Path, home: Option<&Path>) -> Vec<PathBuf> {+ let mut roots = Vec::new();+ if !dir.is_absolute() {+ return roots;+ }+ for folder in dir.ancestors() {+ if home.is_some_and(|home| folder == home) || folder.parent().is_none() {+ break;+ }+ for agent in [".agents", ".claude"] {+ let root = folder.join(agent).join("skills");+ if root.is_dir() {+ roots.push(root);+ }+ }+ if folder.join(".git").exists() {+ break;+ }+ }+ roots+}++#[tauri::command]+pub async fn project_skill_folders(dir: PathBuf) -> Result<Vec<PathBuf>, String> {+ tauri::async_runtime::spawn_blocking(move || {+ project_skill_roots(&dir, std::env::home_dir().as_deref())+ })+ .await+ .map_err(|_| "Could not look for skills folders.".to_owned())+}++#[tauri::command]+pub async fn skill_folders(root: PathBuf) -> Result<Vec<SkillFolder>, String> {+ tauri::async_runtime::spawn_blocking(move || read_skill_folders(&root))+ .await+ .map_err(|_| "Could not read the skills folder.".to_owned())+}++#[tauri::command]+pub async fn skill_folder_file(dir: PathBuf, path: String) -> Result<String, String> {+ tauri::async_runtime::spawn_blocking(move || read_skill_folder_file(&dir, &path))+ .await+ .map_err(|_| "Could not read the skill file.".to_owned())?+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};++ static NEXT: AtomicUsize = AtomicUsize::new(0);++ struct Scratch(PathBuf);++ impl Scratch {+ fn new() -> Self {+ let id = NEXT.fetch_add(1, Ordering::Relaxed);+ let base =+ std::env::temp_dir().join(format!("openpencil-skills-{}-{id}", std::process::id()));+ let _ = fs::remove_dir_all(&base);+ let dir = base.join(".agents").join("skills");+ fs::create_dir_all(&dir).unwrap();+ Self(dir)+ }++ fn write(&self, path: &str, text: &str) {+ let path = self.0.join(path);+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, text).unwrap();+ }+ }++ impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = self+ .0+ .parent()+ .and_then(Path::parent)+ .map(fs::remove_dir_all);+ }+ }++ #[test]+ fn lists_folders_with_a_skill_file_and_their_other_files() {+ let root = Scratch::new();+ root.write("grid/SKILL.md", "---\nname: grid\n---\n");+ root.write("grid/references/spacing.md", "8");+ root.write("grid/.hidden", "");+ root.write("grid/node_modules/x/index.js", "");+ root.write("notes/README.md", "not a skill");+ root.write(".cache/SKILL.md", "hidden");++ let folders = read_skill_folders(&root.0);+ assert_eq!(folders.len(), 1);+ assert_eq!(folders[0].name, "grid");+ assert_eq!(folders[0].skill_file, "---\nname: grid\n---\n");+ assert_eq!(folders[0].files, vec!["references/spacing.md"]);+ }++ #[test]+ fn a_missing_root_has_no_skills() {+ assert!(read_skill_folders(Path::new("/nonexistent/.agents/skills")).is_empty());+ }++ #[test]+ fn reads_only_skills_folders() {+ let root = Scratch::new();+ root.write("grid/SKILL.md", "---\nname: grid\n---\n");+ root.write("grid/notes.md", "8");+ let other = root.0.parent().unwrap().join("other");+ fs::create_dir_all(other.join("grid")).unwrap();+ fs::write(other.join("grid/SKILL.md"), "").unwrap();+ fs::write(other.join("grid/notes.md"), "").unwrap();++ assert!(read_skill_folders(&other).is_empty());+ assert!(read_skill_folder_file(&other.join("grid"), "notes.md").is_err());+ assert_eq!(read_skill_folders(&root.0).len(), 1);+ }++ #[cfg(unix)]+ #[test]+ fn follows_a_symlinked_skill() {+ let root = Scratch::new();+ let checkout = Scratch::new();+ checkout.write("SKILL.md", "---\nname: linked\n---\n");+ std::os::unix::fs::symlink(&checkout.0, root.0.join("linked")).unwrap();+ let folders = read_skill_folders(&root.0);+ assert_eq!(+ folders.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),+ vec!["linked"]+ );+ }++ #[test]+ fn reads_only_files_inside_the_skill() {+ let root = Scratch::new();+ root.write("grid/SKILL.md", "");+ root.write("grid/references/spacing.md", "8");+ root.write("secret.txt", "no");+ let dir = root.0.join("grid");++ assert_eq!(+ read_skill_folder_file(&dir, "references/spacing.md"),+ Ok("8".to_owned())+ );+ assert!(read_skill_folder_file(&dir, "../secret.txt").is_err());+ assert!(read_skill_folder_file(&dir, "/etc/hosts").is_err());+ assert!(read_skill_folder_file(&dir, ".hidden").is_err());+ assert!(read_skill_folder_file(&root.0, "secret.txt").is_err());+ }++ #[test]+ fn finds_skills_folders_up_to_the_repository_root() {+ let scratch = Scratch::new();+ let base = scratch.0.parent().unwrap().parent().unwrap().to_path_buf();+ let repo = base.join("repo");+ let docs = repo.join("design").join("docs");+ fs::create_dir_all(&docs).unwrap();+ fs::create_dir_all(repo.join(".git")).unwrap();+ fs::create_dir_all(repo.join(".claude/skills")).unwrap();+ fs::create_dir_all(repo.join("design/.agents/skills")).unwrap();++ assert_eq!(+ project_skill_roots(&docs, None),+ vec![+ repo.join("design/.agents/skills"),+ repo.join(".claude/skills")+ ]+ );+ // The walk stops at the repository: `base` has a skills folder from `Scratch`.+ assert!(!project_skill_roots(&docs, None).contains(&scratch.0));+ // Home's own folders are the user's skills, not the document's.+ assert_eq!(+ project_skill_roots(&docs, Some(&repo.join("design"))),+ Vec::<PathBuf>::new()+ );+ assert!(project_skill_roots(Path::new("relative/dir"), None).is_empty());+ }++ #[cfg(unix)]+ #[test]+ fn neither_listing_nor_skill_file_follows_a_symlink_out() {+ let root = Scratch::new();+ let outside = Scratch::new();+ outside.write("notes/secret.md", "no");+ outside.write("stolen.md", "---\nname: stolen\ndescription: x\n---\n");+ root.write("grid/SKILL.md", "---\nname: grid\n---\n");+ std::os::unix::fs::symlink(outside.0.join("notes"), root.0.join("grid/notes")).unwrap();+ fs::create_dir_all(root.0.join("stolen")).unwrap();+ std::os::unix::fs::symlink(outside.0.join("stolen.md"), root.0.join("stolen/SKILL.md"))+ .unwrap();++ let folders = read_skill_folders(&root.0);+ assert_eq!(+ folders.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),+ vec!["grid"]+ );+ assert!(folders[0].files.is_empty());+ }++ #[cfg(unix)]+ #[test]+ fn a_fifo_is_not_read() {+ let root = Scratch::new();+ fs::create_dir_all(root.0.join("pipe")).unwrap();+ let status = std::process::Command::new("mkfifo")+ .arg(root.0.join("pipe/SKILL.md"))+ .status()+ .unwrap();+ assert!(status.success());+ assert!(read_skill_folders(&root.0).is_empty());+ }++ #[cfg(unix)]+ #[test]+ fn a_symlink_cannot_lead_out_of_the_skill() {+ let root = Scratch::new();+ root.write("grid/SKILL.md", "");+ root.write("secret.txt", "no");+ let dir = root.0.join("grid");+ std::os::unix::fs::symlink(root.0.join("secret.txt"), dir.join("escape.md")).unwrap();+ assert!(read_skill_folder_file(&dir, "escape.md").is_err());+ }+}diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex 4c6a2d76d..c1632bb4a 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -77,6 +77,9 @@ pub fn run() {credential_store_availability,credential_write,agents::mcp::mcp_lookup,+ agents::skills::skill_folders,+ agents::skills::project_skill_folders,+ agents::skills::skill_folder_file,#[cfg(feature = "native-test")]launch::native_test_open_deep_link,system::opener::open_external_url,diff --git a/package.json b/package.jsonindex 62963d06a..c77ec93a2 100644--- a/package.json+++ b/package.json@@ -219,6 +219,7 @@"vue-stream-markdown": "2.0.0-beta.5","y-indexeddb": "^9.0.12","y-protocols": "^1.0.7",+ "yaml": "^2.9.0","yjs": "^13.6.32","yoga-layout": "npm:@open-pencil/[email protected]","zod": "^4.6.5"diff --git a/packages/docs/de/programmable/ai-chat.md b/packages/docs/de/programmable/ai-chat.mdindex 2a57dbc7a..26610fd8d 100644--- a/packages/docs/de/programmable/ai-chat.md+++ b/packages/docs/de/programmable/ai-chat.md@@ -20,17 +20,17 @@ Mehrere Modelle können getrennt für Gestaltung, Prüfung, schnelle Aufgaben un### Anbieter-| Anbieter | Beispiele | Einrichtung |-|----------|-----------|-------------|-| **OpenRouter** | Claude, GPT, Gemini, DeepSeek, Qwen und weitere | API-Schlüssel von [openrouter.ai](https://openrouter.ai) |-| **Anthropic** | Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.1 und Claude Haiku 5.5 | API-Schlüssel von [console.anthropic.com](https://console.anthropic.com) |-| **OpenAI** | GPT-6.1 Sol, GPT-6 Astra und GPT-6 Luna | API-Schlüssel von [platform.openai.com](https://platform.openai.com) |-| **Google AI** | Gemini 3.8 Flash und Gemini 4 Argon | API-Schlüssel von [aistudio.google.dev](https://aistudio.google.dev) |-| **DeepSeek** | DeepSeek Flash und DeepSeek V4 Pro | API-Schlüssel von [platform.deepseek.com](https://platform.deepseek.com/api_keys) |-| **Z.ai** | GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX und GLM-5V-Turbo | API-Schlüssel laut [Z.ai-Dokumentation](https://docs.z.ai/devpack/quick-start) |-| **MiniMax** | MiniMax-M3.1-Flash und MiniMax-M3 | API-Schlüssel von [platform.minimax.io](https://platform.minimax.io/user-center/basic-information/interface-key) |-| **OpenAI-kompatibel** | Endpunkt im OpenAI-API-Format | Eigene Basisadresse und Schlüssel |-| **Anthropic-kompatibel** | Endpunkt im Anthropic-API-Format | Eigene Basisadresse und Schlüssel |+| Anbieter | Beispiele | Einrichtung |+| ------------------------ | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |+| **OpenRouter** | Claude, GPT, Gemini, DeepSeek, Qwen und weitere | API-Schlüssel von [openrouter.ai](https://openrouter.ai) |+| **Anthropic** | Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.1 und Claude Haiku 5.5 | API-Schlüssel von [console.anthropic.com](https://console.anthropic.com) |+| **OpenAI** | GPT-6.1 Sol, GPT-6 Astra und GPT-6 Luna | API-Schlüssel von [platform.openai.com](https://platform.openai.com) |+| **Google AI** | Gemini 3.8 Flash und Gemini 4 Argon | API-Schlüssel von [aistudio.google.dev](https://aistudio.google.dev) |+| **DeepSeek** | DeepSeek Flash und DeepSeek V4 Pro | API-Schlüssel von [platform.deepseek.com](https://platform.deepseek.com/api_keys) |+| **Z.ai** | GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX und GLM-5V-Turbo | API-Schlüssel laut [Z.ai-Dokumentation](https://docs.z.ai/devpack/quick-start) |+| **MiniMax** | MiniMax-M3.1-Flash und MiniMax-M3 | API-Schlüssel von [platform.minimax.io](https://platform.minimax.io/user-center/basic-information/interface-key) |+| **OpenAI-kompatibel** | Endpunkt im OpenAI-API-Format | Eigene Basisadresse und Schlüssel |+| **Anthropic-kompatibel** | Endpunkt im Anthropic-API-Format | Eigene Basisadresse und Schlüssel |Anfragen gehen direkt an den Anbieter. Im Browser gelten dessen CORS-Regeln. Bereitstellungen unterscheiden sich darin, wie zuverlässig Werkzeugaufrufe gestreamt werden. Messergebnisse stehen unter [BYOK-Kompatibilität](/programmable/byok-provider-compatibility).@@ -44,6 +44,12 @@ Token werden im Anmeldedatenspeicher und erst beim Start einer ACP-Sitzung gelesDer Assistent verfügt über mehr als 90 Werkzeuge für Erstellung, Gestaltung, Anordnung, Komponenten, Variablen, Suche, Prüfung, Analyse, Export und Vektorbearbeitung.+## Skills++Skills sind Ordner mit einer `SKILL.md` im Format [Agent Skills](https://agentskills.io/specification): Anweisungen für eine Art von Arbeit, mit optionalen Referenzdateien. Die eingebaute KI sieht Name und Beschreibung jedes aktiven Skills und lädt seine Anweisungen, wenn eine Anfrage passt; Skripte in einem Skill laufen nicht.++Unter **Einstellungen → Skills** lädst du einen Skill als ZIP seines Ordners oder als `SKILL.md` hoch. In der Desktop-App kommen `~/.agents/skills` und `~/.claude/skills` dazu sowie die Ordner `.agents/skills` und `.claude/skills` neben dem geöffneten Dokument, die erst nach **Ordner vertrauen** gelten. Starte eine Nachricht mit `/skill:name`, um einen Skill auszuführen.+## Visuelle PrüfungNach Änderungen kann der Assistent das Ergebnis mit `export_image` rendern und mit der Anfrage vergleichen. Dadurch werden Anordnungsfehler, fehlende Elemente und abweichende Farben sichtbar. `diff_visual`, standardmäßig aktiviert, vergleicht ein bearbeitetes Objekt mit einer Referenzkopie und liefert die geänderten Pixel und den betroffenen Bereich, sodass der Assistent prüfen kann, ob eine Änderung auf ihr Ziel beschränkt blieb.diff --git a/packages/docs/development/ai-chat.md b/packages/docs/development/ai-chat.mdindex cdb354bdc..f488c46a8 100644--- a/packages/docs/development/ai-chat.md+++ b/packages/docs/development/ai-chat.md@@ -10,6 +10,14 @@ How the built-in AI chat turns a message into edits, how a reply ends, and how wThe model comes from `createAIModelRuntime` (`src/app/ai/models/runtime.ts`), with the connection's saved key. An `openpencil` connection has no key: it names a workspace on the Home Cloud server, and its model talks to the AI service that server's discovery advertises, through `@/app/cloud/integration` (`src/app/cloud/ai/`). Each request carries a short-lived token Cloud signs for that workspace, replaced shortly before it expires and once more when the service refuses it (`cloudAIFetch` in `packages/cloud/src/client/ai.ts`), so the service never sees the person's Cloud session.+## Skills++Skills are SKILL.md folders in the [Agent Skills](https://agentskills.io/specification) format (`src/app/ai/skills/`). The direct chat lists the enabled skills the model may load, by name and description, after its instructions (`skillCatalog`), and offers two tools while any skill is enabled: `load_skill` returns a skill's instructions and the files in its folder, and `read_skill_file` reads one of those files, never a path the skill does not list. Scripts in a skill do not run in this chat. The listing is part of the instructions a saved trace records, so a rebuilt request matches the one sent.++Every message first reads the skills again (`library.ts`): those uploaded in Settings › Skills, kept in IndexedDB as their SKILL.md and text files (`sources/uploaded.ts`), then, on the desktop, `~/.agents/skills` and `~/.claude/skills`, through the shell's `skill_folders` and `skill_folder_file` commands (`desktop/src/agents/skills.rs`). Those read only `.agents/skills` and `.claude/skills` folders, follow symlinked skills, and read nothing outside a folder with a SKILL.md. On the desktop the library also reads the `.agents/skills` and `.claude/skills` folders from the open document's folder up to its repository root, stopping below the home folder (`sources/project.ts`, `project_skill_folders`); their skills come after uploads and before the user's own, nearest folder first, and stay off until the user trusts that folder in Settings › Skills, since a skill is instructions the model follows. Uploads are on from the start; the coding agents' folders hold mostly coding workflows, so they start off, and the AI setup's review step offers their skills one by one (`AISetupSkills`, `withPickedSkills`). Settings › Skills switches sources and skills either way (`preferences.ts`, `settings/use.ts`); of two skills with the same name, the first one switched on is offered, so an upload wins over a folder. A frontmatter that is not valid YAML, usually a description with an unquoted `: `, is read line by line with a warning rather than dropped.++A message that starts with `/skill:name` runs that skill, as in pi: the request carries the skill's instructions in a note after the text (`appendSkillContext`), which the transcript leaves out, so every agent follows it without looking it up. Pi gets the enabled skills the model may load, with their text files, in its session configuration (`skills/harness.ts`), and its harness writes them into Pi's own skills folder; files past a 384 KB budget, counted in UTF-8 bytes, are left out so the configuration stays inside the harness protocol's line limit. ACP agents keep their own skills.+## A run`transports/tool-loop.ts` starts a run (`reply/run.ts`) when the message is sent, before the model is reached, so a Stop at any point ends a run that exists. A `Run` belongs to one reply and holds:diff --git a/packages/docs/es/programmable/ai-chat.md b/packages/docs/es/programmable/ai-chat.mdindex 98b8de277..e6fcedf79 100644--- a/packages/docs/es/programmable/ai-chat.md+++ b/packages/docs/es/programmable/ai-chat.md@@ -33,6 +33,12 @@ El token se guarda en el almacén seguro de credenciales, no en los ajustes ordiLas herramientas cubren lectura, creación, modificación, estructura, variables, vectores, análisis, descripción, generación de código e imágenes de stock. Cada llamada actúa sobre el editor activo y participa en su historial de deshacer cuando corresponde.+## Habilidades++Las habilidades son carpetas con un `SKILL.md` en el formato [Agent Skills](https://agentskills.io/specification): instrucciones para un tipo de trabajo, con archivos de referencia opcionales. La IA integrada ve el nombre y la descripción de cada habilidad activa y carga sus instrucciones cuando una solicitud coincide; los scripts de una habilidad no se ejecutan.++En **Ajustes → Habilidades** sube una habilidad como ZIP de su carpeta o como `SKILL.md`. En la app de escritorio también se leen `~/.agents/skills` y `~/.claude/skills`, y las carpetas `.agents/skills` y `.claude/skills` junto al documento abierto, que solo se usan tras **Confiar en la carpeta**. Empieza un mensaje con `/skill:nombre` para ejecutar una habilidad.+## Verificación visualEl asistente puede comprobar su trabajo visualmente. Con `export_image` activada, captura una imagen tras crear o modificar diseños y la compara con lo que se pidió. `diff_visual`, activada por defecto, compara un objeto editado con una copia de referencia y devuelve los píxeles y la región que cambiaron, de modo que el asistente puede confirmar que la edición se limitó a su objetivo.diff --git a/packages/docs/fr/programmable/ai-chat.md b/packages/docs/fr/programmable/ai-chat.mdindex 7a6273eda..ed0f1e8e4 100644--- a/packages/docs/fr/programmable/ai-chat.md+++ b/packages/docs/fr/programmable/ai-chat.md@@ -33,6 +33,12 @@ Le jeton est conservé dans le stockage sécurisé des identifiants, pas dans leLes outils couvrent lecture, création, modification, structure, variables, vecteurs, analyse, description, génération de code et images de stock. L’inspection comprend `get_jsx` pour la vue JSX aller-retour, `diff_create` et `diff_jsx` pour les différences structurelles, `diff_visual` pour les différences de pixels et `describe` pour le rôle sémantique et la détection des problèmes de design. Chaque appel agit sur l’éditeur actif et participe à l’historique d’annulation lorsque cela s’applique.+## Compétences++Les compétences sont des dossiers contenant un `SKILL.md` au format [Agent Skills](https://agentskills.io/specification) : des instructions pour un type de travail, avec des fichiers de référence facultatifs. L’IA intégrée voit le nom et la description de chaque compétence active et charge ses instructions quand une demande correspond ; les scripts d’une compétence ne s’exécutent pas.++Dans **Réglages → Compétences**, importez une compétence sous forme de ZIP de son dossier ou de `SKILL.md`. Dans l’application de bureau, `~/.agents/skills` et `~/.claude/skills` sont aussi lus, ainsi que les dossiers `.agents/skills` et `.claude/skills` à côté du document ouvert, utilisés seulement après **Faire confiance au dossier**. Commencez un message par `/skill:nom` pour lancer une compétence.+## Vérification visuelleL’assistant peut vérifier visuellement son travail. Lorsque `export_image` est activé, il peut capturer une image après avoir créé ou modifié des designs et comparer le résultat à la demande initiale. Cela permet de repérer les problèmes de disposition, les éléments manquants et les écarts de couleur qu’une réponse purement textuelle laisserait passer. `diff_visual`, activé par défaut, compare un objet modifié à une copie de référence et renvoie les pixels et la zone modifiés ; l’assistant peut ainsi confirmer qu’une modification est restée dans sa cible.diff --git a/packages/docs/it/programmable/ai-chat.md b/packages/docs/it/programmable/ai-chat.mdindex 2135797ed..e6bfb7f13 100644--- a/packages/docs/it/programmable/ai-chat.md+++ b/packages/docs/it/programmable/ai-chat.md@@ -35,6 +35,12 @@ Gli strumenti coprono lettura, creazione, modifica, struttura, variabili, vettorPer l’ispezione, `get_jsx` offre la vista JSX di andata e ritorno, `diff_create` e `diff_jsx` i confronti strutturali, `diff_visual` i confronti pixel per pixel e `describe` il ruolo semantico e il rilevamento dei problemi di design.+## Skill++Le skill sono cartelle con un `SKILL.md` nel formato [Agent Skills](https://agentskills.io/specification): istruzioni per un tipo di lavoro, con file di riferimento facoltativi. L’IA integrata vede nome e descrizione di ogni skill attiva e ne carica le istruzioni quando una richiesta corrisponde; gli script di una skill non vengono eseguiti.++In **Impostazioni → Skill** carica una skill come ZIP della sua cartella o come `SKILL.md`. Nell’app desktop vengono lette anche `~/.agents/skills` e `~/.claude/skills`, e le cartelle `.agents/skills` e `.claude/skills` accanto al documento aperto, usate solo dopo **Fidati della cartella**. Inizia un messaggio con `/skill:nome` per eseguire una skill.+## Verifica visivaL’assistente può verificare visivamente il proprio lavoro. Con `export_image` abilitato, cattura un’immagine dopo aver creato o modificato un design e controlla il risultato rispetto alla richiesta, individuando problemi di disposizione, elementi mancanti e colori sbagliati che una risposta solo testuale non rileverebbe. `diff_visual`, abilitato per impostazione predefinita, confronta un oggetto modificato con una copia di riferimento e restituisce i pixel e l’area cambiati, così l’assistente può confermare che la modifica sia rimasta nel bersaglio previsto.diff --git a/packages/docs/pl/programmable/ai-chat.md b/packages/docs/pl/programmable/ai-chat.mdindex 42e65afaf..c5ba48dcd 100644--- a/packages/docs/pl/programmable/ai-chat.md+++ b/packages/docs/pl/programmable/ai-chat.md@@ -20,17 +20,17 @@ Możesz utworzyć kilka modeli i osobno przypisać je do projektowania, przeglą### Dostawcy-| Dostawca | Modele | Konfiguracja |-|----------|--------|--------------|-| **OpenRouter** | Claude, GPT, Gemini, DeepSeek, Qwen i inne | Klucz API z [openrouter.ai](https://openrouter.ai) |-| **Anthropic** | Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.1, Claude Haiku 5.5 | Klucz API z [console.anthropic.com](https://console.anthropic.com) |-| **OpenAI** | GPT-6.1 Sol, GPT-6 Astra, GPT-6 Luna | Klucz API z [platform.openai.com](https://platform.openai.com) |-| **Google AI** | Gemini 3.8 Flash, Gemini 4 Argon | Klucz API z [aistudio.google.dev](https://aistudio.google.dev) |-| **DeepSeek** | DeepSeek Flash, DeepSeek V4 Pro | Klucz API z [platform.deepseek.com](https://platform.deepseek.com/api_keys) |-| **Z.ai** | GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX, GLM-5V-Turbo | Klucz API zgodnie z [dokumentacją Z.ai](https://docs.z.ai/devpack/quick-start) |-| **MiniMax** | MiniMax-M3.1-Flash, MiniMax-M3 | Klucz API z [platform.minimax.io](https://platform.minimax.io/user-center/basic-information/interface-key) |-| **Zgodny z OpenAI** | Dowolny punkt końcowy w formacie OpenAI API | Własny adres bazowy i klucz; wybór Completions API lub Responses API |-| **Zgodny z Anthropic** | Dowolny punkt końcowy w formacie Anthropic API | Własny adres bazowy i klucz |+| Dostawca | Modele | Konfiguracja |+| ---------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| **OpenRouter** | Claude, GPT, Gemini, DeepSeek, Qwen i inne | Klucz API z [openrouter.ai](https://openrouter.ai) |+| **Anthropic** | Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.1, Claude Haiku 5.5 | Klucz API z [console.anthropic.com](https://console.anthropic.com) |+| **OpenAI** | GPT-6.1 Sol, GPT-6 Astra, GPT-6 Luna | Klucz API z [platform.openai.com](https://platform.openai.com) |+| **Google AI** | Gemini 3.8 Flash, Gemini 4 Argon | Klucz API z [aistudio.google.dev](https://aistudio.google.dev) |+| **DeepSeek** | DeepSeek Flash, DeepSeek V4 Pro | Klucz API z [platform.deepseek.com](https://platform.deepseek.com/api_keys) |+| **Z.ai** | GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX, GLM-5V-Turbo | Klucz API zgodnie z [dokumentacją Z.ai](https://docs.z.ai/devpack/quick-start) |+| **MiniMax** | MiniMax-M3.1-Flash, MiniMax-M3 | Klucz API z [platform.minimax.io](https://platform.minimax.io/user-center/basic-information/interface-key) |+| **Zgodny z OpenAI** | Dowolny punkt końcowy w formacie OpenAI API | Własny adres bazowy i klucz; wybór Completions API lub Responses API |+| **Zgodny z Anthropic** | Dowolny punkt końcowy w formacie Anthropic API | Własny adres bazowy i klucz |OpenPencil nie wymaga osobnego serwera ani subskrypcji: żądania są wysyłane bezpośrednio do dostawcy. W przeglądarce podlegają jego zasadom CORS. Poszczególne wdrożenia modeli różnią się niezawodnością przesyłania wywołań narzędzi. Wyniki pomiarów znajdują się na stronie [Zgodność dostawców i modeli BYOK](/programmable/byok-provider-compatibility).@@ -46,6 +46,12 @@ Zdalny serwer musi używać HTTPS. W lokalnym środowisku programistycznym dozwoAsystent korzysta z ponad 90 narzędzi do tworzenia, stylizowania, układu, komponentów, zmiennych, wyszukiwania, inspekcji, analizy, eksportu i operacji wektorowych. Do inspekcji należą `get_jsx` (widok JSX w obie strony), `diff_create` i `diff_jsx` (różnice strukturalne), `diff_visual` (różnice pikseli) oraz `describe` (rola semantyczna i wykrywanie problemów projektowych).+## Umiejętności++Umiejętności to foldery z plikiem `SKILL.md` w formacie [Agent Skills](https://agentskills.io/specification): instrukcje do określonego rodzaju pracy z opcjonalnymi plikami pomocniczymi. Wbudowane AI widzi nazwę i opis każdej włączonej umiejętności i wczytuje jej instrukcje, gdy prośba pasuje; skrypty z umiejętności nie są uruchamiane.++W **Ustawienia → Umiejętności** prześlij umiejętność jako ZIP jej folderu lub jako `SKILL.md`. W aplikacji desktopowej odczytywane są też `~/.agents/skills` i `~/.claude/skills` oraz foldery `.agents/skills` i `.claude/skills` obok otwartego dokumentu, używane dopiero po **Zaufaj folderowi**. Zacznij wiadomość od `/skill:nazwa`, aby uruchomić umiejętność.+## Kontrola wizualnaPo utworzeniu lub zmianie projektu asystent może wywołać `export_image`, uzyskać obraz wyniku i porównać go z pierwotnym poleceniem. Pozwala to wykryć problemy z układem, brakujące elementy i nieprawidłowe kolory. Domyślnie włączone `diff_visual` porównuje zmieniony obiekt z kopią wzorcową i zwraca zmienione piksele oraz obszar, dzięki czemu asystent może sprawdzić, że zmiana nie wyszła poza cel.diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.mdindex a090ed4a6..01d88ccfd 100644--- a/packages/docs/programmable/ai-chat.md+++ b/packages/docs/programmable/ai-chat.md@@ -36,6 +36,20 @@ The **Local MCP** segment has independent settings for clients connected to OpenTool toggles control which tools are offered, not which operations scripts may perform. An enabled `eval` or other script-capable tool can perform design operations whose dedicated tools are disabled; these switches are not a sandbox.+## Skills++Skills are folders with a `SKILL.md` in the [Agent Skills](https://agentskills.io/specification) format: instructions for a kind of work, with optional reference files. The built-in AI sees each enabled skill's name and description and loads its instructions when a request matches. It can read the skill's files, but scripts in a skill do not run.++Open **Settings → Skills** to see where skills come from:++- **Uploaded**: upload a ZIP of a skill's folder or a single `SKILL.md`. Uploads stay in OpenPencil and work in the browser too.+- **Next to this document** (desktop): `.agents/skills` and `.claude/skills` folders from the open document's folder up to its repository. They stay off until you choose **Trust folder**, because a skill gives the AI instructions it follows.+- **Shared agent skills** and **Claude Code skills** (desktop): `~/.agents/skills` and `~/.claude/skills`, where other coding agents install skills. Most of those are coding workflows, so these folders start off; the review step of the AI setup lists their skills for you to pick the ones that help with design.++Uploads are on as soon as you add them, and any folder or skill can be switched on or off. Open a skill to switch it, read its instructions, see its files, or check warnings about how it departs from the specification. When two skills share a name, the first in that order is used.++To run a skill yourself, start a message with `/skill:name`. Pi gets the enabled skills as its own. ACP agents such as Claude Code and Codex load their own skills.+## Saved ConversationsUse **Conversation history** to return to a saved chat, start a **New chat**, or rename or delete a conversation. History and attachment previews are stored locally; **All chats** lets you browse transcripts from other documents.@@ -90,11 +104,11 @@ The assistant can verify its work visually. With `export_image`, on by default,## Stopping a reply-**Stop** ends a reply at once. A tool call already running finishes, and its edit counts as part of the reply; calls still waiting for their turn change nothing. The reply is marked *Stopped*, its reasoning and any unfinished calls stop showing as running, and your next message tells the assistant whether those calls changed the document.+**Stop** ends a reply at once. A tool call already running finishes, and its edit counts as part of the reply; calls still waiting for their turn change nothing. The reply is marked _Stopped_, its reasoning and any unfinished calls stop showing as running, and your next message tells the assistant whether those calls changed the document.## Undoing the assistant's edits-Each tool call that changes the document is one step in Edit → Undo. Undoing it with <kbd>⌘</kbd><kbd>Z</kbd> marks the call *Undone* in the chat. A reply with only some edits undone says how many; one with all of them undone is dimmed and marked *Changes reverted*. Redo removes the marks. The marks are saved with the conversation.+Each tool call that changes the document is one step in Edit → Undo. Undoing it with <kbd>⌘</kbd><kbd>Z</kbd> marks the call _Undone_ in the chat. A reply with only some edits undone says how many; one with all of them undone is dimmed and marked _Changes reverted_. Redo removes the marks. The marks are saved with the conversation.**Revert changes** on a reply undoes its edits while nothing has been edited since, and **Restore changes** brings undone edits back while Redo still can. **Regenerate** and editing your last message undo the replaced reply's edits first when they can.diff --git a/packages/docs/ru/programmable/ai-chat.md b/packages/docs/ru/programmable/ai-chat.mdindex a05c744f4..7f1ecaf01 100644--- a/packages/docs/ru/programmable/ai-chat.md+++ b/packages/docs/ru/programmable/ai-chat.md@@ -20,17 +20,17 @@ description: Встроенный помощник с более чем 90 ин### Поставщики-| Поставщик | Модели | Настройка |-|-----------|--------|-----------|-| **OpenRouter** | Claude, GPT, Gemini, DeepSeek, Qwen и другие | Ключ API с [openrouter.ai](https://openrouter.ai) |-| **Anthropic** | Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.1, Claude Haiku 5.5 | Ключ API с [console.anthropic.com](https://console.anthropic.com) |-| **OpenAI** | GPT-6.1 Sol, GPT-6 Astra, GPT-6 Luna | Ключ API с [platform.openai.com](https://platform.openai.com) |-| **Google AI** | Gemini 3.8 Flash, Gemini 4 Argon | Ключ API с [aistudio.google.dev](https://aistudio.google.dev) |-| **DeepSeek** | DeepSeek Flash, DeepSeek V4 Pro | Ключ API с [platform.deepseek.com](https://platform.deepseek.com/api_keys) |-| **Z.ai** | GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX, GLM-5V-Turbo | Ключ API из [документации Z.ai](https://docs.z.ai/devpack/quick-start) |-| **MiniMax** | MiniMax-M3.1-Flash, MiniMax-M3 | Ключ API с [platform.minimax.io](https://platform.minimax.io/user-center/basic-information/interface-key) |-| **Совместимый с OpenAI** | Любая конечная точка в формате OpenAI API | Собственные базовый URL и ключ; можно выбрать Completions API или Responses API |-| **Совместимый с Anthropic** | Любая конечная точка в формате Anthropic API | Собственные базовый URL и ключ |+| Поставщик | Модели | Настройка |+| --------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |+| **OpenRouter** | Claude, GPT, Gemini, DeepSeek, Qwen и другие | Ключ API с [openrouter.ai](https://openrouter.ai) |+| **Anthropic** | Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.1, Claude Haiku 5.5 | Ключ API с [console.anthropic.com](https://console.anthropic.com) |+| **OpenAI** | GPT-6.1 Sol, GPT-6 Astra, GPT-6 Luna | Ключ API с [platform.openai.com](https://platform.openai.com) |+| **Google AI** | Gemini 3.8 Flash, Gemini 4 Argon | Ключ API с [aistudio.google.dev](https://aistudio.google.dev) |+| **DeepSeek** | DeepSeek Flash, DeepSeek V4 Pro | Ключ API с [platform.deepseek.com](https://platform.deepseek.com/api_keys) |+| **Z.ai** | GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX, GLM-5V-Turbo | Ключ API из [документации Z.ai](https://docs.z.ai/devpack/quick-start) |+| **MiniMax** | MiniMax-M3.1-Flash, MiniMax-M3 | Ключ API с [platform.minimax.io](https://platform.minimax.io/user-center/basic-information/interface-key) |+| **Совместимый с OpenAI** | Любая конечная точка в формате OpenAI API | Собственные базовый URL и ключ; можно выбрать Completions API или Responses API |+| **Совместимый с Anthropic** | Любая конечная точка в формате Anthropic API | Собственные базовый URL и ключ |Отдельный сервер и подписка OpenPencil не требуются: запросы отправляются поставщику напрямую с вашим ключом. В браузере действуют правила CORS поставщика. Разные развёртывания моделей также по-разному поддерживают потоковые вызовы инструментов. Результаты проверок и инструкции находятся в разделе [Совместимость поставщиков и моделей BYOK](/programmable/byok-provider-compatibility).@@ -57,6 +57,12 @@ description: Встроенный помощник с более чем 90 ин- **Экспорт:** PNG, SVG и JSX с классами Tailwind; визуальная проверка через `export_image`.- **Векторы:** логические операции и изменение контуров.+## Навыки++Навыки — это папки с `SKILL.md` в формате [Agent Skills](https://agentskills.io/specification): инструкции для определённой работы с необязательными справочными файлами. Встроенный ИИ видит имя и описание каждого включённого навыка и загружает его инструкции, когда запрос подходит; скрипты из навыков не запускаются.++В разделе «Настройки → Навыки» загрузите навык как ZIP его папки или как `SKILL.md`. В настольном приложении также читаются `~/.agents/skills` и `~/.claude/skills`, а ещё папки `.agents/skills` и `.claude/skills` рядом с открытым документом — они используются только после «Доверять папке». Начните сообщение с `/skill:имя`, чтобы запустить навык.+## Визуальная проверкаПосле создания или изменения дизайна помощник может вызвать `export_image`, получить снимок результата и сопоставить его с исходным запросом. Так обнаруживаются проблемы компоновки, отсутствующие элементы и неверные цвета. Инструмент `diff_visual`, который включён по умолчанию, сравнивает изменённый объект с эталонной копией и возвращает изменившиеся пиксели и область, поэтому помощник может убедиться, что правка не вышла за пределы цели.diff --git a/packages/harness/src/backends/pi.ts b/packages/harness/src/backends/pi.tsindex 61ba74e30..f20455a6c 100644--- a/packages/harness/src/backends/pi.ts+++ b/packages/harness/src/backends/pi.ts@@ -147,6 +147,7 @@ export class PiHarnessBackend implements HarnessBackend {sandbox: createJustBashSandbox({ cwd: '/workspace' }),sandboxConfig: { workDir: 'workspace' },instructions: configuration.instructions ?? this.defaults.instructions,+ skills: configuration.skills ?? [],permissionMode: permissionMode ?? this.defaults.permissionMode ?? 'allow-edits'})const sessionOptions: {diff --git a/packages/harness/src/index.ts b/packages/harness/src/index.tsindex 885d3fe30..f951fd21e 100644--- a/packages/harness/src/index.ts+++ b/packages/harness/src/index.ts@@ -15,6 +15,7 @@ export {type HarnessSandboxID,type HarnessSessionConfiguration,type HarnessSidecarMessage,+ type HarnessSkill,type HarnessTurnEvent,type HarnessTurnUsage,type JSONValuediff --git a/packages/harness/src/protocol.ts b/packages/harness/src/protocol.tsindex a45adde2e..0198e0205 100644--- a/packages/harness/src/protocol.ts+++ b/packages/harness/src/protocol.ts@@ -14,6 +14,15 @@ export interface HarnessSessionConfiguration {settings?: Record<string, JSONValue>mcpServers?: Record<string, Record<string, JSONValue>>instructions?: string+ skills?: HarnessSkill[]+}++/** A skill the agent may load: its SKILL.md body and the text files beside it. */+export interface HarnessSkill {+ name: string+ description: string+ content: string+ files?: { path: string; content: string }[]}export interface HarnessProviderCapability {@@ -100,6 +109,36 @@ function parseJSONRecord(value: unknown, field: string): Record<string, JSONValu}}+function parseSkillFile(value: unknown, field: string): { path: string; content: string } {+ if (!isRecord(value) || typeof value.content !== 'string') {+ throw new Error(`Expected skill file at ${field}`)+ }+ return { path: requireString(value, 'path'), content: value.content }+}++function parseSkills(value: unknown): HarnessSkill[] | undefined {+ if (value === undefined) return undefined+ if (!Array.isArray(value)) throw new Error('Expected array at skills')+ return value.map((skill: unknown, index) => {+ const field = `skills[${index}]`+ if (!isRecord(skill) || typeof skill.content !== 'string') {+ throw new Error(`Expected skill at ${field}`)+ }+ const parsed: HarnessSkill = {+ name: requireString(skill, 'name'),+ description: requireString(skill, 'description'),+ content: skill.content+ }+ if (skill.files !== undefined) {+ if (!Array.isArray(skill.files)) throw new Error(`Expected array at ${field}.files`)+ parsed.files = skill.files.map((file: unknown, fileIndex) =>+ parseSkillFile(file, `${field}.files[${fileIndex}]`)+ )+ }+ return parsed+ })+}+function parseConfiguration(value: unknown): HarnessSessionConfiguration {if (!isRecord(value)) throw new Error('Expected Harness session configuration')if (!isAdapterID(value.adapter)) throw new Error('Unknown Harness adapter')@@ -116,6 +155,8 @@ function parseConfiguration(value: unknown): HarnessSessionConfiguration {configuration.mcpServers = mcpServers as Record<string, Record<string, JSONValue>>}if (typeof value.instructions === 'string') configuration.instructions = value.instructions+ const skills = parseSkills(value.skills)+ if (skills) configuration.skills = skillsreturn configuration}diff --git a/packages/harness/tests/protocol.test.ts b/packages/harness/tests/protocol.test.tsindex d9a4d578c..41b128cd1 100644--- a/packages/harness/tests/protocol.test.ts+++ b/packages/harness/tests/protocol.test.ts@@ -28,6 +28,31 @@ describe('harness sidecar protocol', () => {})})+ test('carries the skills a session may load, and rejects malformed ones', () => {+ const request = (skills: unknown) =>+ JSON.stringify({+ id: 'request-1',+ method: 'session.create',+ params: {+ sessionId: 'session-1',+ configuration: { adapter: 'pi', sandbox: 'just-bash', model: 'provider/model', skills }+ }+ })+ const grid = {+ name: 'grid',+ description: 'Lay out pages on an eight-point grid.',+ content: 'Snap frames to 8.',+ files: [{ path: 'references/spacing.md', content: '8' }]+ }+ expect(parseHarnessRequest(request([grid]))).toMatchObject({+ params: { configuration: { skills: [grid] } }+ })+ expect(() => parseHarnessRequest(request([{ name: 'grid' }]))).toThrow('skills[0]')+ expect(() => parseHarnessRequest(request([{ ...grid, files: [{ path: 'a.md' }] }]))).toThrow(+ 'skills[0].files[0]'+ )+ })+test('parses a turn request', () => {expect(parseHarnessRequest(diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex 6dcf62528..71771c46d 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "Falls es noch nicht installiert ist, führe Folgendes aus:","aiSetupAgentInstallSupported": "Installiere den unterstützten Adapter:","aiSetupMeteredNote": "OpenRouter bietet Modelle mehrerer Anbieter mit einem Konto und einem Schlüssel.",+ "aiSetupSkillsTitle": "Skills deiner Coding-Agenten",+ "aiSetupSkillsDescription": "Der Design-Chat kann Skills nutzen, die deine Coding-Agenten installiert haben. Die meisten sind Coding-Workflows, wähle also nur die, die beim Design helfen; unter Einstellungen › Skills lässt sich das später ändern.","aiSetupReviewTitle": "Einrichtung prüfen","aiSetupAgentModel": "Vom Agenten gewähltes Modell","aiSetupFinish": "Einrichtung abschließen",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "Der MCP-Server ist installiert, startet aber nicht. Starte OpenPencil neu und prüfe dann erneut.","aiSetupAgentLookupFailed": "Dieser Computer konnte nicht geprüft werden. Versuche es erneut.","chatAgentWorkingOn": "{agent} arbeitet an „{page}“",- "chatGoToPage": "Zur Seite"+ "chatGoToPage": "Zur Seite",+ "skillsUpload": "Skill hochladen",+ "skillsUploadedSource": "Hochgeladen",+ "skillsUploadedSourceDescription": "Skills, die der KI-Chat lädt, wenn eine Anfrage zu ihrer Beschreibung passt. Lade ein ZIP des Skill-Ordners oder eine SKILL.md hoch.",+ "skillsProjectSource": "Neben diesem Dokument",+ "skillsProjectSourceDescription": "Gelesen aus {folder}. Skills hier sind aus, bis du dem Ordner vertraust.",+ "skillsProjectSourceTrusted": "Gelesen aus {folder}, dem du vertraust.",+ "skillsTrustFolder": "Ordner vertrauen",+ "skillsStopTrusting": "Nicht mehr vertrauen",+ "skillsTrustTitle": "Diesem Ordner vertrauen?",+ "skillsTrustDescription": "Skills in {folder} geben dem KI-Chat Anweisungen, die er befolgt. Vertraue einem Ordner nur, wenn du weißt, woher seine Skills stammen.",+ "skillsFolderUntrusted": "Vertraue seinem Ordner, um diesen Skill zu verwenden.",+ "skillsAgentsSource": "Gemeinsame Agenten-Skills",+ "skillsAgentsSourceDescription": "Gelesen aus {folder}, wo pi, Codex, Gemini CLI, Cursor und andere Agenten Skills installieren.",+ "skillsClaudeSource": "Claude-Code-Skills",+ "skillsClaudeSourceDescription": "Gelesen aus {folder}.",+ "skillsNoUploads": "Noch keine hochgeladenen Skills.",+ "skillsNoneInFolder": "Keine Skills in diesem Ordner.",+ "skillsProblems": "Einige Ordner konnten nicht als Skills gelesen werden",+ "skillsUploadFailed": "Der Skill konnte nicht hochgeladen werden",+ "skillsUploadTooLarge": "Die Datei ist größer als 10 MB.",+ "skillsUploadNoSkill": "Das Archiv enthält keine SKILL.md.",+ "skillsUploadSeveral": "Das Archiv enthält mehr als einen Skill. Lade sie einzeln hoch.",+ "skillsUploadUnreadable": "Wähle ein ZIP-Archiv oder eine SKILL.md-Textdatei.",+ "skillsDelete": "Skill löschen",+ "skillsDeleteDescription": "„{name}“ wird aus OpenPencil entfernt.",+ "skillsLocation": "Speicherort",+ "skillsFiles": "Dateien",+ "skillsInstructions": "Anweisungen",+ "skillsWarnings": "Dieser Skill weicht von der Agent-Skills-Spezifikation ab",+ "skillsUseSource": "Skills aus diesem Ordner verwenden",+ "skillsUse": "Diesen Skill verwenden",+ "skillsUseDescription": "Der KI-Chat führt ihn auf und lädt seine Anweisungen, wenn eine Anfrage passt.",+ "skillsSourceOff": "Skills aus diesem Ordner sind ausgeschaltet.",+ "skillsNotUsed": "Nicht verwendet",+ "skillsNotTrusted": "Nicht vertraut",+ "skillsShadowed": "Stattdessen wird ein gleichnamiger Skill aus einer Quelle weiter oben verwendet.",+ "skillWarningPlainFrontmatter": "Das Frontmatter ist kein gültiges YAML und wurde deshalb Zeile für Zeile gelesen. Setze Werte mit „: “ in Anführungszeichen.",+ "skillWarningNameFromFolder": "Das Frontmatter hat keinen Namen, daher wird der Ordnername verwendet.",+ "skillWarningLongName": "Der Name ist länger als {max} Zeichen.",+ "skillWarningNameFormat": "Der Name sollte nur Kleinbuchstaben, Ziffern und einzelne Bindestriche enthalten.",+ "skillWarningNameMismatch": "Der Name stimmt nicht mit dem Ordnernamen überein.",+ "skillWarningLongDescription": "Die Beschreibung ist länger als {max} Zeichen.",+ "skillErrorNoFrontmatter": "SKILL.md beginnt nicht mit YAML-Frontmatter zwischen Zeilen mit ---.",+ "skillErrorInvalidFrontmatter": "Das Frontmatter der SKILL.md ist ungültig: {detail}",+ "skillErrorNoDescription": "Das Frontmatter der SKILL.md hat keine Beschreibung.",+ "skillErrorNoName": "Das Frontmatter der SKILL.md hat keinen Namen."}diff --git a/packages/vue/src/i18n/locales/de/settings.json b/packages/vue/src/i18n/locales/de/settings.jsonindex 6d40cd81f..ce4025a76 100644--- a/packages/vue/src/i18n/locales/de/settings.json+++ b/packages/vue/src/i18n/locales/de/settings.json@@ -32,6 +32,7 @@"media": "Medien","mcp": "MCP","toolAccess": "Werkzeugzugriff",+ "skills": "Skills","storage": "Speicher","cloud": "Cloud","fonts": "Schriften",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 8273c7d42..398174f3a 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "Si aún no está instalado, ejecuta:","aiSetupAgentInstallSupported": "Instala el adaptador compatible:","aiSetupMeteredNote": "OpenRouter te da modelos de varios proveedores con una sola cuenta y una sola clave.",+ "aiSetupSkillsTitle": "Habilidades de tus agentes de programación",+ "aiSetupSkillsDescription": "El chat de diseño puede usar habilidades que instalaron tus agentes de programación. La mayoría son flujos de programación, así que elige solo las que ayudan con el diseño; puedes cambiarlas en Ajustes › Habilidades.","aiSetupReviewTitle": "Revisa tu configuración","aiSetupAgentModel": "Modelo elegido por el agente","aiSetupFinish": "Terminar la configuración",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "El servidor MCP está instalado pero no se inició. Reinicia OpenPencil y vuelve a comprobar.","aiSetupAgentLookupFailed": "No se pudo comprobar este equipo. Vuelve a intentarlo.","chatAgentWorkingOn": "{agent} está trabajando en «{page}»",- "chatGoToPage": "Ir a la página"+ "chatGoToPage": "Ir a la página",+ "skillsUpload": "Subir habilidad",+ "skillsUploadedSource": "Subidas",+ "skillsUploadedSourceDescription": "Habilidades que el chat de IA carga cuando una solicitud coincide con su descripción. Sube un ZIP de la carpeta de la habilidad o un SKILL.md.",+ "skillsProjectSource": "Junto a este documento",+ "skillsProjectSourceDescription": "Se leen de {folder}. Las habilidades de aquí están desactivadas hasta que confíes en la carpeta.",+ "skillsProjectSourceTrusted": "Se leen de {folder}, en la que confías.",+ "skillsTrustFolder": "Confiar en la carpeta",+ "skillsStopTrusting": "Dejar de confiar",+ "skillsTrustTitle": "¿Confiar en esta carpeta?",+ "skillsTrustDescription": "Las habilidades de {folder} dan al chat de IA instrucciones que sigue. Confía en una carpeta solo si sabes de dónde vienen sus habilidades.",+ "skillsFolderUntrusted": "Confía en su carpeta para usar esta habilidad.",+ "skillsAgentsSource": "Habilidades compartidas de agentes",+ "skillsAgentsSourceDescription": "Se leen de {folder}, donde pi, Codex, Gemini CLI, Cursor y otros agentes instalan habilidades.",+ "skillsClaudeSource": "Habilidades de Claude Code",+ "skillsClaudeSourceDescription": "Se leen de {folder}.",+ "skillsNoUploads": "Aún no hay habilidades subidas.",+ "skillsNoneInFolder": "No hay habilidades en esta carpeta.",+ "skillsProblems": "Algunas carpetas no se pudieron leer como habilidades",+ "skillsUploadFailed": "No se pudo subir la habilidad",+ "skillsUploadTooLarge": "El archivo supera los 10 MB.",+ "skillsUploadNoSkill": "El archivo comprimido no contiene SKILL.md.",+ "skillsUploadSeveral": "El archivo comprimido contiene más de una habilidad. Súbelas de una en una.",+ "skillsUploadUnreadable": "Elige un archivo ZIP o un archivo de texto SKILL.md.",+ "skillsDelete": "Eliminar habilidad",+ "skillsDeleteDescription": "«{name}» se eliminará de OpenPencil.",+ "skillsLocation": "Ubicación",+ "skillsFiles": "Archivos",+ "skillsInstructions": "Instrucciones",+ "skillsWarnings": "Esta habilidad se aparta de la especificación Agent Skills",+ "skillsUseSource": "Usar las habilidades de esta carpeta",+ "skillsUse": "Usar esta habilidad",+ "skillsUseDescription": "El chat de IA la incluye en su lista y carga sus instrucciones cuando una solicitud coincide.",+ "skillsSourceOff": "Las habilidades de esta carpeta están desactivadas.",+ "skillsNotUsed": "No se usa",+ "skillsNotTrusted": "Sin confianza",+ "skillsShadowed": "Se usa en su lugar una habilidad con el mismo nombre de una fuente anterior.",+ "skillWarningPlainFrontmatter": "El frontmatter no es YAML válido, así que se leyó línea por línea. Pon entre comillas los valores que contengan «: ».",+ "skillWarningNameFromFolder": "El frontmatter no tiene nombre, así que se usa el nombre de la carpeta.",+ "skillWarningLongName": "El nombre tiene más de {max} caracteres.",+ "skillWarningNameFormat": "El nombre solo debería usar minúsculas, dígitos y guiones sueltos.",+ "skillWarningNameMismatch": "El nombre no coincide con el de la carpeta.",+ "skillWarningLongDescription": "La descripción tiene más de {max} caracteres.",+ "skillErrorNoFrontmatter": "SKILL.md no empieza con un frontmatter YAML entre líneas ---.",+ "skillErrorInvalidFrontmatter": "El frontmatter de SKILL.md no es válido: {detail}",+ "skillErrorNoDescription": "El frontmatter de SKILL.md no tiene descripción.",+ "skillErrorNoName": "El frontmatter de SKILL.md no tiene nombre."}diff --git a/packages/vue/src/i18n/locales/es/settings.json b/packages/vue/src/i18n/locales/es/settings.jsonindex 1a0eb2826..3597d8b01 100644--- a/packages/vue/src/i18n/locales/es/settings.json+++ b/packages/vue/src/i18n/locales/es/settings.json@@ -32,6 +32,7 @@"media": "Multimedia","mcp": "MCP","toolAccess": "Acceso a herramientas",+ "skills": "Habilidades","storage": "Almacenamiento","cloud": "Nube","fonts": "Fuentes",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 5dfa5344f..3b9b968c1 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "S’il n’est pas encore installé, exécutez :","aiSetupAgentInstallSupported": "Installez l’adaptateur pris en charge :","aiSetupMeteredNote": "OpenRouter donne accès aux modèles de plusieurs fournisseurs avec un seul compte et une seule clé.",+ "aiSetupSkillsTitle": "Compétences de vos agents de code",+ "aiSetupSkillsDescription": "Le chat de design peut utiliser les compétences installées par vos agents de code. La plupart sont des workflows de développement : choisissez seulement celles qui aident au design ; Réglages › Compétences permet de les changer ensuite.","aiSetupReviewTitle": "Vérifiez votre configuration","aiSetupAgentModel": "Modèle choisi par l’agent","aiSetupFinish": "Terminer la configuration",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "Le serveur MCP est installé mais n’a pas démarré. Redémarrez OpenPencil, puis vérifiez à nouveau.","aiSetupAgentLookupFailed": "Impossible de vérifier cet ordinateur. Réessayez.","chatAgentWorkingOn": "{agent} travaille sur « {page} »",- "chatGoToPage": "Aller à la page"+ "chatGoToPage": "Aller à la page",+ "skillsUpload": "Importer une compétence",+ "skillsUploadedSource": "Importées",+ "skillsUploadedSourceDescription": "Compétences que le chat IA charge quand une demande correspond à leur description. Importez un ZIP du dossier de la compétence ou un SKILL.md.",+ "skillsProjectSource": "À côté de ce document",+ "skillsProjectSourceDescription": "Lues depuis {folder}. Les compétences ici sont désactivées tant que vous ne faites pas confiance au dossier.",+ "skillsProjectSourceTrusted": "Lues depuis {folder}, auquel vous faites confiance.",+ "skillsTrustFolder": "Faire confiance au dossier",+ "skillsStopTrusting": "Ne plus faire confiance",+ "skillsTrustTitle": "Faire confiance à ce dossier ?",+ "skillsTrustDescription": "Les compétences de {folder} donnent au chat IA des instructions qu’il suit. Ne faites confiance à un dossier que si vous savez d’où viennent ses compétences.",+ "skillsFolderUntrusted": "Faites confiance à son dossier pour utiliser cette compétence.",+ "skillsAgentsSource": "Compétences partagées des agents",+ "skillsAgentsSourceDescription": "Lues depuis {folder}, où pi, Codex, Gemini CLI, Cursor et d’autres agents installent leurs compétences.",+ "skillsClaudeSource": "Compétences de Claude Code",+ "skillsClaudeSourceDescription": "Lues depuis {folder}.",+ "skillsNoUploads": "Aucune compétence importée pour l’instant.",+ "skillsNoneInFolder": "Aucune compétence dans ce dossier.",+ "skillsProblems": "Certains dossiers n’ont pas pu être lus comme des compétences",+ "skillsUploadFailed": "Impossible d’importer la compétence",+ "skillsUploadTooLarge": "Le fichier dépasse 10 Mo.",+ "skillsUploadNoSkill": "L’archive ne contient pas de SKILL.md.",+ "skillsUploadSeveral": "L’archive contient plusieurs compétences. Importez-les une par une.",+ "skillsUploadUnreadable": "Choisissez une archive ZIP ou un fichier texte SKILL.md.",+ "skillsDelete": "Supprimer la compétence",+ "skillsDeleteDescription": "« {name} » sera supprimée d’OpenPencil.",+ "skillsLocation": "Emplacement",+ "skillsFiles": "Fichiers",+ "skillsInstructions": "Instructions générales",+ "skillsWarnings": "Cette compétence s’écarte de la spécification Agent Skills",+ "skillsUseSource": "Utiliser les compétences de ce dossier",+ "skillsUse": "Utiliser cette compétence",+ "skillsUseDescription": "Le chat IA la liste et charge ses instructions quand une demande correspond.",+ "skillsSourceOff": "Les compétences de ce dossier sont désactivées.",+ "skillsNotUsed": "Non utilisée",+ "skillsNotTrusted": "Non approuvé",+ "skillsShadowed": "Une compétence du même nom provenant d’une source plus haut est utilisée à la place.",+ "skillWarningPlainFrontmatter": "Le frontmatter n’est pas du YAML valide ; il a donc été lu ligne par ligne. Mettez entre guillemets les valeurs qui contiennent « : ».",+ "skillWarningNameFromFolder": "Le frontmatter n’a pas de nom ; le nom du dossier est donc utilisé.",+ "skillWarningLongName": "Le nom dépasse {max} caractères.",+ "skillWarningNameFormat": "Le nom ne devrait contenir que des minuscules, des chiffres et des tirets simples.",+ "skillWarningNameMismatch": "Le nom ne correspond pas à celui du dossier.",+ "skillWarningLongDescription": "La description dépasse {max} caractères.",+ "skillErrorNoFrontmatter": "SKILL.md ne commence pas par un frontmatter YAML entre des lignes ---.",+ "skillErrorInvalidFrontmatter": "Le frontmatter de SKILL.md n’est pas valide : {detail}",+ "skillErrorNoDescription": "Le frontmatter de SKILL.md n’a pas de description.",+ "skillErrorNoName": "Le frontmatter de SKILL.md n’a pas de nom."}diff --git a/packages/vue/src/i18n/locales/fr/settings.json b/packages/vue/src/i18n/locales/fr/settings.jsonindex 28c80629f..ce59ddb62 100644--- a/packages/vue/src/i18n/locales/fr/settings.json+++ b/packages/vue/src/i18n/locales/fr/settings.json@@ -32,6 +32,7 @@"media": "Médias","mcp": "MCP","toolAccess": "Accès aux outils",+ "skills": "Compétences","storage": "Stockage","cloud": "Cloud","fonts": "Polices",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex cb5933812..3c8e780fc 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "Se non è ancora installato, esegui:","aiSetupAgentInstallSupported": "Installa l’adattatore supportato:","aiSetupMeteredNote": "OpenRouter offre modelli di più fornitori con un solo account e una sola chiave.",+ "aiSetupSkillsTitle": "Skill dei tuoi agenti di programmazione",+ "aiSetupSkillsDescription": "La chat di design può usare le skill installate dai tuoi agenti di programmazione. La maggior parte sono flussi di sviluppo, quindi scegli solo quelle utili al design; puoi cambiarle in Impostazioni › Skill.","aiSetupReviewTitle": "Controlla la configurazione","aiSetupAgentModel": "Modello scelto dall’agente","aiSetupFinish": "Completa la configurazione",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "Il server MCP è installato ma non si è avviato. Riavvia OpenPencil e controlla di nuovo.","aiSetupAgentLookupFailed": "Impossibile controllare questo computer. Riprova.","chatAgentWorkingOn": "{agent} sta lavorando su «{page}»",- "chatGoToPage": "Vai alla pagina"+ "chatGoToPage": "Vai alla pagina",+ "skillsUpload": "Carica competenza",+ "skillsUploadedSource": "Caricate",+ "skillsUploadedSourceDescription": "Skill che la chat IA carica quando una richiesta corrisponde alla loro descrizione. Carica uno ZIP della cartella della skill o un SKILL.md.",+ "skillsProjectSource": "Accanto a questo documento",+ "skillsProjectSourceDescription": "Lette da {folder}. Le skill qui sono disattivate finché non ti fidi della cartella.",+ "skillsProjectSourceTrusted": "Lette da {folder}, di cui ti fidi.",+ "skillsTrustFolder": "Fidati della cartella",+ "skillsStopTrusting": "Non fidarti più",+ "skillsTrustTitle": "Fidarti di questa cartella?",+ "skillsTrustDescription": "Le skill in {folder} danno alla chat IA istruzioni che segue. Fidati di una cartella solo se sai da dove vengono le sue skill.",+ "skillsFolderUntrusted": "Fidati della sua cartella per usare questa skill.",+ "skillsAgentsSource": "Competenze condivise degli agenti",+ "skillsAgentsSourceDescription": "Lette da {folder}, dove pi, Codex, Gemini CLI, Cursor e altri agenti installano le competenze.",+ "skillsClaudeSource": "Competenze di Claude Code",+ "skillsClaudeSourceDescription": "Lette da {folder}.",+ "skillsNoUploads": "Nessuna competenza caricata.",+ "skillsNoneInFolder": "Nessuna competenza in questa cartella.",+ "skillsProblems": "Alcune cartelle non sono state lette come competenze",+ "skillsUploadFailed": "Impossibile caricare la competenza",+ "skillsUploadTooLarge": "Il file supera i 10 MB.",+ "skillsUploadNoSkill": "L’archivio non contiene un SKILL.md.",+ "skillsUploadSeveral": "L’archivio contiene più di una competenza. Caricale una alla volta.",+ "skillsUploadUnreadable": "Scegli un archivio ZIP o un file di testo SKILL.md.",+ "skillsDelete": "Elimina competenza",+ "skillsDeleteDescription": "«{name}» verrà rimossa da OpenPencil.",+ "skillsLocation": "Posizione",+ "skillsFiles": "File",+ "skillsInstructions": "Istruzioni",+ "skillsWarnings": "Questa competenza si discosta dalla specifica Agent Skills",+ "skillsUseSource": "Usa le skill di questa cartella",+ "skillsUse": "Usa questa skill",+ "skillsUseDescription": "La chat IA la elenca e ne carica le istruzioni quando una richiesta corrisponde.",+ "skillsSourceOff": "Le skill di questa cartella sono disattivate.",+ "skillsNotUsed": "Non usata",+ "skillsNotTrusted": "Non attendibile",+ "skillsShadowed": "Al suo posto viene usata una skill con lo stesso nome da una fonte più in alto.",+ "skillWarningPlainFrontmatter": "Il frontmatter non è YAML valido, quindi è stato letto riga per riga. Metti tra virgolette i valori che contengono «: ».",+ "skillWarningNameFromFolder": "Il frontmatter non ha un nome, quindi viene usato il nome della cartella.",+ "skillWarningLongName": "Il nome supera i {max} caratteri.",+ "skillWarningNameFormat": "Il nome dovrebbe usare solo lettere minuscole, cifre e trattini singoli.",+ "skillWarningNameMismatch": "Il nome non corrisponde a quello della cartella.",+ "skillWarningLongDescription": "La descrizione supera i {max} caratteri.",+ "skillErrorNoFrontmatter": "SKILL.md non inizia con un frontmatter YAML tra righe ---.",+ "skillErrorInvalidFrontmatter": "Il frontmatter di SKILL.md non è valido: {detail}",+ "skillErrorNoDescription": "Il frontmatter di SKILL.md non ha una descrizione.",+ "skillErrorNoName": "Il frontmatter di SKILL.md non ha un nome."}diff --git a/packages/vue/src/i18n/locales/it/settings.json b/packages/vue/src/i18n/locales/it/settings.jsonindex 937c26f36..867b08c20 100644--- a/packages/vue/src/i18n/locales/it/settings.json+++ b/packages/vue/src/i18n/locales/it/settings.json@@ -32,6 +32,7 @@"media": "Media","mcp": "MCP","toolAccess": "Accesso agli strumenti",+ "skills": "Skill","storage": "Archiviazione","cloud": "Cloud","fonts": "Font",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex 113db8392..e36aa378f 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "まだインストールしていない場合は、次を実行してください:","aiSetupAgentInstallSupported": "対応しているアダプターをインストールします:","aiSetupMeteredNote": "OpenRouter なら、1 つのアカウントと 1 つのキーで複数ベンダーのモデルを使えます。",+ "aiSetupSkillsTitle": "コーディングエージェントのスキル",+ "aiSetupSkillsDescription": "デザインチャットでは、コーディングエージェントがインストールしたスキルを使えます。多くは開発用のワークフローなので、デザインに役立つものだけを選んでください。あとから 設定 › スキル で変更できます。","aiSetupReviewTitle": "設定を確認","aiSetupAgentModel": "モデルはエージェントが選択","aiSetupFinish": "設定を完了",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "MCP サーバーはインストール済みですが起動しませんでした。OpenPencil を再起動してから、もう一度確認してください。","aiSetupAgentLookupFailed": "このコンピューターを確認できませんでした。もう一度お試しください。","chatAgentWorkingOn": "{agent}が「{page}」で作業中",- "chatGoToPage": "ページへ移動"+ "chatGoToPage": "ページへ移動",+ "skillsUpload": "スキルをアップロード",+ "skillsUploadedSource": "アップロード済み",+ "skillsUploadedSourceDescription": "リクエストが説明に合うときに AI チャットが読み込むスキルです。スキルのフォルダーの ZIP か SKILL.md をアップロードしてください。",+ "skillsProjectSource": "このドキュメントの近く",+ "skillsProjectSourceDescription": "{folder} から読み込みます。フォルダーを信頼するまで、ここのスキルはオフです。",+ "skillsProjectSourceTrusted": "信頼済みの {folder} から読み込みます。",+ "skillsTrustFolder": "フォルダーを信頼",+ "skillsStopTrusting": "信頼をやめる",+ "skillsTrustTitle": "このフォルダーを信頼しますか?",+ "skillsTrustDescription": "{folder} のスキルは AI チャットが従う指示を与えます。スキルの出どころがわかるフォルダーだけを信頼してください。",+ "skillsFolderUntrusted": "このスキルを使うには、そのフォルダーを信頼してください。",+ "skillsAgentsSource": "共有エージェントスキル",+ "skillsAgentsSourceDescription": "pi、Codex、Gemini CLI、Cursor などのエージェントがスキルをインストールする {folder} から読み込みます。",+ "skillsClaudeSource": "Claude Code のスキル",+ "skillsClaudeSourceDescription": "{folder} から読み込みます。",+ "skillsNoUploads": "アップロードしたスキルはまだありません。",+ "skillsNoneInFolder": "このフォルダーにスキルはありません。",+ "skillsProblems": "スキルとして読み込めなかったフォルダーがあります",+ "skillsUploadFailed": "スキルをアップロードできませんでした",+ "skillsUploadTooLarge": "ファイルが 10 MB を超えています。",+ "skillsUploadNoSkill": "アーカイブに SKILL.md がありません。",+ "skillsUploadSeveral": "アーカイブに複数のスキルが含まれています。1 つずつアップロードしてください。",+ "skillsUploadUnreadable": "ZIP アーカイブか SKILL.md テキストファイルを選んでください。",+ "skillsDelete": "スキルを削除",+ "skillsDeleteDescription": "「{name}」を OpenPencil から削除します。",+ "skillsLocation": "場所",+ "skillsFiles": "ファイル",+ "skillsInstructions": "指示",+ "skillsWarnings": "このスキルは Agent Skills の仕様に沿っていない部分があります",+ "skillsUseSource": "このフォルダーのスキルを使う",+ "skillsUse": "このスキルを使う",+ "skillsUseDescription": "AI チャットはこのスキルを一覧に載せ、リクエストが合うときに指示を読み込みます。",+ "skillsSourceOff": "このフォルダーのスキルはオフになっています。",+ "skillsNotUsed": "未使用",+ "skillsNotTrusted": "未信頼",+ "skillsShadowed": "上のソースにある同じ名前のスキルが代わりに使われます。",+ "skillWarningPlainFrontmatter": "フロントマターが有効な YAML ではないため、1 行ずつ読み取りました。「: 」を含む値は引用符で囲んでください。",+ "skillWarningNameFromFolder": "フロントマターに名前がないため、フォルダー名を使います。",+ "skillWarningLongName": "名前が {max} 文字を超えています。",+ "skillWarningNameFormat": "名前には小文字、数字、単独のハイフンだけを使ってください。",+ "skillWarningNameMismatch": "名前がフォルダー名と一致しません。",+ "skillWarningLongDescription": "説明が {max} 文字を超えています。",+ "skillErrorNoFrontmatter": "SKILL.md が --- 行で囲まれた YAML フロントマターで始まっていません。",+ "skillErrorInvalidFrontmatter": "SKILL.md のフロントマターが無効です: {detail}",+ "skillErrorNoDescription": "SKILL.md のフロントマターに説明がありません。",+ "skillErrorNoName": "SKILL.md のフロントマターに名前がありません。"}diff --git a/packages/vue/src/i18n/locales/ja/settings.json b/packages/vue/src/i18n/locales/ja/settings.jsonindex 8a9b71a04..1bae90ef7 100644--- a/packages/vue/src/i18n/locales/ja/settings.json+++ b/packages/vue/src/i18n/locales/ja/settings.json@@ -32,6 +32,7 @@"media": "メディア","mcp": "MCP","toolAccess": "ツールへのアクセス",+ "skills": "スキル","storage": "ストレージ","cloud": "クラウド","fonts": "フォント",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 0c7a80657..4edf28811 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "Jeśli nie jest jeszcze zainstalowany, uruchom:","aiSetupAgentInstallSupported": "Zainstaluj obsługiwany adapter:","aiSetupMeteredNote": "OpenRouter daje dostęp do modeli wielu dostawców z jednym kontem i jednym kluczem.",+ "aiSetupSkillsTitle": "Umiejętności twoich agentów programistycznych",+ "aiSetupSkillsDescription": "Czat projektowy może używać umiejętności zainstalowanych przez twoich agentów programistycznych. Większość to procesy programistyczne, więc wybierz tylko te, które pomagają w projektowaniu; zmienisz je później w Ustawienia › Umiejętności.","aiSetupReviewTitle": "Sprawdź konfigurację","aiSetupAgentModel": "Model wybrany przez agenta","aiSetupFinish": "Zakończ konfigurację",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "Serwer MCP jest zainstalowany, ale się nie uruchomił. Uruchom ponownie OpenPencil i sprawdź jeszcze raz.","aiSetupAgentLookupFailed": "Nie udało się sprawdzić tego komputera. Spróbuj ponownie.","chatAgentWorkingOn": "{agent} pracuje nad „{page}”",- "chatGoToPage": "Przejdź do strony"+ "chatGoToPage": "Przejdź do strony",+ "skillsUpload": "Prześlij umiejętność",+ "skillsUploadedSource": "Przesłane",+ "skillsUploadedSourceDescription": "Umiejętności, które czat AI wczytuje, gdy prośba pasuje do ich opisu. Prześlij ZIP folderu umiejętności lub plik SKILL.md.",+ "skillsProjectSource": "Obok tego dokumentu",+ "skillsProjectSourceDescription": "Odczytywane z {folder}. Umiejętności stąd są wyłączone, dopóki nie zaufasz folderowi.",+ "skillsProjectSourceTrusted": "Odczytywane z {folder}, któremu ufasz.",+ "skillsTrustFolder": "Zaufaj folderowi",+ "skillsStopTrusting": "Przestań ufać",+ "skillsTrustTitle": "Zaufać temu folderowi?",+ "skillsTrustDescription": "Umiejętności z {folder} dają czatowi AI instrukcje, których przestrzega. Ufaj folderowi tylko wtedy, gdy wiesz, skąd pochodzą jego umiejętności.",+ "skillsFolderUntrusted": "Zaufaj jej folderowi, aby używać tej umiejętności.",+ "skillsAgentsSource": "Wspólne umiejętności agentów",+ "skillsAgentsSourceDescription": "Odczytywane z {folder}, gdzie pi, Codex, Gemini CLI, Cursor i inni agenci instalują umiejętności.",+ "skillsClaudeSource": "Umiejętności Claude Code",+ "skillsClaudeSourceDescription": "Odczytywane z {folder}.",+ "skillsNoUploads": "Brak przesłanych umiejętności.",+ "skillsNoneInFolder": "Brak umiejętności w tym folderze.",+ "skillsProblems": "Niektórych folderów nie udało się odczytać jako umiejętności",+ "skillsUploadFailed": "Nie udało się przesłać umiejętności",+ "skillsUploadTooLarge": "Plik jest większy niż 10 MB.",+ "skillsUploadNoSkill": "Archiwum nie zawiera pliku SKILL.md.",+ "skillsUploadSeveral": "Archiwum zawiera więcej niż jedną umiejętność. Prześlij je pojedynczo.",+ "skillsUploadUnreadable": "Wybierz archiwum ZIP lub plik tekstowy SKILL.md.",+ "skillsDelete": "Usuń umiejętność",+ "skillsDeleteDescription": "„{name}” zostanie usunięta z OpenPencil.",+ "skillsLocation": "Lokalizacja",+ "skillsFiles": "Pliki",+ "skillsInstructions": "Instrukcje",+ "skillsWarnings": "Ta umiejętność odbiega od specyfikacji Agent Skills",+ "skillsUseSource": "Używaj umiejętności z tego folderu",+ "skillsUse": "Używaj tej umiejętności",+ "skillsUseDescription": "Czat AI pokazuje ją na liście i wczytuje jej instrukcje, gdy prośba pasuje.",+ "skillsSourceOff": "Umiejętności z tego folderu są wyłączone.",+ "skillsNotUsed": "Nieużywana",+ "skillsNotTrusted": "Niezaufany",+ "skillsShadowed": "Zamiast niej używana jest umiejętność o tej samej nazwie ze źródła wyżej.",+ "skillWarningPlainFrontmatter": "Frontmatter nie jest poprawnym YAML-em, więc odczytano go wiersz po wierszu. Ujmij w cudzysłów wartości zawierające „: ”.",+ "skillWarningNameFromFolder": "Frontmatter nie ma nazwy, więc użyto nazwy folderu.",+ "skillWarningLongName": "Nazwa jest dłuższa niż {max} znaki.",+ "skillWarningNameFormat": "Nazwa powinna zawierać tylko małe litery, cyfry i pojedyncze łączniki.",+ "skillWarningNameMismatch": "Nazwa nie zgadza się z nazwą folderu.",+ "skillWarningLongDescription": "Opis jest dłuższy niż {max} znaki.",+ "skillErrorNoFrontmatter": "SKILL.md nie zaczyna się od frontmattera YAML między wierszami ---.",+ "skillErrorInvalidFrontmatter": "Frontmatter pliku SKILL.md jest nieprawidłowy: {detail}",+ "skillErrorNoDescription": "Frontmatter pliku SKILL.md nie ma opisu.",+ "skillErrorNoName": "Frontmatter pliku SKILL.md nie ma nazwy."}diff --git a/packages/vue/src/i18n/locales/pl/settings.json b/packages/vue/src/i18n/locales/pl/settings.jsonindex 339894b52..b3f538698 100644--- a/packages/vue/src/i18n/locales/pl/settings.json+++ b/packages/vue/src/i18n/locales/pl/settings.json@@ -32,6 +32,7 @@"media": "Media","mcp": "MCP","toolAccess": "Dostęp do narzędzi",+ "skills": "Umiejętności","storage": "Przechowywanie","cloud": "Chmura","fonts": "Czcionki",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex b9b863a09..30e3b4559 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "Если он ещё не установлен, выполните:","aiSetupAgentInstallSupported": "Установите поддерживаемый адаптер:","aiSetupMeteredNote": "OpenRouter даёт доступ к моделям разных компаний с одним аккаунтом и одним ключом.",+ "aiSetupSkillsTitle": "Навыки ваших агентов для кода",+ "aiSetupSkillsDescription": "Чат для дизайна может пользоваться навыками, которые установили ваши агенты для кода. Большинство из них — процессы разработки, поэтому выберите только те, что помогают в дизайне; изменить выбор можно в разделе «Настройки › Навыки».","aiSetupReviewTitle": "Проверьте настройку","aiSetupAgentModel": "Модель выбирает агент","aiSetupFinish": "Завершить настройку",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "MCP-сервер установлен, но не запустился. Перезапустите OpenPencil и проверьте снова.","aiSetupAgentLookupFailed": "Не удалось проверить этот компьютер. Попробуйте снова.","chatAgentWorkingOn": "{agent} работает над «{page}»",- "chatGoToPage": "Перейти к странице"+ "chatGoToPage": "Перейти к странице",+ "skillsUpload": "Загрузить навык",+ "skillsUploadedSource": "Загруженные",+ "skillsUploadedSourceDescription": "Навыки, которые ИИ-чат загружает, когда запрос подходит под их описание. Загрузите ZIP папки навыка или файл SKILL.md.",+ "skillsProjectSource": "Рядом с этим документом",+ "skillsProjectSourceDescription": "Читаются из {folder}. Навыки отсюда выключены, пока вы не доверите папку.",+ "skillsProjectSourceTrusted": "Читаются из {folder}, которой вы доверяете.",+ "skillsTrustFolder": "Доверять папке",+ "skillsStopTrusting": "Перестать доверять",+ "skillsTrustTitle": "Доверять этой папке?",+ "skillsTrustDescription": "Навыки из {folder} дают ИИ-чату инструкции, которым он следует. Доверяйте папке, только если знаете, откуда в ней навыки.",+ "skillsFolderUntrusted": "Доверьте его папку, чтобы использовать этот навык.",+ "skillsAgentsSource": "Общие навыки агентов",+ "skillsAgentsSourceDescription": "Читаются из {folder}, куда pi, Codex, Gemini CLI, Cursor и другие агенты устанавливают навыки.",+ "skillsClaudeSource": "Навыки Claude Code",+ "skillsClaudeSourceDescription": "Читаются из {folder}.",+ "skillsNoUploads": "Загруженных навыков пока нет.",+ "skillsNoneInFolder": "В этой папке нет навыков.",+ "skillsProblems": "Некоторые папки не удалось прочитать как навыки",+ "skillsUploadFailed": "Не удалось загрузить навык",+ "skillsUploadTooLarge": "Файл больше 10 МБ.",+ "skillsUploadNoSkill": "В архиве нет SKILL.md.",+ "skillsUploadSeveral": "В архиве больше одного навыка. Загрузите их по одному.",+ "skillsUploadUnreadable": "Выберите ZIP-архив или текстовый файл SKILL.md.",+ "skillsDelete": "Удалить навык",+ "skillsDeleteDescription": "«{name}» будет удалён из OpenPencil.",+ "skillsLocation": "Расположение",+ "skillsFiles": "Файлы",+ "skillsInstructions": "Инструкции",+ "skillsWarnings": "Этот навык отступает от спецификации Agent Skills",+ "skillsUseSource": "Использовать навыки из этой папки",+ "skillsUse": "Использовать этот навык",+ "skillsUseDescription": "ИИ-чат показывает его в списке и загружает его инструкции, когда запрос подходит.",+ "skillsSourceOff": "Навыки из этой папки выключены.",+ "skillsNotUsed": "Не используется",+ "skillsNotTrusted": "Нет доверия",+ "skillsShadowed": "Вместо него используется навык с тем же именем из источника выше.",+ "skillWarningPlainFrontmatter": "Frontmatter — некорректный YAML, поэтому он прочитан построчно. Заключите в кавычки значения, в которых есть «: ».",+ "skillWarningNameFromFolder": "Во frontmatter нет имени, поэтому используется имя папки.",+ "skillWarningLongName": "Имя длиннее {max} символов.",+ "skillWarningNameFormat": "В имени должны быть только строчные латинские буквы, цифры и одиночные дефисы.",+ "skillWarningNameMismatch": "Имя не совпадает с именем папки.",+ "skillWarningLongDescription": "Описание длиннее {max} символов.",+ "skillErrorNoFrontmatter": "SKILL.md не начинается с YAML-frontmatter между строками ---.",+ "skillErrorInvalidFrontmatter": "Frontmatter файла SKILL.md некорректен: {detail}",+ "skillErrorNoDescription": "Во frontmatter файла SKILL.md нет описания.",+ "skillErrorNoName": "Во frontmatter файла SKILL.md нет имени."}diff --git a/packages/vue/src/i18n/locales/ru/settings.json b/packages/vue/src/i18n/locales/ru/settings.jsonindex daba3accf..c7c9fe16f 100644--- a/packages/vue/src/i18n/locales/ru/settings.json+++ b/packages/vue/src/i18n/locales/ru/settings.json@@ -32,6 +32,7 @@"media": "Медиа","mcp": "MCP","toolAccess": "Доступ к инструментам",+ "skills": "Навыки","storage": "Хранилище","cloud": "Облако","fonts": "Шрифты",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 019718099..9a5722cd0 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -247,6 +247,8 @@"aiSetupAgentInstall": "如果尚未安装,请运行:","aiSetupAgentInstallSupported": "安装受支持的适配器:","aiSetupMeteredNote": "OpenRouter 让你用一个账户和一个密钥使用多家厂商的模型。",+ "aiSetupSkillsTitle": "编程智能体的技能",+ "aiSetupSkillsDescription": "设计聊天可以使用你的编程智能体安装的技能。其中大多是编程工作流,所以只选对设计有帮助的;之后可在“设置 › 技能”中更改。","aiSetupReviewTitle": "检查你的设置","aiSetupAgentModel": "模型由智能体选择","aiSetupFinish": "完成设置",@@ -348,5 +350,51 @@"aiSetupAgentMCPStartFailed": "MCP 服务器已安装但未能启动。请重启 OpenPencil,然后重新检查。","aiSetupAgentLookupFailed": "无法检查这台电脑,请重试。","chatAgentWorkingOn": "{agent} 正在处理“{page}”",- "chatGoToPage": "转到页面"+ "chatGoToPage": "转到页面",+ "skillsUpload": "上传技能",+ "skillsUploadedSource": "已上传",+ "skillsUploadedSourceDescription": "当请求与描述相符时,AI 聊天会加载这些技能。上传技能文件夹的 ZIP 或一个 SKILL.md。",+ "skillsProjectSource": "此文档旁边",+ "skillsProjectSourceDescription": "从 {folder} 读取。在你信任该文件夹之前,这里的技能处于关闭状态。",+ "skillsProjectSourceTrusted": "从你信任的 {folder} 读取。",+ "skillsTrustFolder": "信任文件夹",+ "skillsStopTrusting": "不再信任",+ "skillsTrustTitle": "信任此文件夹?",+ "skillsTrustDescription": "{folder} 中的技能会给 AI 聊天下达它会遵循的说明。只信任你清楚其技能来源的文件夹。",+ "skillsFolderUntrusted": "信任它所在的文件夹后才能使用此技能。",+ "skillsAgentsSource": "共享智能体技能",+ "skillsAgentsSourceDescription": "从 {folder} 读取,pi、Codex、Gemini CLI、Cursor 等智能体会把技能安装在这里。",+ "skillsClaudeSource": "Claude Code 技能",+ "skillsClaudeSourceDescription": "从 {folder} 读取。",+ "skillsNoUploads": "还没有上传的技能。",+ "skillsNoneInFolder": "此文件夹中没有技能。",+ "skillsProblems": "部分文件夹无法作为技能读取",+ "skillsUploadFailed": "无法上传技能",+ "skillsUploadTooLarge": "文件超过 10 MB。",+ "skillsUploadNoSkill": "压缩包中没有 SKILL.md。",+ "skillsUploadSeveral": "压缩包中包含多个技能,请逐个上传。",+ "skillsUploadUnreadable": "请选择 ZIP 压缩包或 SKILL.md 文本文件。",+ "skillsDelete": "删除技能",+ "skillsDeleteDescription": "“{name}”将从 OpenPencil 中移除。",+ "skillsLocation": "位置",+ "skillsFiles": "文件",+ "skillsInstructions": "指令",+ "skillsWarnings": "此技能与 Agent Skills 规范存在出入",+ "skillsUseSource": "使用此文件夹中的技能",+ "skillsUse": "使用此技能",+ "skillsUseDescription": "AI 聊天会列出它,并在请求相符时加载它的说明。",+ "skillsSourceOff": "此文件夹中的技能已关闭。",+ "skillsNotUsed": "未使用",+ "skillsNotTrusted": "未信任",+ "skillsShadowed": "改用上方来源中同名的技能。",+ "skillWarningPlainFrontmatter": "frontmatter 不是有效的 YAML,因此已逐行读取。请给包含“: ”的值加上引号。",+ "skillWarningNameFromFolder": "frontmatter 中没有名称,因此使用文件夹名称。",+ "skillWarningLongName": "名称超过 {max} 个字符。",+ "skillWarningNameFormat": "名称只应使用小写字母、数字和单个连字符。",+ "skillWarningNameMismatch": "名称与文件夹名称不一致。",+ "skillWarningLongDescription": "描述超过 {max} 个字符。",+ "skillErrorNoFrontmatter": "SKILL.md 没有以 --- 行之间的 YAML frontmatter 开头。",+ "skillErrorInvalidFrontmatter": "SKILL.md 的 frontmatter 无效:{detail}",+ "skillErrorNoDescription": "SKILL.md 的 frontmatter 中没有描述。",+ "skillErrorNoName": "SKILL.md 的 frontmatter 中没有名称。"}diff --git a/packages/vue/src/i18n/locales/zh-cn/settings.json b/packages/vue/src/i18n/locales/zh-cn/settings.jsonindex 420a099a5..3d8f50d6c 100644--- a/packages/vue/src/i18n/locales/zh-cn/settings.json+++ b/packages/vue/src/i18n/locales/zh-cn/settings.json@@ -32,6 +32,7 @@"media": "媒体","mcp": "MCP","toolAccess": "工具访问权限",+ "skills": "技能","storage": "存储","cloud": "云","fonts": "字体",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex f161373d4..ce10609a6 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -354,6 +354,9 @@ export const aiMessageDefaults = {aiSetupGetDesktop: 'Get the desktop app',aiSetupMeteredNote:'OpenRouter gives you models from several vendors with one account and one key.',+ aiSetupSkillsTitle: 'Skills from your coding agents',+ aiSetupSkillsDescription:+ 'The design chat can use skills your coding agents installed. Most are coding workflows, so pick only the ones that help with design; Settings › Skills changes them later.',aiSetupReviewTitle: 'Review your setup',aiSetupAgentModel: 'Model chosen by the agent',aiSetupFinish: 'Finish setup',@@ -404,7 +407,61 @@ export const aiMessageDefaults = {aiSetupSavedSignInHint: 'Your saved sign-in will be used.',aiSetupUseRecommended: 'Use recommended setup',aiSetupRolesDescription:- 'Choose a model for each kind of work. We picked recommended ones from what you connected; anything else you configured stays as it is.'+ 'Choose a model for each kind of work. We picked recommended ones from what you connected; anything else you configured stays as it is.',+ skillsUpload: 'Upload skill',+ skillsUploadedSource: 'Uploaded',+ skillsUploadedSourceDescription:+ 'Skills the AI chat loads when a request matches their description. Upload a ZIP of a skill’s folder or a SKILL.md.',+ skillsProjectSource: 'Next to this document',+ skillsProjectSourceDescription: params(+ 'Read from {folder}. Skills here are off until you trust the folder.'+ ),+ skillsProjectSourceTrusted: params('Read from {folder}, which you trust.'),+ skillsTrustFolder: 'Trust folder',+ skillsStopTrusting: 'Stop trusting',+ skillsTrustTitle: 'Trust this folder?',+ skillsTrustDescription: params(+ 'Skills in {folder} give the AI chat instructions it follows. Trust a folder only if you know where its skills come from.'+ ),+ skillsFolderUntrusted: 'Trust its folder to use this skill.',+ skillsAgentsSource: 'Shared agent skills',+ skillsAgentsSourceDescription: params(+ 'Read from {folder}, where pi, Codex, Gemini CLI, Cursor, and other agents install skills.'+ ),+ skillsClaudeSource: 'Claude Code skills',+ skillsClaudeSourceDescription: params('Read from {folder}.'),+ skillsNoUploads: 'No uploaded skills yet.',+ skillsNoneInFolder: 'No skills in this folder.',+ skillsProblems: 'Some folders could not be read as skills',+ skillsUploadFailed: 'Could not upload the skill',+ skillsUploadTooLarge: 'The file is larger than 10 MB.',+ skillsUploadNoSkill: 'The archive has no SKILL.md.',+ skillsUploadSeveral: 'The archive holds more than one skill. Upload them one at a time.',+ skillsUploadUnreadable: 'Choose a ZIP archive or a SKILL.md text file.',+ skillsDelete: 'Delete skill',+ skillsDeleteDescription: params('“{name}” will be removed from OpenPencil.'),+ skillsLocation: 'Location',+ skillsFiles: 'Files',+ skillsInstructions: 'Instructions',+ skillsWarnings: 'This skill departs from the Agent Skills specification',+ skillsUseSource: 'Use skills from this folder',+ skillsUse: 'Use this skill',+ skillsUseDescription: 'The AI chat lists it and loads its instructions when a request matches.',+ skillsSourceOff: 'Skills from this folder are turned off.',+ skillsNotUsed: 'Not used',+ skillsNotTrusted: 'Not trusted',+ skillsShadowed: 'A skill with the same name from a source above is used instead.',+ skillWarningPlainFrontmatter:+ 'The frontmatter is not valid YAML, so it was read line by line. Quote values that contain “: ”.',+ skillWarningNameFromFolder: 'The frontmatter has no name, so the folder name is used.',+ skillWarningLongName: params('The name is longer than {max} characters.'),+ skillWarningNameFormat: 'The name should use only lowercase letters, digits, and single hyphens.',+ skillWarningNameMismatch: 'The name does not match the folder name.',+ skillWarningLongDescription: params('The description is longer than {max} characters.'),+ skillErrorNoFrontmatter: 'SKILL.md does not start with YAML frontmatter between --- lines.',+ skillErrorInvalidFrontmatter: params('The SKILL.md frontmatter is invalid: {detail}'),+ skillErrorNoDescription: 'The SKILL.md frontmatter has no description.',+ skillErrorNoName: 'The SKILL.md frontmatter has no name.'} as constexport const aiMessages = i18n('ai', aiMessageDefaults)diff --git a/packages/vue/src/i18n/messages/settings.ts b/packages/vue/src/i18n/messages/settings.tsindex feaa4c63d..13cc6bbbe 100644--- a/packages/vue/src/i18n/messages/settings.ts+++ b/packages/vue/src/i18n/messages/settings.ts@@ -62,6 +62,7 @@ export const settingsMessageDefaults = {media: 'Media',mcp: 'MCP',toolAccess: 'Tool access',+ skills: 'Skills',edit: 'Edit',configured: 'Configured',notConfigured: 'Not configured',diff --git a/src/app/ai/chat/context.ts b/src/app/ai/chat/context.tsindex 4c2ea76a2..a2cb85ad5 100644--- a/src/app/ai/chat/context.ts+++ b/src/app/ai/chat/context.ts@@ -1,3 +1,5 @@+import { escape } from 'es-toolkit/string'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'export const MAX_REFERENCED_NODES = 20@@ -88,8 +90,26 @@ export function appendUndoneCallsContext(text: string, calls: UndoneCalls): strireturn description ? `${text}${UNDONE_CALLS_CONTEXT_MARKER}${description}` : text}+export const SKILL_CONTEXT_MARKER = '\n\n[Skill the user ran — follow its instructions]\n'++/** A skill the user ran by name, as `/skill:name`. */+export interface InvokedSkill {+ name: string+ instructions: string+}++/** Gives the model the instructions of the skill the user ran, so no agent has to look it up. */+export function appendSkillContext(text: string, skill: InvokedSkill | null): string {+ if (!skill) return text+ return `${text}${SKILL_CONTEXT_MARKER}<skill name="${escape(skill.name)}">\n${skill.instructions}\n</skill>`+}+/** Each note the chat adds to a request for the model only starts with one of these. */-const MODEL_NOTE_MARKERS = [REFERENCED_NODE_CONTEXT_MARKER, UNDONE_CALLS_CONTEXT_MARKER]+const MODEL_NOTE_MARKERS = [+ REFERENCED_NODE_CONTEXT_MARKER,+ UNDONE_CALLS_CONTEXT_MARKER,+ SKILL_CONTEXT_MARKER+]/** What the person wrote, without the notes the chat added for the model after it. */export function stripModelNotes(text: string): string {diff --git a/src/app/ai/chat/session.ts b/src/app/ai/chat/session.tsindex e7a6e1338..840e569b3 100644--- a/src/app/ai/chat/session.ts+++ b/src/app/ai/chat/session.ts@@ -159,11 +159,13 @@ export function createChatSessionManager({const runtime = await createAIModelRuntime('design')if (runtime?.kind !== 'harness') throw new Error('The Design agent is not configured for Pi')await assertAgentReady('pi')- const [{ HarnessChatTransport }, { buildPiMCPServers }, { readPiAccount }] = await Promise.all([- import('@/app/ai/transports/pi'),- import('@/app/integrations/mcp'),- import('@/app/ai/agents/pi/settings')- ])+ const [{ HarnessChatTransport }, { buildPiMCPServers }, { readPiAccount }, { harnessSkills }] =+ await Promise.all([+ import('@/app/ai/transports/pi'),+ import('@/app/integrations/mcp'),+ import('@/app/ai/agents/pi/settings'),+ import('@/app/ai/skills/harness')+ ])// A saved key is an AI Gateway key; without one, Pi uses the CLI's own sign-in.const apiKey = await resolveModelConnectionAPIKey(runtime.role.connection.id)const account = apiKey ? null : await readPiAccount()@@ -187,7 +189,8 @@ export function createChatSessionManager({permissionMode: runtime.role.profile.harnessPermissionMode ?? 'allow-edits'},instructions: SYSTEM_PROMPT,- mcpServers: await buildPiMCPServers()+ mcpServers: await buildPiMCPServers(),+ skills: await harnessSkills()},apiKey? { OPENPENCIL_HARNESS_API_KEY: apiKey }diff --git a/src/app/ai/chat/storage.ts b/src/app/ai/chat/storage.tsindex 66d561bbb..72b639685 100644--- a/src/app/ai/chat/storage.ts+++ b/src/app/ai/chat/storage.ts@@ -16,6 +16,7 @@ import {modelCredentialRevision} from '@/app/ai/models'import { OPENPENCIL_AI_PROVIDER } from '@/app/ai/providers/openpencil/provider'+import { enabledSkills } from '@/app/ai/skills/library'import { cloudAIAvailable } from '@/app/cloud/integration'import { appCredentialServices, browserCredentialsRemembered } from '@/app/settings/credentials/app'import {@@ -125,6 +126,19 @@ export function registerAIChatEffects(markTransportDirty: () => void) {markTransportDirty()})watch(credentialRevision, markTransportDirty)+ // Pi gets the skills when its session starts; the built-in chat reads them per message anyway.+ watch(+ () =>+ enabledSkills.value+ .filter((skill) => skill.modelInvocable)+ .map((skill) =>+ [skill.name, skill.location, skill.description, skill.instructions, ...skill.files].join(+ '\n'+ )+ )+ .join('\0'),+ markTransportDirty+ )// A key saved in Settings; the chat reads it when it builds its transport.watch(modelCredentialRevision, () => {void refreshAIProviderStatus()diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.tsindex 0a71ae6d1..c1e488fb4 100644--- a/src/app/ai/chat/submission/use.ts+++ b/src/app/ai/chat/submission/use.ts@@ -11,6 +11,7 @@ import {deleteMessageAttachments,setMessageAttachments} from '@/app/ai/attachment/presentation/store'+import { appendSkillContext } from '@/app/ai/chat/context'import { setVisibleMessageText } from '@/app/ai/chat/presentation'import { reportSubmissionError, type SubmissionErrorOptions } from '@/app/ai/chat/submission/errors'import { prepareSubmittedImages } from '@/app/ai/chat/submission/images'@@ -18,6 +19,7 @@ import { chatToResend } from '@/app/ai/chat/submission/resend'import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'import { restoreTurn, revertTurn } from '@/app/ai/reply/turns'import { useUndoRecords } from '@/app/ai/reply/undo'+import { invokedSkill } from '@/app/ai/skills/invoke'import type { EditorStore } from '@/app/editor/active-store'interface SubmissionOptions extends SubmissionErrorOptions {@@ -152,6 +154,8 @@ export function useChatSubmission(options: SubmissionOptions) {isPreparingAttachments.value = submission.images.length > 0options.clearFailure()try {+ // Read before the version check below, so a cancel or newer message meanwhile wins.+ const skill = await invokedSkill(submission.displayText)const currentChat = await options.ensureChat()if (currentChat && version === operationVersion) options.chat.value = markRaw(currentChat)if (!currentChat || version !== operationVersion) {@@ -159,7 +163,7 @@ export function useChatSubmission(options: SubmissionOptions) {return false}const note = undone.note(submission.modelText, currentChat.messages)- const noted = { ...submission, modelText: note.text }+ const noted = { ...submission, modelText: appendSkillContext(note.text, skill) }const previousIds = new Set(currentChat.messages.map((message) => message.id))if (submission.images.length === 0 && submission.nodes.length === 0) {await sendText(currentChat, noted, dispatch)diff --git a/src/app/ai/skills/catalog.md b/src/app/ai/skills/catalog.mdnew file mode 100644index 000000000..e3f9f4eae--- /dev/null+++ b/src/app/ai/skills/catalog.md@@ -0,0 +1,3 @@+## Skills++Skills are instructions the user installed for particular kinds of work. When a request matches a skill's description, call `load_skill` with its name before you start, and follow what it says. A skill may mention other files in its folder; read them with `read_skill_file` only when you need them. Scripts in a skill cannot run here, so treat them as reference.diff --git a/src/app/ai/skills/catalog.ts b/src/app/ai/skills/catalog.tsnew file mode 100644index 000000000..23839348d--- /dev/null+++ b/src/app/ai/skills/catalog.ts@@ -0,0 +1,32 @@+import { escape } from 'es-toolkit/string'++import guidance from './catalog.md?raw'+import type { Skill } from './types'++/** The specification's description limit, applied to every listing so no skill crowds the rest. */+const MAX_LISTED_DESCRIPTION = 1024++function listedDescription(description: string): string {+ return description.length > MAX_LISTED_DESCRIPTION+ ? `${description.slice(0, MAX_LISTED_DESCRIPTION - 1)}…`+ : description+}++/**+ * The part of the model's instructions that lists skills by name and description, in the+ * `<available_skills>` form pi and Claude Code use; the instructions themselves load on demand.+ * Skills the user runs only by name are left out. Empty when nothing is listed.+ */+export function skillCatalog(skills: readonly Skill[]): string {+ const listed = skills.filter((skill) => skill.modelInvocable)+ if (listed.length === 0) return ''+ const entries = listed.map((skill) =>+ [+ ' <skill>',+ ` <name>${escape(skill.name)}</name>`,+ ` <description>${escape(listedDescription(skill.description))}</description>`,+ ' </skill>'+ ].join('\n')+ )+ return [guidance.trim(), '<available_skills>', ...entries, '</available_skills>'].join('\n')+}diff --git a/src/app/ai/skills/folder.ts b/src/app/ai/skills/folder.tsnew file mode 100644index 000000000..c4f898e2a--- /dev/null+++ b/src/app/ai/skills/folder.ts@@ -0,0 +1,28 @@+import { parseSkill } from './parse'+import type { Skill, SkillProblem, SkillSourceID } from './types'++/** A skill folder as a source holds it: its SKILL.md and the other files it can read. */+export interface SkillFolderContents {+ source: SkillSourceID+ /** The folder's name, or null for a SKILL.md that came without one. */+ folder: string | null+ location: string+ skillsFolder?: string+ skillFile: string+ files: readonly string[]+ readFile: (path: string) => Promise<string>+}++/** The skill a folder holds, or why it holds none. */+export function skillFromFolder(contents: SkillFolderContents): Skill | SkillProblem {+ const { source, folder, location, skillsFolder, skillFile, files, readFile } = contents+ const parsed = parseSkill(skillFile, folder)+ const found =+ skillsFolder === undefined ? { source, location } : { source, location, skillsFolder }+ if (!parsed.ok) return { ...found, folder: folder ?? location, error: parsed.error }+ return { ...parsed.skill, ...found, files, readFile, warnings: parsed.warnings }+}++export function isSkill(entry: Skill | SkillProblem): entry is Skill {+ return !('error' in entry)+}diff --git a/src/app/ai/skills/harness.ts b/src/app/ai/skills/harness.tsnew file mode 100644index 000000000..0be17acd0--- /dev/null+++ b/src/app/ai/skills/harness.ts@@ -0,0 +1,52 @@+import type { HarnessSkill } from '@open-pencil/harness'++import { appSkillLibrary, type SkillLibrary } from './library'+import type { Skill } from './types'++/**+ * Bytes a session may carry in skills, counted as the JSON the harness protocol sends, well+ * inside its 1 MB line, which also holds the instructions and MCP settings. Files past it are+ * left out; the instructions stay.+ */+const MAX_SKILLS_BYTES = 384 * 1024++const encoder = new TextEncoder()+/** The size of `text` as a JSON string, where escapes can take six bytes per character. */+const byteLength = (text: string) => encoder.encode(JSON.stringify(text)).byteLength++async function skillFiles(skill: Skill, budget: { left: number }): Promise<HarnessSkill['files']> {+ const files: NonNullable<HarnessSkill['files']> = []+ for (const path of skill.files) {+ const content = await skill.readFile(path).catch(() => null)+ const size = content === null ? 0 : byteLength(content)+ if (content === null || size > budget.left) continue+ budget.left -= size+ files.push({ path, content })+ }+ return files+}++/**+ * The enabled skills the model may load, as Pi's harness writes them into its own skills+ * folder; Pi lists them and loads them itself.+ */+export async function harnessSkills(+ library: SkillLibrary = appSkillLibrary+): Promise<HarnessSkill[]> {+ await library.refresh()+ const budget = { left: MAX_SKILLS_BYTES }+ const skills: HarnessSkill[] = []+ for (const skill of library.enabled()) {+ if (!skill.modelInvocable) continue+ const size = byteLength(skill.description) + byteLength(skill.instructions)+ if (size > budget.left) continue+ budget.left -= size+ skills.push({+ name: skill.name,+ description: skill.description,+ content: skill.instructions,+ files: await skillFiles(skill, budget)+ })+ }+ return skills+}diff --git a/src/app/ai/skills/invoke.ts b/src/app/ai/skills/invoke.tsnew file mode 100644index 000000000..dcc320226--- /dev/null+++ b/src/app/ai/skills/invoke.ts@@ -0,0 +1,21 @@+import { appSkillLibrary, type SkillLibrary } from './library'+import type { Skill } from './types'++/** How a message runs a skill by name, as in pi: `/skill:brand-review check the hero`. */+const SKILL_COMMAND = /^\/skill:([^\s]+)/++/** The skills the user can run by name: those switched on that allow it. */+export function runnableSkills(skills: readonly Skill[]): Skill[] {+ return skills.filter((skill) => skill.userInvocable)+}++/** The skill a message starts by running, read fresh; null when it names none that can run. */+export async function invokedSkill(+ text: string,+ library: SkillLibrary = appSkillLibrary+): Promise<Skill | null> {+ const name = SKILL_COMMAND.exec(text.trimStart())?.[1]+ if (!name) return null+ await library.refresh()+ return runnableSkills(library.enabled()).find((skill) => skill.name === name) ?? null+}diff --git a/src/app/ai/skills/library.ts b/src/app/ai/skills/library.tsnew file mode 100644index 000000000..bc0ded501--- /dev/null+++ b/src/app/ai/skills/library.ts@@ -0,0 +1,144 @@+import { computed, shallowRef } from 'vue'++import { IS_TAURI } from '@open-pencil/core/constants'++import { getActiveEditorStoreOrNull } from '@/app/editor/active-store'++import { enabledSkillsFrom, skillPreferences } from './preferences'+import { nativeHomeSkillReader, readHomeSkills } from './sources/home'+import {+ nativeProjectSkillReader,+ readProjectSkills,+ type ProjectSkillsFolder+} from './sources/project'+import {+ createIDBUploadedSkillStore,+ skillFromUpload,+ skillsFromUploads,+ type SkillUpload,+ type UploadedSkillStore+} from './sources/uploaded'+import type { Skill, SkillScan } from './types'++/** What the chat needs from skills: a fresh read before a message, then the enabled list. */+export interface SkillLibrary {+ refresh: () => Promise<void>+ enabled: () => readonly Skill[]+}++/** Every skill found, and the folders that failed, from the last read. */+export const foundSkills = shallowRef<SkillScan>({ skills: [], problems: [] })++/** The skills folders near the open document, from the last read. */+export const projectSkillsFolders = shallowRef<ProjectSkillsFolder[]>([])++export const enabledSkills = computed(() =>+ enabledSkillsFrom(foundSkills.value.skills, skillPreferences.value)+)++let uploads: UploadedSkillStore | null = null+function uploadedSkillStore(): UploadedSkillStore {+ uploads ??= createIDBUploadedSkillStore()+ return uploads+}++const NO_SKILLS: SkillScan = { skills: [], problems: [] }++/** The folders around the open document, then the user's own; the browser has neither. */+async function readFolders(): Promise<{ project: SkillScan; home: SkillScan }> {+ if (!IS_TAURI) {+ projectSkillsFolders.value = []+ return { project: NO_SKILLS, home: NO_SKILLS }+ }+ const { dirname, homeDir } = await import('@tauri-apps/api/path')+ const home = await homeDir()+ const reader = await nativeHomeSkillReader()+ const documentPath = getActiveEditorStoreOrNull()?.getDocumentFilePath() ?? null+ const [project, homeSkills] = await Promise.all([+ documentPath+ ? readProjectSkills(await dirname(documentPath), home, await nativeProjectSkillReader(reader))+ : null,+ readHomeSkills(home, reader)+ ])+ projectSkillsFolders.value = project?.folders ?? []+ return { project: project ?? NO_SKILLS, home: homeSkills }+}++let reading: Promise<void> | null = null+/** Counts refresh requests, so a read knows whether another came in while it ran. */+let requests = 0++/**+ * Reads uploaded skills and the skill folders again. A repeated name resolves to the first:+ * uploads, then the document's folders, nearest first, then the user's own, as project skills+ * win over personal ones in Claude Code and pi.+ */+export function refreshSkills(): Promise<void> {+ // A caller that arrives mid-read, such as one that just saved an upload, gets a read that+ // starts after it did, not the one already under way.+ requests += 1+ if (reading) return reading+ reading = (async () => {+ try {+ let read: number+ do {+ read = requests+ await readSkills()+ } while (requests !== read)+ } finally {+ reading = null+ }+ })()+ return reading+}++async function readSkills(): Promise<void> {+ try {+ const [uploaded, { project, home }] = await Promise.all([+ uploadedSkillStore().list().then(skillsFromUploads),+ readFolders()+ ])+ foundSkills.value = {+ skills: [...uploaded.skills, ...project.skills, ...home.skills],+ problems: [...uploaded.problems, ...project.problems, ...home.problems]+ }+ } catch (error) {+ // The last read stays, so a message never fails over a folder, except the skills next to+ // the document, which may belong to one no longer open.+ console.warn('Could not read skills', error)+ projectSkillsFolders.value = []+ const { skills, problems } = foundSkills.value+ foundSkills.value = {+ skills: skills.filter((skill) => skill.source !== 'project'),+ problems: problems.filter((problem) => problem.source !== 'project')+ }+ }+}++/** Keeps a picked file as a skill when it is one, replacing an upload with the same name. */+export async function uploadSkill(file: File): Promise<SkillUpload> {+ const upload = await skillFromUpload(file)+ if (upload.ok) {+ await uploadedSkillStore().put(upload.skill)+ await refreshSkills()+ }+ return upload+}++export async function removeUploadedSkill(name: string): Promise<void> {+ await uploadedSkillStore().remove(name)+ // Gone at once, even if the read that follows fails and keeps the rest of the last one.+ const { skills, problems } = foundSkills.value+ const removed = (entry: { source: string; location: string }) =>+ entry.source === 'openpencil' && entry.location === name+ foundSkills.value = {+ skills: skills.filter((skill) => !removed(skill)),+ problems: problems.filter((problem) => !removed(problem))+ }+ await refreshSkills()+}++export const appSkillLibrary: SkillLibrary = {+ refresh: refreshSkills,+ enabled: () => enabledSkills.value+}diff --git a/src/app/ai/skills/parse.ts b/src/app/ai/skills/parse.tsnew file mode 100644index 000000000..c5c00e802--- /dev/null+++ b/src/app/ai/skills/parse.ts@@ -0,0 +1,104 @@+import * as v from 'valibot'+import { parse as parseYAML } from 'yaml'++import type { SkillDefinition, SkillParseError, SkillWarning } from './types'++/** Limits from the Agent Skills specification (https://agentskills.io/specification). */+export const MAX_SKILL_NAME_LENGTH = 64+export const MAX_SKILL_DESCRIPTION_LENGTH = 1024+const NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/++const FRONTMATTER = /^?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/++const frontmatterSchema = v.object({+ name: v.optional(v.string()),+ description: v.optional(v.string()),+ 'disable-model-invocation': v.optional(v.boolean()),+ 'user-invocable': v.optional(v.boolean())+})++export type SkillParseResult =+ | { ok: true; skill: SkillDefinition; warnings: SkillWarning[] }+ | { ok: false; error: SkillParseError }++const PLAIN_LINE = /^([A-Za-z][\w-]*):[ \t]*(.*)$/++/**+ * Frontmatter that is not valid YAML read as one `key: value` per line, indented lines+ * continuing the value above. Descriptions with an unquoted ": " are the usual cause, and other+ * agents still load those skills.+ */+function readPlainFrontmatter(source: string): Record<string, string | boolean> {+ const fields: Record<string, string> = {}+ let key: string | null = null+ for (const line of source.split(/\r?\n/)) {+ const field = PLAIN_LINE.exec(line)+ if (field?.[1] !== undefined) {+ key = field[1]+ fields[key] = field[2]?.trim() ?? ''+ } else if (key !== null && /^\s+\S/.test(line)) {+ fields[key] = `${fields[key] ?? ''} ${line.trim()}`.trim()+ }+ }+ return Object.fromEntries(+ Object.entries(fields).map(([name, value]) => [name, plainValue(value)])+ )+}++function plainValue(value: string): string | boolean {+ if (value === 'true') return true+ if (value === 'false') return false+ return value.replace(/^(["'])(.*)\1$/, '$2')+}++function readFrontmatter(+ text: string+): { data: unknown; body: string; plain?: true } | { error: SkillParseError } {+ const match = FRONTMATTER.exec(text)+ if (!match) return { error: { code: 'no-frontmatter' } }+ const source = match[1] ?? ''+ const body = text.slice(match[0].length)+ try {+ return { data: parseYAML(source), body }+ } catch {+ return { data: readPlainFrontmatter(source), body, plain: true }+ }+}++/**+ * Reads a SKILL.md as pi and Claude Code do: a skill without a description cannot be offered,+ * so it fails; other departures from the specification are warnings and the skill still loads.+ * A SKILL.md that came without a folder, such as an upload, must name itself.+ */+export function parseSkill(text: string, folderName: string | null): SkillParseResult {+ const frontmatter = readFrontmatter(text)+ if ('error' in frontmatter) return { ok: false, error: frontmatter.error }+ const parsed = v.safeParse(frontmatterSchema, frontmatter.data ?? {})+ if (!parsed.success) {+ return { ok: false, error: { code: 'invalid-frontmatter', detail: v.summarize(parsed.issues) } }+ }+ const fields = parsed.output+ const description = fields.description?.trim() ?? ''+ if (!description) return { ok: false, error: { code: 'no-description' } }++ const warnings: SkillWarning[] = frontmatter.plain ? ['plain-frontmatter'] : []+ const name = fields.name?.trim() || folderName+ if (!name) return { ok: false, error: { code: 'no-name' } }+ if (!fields.name?.trim()) warnings.push('name-from-folder')+ if (name.length > MAX_SKILL_NAME_LENGTH) warnings.push('long-name')+ if (!NAME_PATTERN.test(name)) warnings.push('name-format')+ if (folderName !== null && name !== folderName) warnings.push('name-mismatch')+ if (description.length > MAX_SKILL_DESCRIPTION_LENGTH) warnings.push('long-description')++ return {+ ok: true,+ skill: {+ name,+ description,+ instructions: frontmatter.body.trim(),+ modelInvocable: fields['disable-model-invocation'] !== true,+ userInvocable: fields['user-invocable'] !== false+ },+ warnings+ }+}diff --git a/src/app/ai/skills/preferences.ts b/src/app/ai/skills/preferences.tsnew file mode 100644index 000000000..4946df575--- /dev/null+++ b/src/app/ai/skills/preferences.ts@@ -0,0 +1,109 @@+import { useLocalStorage } from '@vueuse/core'+import * as v from 'valibot'++import type { Skill, SkillSourceID } from './types'++const skillPreferencesSchema = v.object({+ sources: v.optional(v.record(v.string(), v.boolean()), {}),+ skills: v.optional(v.record(v.string(), v.boolean()), {}),+ trustedFolders: v.optional(v.record(v.string(), v.boolean()), {}),+ pickedSources: v.optional(v.record(v.string(), v.boolean()), {})+})++/**+ * The sources and skills the user turned on or off, and the skills folders near documents the+ * user trusts, where everything else is off. A source in `pickedSources` was turned on for the+ * skills picked from it, so a skill that appears there later stays off until picked too.+ */+export type SkillPreferences = v.InferOutput<typeof skillPreferencesSchema>++const storedPreferencesSchema = v.pipe(v.string(), v.parseJson(), skillPreferencesSchema)++export const skillPreferences = useLocalStorage<SkillPreferences>(+ 'open-pencil:ai:skills',+ { sources: {}, skills: {}, trustedFolders: {}, pickedSources: {} },+ {+ serializer: {+ read: (raw) => {+ const result = v.safeParse(storedPreferencesSchema, raw)+ return result.success+ ? result.output+ : { sources: {}, skills: {}, trustedFolders: {}, pickedSources: {} }+ },+ write: JSON.stringify+ }+ }+)++/** A skill's toggle belongs to its source and folder, so the same name elsewhere keeps its own. */+export function skillPreferenceKey(skill: Pick<Skill, 'source' | 'name' | 'skillsFolder'>): string {+ return skill.skillsFolder === undefined+ ? `${skill.source}/${skill.name}`+ : `${skill.source}/${skill.skillsFolder}/${skill.name}`+}++/** A skills folder near a document runs nothing until the user trusts it. */+export function isSkillsFolderTrusted(path: string, preferences: SkillPreferences): boolean {+ return preferences.trustedFolders[path] ?? false+}++/**+ * Uploads and folders next to a document are chosen for design work; the folders coding agents+ * share hold their own workflows, such as releases or email, so they start off until picked.+ */+const SOURCES_ON_BY_DEFAULT: Record<SkillSourceID, boolean> = {+ openpencil: true,+ project: true,+ agents: false,+ claude: false+}++export function isSkillSourceEnabled(source: SkillSourceID, preferences: SkillPreferences) {+ return preferences.sources[source] ?? SOURCES_ON_BY_DEFAULT[source]+}++/**+ * Preferences that use exactly the picked skills among `offered`, from coding agents' folders:+ * a folder turns on when any of its skills is picked, and its other skills turn off.+ */+export function withPickedSkills(+ preferences: SkillPreferences,+ offered: readonly Skill[],+ picked: ReadonlySet<string>+): SkillPreferences {+ const sources = { ...preferences.sources }+ const skills = { ...preferences.skills }+ const pickedSources = { ...preferences.pickedSources }+ for (const skill of offered) {+ const key = skillPreferenceKey(skill)+ skills[key] = picked.has(key)+ if (!picked.has(key)) continue+ sources[skill.source] = true+ pickedSources[skill.source] = true+ }+ return { ...preferences, sources, skills, pickedSources }+}++export function isSkillEnabled(skill: Skill, preferences: SkillPreferences): boolean {+ return (+ isSkillSourceEnabled(skill.source, preferences) &&+ (skill.skillsFolder === undefined || isSkillsFolderTrusted(skill.skillsFolder, preferences)) &&+ (preferences.skills[skillPreferenceKey(skill)] ?? !preferences.pickedSources[skill.source])+ )+}++/**+ * The skills the chat offers: those switched on, the first of each name in source order, as+ * pi and Amp resolve a name found twice. Turning the first off lets the next one through.+ */+export function enabledSkillsFrom(+ skills: readonly Skill[],+ preferences: SkillPreferences+): Skill[] {+ const seen = new Set<string>()+ return skills.filter((skill) => {+ if (!isSkillEnabled(skill, preferences) || seen.has(skill.name)) return false+ seen.add(skill.name)+ return true+ })+}diff --git a/src/app/ai/skills/settings/use.ts b/src/app/ai/skills/settings/use.tsnew file mode 100644index 000000000..89821819a--- /dev/null+++ b/src/app/ai/skills/settings/use.ts@@ -0,0 +1,207 @@+import { computed, ref, shallowRef } from 'vue'++import { IS_TAURI } from '@open-pencil/core/constants'++import {+ enabledSkills,+ foundSkills,+ projectSkillsFolders,+ refreshSkills,+ removeUploadedSkill,+ uploadSkill+} from '../library'+import {+ isSkillEnabled,+ isSkillsFolderTrusted,+ isSkillSourceEnabled,+ skillPreferenceKey,+ skillPreferences+} from '../preferences'+import { HOME_SKILL_SOURCES } from '../sources/home'+import type { SkillUploadFailure } from '../sources/uploaded'+import type { Skill, SkillProblem, SkillSourceID } from '../types'++export interface SkillListEntry {+ skill: Skill+ enabled: boolean+ /** On, but another source's skill with the same name is offered instead. */+ shadowed: boolean+ /** Off because its folder is near the document and not trusted yet. */+ untrusted: boolean+}++/** The skill the details show, with whether its source is on. */+export interface SelectedSkill extends SkillListEntry {+ sourceEnabled: boolean+}++export interface SkillSourceGroup {+ key: string+ source: SkillSourceID+ /** The folder it reads, as the user sees it; null for uploads. */+ folder: string | null+ /** On for the chat: switched on, or, for a folder near the document, trusted. */+ enabled: boolean+ /** The path of a folder near the document, which the user trusts instead of switching on. */+ trustPath: string | null+ skills: SkillListEntry[]+ problems: SkillProblem[]+}++/** The folders other agents keep, read only on the desktop. */+const HOME_SOURCES: readonly { source: SkillSourceID; folder: string }[] = IS_TAURI+ ? HOME_SKILL_SOURCES.map(({ id, folder }) => ({ source: id, folder: `~/${folder.join('/')}` }))+ : []++export function useSkillsSettings() {+ const loading = ref(true)+ const uploading = ref(false)+ const uploadFailure = shallowRef<SkillUploadFailure | null>(null)+ const selectedKey = ref<string | null>(null)+ /** The details stay on the skill they showed while they slide away. */+ const detailOpen = ref(false)++ const groups = computed<SkillSourceGroup[]>(() => {+ const preferences = skillPreferences.value+ const offered = new Set(enabledSkills.value)+ const { skills, problems } = foundSkills.value+ const group = (+ base: Pick<SkillSourceGroup, 'key' | 'source' | 'folder' | 'enabled' | 'trustPath'>,+ belongs: (entry: Skill | SkillProblem) => boolean+ ): SkillSourceGroup => ({+ ...base,+ skills: skills.filter(belongs).map((skill) => {+ const enabled = isSkillEnabled(skill, preferences)+ const untrusted =+ skill.skillsFolder !== undefined &&+ !isSkillsFolderTrusted(skill.skillsFolder, preferences)+ return { skill, enabled, shadowed: enabled && !offered.has(skill), untrusted }+ }),+ problems: problems.filter(belongs)+ })+ const source = (id: SkillSourceID, folder: string | null) =>+ group(+ {+ key: id,+ source: id,+ folder,+ enabled: isSkillSourceEnabled(id, preferences),+ trustPath: null+ },+ (entry) => entry.source === id+ )+ // Uploads, the document's folders, then the user's: the order a repeated name resolves in.+ return [+ source('openpencil', null),+ ...projectSkillsFolders.value.map(({ path, location }) =>+ group(+ {+ key: path,+ source: 'project',+ folder: location,+ enabled: isSkillsFolderTrusted(path, preferences),+ trustPath: path+ },+ (entry) => entry.skillsFolder === path+ )+ ),+ ...HOME_SOURCES.map(({ source: id, folder }) => source(id, folder))+ ]+ })++ const selected = computed<SelectedSkill | null>(() => {+ const key = selectedKey.value+ if (key === null) return null+ for (const group of groups.value) {+ const entry = group.skills.find(({ skill }) => skillPreferenceKey(skill) === key)+ if (entry) return { ...entry, sourceEnabled: group.enabled }+ }+ return null+ })++ async function reload() {+ loading.value = true+ try {+ await refreshSkills()+ } finally {+ loading.value = false+ }+ }++ /** The whole source, every skill in it included, as against the skills picked in AI setup. */+ function setSourceEnabled(source: SkillSourceID, enabled: boolean) {+ const preferences = skillPreferences.value+ skillPreferences.value = {+ ...preferences,+ sources: { ...preferences.sources, [source]: enabled },+ pickedSources: { ...preferences.pickedSources, [source]: false }+ }+ }++ function setFolderTrusted(path: string, trusted: boolean) {+ const preferences = skillPreferences.value+ skillPreferences.value = {+ ...preferences,+ trustedFolders: { ...preferences.trustedFolders, [path]: trusted }+ }+ }++ function setSkillEnabled(skill: Skill, enabled: boolean) {+ const preferences = skillPreferences.value+ skillPreferences.value = {+ ...preferences,+ skills: { ...preferences.skills, [skillPreferenceKey(skill)]: enabled }+ }+ }++ async function upload(file: File) {+ uploading.value = true+ uploadFailure.value = null+ try {+ const result = await uploadSkill(file)+ if (!result.ok) uploadFailure.value = result+ } catch {+ uploadFailure.value = { reason: 'unreadable' }+ } finally {+ uploading.value = false+ }+ }++ function open(skill: Skill) {+ selectedKey.value = skillPreferenceKey(skill)+ detailOpen.value = true+ }++ function close() {+ detailOpen.value = false+ }++ function closed() {+ if (!detailOpen.value) selectedKey.value = null+ }++ async function remove(skill: Skill) {+ await removeUploadedSkill(skill.name)+ if (selectedKey.value === skillPreferenceKey(skill)) close()+ }++ void reload()++ return {+ groups,+ loading,+ uploading,+ uploadFailure,+ selected,+ detailOpen,+ open,+ close,+ closed,+ reload,+ setSourceEnabled,+ setFolderTrusted,+ setSkillEnabled,+ upload,+ remove+ }+}diff --git a/src/app/ai/skills/sources/home.ts b/src/app/ai/skills/sources/home.tsnew file mode 100644index 000000000..00a7cddc5--- /dev/null+++ b/src/app/ai/skills/sources/home.ts@@ -0,0 +1,85 @@+import { partition } from 'es-toolkit'+import * as v from 'valibot'++import { isSkill, skillFromFolder } from '../folder'+import type { SkillScan, SkillSourceID } from '../types'++/** The folders other agents install skills into, in the order a repeated name resolves. */+export const HOME_SKILL_SOURCES: readonly { id: SkillSourceID; folder: readonly string[] }[] = [+ { id: 'agents', folder: ['.agents', 'skills'] },+ { id: 'claude', folder: ['.claude', 'skills'] }+]++const skillFoldersSchema = v.array(+ v.object({+ name: v.string(),+ path: v.string(),+ skillFile: v.string(),+ files: v.array(v.string())+ })+)++export type SkillFolder = v.InferOutput<typeof skillFoldersSchema>[number]++export interface HomeSkillReader {+ /** The skill folders directly inside `root`; empty when it does not exist. */+ folders: (root: string) => Promise<unknown>+ readFile: (dir: string, path: string) => Promise<string>+}++/** The folders in a skills folder, or none when it cannot be read. */+export async function readSkillFolders(+ reader: Pick<HomeSkillReader, 'folders'>,+ root: string+): Promise<SkillFolder[]> {+ const result = v.safeParse(skillFoldersSchema, await reader.folders(root).catch(() => []))+ return result.success ? result.output : []+}++/** Turns the folders one source holds into skills, and the ones that are not into problems. */+export function skillsFromFolders(+ source: SkillSourceID,+ displayRoot: string,+ folders: readonly SkillFolder[],+ readFile: HomeSkillReader['readFile'],+ skillsFolder?: string+): SkillScan {+ const [skills, problems] = partition(+ folders.map((folder) =>+ skillFromFolder({+ source,+ folder: folder.name,+ location: `${displayRoot}/${folder.name}`,+ ...(skillsFolder !== undefined && { skillsFolder }),+ skillFile: folder.skillFile,+ files: folder.files,+ readFile: (path) => readFile(folder.path, path)+ })+ ),+ isSkill+ )+ return { skills, problems }+}++/** Reads every home source; a source that cannot be read contributes nothing. */+export async function readHomeSkills(home: string, reader: HomeSkillReader): Promise<SkillScan> {+ const scans = await Promise.all(+ HOME_SKILL_SOURCES.map(async ({ id, folder }) => {+ const folders = await readSkillFolders(reader, [home, ...folder].join('/'))+ return skillsFromFolders(id, `~/${folder.join('/')}`, folders, reader.readFile)+ })+ )+ return {+ skills: scans.flatMap((scan) => scan.skills),+ problems: scans.flatMap((scan) => scan.problems)+ }+}++/** The desktop's reader, through the shell's skill commands. */+export async function nativeHomeSkillReader(): Promise<HomeSkillReader> {+ const { invoke } = await import('@tauri-apps/api/core')+ return {+ folders: (root) => invoke<unknown>('skill_folders', { root }),+ readFile: (dir, path) => invoke<string>('skill_folder_file', { dir, path })+ }+}diff --git a/src/app/ai/skills/sources/project.ts b/src/app/ai/skills/sources/project.tsnew file mode 100644index 000000000..7b93b125b--- /dev/null+++ b/src/app/ai/skills/sources/project.ts@@ -0,0 +1,67 @@+import * as v from 'valibot'++import type { SkillScan } from '../types'+import { readSkillFolders, skillsFromFolders, type HomeSkillReader } from './home'++const skillsFoldersSchema = v.array(v.string())++export interface ProjectSkillReader extends HomeSkillReader {+ /** The skills folders a document's folder sees, nearest first. */+ skillsFolders: (dir: string) => Promise<unknown>+}++/** A skills folder near the open document, which the chat uses only once the user trusts it. */+export interface ProjectSkillsFolder {+ path: string+ /** The path as the user sees it, with the home folder as `~`. */+ location: string+}++export interface ProjectSkillScan extends SkillScan {+ folders: ProjectSkillsFolder[]+}++function displayPath(path: string, home: string): string {+ return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path+}++/**+ * Reads the `.agents/skills` and `.claude/skills` folders from a document's folder up to its+ * repository, as Claude Code and pi read a project's skills; nearer folders come first.+ */+export async function readProjectSkills(+ documentDir: string,+ home: string,+ reader: ProjectSkillReader+): Promise<ProjectSkillScan> {+ const found = v.safeParse(+ skillsFoldersSchema,+ await reader.skillsFolders(documentDir).catch(() => [])+ )+ const folders = (found.success ? found.output : []).map((path) => ({+ path,+ location: displayPath(path, home)+ }))+ const scans = await Promise.all(+ folders.map(async (folder) =>+ skillsFromFolders(+ 'project',+ folder.location,+ await readSkillFolders(reader, folder.path),+ reader.readFile,+ folder.path+ )+ )+ )+ return {+ folders,+ skills: scans.flatMap((scan) => scan.skills),+ problems: scans.flatMap((scan) => scan.problems)+ }+}++/** The desktop's reader, through the shell's skill commands. */+export async function nativeProjectSkillReader(home: HomeSkillReader): Promise<ProjectSkillReader> {+ const { invoke } = await import('@tauri-apps/api/core')+ return { ...home, skillsFolders: (dir) => invoke<unknown>('project_skill_folders', { dir }) }+}diff --git a/src/app/ai/skills/sources/uploaded.ts b/src/app/ai/skills/sources/uploaded.tsnew file mode 100644index 000000000..4a7df72e5--- /dev/null+++ b/src/app/ai/skills/sources/uploaded.ts@@ -0,0 +1,186 @@+import { partition } from 'es-toolkit'+import { unzipSync } from 'fflate'+import type { DBSchema } from 'idb'++import { APP_DATABASE_NAMES, connectAppDatabase, defineAppDatabase } from '@/app/storage/idb'++import { isSkill, skillFromFolder } from '../folder'+import { parseSkill } from '../parse'+import type { SkillParseError, SkillScan } from '../types'++const SKILL_FILE = 'SKILL.md'+/** The same bounds the desktop applies to skill folders it reads. */+const MAX_ARCHIVE_BYTES = 10 * 1024 * 1024+const MAX_FILE_BYTES = 1024 * 1024+const MAX_FILES = 200+/** What an archive may unpack to; a few kilobytes of zeros can otherwise inflate to gigabytes. */+const MAX_UNPACKED_BYTES = 20 * 1024 * 1024++/** A text file in an uploaded skill, by its path inside the skill's folder. */+export interface StoredSkillFile {+ path: string+ content: string+}++/** An uploaded skill: its SKILL.md and its other text files. */+export interface StoredSkill {+ name: string+ skillFile: string+ files: StoredSkillFile[]+ uploadedAt: number+}++export type SkillUploadFailure =+ | { reason: 'too-large' }+ | { reason: 'no-skill' }+ | { reason: 'several-skills' }+ | { reason: 'unreadable' }+ | { reason: 'invalid'; error: SkillParseError }++export type SkillUpload = { ok: true; skill: StoredSkill } | ({ ok: false } & SkillUploadFailure)++/** A path OpenPencil keeps: no hidden or packaging folders, which skills never refer to. */+function isKeptPath(path: string): boolean {+ return path+ .split('/')+ .every((part) => part.length > 0 && !part.startsWith('.') && part !== '__MACOSX')+}++const textDecoder = new TextDecoder('utf-8', { fatal: true })++function decodeText(bytes: Uint8Array): string | null {+ try {+ return textDecoder.decode(bytes)+ } catch {+ return null+ }+}++/**+ * The skill an archive holds: one SKILL.md at its root or in one top folder, as Claude and+ * skill registries package them. Binary files are left out, since the chat reads only text.+ */+export function skillFromArchive(bytes: Uint8Array, uploadedAt: number): SkillUpload {+ if (bytes.byteLength > MAX_ARCHIVE_BYTES) return { ok: false, reason: 'too-large' }+ let entries: Record<string, Uint8Array>+ // Counted before anything inflates, from the sizes the archive declares.+ const unpacking = { kept: 0, bytes: 0, tooLarge: false }+ try {+ entries = unzipSync(bytes, {+ filter: (entry) => {+ if (unpacking.tooLarge || !isKeptPath(entry.name) || entry.originalSize > MAX_FILE_BYTES) {+ return false+ }+ unpacking.kept += 1+ unpacking.bytes += entry.originalSize+ unpacking.tooLarge = unpacking.kept > MAX_FILES + 1 || unpacking.bytes > MAX_UNPACKED_BYTES+ return !unpacking.tooLarge+ }+ })+ } catch {+ return { ok: false, reason: 'unreadable' }+ }+ if (unpacking.tooLarge) return { ok: false, reason: 'too-large' }+ const roots = Object.keys(entries)+ .filter((path) => path === SKILL_FILE || /^[^/]+\/SKILL\.md$/.test(path))+ .map((path) => path.slice(0, -SKILL_FILE.length))+ if (roots.length === 0) return { ok: false, reason: 'no-skill' }+ if (roots.length > 1) return { ok: false, reason: 'several-skills' }+ const [root = ''] = roots+ const skillFile = decodeText(entries[`${root}${SKILL_FILE}`] ?? new Uint8Array())+ if (skillFile === null) return { ok: false, reason: 'unreadable' }++ const files: StoredSkillFile[] = []+ for (const [path, content] of Object.entries(entries)) {+ if (!path.startsWith(root) || path === `${root}${SKILL_FILE}` || path.endsWith('/')) continue+ if (files.length >= MAX_FILES) break+ const text = decodeText(content)+ if (text !== null) files.push({ path: path.slice(root.length), content: text })+ }+ files.sort((a, b) => a.path.localeCompare(b.path))+ return storedSkill(skillFile, root ? root.slice(0, -1) : null, files, uploadedAt)+}++function storedSkill(+ skillFile: string,+ folder: string | null,+ files: StoredSkillFile[],+ uploadedAt: number+): SkillUpload {+ const parsed = parseSkill(skillFile, folder)+ if (!parsed.ok) return { ok: false, reason: 'invalid', error: parsed.error }+ return { ok: true, skill: { name: parsed.skill.name, skillFile, files, uploadedAt } }+}++/** A picked file as a skill: a ZIP of the folder, or a SKILL.md on its own. */+export async function skillFromUpload(file: File, uploadedAt = Date.now()): Promise<SkillUpload> {+ if (file.size > MAX_ARCHIVE_BYTES) return { ok: false, reason: 'too-large' }+ if (/\.zip$/i.test(file.name)) {+ return skillFromArchive(new Uint8Array(await file.arrayBuffer()), uploadedAt)+ }+ if (file.size > MAX_FILE_BYTES) return { ok: false, reason: 'too-large' }+ const text = decodeText(new Uint8Array(await file.arrayBuffer()))+ if (text === null) return { ok: false, reason: 'unreadable' }+ return storedSkill(text, null, [], uploadedAt)+}++/** Uploaded skills as the chat reads them; uploads are named by their skill's name. */+export function skillsFromUploads(stored: readonly StoredSkill[]): SkillScan {+ const [skills, problems] = partition(+ stored.map((upload) =>+ skillFromFolder({+ source: 'openpencil',+ // The name it was stored under stands in for a folder, which a SKILL.md may name itself by.+ folder: upload.name,+ location: upload.name,+ skillFile: upload.skillFile,+ files: upload.files.map((file) => file.path),+ readFile: async (path) => {+ const file = upload.files.find((candidate) => candidate.path === path)+ if (!file) throw new Error(`"${path}" is not in the skill.`)+ return file.content+ }+ })+ ),+ isSkill+ )+ return { skills, problems }+}++interface SkillsDatabase extends DBSchema {+ skills: { key: string; value: StoredSkill }+}++const skillsDatabase = defineAppDatabase<SkillsDatabase>({+ name: APP_DATABASE_NAMES.skills,+ version: 1,+ callbacks: {+ upgrade(database) {+ if (!database.objectStoreNames.contains('skills')) {+ database.createObjectStore('skills', { keyPath: 'name' })+ }+ }+ }+})++export interface UploadedSkillStore {+ list(): Promise<StoredSkill[]>+ /** Adds the skill, replacing an upload with the same name. */+ put(skill: StoredSkill): Promise<void>+ remove(name: string): Promise<void>+}++export function createIDBUploadedSkillStore(): UploadedSkillStore {+ const database = connectAppDatabase(skillsDatabase)+ return {+ async list() {+ return (await database.open()).getAll('skills')+ },+ async put(skill) {+ await (await database.open()).put('skills', skill)+ },+ async remove(name) {+ await (await database.open()).delete('skills', name)+ }+ }+}diff --git a/src/app/ai/skills/tools.ts b/src/app/ai/skills/tools.tsnew file mode 100644index 000000000..055e6e702--- /dev/null+++ b/src/app/ai/skills/tools.ts@@ -0,0 +1,59 @@+import { valibotSchema } from '@ai-sdk/valibot'+import { tool } from 'ai'+import * as v from 'valibot'++import type { Skill } from './types'++/** Long enough for any reference the specification has in mind, short of flooding the context. */+const MAX_FILE_LENGTH = 64_000++export const SKILL_TOOL_NAMES: readonly string[] = ['load_skill', 'read_skill_file']++function unknownSkill(name: string, skills: readonly Skill[]): { error: string } {+ const names = skills.map((skill) => skill.name).join(', ')+ return { error: `No skill named "${name}". Available: ${names || 'none'}.` }+}++/** Tools that load a skill's instructions and files; `getSkills` is read at every call. */+export function createSkillTools(getSkills: () => readonly Skill[]) {+ function findSkill(name: string): Skill | undefined {+ return getSkills().find((skill) => skill.name === name)+ }++ return {+ load_skill: tool({+ description:+ 'Load the instructions of a skill listed under Skills, by name. Call it before starting work that matches the skill.',+ inputSchema: valibotSchema(v.object({ name: v.string() })),+ execute: ({ name }) => {+ const skill = findSkill(name)+ if (!skill) return unknownSkill(name, getSkills())+ return { name: skill.name, instructions: skill.instructions, files: skill.files }+ }+ }),+ read_skill_file: tool({+ description:+ "Read a file from a skill's folder, by the skill's name and the file's path as load_skill listed it.",+ inputSchema: valibotSchema(v.object({ name: v.string(), path: v.string() })),+ execute: async ({ name, path }) => {+ const skill = findSkill(name)+ if (!skill) return unknownSkill(name, getSkills())+ // Only listed files: a path the model makes up must not reach the file system.+ if (!skill.files.includes(path)) {+ return {+ error: `"${path}" is not in skill "${name}". Its files: ${skill.files.join(', ') || 'none'}.`+ }+ }+ try {+ const text = await skill.readFile(path)+ if (text.length <= MAX_FILE_LENGTH) return { path, text }+ return { path, text: text.slice(0, MAX_FILE_LENGTH), truncated: true }+ } catch (error) {+ // The reader's message can name places on disk the model has no need to see.+ console.warn('Could not read a skill file', error)+ return { error: `Could not read "${path}".` }+ }+ }+ })+ }+}diff --git a/src/app/ai/skills/types.ts b/src/app/ai/skills/types.tsnew file mode 100644index 000000000..cf77b4d57--- /dev/null+++ b/src/app/ai/skills/types.ts@@ -0,0 +1,59 @@+/** What a SKILL.md says about itself: its frontmatter and the instructions below it. */+export interface SkillDefinition {+ name: string+ description: string+ /** The Markdown body, which the model reads when it loads the skill. */+ instructions: string+ /** Listed for the model to load on its own; `disable-model-invocation` turns this off. */+ modelInvocable: boolean+ /** Offered for the user to run by name; `user-invocable: false` turns this off. */+ userInvocable: boolean+}++/**+ * Where skills come from: uploaded to OpenPencil, the folders around the open document, the+ * shared Agent Skills folder, Claude Code's.+ */+export type SkillSourceID = 'openpencil' | 'project' | 'agents' | 'claude'++/** Departures from the Agent Skills specification that do not stop a skill loading. */+export type SkillWarning =+ | 'plain-frontmatter'+ | 'name-from-folder'+ | 'long-name'+ | 'name-format'+ | 'name-mismatch'+ | 'long-description'++/** Why a SKILL.md could not be read as a skill. */+export type SkillParseError =+ | { code: 'no-frontmatter' }+ | { code: 'invalid-frontmatter'; detail: string }+ | { code: 'no-description' }+ | { code: 'no-name' }++export interface Skill extends SkillDefinition {+ source: SkillSourceID+ /** Where the skill was found, as the user sees it. */+ location: string+ /** The skills folder it was found in, for skills that need it trusted first. */+ skillsFolder?: string+ /** Files in the skill's folder other than SKILL.md, relative to the folder. */+ files: readonly string[]+ readFile: (path: string) => Promise<string>+ warnings: readonly SkillWarning[]+}++/** A folder with a SKILL.md that could not be read as a skill. */+export interface SkillProblem {+ source: SkillSourceID+ folder: string+ location: string+ skillsFolder?: string+ error: SkillParseError+}++export interface SkillScan {+ skills: Skill[]+ problems: SkillProblem[]+}diff --git a/src/app/ai/transports/tool-loop.ts b/src/app/ai/transports/tool-loop.tsindex 6c072af85..f4504ece5 100644--- a/src/app/ai/transports/tool-loop.ts+++ b/src/app/ai/transports/tool-loop.ts@@ -13,7 +13,17 @@ import { promptCachingOptions } from '@/app/ai/models/caching'import { reasoningCallSettings, type AIProviderOptions } from '@/app/ai/models/reasoning/settings'import type { ThinkingLevel } from '@/app/ai/models/types'import { createRunPreview } from '@/app/ai/preview/run'-import { createAITools, currentRun, endRun, recordStep, startRun } from '@/app/ai/tools'+import { skillCatalog } from '@/app/ai/skills/catalog'+import { appSkillLibrary, type SkillLibrary } from '@/app/ai/skills/library'+import { createSkillTools, SKILL_TOOL_NAMES } from '@/app/ai/skills/tools'+import {+ createAITools,+ currentRun,+ endRun,+ recordStep,+ startRun,+ type AITools+} from '@/app/ai/tools'import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'import { aiToolOverrides } from '@/app/ai/tools/preferences'import { recordModelStepCompleted } from '@/app/diagnostics/events'@@ -35,6 +45,7 @@ export type ToolLoopTransportOptions = {diagnosticContext?: AIDiagnosticContext/** Records each run so a saved trace can rebuild its requests. */recorder?: RunRecorder+ skills?: SkillLibrary}function callSettings(@@ -66,9 +77,18 @@ export function createToolLoopTransport({thinkingLevel,onError,diagnosticContext = {},- recorder+ recorder,+ skills = appSkillLibrary}: ToolLoopTransportOptions) {- const tools = createAITools(store, diagnosticContext)+ const tools: AITools = {+ ...createAITools(store, diagnosticContext),+ ...createSkillTools(() => offeredSkills)+ }+ // Read again for each message, so skills installed or switched off since apply to the next one.+ // Only skills the model may load: one the user runs by name stays out of the listing and tools.+ const modelSkills = () => skills.enabled().filter((skill) => skill.modelInvocable)+ let offeredSkills = modelSkills()+ let instructions = SYSTEM_PROMPT// The reply in progress; a transport sends one message at a time.let run = currentRun(store)// While JSX streams, the chat's agent moves through the elements as they appear, here and@@ -93,6 +113,7 @@ export function createToolLoopTransport({const enabledNames = new Set(enabledAIToolDefinitions(aiToolOverrides.value).map((tool) => tool.name))+ if (offeredSkills.length > 0) for (const name of SKILL_TOOL_NAMES) enabledNames.add(name)preview.clear()// Keep the full catalog for validating history; offer only enabled tools to this request.const offered = Object.fromEntries(@@ -101,6 +122,7 @@ export function createToolLoopTransport({recording?.offer(offered)return {...options,+ instructions,stopWhen: stepCountIs(currentRun(store).maxSteps),tools: offered,maxOutputTokens,@@ -148,6 +170,10 @@ export function createToolLoopTransport({// The run starts as the message is sent, so a Stop before the model is reached ends it.const started = startRun(store, maxAgentSteps.value, effectiveModelID)run = started+ await skills.refresh()+ offeredSkills = modelSkills()+ const catalog = skillCatalog(offeredSkills)+ instructions = catalog ? `${SYSTEM_PROMPT}\n\n${catalog}` : SYSTEM_PROMPTconst { sessionId, runId } = diagnosticContextconst startedRecording =sessionId && runId@@ -161,7 +187,7 @@ export function createToolLoopTransport({thinking: thinkingLevel(),cache: cacheProviderOptions !== undefined},- instructions: SYSTEM_PROMPT,+ instructions,messages: options.messages}): undefineddiff --git a/src/app/settings/dialog.ts b/src/app/settings/dialog.tsindex 717203cb9..2f1ecf440 100644--- a/src/app/settings/dialog.ts+++ b/src/app/settings/dialog.ts@@ -9,6 +9,7 @@ export type SettingsSection =| 'privacy'| 'mcp'| 'tools'+ | 'skills'| 'fonts'| 'media'| 'storage'diff --git a/src/app/storage/idb/database-names.ts b/src/app/storage/idb/database-names.tsindex bb7e86442..404b52e86 100644--- a/src/app/storage/idb/database-names.ts+++ b/src/app/storage/idb/database-names.ts@@ -7,6 +7,7 @@ export const APP_DATABASE_NAMES = {outbox: 'open-pencil-cloud-outbox',recovery: 'open-pencil-recovery',diagnostics: 'open-pencil-diagnostics',+ skills: 'open-pencil-skills',/** Written and deleted once per page, to learn whether the engine stores Blobs. */blobProbe: 'open-pencil-blob-probe'} as constdiff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vueindex c2d737d70..d449f45f9 100644--- a/src/components/settings/SettingsDialog.vue+++ b/src/components/settings/SettingsDialog.vue@@ -25,6 +25,7 @@ import MCPWorkspacePanel from '@/components/settings/mcp/MCPWorkspacePanel.vue'import MediaSettingsPanel from '@/components/settings/media/MediaSettingsPanel.vue'import ModelsPanel from '@/components/settings/models/ModelsPanel.vue'import PrivacySettingsPanel from '@/components/settings/privacy/PrivacySettingsPanel.vue'+import SkillsSettingsPanel from '@/components/settings/skills/SkillsSettingsPanel.vue'import StorageSettingsPanel from '@/components/settings/storage/StorageSettingsPanel.vue'import ToolAccessSettingsPanel from '@/components/settings/tool-access/ToolAccessSettingsPanel.vue'import ToolbarSettingsPanel from '@/components/settings/toolbar/ToolbarSettingsPanel.vue'@@ -55,6 +56,7 @@ const sections = computed({ value: 'privacy', label: settings.value.privacy },{ value: 'mcp', label: settings.value.mcp },{ value: 'tools', label: settings.value.toolAccess },+ { value: 'skills', label: settings.value.skills },{ value: 'fonts', label: settings.value.fonts },{ value: 'media', label: settings.value.media },{ value: 'storage', label: settings.value.storage },@@ -153,6 +155,10 @@ function onOpenChange(open: boolean): void {<template #leading><icon-lucide-sliders-horizontal class="size-3.5" /></template>{{ settings.toolAccess }}</AppTabsTrigger>+ <AppTabsTrigger value="skills" data-test-id="settings-section-skills">+ <template #leading><icon-lucide-book-open class="size-3.5" /></template>+ {{ settings.skills }}+ </AppTabsTrigger><AppTabsTrigger value="fonts" data-test-id="settings-section-fonts"><template #leading><icon-lucide-type class="size-3.5" /></template>{{ settings.fonts }}@@ -199,6 +205,9 @@ function onOpenChange(open: boolean): void {<AppTabsContent value="tools" as-child><ToolAccessSettingsPanel /></AppTabsContent>+ <AppTabsContent value="skills" as-child>+ <SkillsSettingsPanel />+ </AppTabsContent><AppTabsContent value="fonts" as-child><FontSettingsPanel /></AppTabsContent>diff --git a/src/components/settings/ai-setup/AISetupFlow.vue b/src/components/settings/ai-setup/AISetupFlow.vueindex b404db44f..ba5f90911 100644--- a/src/components/settings/ai-setup/AISetupFlow.vue+++ b/src/components/settings/ai-setup/AISetupFlow.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { tv } from 'tailwind-variants'-import { computed, ref } from 'vue'+import { computed, ref, useTemplateRef } from 'vue'import { IS_TAURI } from '@open-pencil/core/constants'import { useI18n } from '@open-pencil/vue/i18n'@@ -19,6 +19,7 @@ import AISetupAccess from './AISetupAccess.vue'import AISetupConnection from './AISetupConnection.vue'import AISetupReview from './AISetupReview.vue'import AISetupRoles from './AISetupRoles.vue'+import AISetupSkills from './AISetupSkills.vue'const {entry,@@ -98,8 +99,12 @@ function back(): void {else emit('close')}+const skills = useTemplateRef<{ apply: () => void }>('skills')+async function finish(): Promise<void> {- if ((await onboarding.apply()) === 'saved') phase.value = 'saved'+ if ((await onboarding.apply()) !== 'saved') return+ skills.value?.apply()+ phase.value = 'saved'}</script>@@ -225,6 +230,7 @@ async function finish(): Promise<void> {@choose="roles.choose"@use-recommended="roles.useRecommended"/>+ <AISetupSkills v-if="agentsAvailable" ref="skills" /><SettingsSaveFeedback:result="saveResult":error="saveResult === 'saved' ? null : saveResult"diff --git a/src/components/settings/ai-setup/AISetupSkills.vue b/src/components/settings/ai-setup/AISetupSkills.vuenew file mode 100644index 000000000..887984250--- /dev/null+++ b/src/components/settings/ai-setup/AISetupSkills.vue@@ -0,0 +1,82 @@+<script setup lang="ts">+import { computed, onMounted, ref } from 'vue'++import { useAIMessages } from '@open-pencil/vue/i18n'++import { foundSkills, refreshSkills } from '@/app/ai/skills/library'+import {+ isSkillEnabled,+ skillPreferenceKey,+ skillPreferences,+ withPickedSkills+} from '@/app/ai/skills/preferences'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsRow from '@/components/settings/layout/SettingsRow.vue'+import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'++/**+ * The skills coding agents installed, offered to the design chat one by one: most are coding+ * workflows, so none is picked unless it already was. Shown only when there are some.+ */+const ai = useAIMessages()+const offered = computed(() =>+ foundSkills.value.skills.filter((skill) => skill.source === 'agents' || skill.source === 'claude')+)+const picked = ref(new Set<string>())+/** Ticks made while the folders are read, applied over what the read finds. */+const edits = new Map<string, boolean>()++function withEdits(base: Iterable<string>): Set<string> {+ const next = new Set(base)+ for (const [key, on] of edits) {+ if (on) next.add(key)+ else next.delete(key)+ }+ return next+}++onMounted(async () => {+ await refreshSkills()+ picked.value = withEdits(+ offered.value+ .filter((skill) => isSkillEnabled(skill, skillPreferences.value))+ .map(skillPreferenceKey)+ )+})++function toggle(key: string, on: boolean) {+ edits.set(key, on)+ picked.value = withEdits(picked.value)+}++/** Saves the picks with the rest of the setup. */+function apply() {+ if (offered.value.length === 0) return+ skillPreferences.value = withPickedSkills(skillPreferences.value, offered.value, picked.value)+}++defineExpose({ apply })+</script>++<template>+ <SettingsSection v-if="offered.length" data-test-id="ai-setup-skills">+ <template #title>{{ ai.aiSetupSkillsTitle }}</template>+ <template #description>{{ ai.aiSetupSkillsDescription }}</template>+ <SettingsGroup>+ <SettingsRow+ v-for="skill in offered"+ :key="skillPreferenceKey(skill)"+ as="label"+ :label="skill.name"+ :description="skill.description"+ >+ <AppCheckbox+ :model-value="picked.has(skillPreferenceKey(skill))"+ :ariaLabel="skill.name"+ @update:model-value="toggle(skillPreferenceKey(skill), $event)"+ />+ </SettingsRow>+ </SettingsGroup>+ </SettingsSection>+</template>diff --git a/src/components/settings/skills/SkillDetails.vue b/src/components/settings/skills/SkillDetails.vuenew file mode 100644index 000000000..f2265bb77--- /dev/null+++ b/src/components/settings/skills/SkillDetails.vue@@ -0,0 +1,91 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useAIMessages, useCommonMessages } from '@open-pencil/vue/i18n'++import type { SelectedSkill } from '@/app/ai/skills/settings/use'+import MarkdownContent from '@/components/markdown/MarkdownContent.vue'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsPage from '@/components/settings/layout/SettingsPage.vue'+import SettingsRow from '@/components/settings/layout/SettingsRow.vue'+import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'++import { useSkillMessages } from './messages'++const { entry } = defineProps<{ entry: SelectedSkill }>()++const emit = defineEmits<{ done: []; remove: []; 'set-enabled': [enabled: boolean] }>()++const ai = useAIMessages()+const common = useCommonMessages()+const messages = useSkillMessages()++const skill = computed(() => entry.skill)+const uploaded = computed(() => skill.value.source === 'openpencil')+const useDescription = computed(() => {+ if (entry.untrusted) return ai.value.skillsFolderUntrusted+ if (!entry.sourceEnabled) return ai.value.skillsSourceOff+ if (entry.shadowed) return ai.value.skillsShadowed+ return ai.value.skillsUseDescription+})+</script>++<template>+ <SettingsPage data-test-id="settings-skill-details">+ <div class="flex flex-col gap-6">+ <SettingsSection>+ <template #title>{{ skill.name }}</template>+ <template #description>{{ skill.description }}</template>+ <SettingsGroup>+ <SettingsRow as="label" :label="ai.skillsUse" :description="useDescription">+ <AppSwitch+ :model-value="entry.enabled"+ :label="ai.skillsUse"+ :disabled="!entry.sourceEnabled"+ @update:model-value="emit('set-enabled', $event)"+ />+ </SettingsRow>+ <SettingsRow v-if="!uploaded" :label="ai.skillsLocation">+ <code class="text-[11px] break-all text-muted">{{ skill.location }}</code>+ </SettingsRow>+ <SettingsRow v-if="skill.files.length" :label="ai.skillsFiles">+ <template #description>+ <ul class="mt-1 flex flex-col gap-0.5">+ <li v-for="file in skill.files" :key="file">+ <code class="text-[11px] break-all text-muted">{{ file }}</code>+ </li>+ </ul>+ </template>+ </SettingsRow>+ </SettingsGroup>+ <AppAlert v-if="skill.warnings.length" tone="warning" :heading="ai.skillsWarnings">+ <ul class="flex flex-col gap-0.5">+ <li v-for="warning in skill.warnings" :key="warning">+ {{ messages.warning(warning) }}+ </li>+ </ul>+ </AppAlert>+ </SettingsSection>+ <SettingsSection>+ <template #title>{{ ai.skillsInstructions }}</template>+ <div class="rounded border border-border px-4 py-3">+ <MarkdownContent :content="skill.instructions" />+ </div>+ </SettingsSection>+ </div>+ <template #footer>+ <AppButton+ v-if="uploaded"+ class="mr-auto"+ color="error"+ variant="link"+ @click="emit('remove')"+ >{{ ai.skillsDelete }}</AppButton+ >+ <AppButton color="primary" variant="solid" @click="emit('done')">{{ common.done }}</AppButton>+ </template>+ </SettingsPage>+</template>diff --git a/src/components/settings/skills/SkillList.stories.ts b/src/components/settings/skills/SkillList.stories.tsnew file mode 100644index 000000000..44f3b5a8e--- /dev/null+++ b/src/components/settings/skills/SkillList.stories.ts@@ -0,0 +1,76 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'+import { ref } from 'vue'++import type { SkillListEntry } from '@/app/ai/skills/settings/use'+import type { Skill } from '@/app/ai/skills/types'++import SkillList from './SkillList.vue'++function skill(name: string, description: string): Skill {+ return {+ name,+ description,+ instructions: '',+ modelInvocable: true,+ userInvocable: true,+ source: 'agents',+ location: `~/.agents/skills/${name}`,+ files: [],+ readFile: () => Promise.resolve(''),+ warnings: []+ }+}++const entries: SkillListEntry[] = [+ {+ skill: skill(+ 'brand-review',+ 'Check a layout against the brand guide: colors, type scale, spacing, and logo clear space. Use when reviewing or polishing marketing pages before they ship.'+ ),+ enabled: true,+ shadowed: false,+ untrusted: false+ },+ {+ skill: skill('grid', 'Lay out pages on an eight-point grid.'),+ enabled: true,+ shadowed: true,+ untrusted: false+ },+ {+ skill: skill('pr-review', 'Review GitHub pull requests.'),+ enabled: false,+ shadowed: false,+ untrusted: false+ }+]++const meta = {+ title: 'App/Settings/Skills/List',+ render: () => ({+ components: { SkillList },+ setup: () => ({ entries, opened: ref('') }),+ template: `+ <div class="max-w-lg bg-panel p-3 text-surface">+ <SkillList :entries="entries" @open="(skill) => (opened = skill.name)" />+ <p class="mt-3 text-xs text-muted" data-opened>{{ opened }}</p>+ </div>`+ })+} satisfies Meta++export default meta+type Story = StoryObj<typeof meta>++export const States: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('button', { name: /^brand-review / })).toHaveTextContent(+ 'Enabled'+ )+ await expect(canvas.getByRole('button', { name: /^grid / })).toHaveTextContent('Not used')+ await expect(canvas.getByRole('button', { name: /^pr-review / })).toHaveTextContent('Disabled')+ await userEvent.click(canvas.getByRole('button', { name: /^grid / }))+ await expect(canvasElement.querySelector('[data-opened]')).toHaveTextContent('grid')+ }+}diff --git a/src/components/settings/skills/SkillList.vue b/src/components/settings/skills/SkillList.vuenew file mode 100644index 000000000..0e0fbdd67--- /dev/null+++ b/src/components/settings/skills/SkillList.vue@@ -0,0 +1,41 @@+<script setup lang="ts">+import { useAIMessages, useCommonMessages } from '@open-pencil/vue/i18n'++import type { SkillListEntry } from '@/app/ai/skills/settings/use'+import type { Skill } from '@/app/ai/skills/types'+import AppActionRow from '@/components/ui/list/AppActionRow.vue'++const { entries } = defineProps<{ entries: SkillListEntry[] }>()++const emit = defineEmits<{ open: [skill: Skill] }>()++const ai = useAIMessages()+const common = useCommonMessages()++function status(entry: SkillListEntry): string {+ if (entry.untrusted) return ai.value.skillsNotTrusted+ if (entry.shadowed) return ai.value.skillsNotUsed+ return entry.enabled ? common.value.enabled : common.value.disabled+}+</script>++<template>+ <div class="flex flex-col gap-1.5" data-slot="skill-list">+ <AppActionRow+ v-for="entry in entries"+ :key="entry.skill.name"+ :data-skill="entry.skill.name"+ @click="emit('open', entry.skill)"+ >+ <template #leading><icon-lucide-book-open class="size-3.5" /></template>+ {{ entry.skill.name }}+ <template #description>+ <span class="line-clamp-2">{{ entry.skill.description }}</span>+ </template>+ <template #trailing>+ <span class="text-xs">{{ status(entry) }}</span>+ <icon-lucide-chevron-right class="size-3.5" />+ </template>+ </AppActionRow>+ </div>+</template>diff --git a/src/components/settings/skills/SkillsSettingsPanel.vue b/src/components/settings/skills/SkillsSettingsPanel.vuenew file mode 100644index 000000000..e4ddc27b8--- /dev/null+++ b/src/components/settings/skills/SkillsSettingsPanel.vue@@ -0,0 +1,216 @@+<script setup lang="ts">+import { useFileDialog } from '@vueuse/core'+import { AlertDialogAction, AlertDialogCancel } from 'reka-ui'+import { computed, ref } from 'vue'++import { useAIMessages, useCommonMessages, useSettingsMessages } from '@open-pencil/vue/i18n'++import { useSkillsSettings, type SkillSourceGroup } from '@/app/ai/skills/settings/use'+import { useSettingsFormGuard } from '@/app/settings/navigation/use'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsPage from '@/components/settings/layout/SettingsPage.vue'+import SettingsRow from '@/components/settings/layout/SettingsRow.vue'+import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import { AppAlertDialogRoot, AppDialogFooter, AppDialogHeader } from '@/components/ui/dialog'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import PanelDrillIn from '@/components/ui/panel/PanelDrillIn.vue'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'++import { useSkillMessages } from './messages'+import SkillDetails from './SkillDetails.vue'+import SkillList from './SkillList.vue'++const ai = useAIMessages()+const common = useCommonMessages()+const settings = useSettingsMessages()+const messages = useSkillMessages()+const skills = useSkillsSettings()+const { groups, loading, uploading, uploadFailure, selected, detailOpen } = skills+const deleteOpen = ref(false)+const trustOpen = ref(false)+/** The folder near the document the person is asked to trust; kept while the dialog closes. */+const trusting = ref<SkillSourceGroup | null>(null)+const removing = ref(false)++useSettingsFormGuard(+ {+ dirty: computed(() => false),+ busy: removing,+ cancel: skills.close,+ crumb: { parent: () => settings.value.skills, title: () => selected.value?.skill.name ?? '' }+ },+ detailOpen+)++const fileDialog = useFileDialog({+ accept: '.zip,.md,application/zip,text/markdown',+ multiple: false,+ reset: true+})+fileDialog.onChange((files) => {+ const file = files?.[0]+ if (file) void skills.upload(file)+})++function sourceTitle(group: SkillSourceGroup): string {+ if (group.source === 'project') return ai.value.skillsProjectSource+ if (group.source === 'agents') return ai.value.skillsAgentsSource+ if (group.source === 'claude') return ai.value.skillsClaudeSource+ return ai.value.skillsUploadedSource+}++function sourceDescription(group: SkillSourceGroup): string {+ const folder = group.folder ?? ''+ if (group.source === 'project') {+ return group.enabled+ ? ai.value.skillsProjectSourceTrusted({ folder })+ : ai.value.skillsProjectSourceDescription({ folder })+ }+ if (group.source === 'agents') return ai.value.skillsAgentsSourceDescription({ folder })+ if (group.source === 'claude') return ai.value.skillsClaudeSourceDescription({ folder })+ return ai.value.skillsUploadedSourceDescription+}++const trustDescription = computed(() =>+ ai.value.skillsTrustDescription({ folder: trusting.value?.folder ?? '' })+)++function askTrust(group: SkillSourceGroup) {+ trusting.value = group+ trustOpen.value = true+}++function trust() {+ if (trusting.value?.trustPath) skills.setFolderTrusted(trusting.value.trustPath, true)+ trustOpen.value = false+}++const deleteDescription = computed(() =>+ ai.value.skillsDeleteDescription({ name: selected.value?.skill.name ?? '' })+)++async function remove() {+ const skill = selected.value?.skill+ removing.value = true+ try {+ if (skill) await skills.remove(skill)+ } finally {+ removing.value = false+ deleteOpen.value = false+ }+}+</script>++<template>+ <PanelDrillIn :open="detailOpen" data-test-id="settings-skills-panel" @closed="skills.closed">+ <template #detail>+ <SkillDetails+ v-if="selected"+ :entry="selected"+ @done="skills.close"+ @remove="deleteOpen = true"+ @set-enabled="skills.setSkillEnabled(selected.skill, $event)"+ />+ </template>+ <SettingsPage>+ <div class="flex flex-col gap-6" :aria-busy="loading">+ <SettingsSection v-for="group in groups" :key="group.key" :data-skill-source="group.source">+ <template #title>{{ sourceTitle(group) }}</template>+ <template #description>{{ sourceDescription(group) }}</template>+ <template #actions>+ <AppButton+ v-if="group.source === 'openpencil'"+ variant="outline"+ :loading="uploading"+ @click="fileDialog.open()"+ >+ <template #leading><icon-lucide-upload class="size-3.5" /></template>+ {{ ai.skillsUpload }}+ </AppButton>+ <AppButton+ v-else-if="group.trustPath && group.enabled"+ variant="outline"+ @click="skills.setFolderTrusted(group.trustPath, false)"+ >+ {{ ai.skillsStopTrusting }}+ </AppButton>+ <AppButton v-else-if="group.trustPath" variant="outline" @click="askTrust(group)">+ <template #leading><icon-lucide-shield-check class="size-3.5" /></template>+ {{ ai.skillsTrustFolder }}+ </AppButton>+ <AppButton v-else variant="outline" :loading="loading" @click="skills.reload">+ <template #leading><icon-lucide-refresh-cw class="size-3.5" /></template>+ {{ common.refresh }}+ </AppButton>+ </template>+ <AppAlert+ v-if="group.source === 'openpencil' && uploadFailure"+ tone="error"+ :heading="ai.skillsUploadFailed"+ :description="messages.uploadFailure(uploadFailure)"+ />+ <SettingsGroup v-if="group.folder && !group.trustPath">+ <SettingsRow as="label" :label="ai.skillsUseSource">+ <AppSwitch+ :model-value="group.enabled"+ :label="ai.skillsUseSource"+ @update:model-value="skills.setSourceEnabled(group.source, $event)"+ />+ </SettingsRow>+ </SettingsGroup>+ <SkillList v-if="group.skills.length" :entries="group.skills" @open="skills.open" />+ <AppPlaceholder+ v-else+ size="compact"+ :fill="false"+ :label="group.folder ? ai.skillsNoneInFolder : ai.skillsNoUploads"+ />+ <AppAlert v-if="group.problems.length" tone="warning" :heading="ai.skillsProblems">+ <ul class="flex flex-col gap-0.5">+ <li v-for="problem in group.problems" :key="problem.location">+ <code>{{ problem.location }}</code+ >: {{ messages.error(problem.error) }}+ </li>+ </ul>+ </AppAlert>+ </SettingsSection>+ </div>+ </SettingsPage>+ </PanelDrillIn>+ <AppAlertDialogRoot v-model:open="trustOpen">+ <AppDialogHeader+ :heading="ai.skillsTrustTitle"+ :description="trustDescription"+ :show-close="false"+ />+ <AppDialogFooter>+ <AlertDialogCancel as-child>+ <AppButton>{{ common.cancel }}</AppButton>+ </AlertDialogCancel>+ <AlertDialogAction as-child>+ <AppButton color="primary" variant="solid" @click="trust">+ {{ ai.skillsTrustFolder }}+ </AppButton>+ </AlertDialogAction>+ </AppDialogFooter>+ </AppAlertDialogRoot>+ <AppAlertDialogRoot v-model:open="deleteOpen">+ <AppDialogHeader+ :heading="ai.skillsDelete"+ :description="deleteDescription"+ :show-close="false"+ />+ <AppDialogFooter>+ <AlertDialogCancel as-child>+ <AppButton>{{ common.cancel }}</AppButton>+ </AlertDialogCancel>+ <AlertDialogAction as-child>+ <AppButton color="error" variant="solid" :loading="removing" @click="remove">+ {{ ai.skillsDelete }}+ </AppButton>+ </AlertDialogAction>+ </AppDialogFooter>+ </AppAlertDialogRoot>+</template>diff --git a/src/components/settings/skills/messages.ts b/src/components/settings/skills/messages.tsnew file mode 100644index 000000000..34756d077--- /dev/null+++ b/src/components/settings/skills/messages.ts@@ -0,0 +1,49 @@+import { useAIMessages } from '@open-pencil/vue/i18n'++import { MAX_SKILL_DESCRIPTION_LENGTH, MAX_SKILL_NAME_LENGTH } from '@/app/ai/skills/parse'+import type { SkillUploadFailure } from '@/app/ai/skills/sources/uploaded'+import type { SkillParseError, SkillWarning } from '@/app/ai/skills/types'++/** What a skill's warnings, read errors, and upload failures say, in the user's language. */+export function useSkillMessages() {+ const ai = useAIMessages()++ function warning(code: SkillWarning): string {+ const messages: Record<SkillWarning, string> = {+ 'plain-frontmatter': ai.value.skillWarningPlainFrontmatter,+ 'name-from-folder': ai.value.skillWarningNameFromFolder,+ 'long-name': ai.value.skillWarningLongName({ max: MAX_SKILL_NAME_LENGTH }),+ 'name-format': ai.value.skillWarningNameFormat,+ 'name-mismatch': ai.value.skillWarningNameMismatch,+ 'long-description': ai.value.skillWarningLongDescription({+ max: MAX_SKILL_DESCRIPTION_LENGTH+ })+ }+ return messages[code]+ }++ function error(parseError: SkillParseError): string {+ if (parseError.code === 'invalid-frontmatter') {+ return ai.value.skillErrorInvalidFrontmatter({ detail: parseError.detail })+ }+ const messages: Record<Exclude<SkillParseError['code'], 'invalid-frontmatter'>, string> = {+ 'no-frontmatter': ai.value.skillErrorNoFrontmatter,+ 'no-description': ai.value.skillErrorNoDescription,+ 'no-name': ai.value.skillErrorNoName+ }+ return messages[parseError.code]+ }++ function uploadFailure(failure: SkillUploadFailure): string {+ if (failure.reason === 'invalid') return error(failure.error)+ const messages: Record<Exclude<SkillUploadFailure['reason'], 'invalid'>, string> = {+ 'too-large': ai.value.skillsUploadTooLarge,+ 'no-skill': ai.value.skillsUploadNoSkill,+ 'several-skills': ai.value.skillsUploadSeveral,+ unreadable: ai.value.skillsUploadUnreadable+ }+ return messages[failure.reason]+ }++ return { warning, error, uploadFailure }+}diff --git a/tests/app/ai/skills/catalog.test.ts b/tests/app/ai/skills/catalog.test.tsnew file mode 100644index 000000000..594bd5630--- /dev/null+++ b/tests/app/ai/skills/catalog.test.ts@@ -0,0 +1,33 @@+import { describe, expect, test } from 'bun:test'++import { skillCatalog } from '@/app/ai/skills/catalog'++import { skillFixture } from '#tests/helpers/chat/skills'++describe('skillCatalog', () => {+ test('is empty when no skill is listed for the model', () => {+ expect(skillCatalog([])).toBe('')+ expect(skillCatalog([skillFixture({ modelInvocable: false })])).toBe('')+ })++ test('lists the skills the model may load, by name and description', () => {+ const catalog = skillCatalog([+ skillFixture(),+ skillFixture({ name: 'release-notes', modelInvocable: false })+ ])+ expect(catalog).toContain('<name>grid</name>')+ expect(catalog).toContain('<description>Lay out pages on an eight-point grid.</description>')+ expect(catalog).not.toContain('release-notes')+ })++ test('keeps a description from breaking the listing', () => {+ const catalog = skillCatalog([skillFixture({ description: '</description><name>x</name>' })])+ expect(catalog.match(/<name>/g)).toHaveLength(1)+ })++ test('bounds every listed description', () => {+ const short = skillCatalog([skillFixture()])+ const long = skillCatalog([skillFixture({ description: 'x'.repeat(10_000) })])+ expect(long.length).toBeLessThan(short.length + 2_000)+ })+})diff --git a/tests/app/ai/skills/harness.test.ts b/tests/app/ai/skills/harness.test.tsnew file mode 100644index 000000000..51df55288--- /dev/null+++ b/tests/app/ai/skills/harness.test.ts@@ -0,0 +1,60 @@+import { expect, test } from 'bun:test'++import { harnessSkills } from '@/app/ai/skills/harness'+import type { Skill } from '@/app/ai/skills/types'++import { skillFixture } from '#tests/helpers/chat/skills'++function library(skills: Skill[]) {+ return { refresh: async () => undefined, enabled: () => skills }+}++test('Pi gets the skills the model may load, with their files', async () => {+ const files: Record<string, string> = { 'references/spacing.md': '8', 'gone.md': '' }+ const grid = skillFixture({+ files: Object.keys(files),+ readFile: (path) =>+ path === 'gone.md' ? Promise.reject(new Error('Gone')) : Promise.resolve(files[path] ?? '')+ })+ const manual = skillFixture({ name: 'manual', modelInvocable: false })+ expect(await harnessSkills(library([grid, manual]))).toEqual([+ {+ name: 'grid',+ description: grid.description,+ content: grid.instructions,+ files: [{ path: 'references/spacing.md', content: '8' }]+ }+ ])+})++test('files past the size budget are left out, the instructions stay', async () => {+ const large = 'x'.repeat(300 * 1024)+ const skills = ['first', 'second'].map((name) =>+ skillFixture({ name, files: ['big.md'], readFile: () => Promise.resolve(large) })+ )+ const result = await harnessSkills(library(skills))+ expect(result.map((skill) => [skill.name, skill.files?.length])).toEqual([+ ['first', 1],+ ['second', 0]+ ])+})++test('the budget counts UTF-8 bytes, which non-Latin text takes more of', async () => {+ // 200 000 characters, 400 000 bytes: past the budget though shorter than it in characters.+ const wide = skillFixture({+ files: ['notes.md'],+ readFile: () => Promise.resolve('é'.repeat(200_000))+ })+ const [skill] = await harnessSkills(library([wide]))+ expect(skill?.files).toEqual([])+})++test('the budget counts the JSON escapes control characters take', async () => {+ // 100 000 NUL bytes become 600 000 bytes of `\u0000` escapes.+ const nul = skillFixture({+ files: ['blob.txt'],+ readFile: () => Promise.resolve('\u0000'.repeat(100_000))+ })+ const [skill] = await harnessSkills(library([nul]))+ expect(skill?.files).toEqual([])+})diff --git a/tests/app/ai/skills/invoke.test.ts b/tests/app/ai/skills/invoke.test.tsnew file mode 100644index 000000000..af6e2a840--- /dev/null+++ b/tests/app/ai/skills/invoke.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from 'bun:test'++import { appendSkillContext, stripModelNotes } from '@/app/ai/chat/context'+import { invokedSkill } from '@/app/ai/skills/invoke'+import type { SkillLibrary } from '@/app/ai/skills/library'+import type { Skill } from '@/app/ai/skills/types'++import { skillFixture } from '#tests/helpers/chat/skills'++function library(skills: Skill[]): SkillLibrary & { reads: number } {+ const result = {+ reads: 0,+ refresh: async () => {+ result.reads+++ },+ enabled: () => skills+ }+ return result+}++describe('running a skill by name', () => {+ test('finds the skill a message starts with, read fresh', async () => {+ const skills = library([skillFixture()])+ expect(await invokedSkill('/skill:grid lay out the hero', skills)).toMatchObject({+ name: 'grid'+ })+ expect(skills.reads).toBe(1)+ })++ test('ignores text without a command, unknown names, and skills not run by name', async () => {+ const skills = library([skillFixture(), skillFixture({ name: 'brand', userInvocable: false })])+ expect(await invokedSkill('lay out /skill:grid', skills)).toBeNull()+ expect(await invokedSkill('/skill:missing', skills)).toBeNull()+ expect(await invokedSkill('/skill:brand', skills)).toBeNull()+ expect(skills.reads).toBe(2)+ })++ test('gives the model the instructions in a note the transcript leaves out', () => {+ const text = appendSkillContext('/skill:grid lay out the hero', {+ name: 'grid',+ instructions: 'Snap every frame to multiples of 8.'+ })+ expect(text).toContain('<skill name="grid">\nSnap every frame to multiples of 8.\n</skill>')+ expect(stripModelNotes(text)).toBe('/skill:grid lay out the hero')+ expect(appendSkillContext('hello', null)).toBe('hello')+ })+})diff --git a/tests/app/ai/skills/parse.test.ts b/tests/app/ai/skills/parse.test.tsnew file mode 100644index 000000000..60dcd36b0--- /dev/null+++ b/tests/app/ai/skills/parse.test.ts@@ -0,0 +1,80 @@+import { describe, expect, test } from 'bun:test'++import dedent from 'dedent'++import { parseSkill } from '@/app/ai/skills/parse'++describe('parseSkill', () => {+ test('reads the frontmatter and the instructions below it', () => {+ const result = parseSkill(+ dedent`+ ---+ name: brand-review+ description: Check a layout against the brand guide.+ disable-model-invocation: true+ ---++ # Brand review++ Use the brand colors only.+ `,+ 'brand-review'+ )+ expect(result).toEqual({+ ok: true,+ skill: {+ name: 'brand-review',+ description: 'Check a layout against the brand guide.',+ instructions: '# Brand review\n\nUse the brand colors only.',+ modelInvocable: false,+ userInvocable: true+ },+ warnings: []+ })+ })++ test('keeps fields it does not use out of the way', () => {+ const result = parseSkill(+ '---\nname: grid\ndescription: Grids.\nlicense: MIT\nmetadata:\n author: someone\n---\nBody',+ 'grid'+ )+ expect(result.ok && result.warnings).toEqual([])+ })++ test('fails a skill that cannot be offered', () => {+ expect(parseSkill('# No frontmatter', 'grid')).toEqual({+ ok: false,+ error: { code: 'no-frontmatter' }+ })+ expect(parseSkill('---\nname: grid\n---\nBody', 'grid')).toEqual({+ ok: false,+ error: { code: 'no-description' }+ })+ const invalid = parseSkill('---\nname: grid\ndescription: 42\n---\n', 'grid')+ expect(!invalid.ok && invalid.error.code).toBe('invalid-frontmatter')+ expect(parseSkill('---\ndescription: Grids.\n---\n', null)).toEqual({+ ok: false,+ error: { code: 'no-name' }+ })+ })++ test('reads frontmatter that is not valid YAML line by line, with a warning', () => {+ const result = parseSkill(+ '---\nname: grid\ndescription: Grids: columns, gutters,\n and margins.\ndisable-model-invocation: true\n---\nBody',+ 'grid'+ )+ expect(result.ok && result.skill.description).toBe('Grids: columns, gutters, and margins.')+ expect(result.ok && result.skill.modelInvocable).toBe(false)+ expect(result.ok && result.warnings).toEqual(['plain-frontmatter'])+ })++ test('loads a skill that departs from the specification, with warnings', () => {+ const unnamed = parseSkill('---\ndescription: Grids.\n---\nBody', 'grid')+ expect(unnamed.ok && unnamed.skill.name).toBe('grid')+ expect(unnamed.ok && unnamed.warnings).toEqual(['name-from-folder'])++ const misnamed = parseSkill('---\nname: Grid Rules\ndescription: Grids.\n---\nBody', 'grid')+ expect(misnamed.ok && misnamed.skill.name).toBe('Grid Rules')+ expect(misnamed.ok && misnamed.warnings).toEqual(['name-format', 'name-mismatch'])+ })+})diff --git a/tests/app/ai/skills/preferences.test.ts b/tests/app/ai/skills/preferences.test.tsnew file mode 100644index 000000000..d2877155e--- /dev/null+++ b/tests/app/ai/skills/preferences.test.ts@@ -0,0 +1,66 @@+import { describe, expect, test } from 'bun:test'++import {+ enabledSkillsFrom,+ withPickedSkills,+ type SkillPreferences+} from '@/app/ai/skills/preferences'++import { skillFixture } from '#tests/helpers/chat/skills'++const none: SkillPreferences = { sources: {}, skills: {}, trustedFolders: {}, pickedSources: {} }+/** Coding agents' folders switched on, as after picking one of their skills. */+const homeOn: SkillPreferences = { ...none, sources: { agents: true, claude: true } }++describe('enabledSkillsFrom', () => {+ test('offers uploads at once, and coding agents’ skills only once their folder is on', () => {+ const upload = skillFixture({ name: 'brand', source: 'openpencil' })+ const skills = [upload, skillFixture(), skillFixture({ name: 'type-scale', source: 'claude' })]+ expect(enabledSkillsFrom(skills, none)).toEqual([upload])+ expect(enabledSkillsFrom(skills, homeOn)).toEqual(skills)+ })++ test('leaves out a source or a skill the user turned off', () => {+ const grid = skillFixture()+ const scale = skillFixture({ name: 'type-scale', source: 'claude' })+ expect(+ enabledSkillsFrom([grid, scale], { ...homeOn, sources: { agents: true, claude: false } })+ ).toEqual([grid])+ expect(+ enabledSkillsFrom([grid, scale], { ...homeOn, skills: { 'agents/grid': false } })+ ).toEqual([scale])+ })++ test('offers the first skill of a name, and the next once the first is off', () => {+ const shared = skillFixture()+ const claude = skillFixture({ source: 'claude' })+ expect(enabledSkillsFrom([shared, claude], homeOn)).toEqual([shared])+ expect(+ enabledSkillsFrom([shared, claude], { ...homeOn, skills: { 'agents/grid': false } })+ ).toEqual([claude])+ })++ test('offers a skill from a folder near the document only once the folder is trusted', () => {+ const folder = '/work/site/.agents/skills'+ const project = skillFixture({ source: 'project', skillsFolder: folder })+ const shared = skillFixture({ name: 'type-scale', source: 'openpencil' })+ expect(enabledSkillsFrom([project, shared], none)).toEqual([shared])+ const trusted = { ...none, trustedFolders: { [folder]: true } }+ expect(enabledSkillsFrom([project, shared], trusted)).toEqual([project, shared])+ expect(+ enabledSkillsFrom([project], { ...trusted, skills: { [`project/${folder}/grid`]: false } })+ ).toEqual([])+ })++ test('picking skills turns on their folders and only them', () => {+ const grid = skillFixture()+ const release = skillFixture({ name: 'release' })+ const review = skillFixture({ name: 'pr-review', source: 'claude' })+ const picked = withPickedSkills(none, [grid, release, review], new Set(['agents/grid']))+ expect(enabledSkillsFrom([grid, release, review], picked)).toEqual([grid])+ expect(picked.sources).toEqual({ agents: true })+ // A skill installed in that folder later was never picked, so it stays off.+ const later = skillFixture({ name: 'later' })+ expect(enabledSkillsFrom([grid, later], picked)).toEqual([grid])+ })+})diff --git a/tests/app/ai/skills/sources/home.test.ts b/tests/app/ai/skills/sources/home.test.tsnew file mode 100644index 000000000..5072c2e43--- /dev/null+++ b/tests/app/ai/skills/sources/home.test.ts@@ -0,0 +1,59 @@+import { describe, expect, test } from 'bun:test'++import { readHomeSkills, type HomeSkillReader } from '@/app/ai/skills/sources/home'++const SKILL = '---\nname: grid\ndescription: Lay out pages on a grid.\n---\nSnap to 8.'++function reader(roots: Record<string, unknown>): HomeSkillReader & { reads: string[] } {+ const reads: string[] = []+ return {+ reads,+ folders: async (root) => {+ if (!(root in roots)) throw new Error('No such folder')+ return roots[root]+ },+ readFile: async (dir, path) => {+ reads.push(`${dir}/${path}`)+ return 'reference'+ }+ }+}++describe('readHomeSkills', () => {+ test('reads skills from the shared folder before Claude Code’s', async () => {+ const files = reader({+ '/home/.agents/skills': [+ { name: 'grid', path: '/home/.agents/skills/grid', skillFile: SKILL, files: ['ref.md'] }+ ],+ '/home/.claude/skills': [+ { name: 'grid', path: '/home/.claude/skills/grid', skillFile: SKILL, files: [] }+ ]+ })+ const scan = await readHomeSkills('/home', files)+ expect(scan.skills.map((skill) => [skill.source, skill.location])).toEqual([+ ['agents', '~/.agents/skills/grid'],+ ['claude', '~/.claude/skills/grid']+ ])+ await scan.skills[0]?.readFile('ref.md')+ expect(files.reads).toEqual(['/home/.agents/skills/grid/ref.md'])+ })++ test('reports a folder that is not a valid skill and keeps the rest', async () => {+ const scan = await readHomeSkills(+ '/home',+ reader({+ '/home/.agents/skills': [+ { name: 'broken', path: '/x/broken', skillFile: 'no frontmatter', files: [] },+ { name: 'grid', path: '/x/grid', skillFile: SKILL, files: [] }+ ]+ })+ )+ expect(scan.skills.map((skill) => skill.name)).toEqual(['grid'])+ expect(scan.problems.map((problem) => problem.folder)).toEqual(['broken'])+ })++ test('finds nothing in a missing or unreadable folder', async () => {+ const scan = await readHomeSkills('/home', reader({ '/home/.claude/skills': 'not a list' }))+ expect(scan).toEqual({ skills: [], problems: [] })+ })+})diff --git a/tests/app/ai/skills/sources/project.test.ts b/tests/app/ai/skills/sources/project.test.tsnew file mode 100644index 000000000..b8505b03c--- /dev/null+++ b/tests/app/ai/skills/sources/project.test.ts@@ -0,0 +1,55 @@+import { expect, test } from 'bun:test'++import { readProjectSkills, type ProjectSkillReader } from '@/app/ai/skills/sources/project'++const SKILL = '---\nname: grid\ndescription: Lay out pages on a grid.\n---\nSnap to 8.'++test('reads the skills folders a document sees, nearest first, marked with their folder', async () => {+ const roots: Record<string, unknown> = {+ '/home/me/site/design/.agents/skills': [+ {+ name: 'grid',+ path: '/home/me/site/design/.agents/skills/grid',+ skillFile: SKILL,+ files: []+ }+ ],+ '/home/me/site/.claude/skills': [+ { name: 'broken', path: '/home/me/site/.claude/skills/broken', skillFile: '# x', files: [] }+ ]+ }+ const reader: ProjectSkillReader = {+ skillsFolders: async (dir) => (dir === '/home/me/site/design' ? Object.keys(roots) : []),+ folders: async (root) => roots[root] ?? [],+ readFile: async () => ''+ }+ const scan = await readProjectSkills('/home/me/site/design', '/home/me', reader)+ expect(scan.folders).toEqual([+ { path: '/home/me/site/design/.agents/skills', location: '~/site/design/.agents/skills' },+ { path: '/home/me/site/.claude/skills', location: '~/site/.claude/skills' }+ ])+ expect(scan.skills).toMatchObject([+ {+ name: 'grid',+ source: 'project',+ location: '~/site/design/.agents/skills/grid',+ skillsFolder: '/home/me/site/design/.agents/skills'+ }+ ])+ expect(scan.problems).toMatchObject([+ { source: 'project', skillsFolder: '/home/me/site/.claude/skills', folder: 'broken' }+ ])+})++test('a document folder that cannot be searched has no skills', async () => {+ const reader: ProjectSkillReader = {+ skillsFolders: () => Promise.reject(new Error('No access')),+ folders: async () => [],+ readFile: async () => ''+ }+ expect(await readProjectSkills('/tmp', '/home/me', reader)).toEqual({+ folders: [],+ skills: [],+ problems: []+ })+})diff --git a/tests/app/ai/skills/sources/uploaded.test.ts b/tests/app/ai/skills/sources/uploaded.test.tsnew file mode 100644index 000000000..19cc4311b--- /dev/null+++ b/tests/app/ai/skills/sources/uploaded.test.ts@@ -0,0 +1,120 @@+import { describe, expect, test } from 'bun:test'++import { strToU8, zipSync } from 'fflate'++import {+ skillFromArchive,+ skillFromUpload,+ skillsFromUploads+} from '@/app/ai/skills/sources/uploaded'++const SKILL = '---\nname: grid\ndescription: Lay out pages on a grid.\n---\nSnap to 8.'++function archive(files: Record<string, string | Uint8Array>): Uint8Array {+ return zipSync(+ Object.fromEntries(+ Object.entries(files).map(([path, content]) => [+ path,+ typeof content === 'string' ? strToU8(content) : content+ ])+ )+ )+}++describe('skillFromArchive', () => {+ test('reads a skill folder packed with its files', () => {+ const upload = skillFromArchive(+ archive({+ 'grid/SKILL.md': SKILL,+ 'grid/references/spacing.md': '8, 16, 24',+ 'grid/assets/logo.png': new Uint8Array([0x89, 0x50, 0xff, 0xfe]),+ '__MACOSX/grid/._SKILL.md': 'resource fork',+ 'grid/.DS_Store': 'finder'+ }),+ 1+ )+ expect(upload).toEqual({+ ok: true,+ skill: {+ name: 'grid',+ skillFile: SKILL,+ files: [{ path: 'references/spacing.md', content: '8, 16, 24' }],+ uploadedAt: 1+ }+ })+ })++ test('reads a skill packed at the archive root', () => {+ const upload = skillFromArchive(archive({ 'SKILL.md': SKILL, 'notes.md': 'n' }), 1)+ expect(upload.ok && upload.skill.files.map((file) => file.path)).toEqual(['notes.md'])+ })++ test('refuses an archive without exactly one skill', () => {+ expect(skillFromArchive(archive({ 'README.md': 'no skill' }), 1)).toMatchObject({+ reason: 'no-skill'+ })+ expect(+ skillFromArchive(archive({ 'a/SKILL.md': SKILL, 'b/SKILL.md': SKILL }), 1)+ ).toMatchObject({ reason: 'several-skills' })+ expect(skillFromArchive(strToU8('not a zip'), 1)).toMatchObject({ reason: 'unreadable' })+ expect(skillFromArchive(archive({ 'grid/SKILL.md': '# no frontmatter' }), 1)).toMatchObject({+ reason: 'invalid'+ })+ })+})++test('refuses an archive that would unpack past its limits before inflating it', () => {+ // Zeros deflate to almost nothing; together these declare far more than an upload may hold.+ const zeros = new Uint8Array(1024 * 1024)+ const files = Object.fromEntries(+ Array.from({ length: 30 }, (_, index) => [`grid/zeros-${index}.txt`, zeros])+ )+ expect(skillFromArchive(archive({ 'grid/SKILL.md': SKILL, ...files }), 0)).toEqual({+ ok: false,+ reason: 'too-large'+ })+ const many = Object.fromEntries(+ Array.from({ length: 250 }, (_, index) => [`grid/notes-${index}.md`, 'x'])+ )+ expect(skillFromArchive(archive({ 'grid/SKILL.md': SKILL, ...many }), 0)).toEqual({+ ok: false,+ reason: 'too-large'+ })+})++describe('skillFromUpload', () => {+ test('reads a SKILL.md on its own, which must name itself', async () => {+ const upload = await skillFromUpload(new File([SKILL], 'SKILL.md'), 1)+ expect(upload.ok && upload.skill.name).toBe('grid')+ const unnamed = new File(['---\ndescription: Grids.\n---\n'], 'SKILL.md')+ expect(await skillFromUpload(unnamed, 1)).toMatchObject({ reason: 'invalid' })+ })+})++describe('skillsFromUploads', () => {+ test('offers an upload’s files to the chat', async () => {+ const { skills } = skillsFromUploads([+ {+ name: 'grid',+ skillFile: SKILL,+ files: [{ path: 'references/spacing.md', content: '8' }],+ uploadedAt: 1+ }+ ])+ expect(skills.map((skill) => [skill.source, skill.name, skill.files])).toEqual([+ ['openpencil', 'grid', ['references/spacing.md']]+ ])+ expect(await skills[0]?.readFile('references/spacing.md')).toBe('8')+ })+})++test('an upload named by its folder still loads when read back', () => {+ const upload = skillFromArchive(+ archive({ 'grid/SKILL.md': '---\ndescription: Lay out pages on a grid.\n---\nSnap to 8.' }),+ 0+ )+ if (!upload.ok) throw new Error('Expected the upload to be accepted')+ const { skills, problems } = skillsFromUploads([upload.skill])+ expect(problems).toEqual([])+ expect(skills).toMatchObject([{ name: 'grid', warnings: ['name-from-folder'] }])+})diff --git a/tests/app/ai/skills/tools.test.ts b/tests/app/ai/skills/tools.test.tsnew file mode 100644index 000000000..058f746a6--- /dev/null+++ b/tests/app/ai/skills/tools.test.ts@@ -0,0 +1,73 @@+import { describe, expect, test } from 'bun:test'++import { createSkillTools } from '@/app/ai/skills/tools'+import type { Skill } from '@/app/ai/skills/types'++import { skillFixture } from '#tests/helpers/chat/skills'++const callOptions = { toolCallId: 'call', messages: [], context: {} }++function toolsFor(skills: Skill[]) {+ const tools = createSkillTools(() => skills)+ return {+ load: (input: { name: string }) => tools.load_skill.execute?.(input, callOptions),+ read: (input: { name: string; path: string }) =>+ tools.read_skill_file.execute?.(input, callOptions)+ }+}++describe('load_skill', () => {+ test('returns the instructions and the files the skill can offer', async () => {+ const tools = toolsFor([skillFixture({ files: ['references/spacing.md'] })])+ expect(await tools.load({ name: 'grid' })).toEqual({+ name: 'grid',+ instructions: 'Snap every frame to multiples of 8.',+ files: ['references/spacing.md']+ })+ })++ test('fails for a skill that is not enabled', async () => {+ expect(await toolsFor([skillFixture()]).load({ name: 'missing' })).toHaveProperty('error')+ })+})++describe('read_skill_file', () => {+ test('reads a file the skill lists', async () => {+ const skill = skillFixture({+ files: ['references/spacing.md'],+ readFile: (path) => Promise.resolve(`contents of ${path}`)+ })+ expect(await toolsFor([skill]).read({ name: 'grid', path: 'references/spacing.md' })).toEqual({+ path: 'references/spacing.md',+ text: 'contents of references/spacing.md'+ })+ })++ test('never reads a path the skill does not list', async () => {+ const requested: string[] = []+ const skill = skillFixture({+ files: ['references/spacing.md'],+ readFile: (path) => {+ requested.push(path)+ return Promise.resolve('')+ }+ })+ const result = await toolsFor([skill]).read({ name: 'grid', path: '../../.ssh/id_rsa' })+ expect(result).toHaveProperty('error')+ expect(requested).toEqual([])+ })++ test('shortens a long file and says so', async () => {+ const skill = skillFixture({+ files: ['big.md'],+ readFile: () => Promise.resolve('x'.repeat(1_000_000))+ })+ const result = await toolsFor([skill]).read({ name: 'grid', path: 'big.md' })+ expect(result).toMatchObject({ truncated: true })+ })++ test('reports a file that cannot be read', async () => {+ const skill = skillFixture({ files: ['gone.md'] })+ expect(await toolsFor([skill]).read({ name: 'grid', path: 'gone.md' })).toHaveProperty('error')+ })+})diff --git a/tests/app/ai/transports/tool-loop.test.ts b/tests/app/ai/transports/tool-loop.test.tsindex 41683bf6a..34497b609 100644--- a/tests/app/ai/transports/tool-loop.test.ts+++ b/tests/app/ai/transports/tool-loop.test.ts@@ -10,10 +10,12 @@ import type { AIProviderID } from '@open-pencil/core/constants'import { createRunRecorder } from '@/app/ai/chat/trace/recorder'import type { ThinkingLevel } from '@/app/ai/models/types'import { modelProviderAdapter } from '@/app/ai/providers/registry'+import type { Skill } from '@/app/ai/skills/types'import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import { createEditorStore } from '@/app/editor/session/create'import { expectDefined } from '#tests/helpers/assert'+import { skillFixture } from '#tests/helpers/chat/skills'import { memoryTraceStore } from '#tests/helpers/chat/trace-store'import { MOCK_USAGE } from '#tests/helpers/chat/usage'import { fetchStub } from '#tests/helpers/fetch'@@ -193,3 +195,64 @@ test('Z.AI caches automatically and gets no cache marker', async () => {const body = await serializedRequest('zai', 'glm-4.6', 'default')expect(body.cache_control).toBeUndefined()})++test('enabled skills reach the model as a listing and the tools that load them', async () => {+ const store = createEditorStore()+ const model = replyModel()+ // Each message reads the skills again; the second finds none left.+ const reads: Skill[][] = [[skillFixture()], []]+ let enabled: Skill[] = []+ try {+ const transport = createToolLoopTransport({+ store,+ providerID: 'anthropic',+ model,+ effectiveModelID: 'claude-test',+ maxOutputTokens: 100,+ thinkingLevel: () => 'default',+ skills: {+ refresh: async () => {+ enabled = reads.shift() ?? []+ },+ enabled: () => enabled+ }+ })+ await send(transport)+ await send(transport)+ const [withSkills, without] = model.doStreamCalls.map((call) => ({+ system: call.prompt.flatMap((message) =>+ message.role === 'system' ? [message.content] : []+ ),+ tools: (call.tools ?? []).map((tool) => tool.name)+ }))+ expect(withSkills?.system.join('\n')).toContain('<name>grid</name>')+ expect(withSkills?.tools).toEqual(expect.arrayContaining(['load_skill', 'read_skill_file']))+ expect(without?.system.join('\n')).not.toContain('<name>grid</name>')+ expect(without?.tools).not.toContain('load_skill')+ } finally {+ store.dispose()+ }+})++test('skills the user runs only by name are neither listed nor loadable', async () => {+ const store = createEditorStore()+ const model = replyModel()+ const manual = skillFixture({ name: 'release', modelInvocable: false })+ try {+ const transport = createToolLoopTransport({+ store,+ providerID: 'anthropic',+ model,+ effectiveModelID: 'claude-test',+ maxOutputTokens: 100,+ thinkingLevel: () => 'default',+ skills: { refresh: async () => undefined, enabled: () => [manual] }+ })+ await send(transport)+ const [call] = model.doStreamCalls+ expect((call?.tools ?? []).map((tool) => tool.name)).not.toContain('load_skill')+ expect(JSON.stringify(call?.prompt)).not.toContain('release')+ } finally {+ store.dispose()+ }+})diff --git a/tests/e2e/settings/skills.spec.ts b/tests/e2e/settings/skills.spec.tsnew file mode 100644index 000000000..a700cfe6f--- /dev/null+++ b/tests/e2e/settings/skills.spec.ts@@ -0,0 +1,58 @@+import { expect, test, type Page } from '@playwright/test'+import { strToU8, zipSync } from 'fflate'++import { CanvasHelper } from '#tests/helpers/canvas'++const SKILL =+ '---\nname: grid\ndescription: Lay out pages on an eight-point grid.\n---\n# Grid\n\nSnap every frame to multiples of 8.'++async function openSkills(page: Page) {+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+,' : 'Control+,')+ await page.getByRole('tab', { name: 'Skills', exact: true }).click()+}++async function upload(page: Page, name: string, buffer: Buffer) {+ const chooser = page.waitForEvent('filechooser')+ await page.getByRole('button', { name: 'Upload skill' }).click()+ await (await chooser).setFiles({ name, mimeType: 'application/octet-stream', buffer })+}++test('an uploaded skill can be read, turned off, and deleted', async ({ page }) => {+ await page.goto('/?test')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()+ await openSkills(page)++ await upload(page, 'grid.zip', Buffer.from(zipSync({ 'grid/SKILL.md': strToU8(SKILL) })))+ const row = page.getByRole('button', { name: /^grid / })+ await row.click()++ const details = page.getByTestId('settings-skill-details')+ await expect(details.getByRole('heading', { name: 'Grid', exact: true })).toBeVisible()+ await expect(page.getByTestId('settings-breadcrumb')).toContainText('grid')+ const use = details.getByRole('switch')+ await expect(use).toHaveAttribute('data-state', 'checked')+ await use.click()+ await page.getByTestId('settings-editor-back').click()+ await expect(details).toBeHidden()++ await page.reload()+ await canvas.waitForInit()+ await openSkills(page)+ await row.click()+ await expect(use).toHaveAttribute('data-state', 'unchecked')++ await details.getByRole('button', { name: 'Delete skill' }).click()+ await page.getByRole('alertdialog').getByRole('button', { name: 'Delete skill' }).click()+ await expect(details).toBeHidden()+ await expect(row).toHaveCount(0)+})++test('a file that holds no skill is refused', async ({ page }) => {+ await page.goto('/?test')+ await new CanvasHelper(page).waitForInit()+ await openSkills(page)+ await upload(page, 'notes.zip', Buffer.from(zipSync({ 'README.md': strToU8('# Notes') })))+ await expect(page.getByRole('alert')).toBeVisible()+ await expect(page.locator('[data-skill]')).toHaveCount(0)+})diff --git a/tests/helpers/chat/skills.ts b/tests/helpers/chat/skills.tsnew file mode 100644index 000000000..7f98c6cf3--- /dev/null+++ b/tests/helpers/chat/skills.ts@@ -0,0 +1,17 @@+import type { Skill } from '@/app/ai/skills/types'++export function skillFixture(overrides: Partial<Skill> = {}): Skill {+ return {+ name: 'grid',+ description: 'Lay out pages on an eight-point grid.',+ instructions: 'Snap every frame to multiples of 8.',+ modelInvocable: true,+ userInvocable: true,+ source: 'agents',+ location: '~/.agents/skills/grid',+ files: [],+ readFile: () => Promise.reject(new Error('No files')),+ warnings: [],+ ...overrides+ }+}diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 74845dd69..dc5033983 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -570,3 +570,34 @@ ja:ai.connectionTestCloudCreditsExhaustedzh-cn:ai.chatCloudAllowanceUsedzh-cn:ai.chatCloudAllowanceUsedUntilzh-cn:ai.connectionTestCloudCreditsExhausted+ja:ai.skillsUploadedSourceDescription+ja:ai.skillsAgentsSourceDescription+ja:ai.skillsClaudeSource+ja:ai.skillsUploadTooLarge+ja:ai.skillsUploadNoSkill+ja:ai.skillsUploadUnreadable+ja:ai.skillsDeleteDescription+ja:ai.skillsWarnings+ja:ai.skillsUseDescription+ja:ai.skillWarningPlainFrontmatter+ja:ai.skillErrorNoFrontmatter+ja:ai.skillErrorInvalidFrontmatter+ja:ai.skillErrorNoDescription+ja:ai.skillErrorNoName+zh-cn:ai.skillsUploadedSourceDescription+zh-cn:ai.skillsAgentsSourceDescription+zh-cn:ai.skillsClaudeSource+zh-cn:ai.skillsUploadTooLarge+zh-cn:ai.skillsUploadNoSkill+zh-cn:ai.skillsUploadUnreadable+zh-cn:ai.skillsDeleteDescription+zh-cn:ai.skillsWarnings+zh-cn:ai.skillsUseDescription+zh-cn:ai.skillWarningPlainFrontmatter+zh-cn:ai.skillWarningNameFromFolder+zh-cn:ai.skillErrorNoFrontmatter+zh-cn:ai.skillErrorInvalidFrontmatter+zh-cn:ai.skillErrorNoDescription+zh-cn:ai.skillErrorNoName+ja:ai.skillsTrustDescription+zh-cn:ai.skillsTrustDescriptiondiff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 6a7f77669..96c3e53e9 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -527,3 +527,4 @@ pl:shapes.engFolderru:cloud.productNameru:cloud.homeCloudOnHostru:cloud.inviteEmailPlaceholder+de:settings.skills