Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(skill):Add skills cli and api, support add skills from git, support update skills (#2453)
DuTao78471b6485ce
diff --git a/Cargo.lock b/Cargo.lockindex 8e0690037..e721fe096 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3251,6 +3251,7 @@ dependencies = ["rustyline","serde","serde_json",+ "serde_yaml","tempfile","termimad","thiserror 1.0.69",@@ -4338,6 +4339,19 @@ dependencies = ["serde",]+[[package]]+name = "serde_yaml"+version = "0.9.34+deprecated"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"+dependencies = [+ "indexmap",+ "itoa",+ "ryu",+ "serde",+ "unsafe-libyaml",+]+[[package]]name = "sha1"version = "0.10.6"@@ -5192,6 +5206,12 @@ dependencies = ["subtle",]+[[package]]+name = "unsafe-libyaml"+version = "0.2.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"+[[package]]name = "untrusted"version = "0.9.0"diff --git a/crates/ov_cli/Cargo.toml b/crates/ov_cli/Cargo.tomlindex c8232e542..a3bcbf3d4 100644--- a/crates/ov_cli/Cargo.toml+++ b/crates/ov_cli/Cargo.toml@@ -16,6 +16,7 @@ clap = { version = "4.5", features = ["derive", "env"] }reqwest = { version = "0.12", features = ["json", "multipart", "rustls-tls"], default-features = false }serde = { version = "1.0", features = ["derive"] }serde_json = { version = "1.0", features = ["preserve_order"] }+serde_yaml = "0.9"tokio = { version = "1.38", features = ["full"] }futures = "0.3"colored = "2.1"diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rsindex 71efdec7a..f8419447a 100644--- a/crates/ov_cli/src/base_client.rs+++ b/crates/ov_cli/src/base_client.rs@@ -574,15 +574,7 @@ mod tests {#[test]fn append_profile_query_adds_flag_when_enabled() {- let client = BaseClient::new(- "http://localhost:1933",- None,- None,- None,- 5.0,- true,- None,- );+ let client = BaseClient::new("http://localhost:1933", None, None, None, 5.0, true, None);let params =client.append_profile_query(&[("to_uri".to_string(), "viking://x".to_string())]);@@ -598,15 +590,7 @@ mod tests {#[test]fn append_profile_query_keeps_existing_profile_flag() {- let client = BaseClient::new(- "http://localhost:1933",- None,- None,- None,- 5.0,- true,- None,- );+ let client = BaseClient::new("http://localhost:1933", None, None, None, 5.0, true, None);let params = client.append_profile_query(&[("profile".to_string(), "1".to_string())]);diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 70fdd09a9..6f228e68f 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -629,6 +629,7 @@ impl HttpClient {timeout: Option<f64>,show_progress: bool,verbose: bool,+ source_metadata: Option<Value>,) -> Result<serde_json::Value> {let path_obj = Path::new(data);@@ -646,11 +647,14 @@ impl HttpClient {self.upload_temp_file(zip_file.path()).await?};- let body = serde_json::json!({+ let mut body = serde_json::json!({"temp_file_id": temp_file_id,"wait": wait,"timeout": timeout,});+ if let Some(source_metadata) = source_metadata.clone() {+ body["source_metadata"] = source_metadata;+ }let dynamic_timeout =TimeoutConfig::for_resource_processing().calculate(zip_file.path())?;self.base@@ -664,34 +668,218 @@ impl HttpClient {self.upload_temp_file(path_obj).await?};- let body = serde_json::json!({+ let mut body = serde_json::json!({"temp_file_id": temp_file_id,"wait": wait,"timeout": timeout,});+ if let Some(source_metadata) = source_metadata.clone() {+ body["source_metadata"] = source_metadata;+ }let dynamic_timeout =TimeoutConfig::for_resource_processing().calculate(path_obj)?;self.base.post_with_timeout("/api/v1/skills", &body, dynamic_timeout).await} else {- let body = serde_json::json!({+ let mut body = serde_json::json!({"data": data,"wait": wait,"timeout": timeout,});+ if let Some(source_metadata) = source_metadata.clone() {+ body["source_metadata"] = source_metadata;+ }self.post("/api/v1/skills", &body).await}} else {- let body = serde_json::json!({+ let mut body = serde_json::json!({"data": data,"wait": wait,"timeout": timeout,});+ if let Some(source_metadata) = source_metadata {+ body["source_metadata"] = source_metadata;+ }self.post("/api/v1/skills", &body).await}}+ pub async fn skills_list(&self, node_limit: i32) -> Result<serde_json::Value> {+ let params = vec![("node_limit".to_string(), node_limit.to_string())];+ self.get("/api/v1/skills", ¶ms).await+ }++ pub async fn skill_show(+ &self,+ name: &str,+ include_content: bool,+ include_files: bool,+ include_source: bool,+ level: Option<i32>,+ ) -> Result<serde_json::Value> {+ let path = format!("/api/v1/skills/{}", name);+ let mut params = vec![+ ("include_content".to_string(), include_content.to_string()),+ ("include_files".to_string(), include_files.to_string()),+ ("include_source".to_string(), include_source.to_string()),+ ];+ if let Some(level) = level {+ params.push(("level".to_string(), level.to_string()));+ }+ self.get(&path, ¶ms).await+ }++ pub async fn skill_find(+ &self,+ query: &str,+ node_limit: i32,+ threshold: Option<f64>,+ level: Option<Vec<i32>>,+ ) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "query": query,+ "limit": node_limit,+ "score_threshold": threshold,+ "level": level,+ });+ self.post("/api/v1/skills/find", &body).await+ }++ pub async fn skill_validate(&self, path: &str, strict: bool) -> Result<serde_json::Value> {+ let path_obj = Path::new(path);+ if !path_obj.exists() {+ return Err(Error::Client(format!(+ "Skill path '{}' does not exist.",+ path+ )));+ }++ let skill_file = if path_obj.is_dir() {+ let skill_file = path_obj.join("SKILL.md");+ if !skill_file.is_file() {+ return Err(Error::Client(format!(+ "SKILL.md not found in '{}'.",+ path_obj.display()+ )));+ }+ skill_file+ } else if path_obj.is_file() {+ if path_obj.file_name().and_then(|name| name.to_str()) != Some("SKILL.md") {+ return Err(Error::Client(+ "Validate expects a SKILL.md file or a skill directory.".to_string(),+ ));+ }+ path_obj.to_path_buf()+ } else {+ return Err(Error::Client(format!(+ "Skill path '{}' is not a file or directory.",+ path+ )));+ };++ let content = std::fs::read_to_string(&skill_file).map_err(|e| {+ Error::Client(format!(+ "Failed to read skill file '{}': {}",+ skill_file.display(),+ e+ ))+ })?;+ let skill_dir_name = skill_file+ .parent()+ .and_then(|parent| parent.file_name())+ .and_then(|name| name.to_str())+ .unwrap_or("")+ .to_string();+ let body = serde_json::json!({+ "data": content,+ "strict": strict,+ "source_path": skill_file.to_string_lossy(),+ "skill_dir_name": skill_dir_name,+ });+ self.post("/api/v1/skills/validate", &body).await+ }++ pub async fn skill_update(+ &self,+ name: &str,+ data: &str,+ wait: bool,+ timeout: Option<f64>,+ show_progress: bool,+ verbose: bool,+ source_metadata: Option<Value>,+ ) -> Result<serde_json::Value> {+ let endpoint = format!("/api/v1/skills/{}", name);+ let path_obj = Path::new(data);++ if path_obj.exists() {+ if path_obj.is_dir() {+ let zip_file = if show_progress {+ self.zip_directory_with_progress(path_obj, verbose, None)?+ } else {+ self.zip_directory(path_obj, None)?+ };+ let temp_file_id = if show_progress {+ self.upload_temp_file_with_progress(zip_file.path(), verbose)+ .await?+ } else {+ self.upload_temp_file(zip_file.path()).await?+ };+ let mut body = serde_json::json!({+ "temp_file_id": temp_file_id,+ "wait": wait,+ "timeout": timeout,+ });+ if let Some(source_metadata) = source_metadata.clone() {+ body["source_metadata"] = source_metadata;+ }+ self.put(&endpoint, &body).await+ } else if path_obj.is_file() {+ let temp_file_id = if show_progress {+ self.upload_temp_file_with_progress(path_obj, verbose)+ .await?+ } else {+ self.upload_temp_file(path_obj).await?+ };+ let mut body = serde_json::json!({+ "temp_file_id": temp_file_id,+ "wait": wait,+ "timeout": timeout,+ });+ if let Some(source_metadata) = source_metadata.clone() {+ body["source_metadata"] = source_metadata;+ }+ self.put(&endpoint, &body).await+ } else {+ let mut body = serde_json::json!({+ "data": data,+ "wait": wait,+ "timeout": timeout,+ });+ if let Some(source_metadata) = source_metadata.clone() {+ body["source_metadata"] = source_metadata;+ }+ self.put(&endpoint, &body).await+ }+ } else {+ let mut body = serde_json::json!({+ "data": data,+ "wait": wait,+ "timeout": timeout,+ });+ if let Some(source_metadata) = source_metadata {+ body["source_metadata"] = source_metadata;+ }+ self.put(&endpoint, &body).await+ }+ }++ pub async fn skill_remove(&self, name: &str) -> Result<serde_json::Value> {+ let path = format!("/api/v1/skills/{}", name);+ self.delete(&path, &[]).await+ }+// ============ Task Methods ============pub async fn get_task(&self, task_id: &str) -> Result<serde_json::Value> {diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rsindex 371b653d8..60130d306 100644--- a/crates/ov_cli/src/commands/content.rs+++ b/crates/ov_cli/src/commands/content.rs@@ -46,15 +46,7 @@ pub async fn write(output_format: OutputFormat,compact: bool,) -> Result<()> {- let result = client- .write(- uri,- content,- mode,- wait,- timeout,- )- .await?;+ let result = client.write(uri, content, mode, wait, timeout).await?;crate::output::output_success(result, output_format, compact);Ok(())}@@ -133,17 +125,7 @@ mod tests {assert_eq!(rendered,- Some(- [- "content",- "",- "profile",- "line one",- "line two",- "",- ]- .join("\n")- )+ Some(["content", "", "profile", "line one", "line two", "",].join("\n")));}}diff --git a/crates/ov_cli/src/commands/mod.rs b/crates/ov_cli/src/commands/mod.rsindex 13e390ac4..3673431b6 100644--- a/crates/ov_cli/src/commands/mod.rs+++ b/crates/ov_cli/src/commands/mod.rs@@ -11,6 +11,7 @@ pub(crate) mod render_utils;pub mod resources;pub mod search;pub mod session;+pub mod skills;pub mod system;pub mod task;pub mod watch;diff --git a/crates/ov_cli/src/commands/privacy.rs b/crates/ov_cli/src/commands/privacy.rsindex fa40b7c0d..a99cf1dbe 100644--- a/crates/ov_cli/src/commands/privacy.rs+++ b/crates/ov_cli/src/commands/privacy.rs@@ -8,7 +8,10 @@ fn parse_kv_pairs(pairs: &[String]) -> Result<HashMap<String, String>> {let mut parsed: HashMap<String, String> = HashMap::new();for pair in pairs {let (key, value) = pair.split_once('=').ok_or_else(|| {- Error::Client(format!("Invalid --key format: {} (expected key=value)", pair))+ Error::Client(format!(+ "Invalid --key format: {} (expected key=value)",+ pair+ ))})?;let key = key.trim();if key.is_empty() {@@ -63,13 +66,13 @@ fn to_kv_row(key: &str, value: &Value) -> Value {fn to_kv_rows(map: &Map<String, Value>) -> Vec<Value> {let mut items: Vec<(&String, &Value)> = map.iter().collect();items.sort_by(|(a, _), (b, _)| a.cmp(b));- items- .into_iter()- .map(|(k, v)| to_kv_row(k, v))- .collect()+ items.into_iter().map(|(k, v)| to_kv_row(k, v)).collect()}-fn split_kv_rows_by_keys(map: &Map<String, Value>, selected_keys: &HashSet<String>) -> (Vec<Value>, Vec<Value>) {+fn split_kv_rows_by_keys(+ map: &Map<String, Value>,+ selected_keys: &HashSet<String>,+) -> (Vec<Value>, Vec<Value>) {let mut items: Vec<(&String, &Value)> = map.iter().collect();items.sort_by(|(a, _), (b, _)| a.cmp(b));@@ -183,11 +186,18 @@ fn output_version_like_tables(result: &Value, _compact: bool) -> Result<()> {.ok_or_else(|| Error::Parse("Expected values object in response".to_string()))?;let rendered = render_meta_current_tables(&meta, &values);- println!("{}", crate::output::append_profile_to_rendered(rendered, result));+ println!(+ "{}",+ crate::output::append_profile_to_rendered(rendered, result)+ );Ok(())}-pub async fn categories(client: &HttpClient, output_format: OutputFormat, compact: bool) -> Result<()> {+pub async fn categories(+ client: &HttpClient,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {let result = client.privacy_list_categories().await?;output_success(&result, output_format, compact);Ok(())@@ -225,7 +235,10 @@ pub async fn get_current(.ok_or_else(|| Error::Parse("Expected current.values object in response".to_string()))?.clone();let rendered = render_meta_current_tables(&meta, &values);- println!("{}", crate::output::append_profile_to_rendered(rendered, &result));+ println!(+ "{}",+ crate::output::append_profile_to_rendered(rendered, &result)+ );return Ok(());}@@ -253,7 +266,9 @@ pub async fn get_version(output_format: OutputFormat,compact: bool,) -> Result<()> {- let result = client.privacy_get_version(category, target_key, version).await?;+ let result = client+ .privacy_get_version(category, target_key, version)+ .await?;if matches!(output_format, OutputFormat::Table) {return output_version_like_tables(&result, compact);}@@ -270,7 +285,9 @@ pub async fn activate(output_format: OutputFormat,compact: bool,) -> Result<()> {- let result = client.privacy_activate(category, target_key, version).await?;+ let result = client+ .privacy_activate(category, target_key, version)+ .await?;if matches!(output_format, OutputFormat::Table) {return output_version_like_tables(&result, compact);}@@ -308,7 +325,9 @@ pub async fn upsert(.and_then(|v| v.get("values")).and_then(Value::as_object).ok_or_else(|| {- Error::Parse("privacy get current response missing current.values object".to_string())+ Error::Parse(+ "privacy get current response missing current.values object".to_string(),+ )})?.clone();@@ -334,7 +353,9 @@ pub async fn upsert(let parsed: Value = serde_json::from_str(raw).map_err(|e| Error::Client(format!("Invalid JSON for --labels-json: {}", e)))?;if !parsed.is_object() {- return Err(Error::Client("--labels-json must be a JSON object".to_string()));+ return Err(Error::Client(+ "--labels-json must be a JSON object".to_string(),+ ));}Some(parsed)} else {@@ -349,7 +370,9 @@ pub async fn upsert(payload["labels"] = labels;}- let result = client.privacy_upsert(category, target_key, &payload).await?;+ let result = client+ .privacy_upsert(category, target_key, &payload)+ .await?;if matches!(output_format, OutputFormat::Table) {let values = result.get("values")@@ -362,7 +385,10 @@ pub async fn upsert(render_section_table("updated", updated_rows),render_section_table("unchanged", unchanged_rows));- println!("{}", crate::output::append_profile_to_rendered(rendered, &result));+ println!(+ "{}",+ crate::output::append_profile_to_rendered(rendered, &result)+ );return Ok(());}@@ -388,10 +414,7 @@ mod tests {]});- let mut meta = result- .as_object()- .expect("object")- .clone();+ let mut meta = result.as_object().expect("object").clone();let values = meta.remove("values").and_then(|v| v.as_object().cloned())@@ -401,10 +424,7 @@ mod tests {render_kv_ascii_table(&to_kv_rows(&meta)),render_kv_ascii_table(&to_kv_rows(&values)));- let final_rendered = crate::output::append_profile_to_rendered(- rendered,- &result,- );+ let final_rendered = crate::output::append_profile_to_rendered(rendered, &result);assert!(final_rendered.contains("profile\nprivacy took 3ms\n"));}diff --git a/crates/ov_cli/src/commands/resources.rs b/crates/ov_cli/src/commands/resources.rsindex b3e8a811d..ca9c404cd 100644--- a/crates/ov_cli/src/commands/resources.rs+++ b/crates/ov_cli/src/commands/resources.rs@@ -46,7 +46,9 @@ pub async fn add_resource(if !wait && matches!(format, OutputFormat::Table) {eprintln!("Note: Resource is being processed in the background.");- eprintln!("Use 'ov task status <task_id>' to check progress, or 'ov task list' to see all tasks.");+ eprintln!(+ "Use 'ov task status <task_id>' to check progress, or 'ov task list' to see all tasks."+ );}output_success(&result, format, compact);@@ -64,12 +66,14 @@ pub async fn add_skill(compact: bool,) -> Result<()> {let result = client- .add_skill(data, wait, timeout, show_progress, verbose)+ .add_skill(data, wait, timeout, show_progress, verbose, None).await?;if !wait && matches!(format, OutputFormat::Table) {eprintln!("Note: Skill is being processed in the background.");- eprintln!("Use 'ov task status <task_id>' to check progress, or 'ov task list' to see all tasks.");+ eprintln!(+ "Use 'ov task status <task_id>' to check progress, or 'ov task list' to see all tasks."+ );}output_success(&result, format, compact);diff --git a/crates/ov_cli/src/commands/skills.rs b/crates/ov_cli/src/commands/skills.rsnew file mode 100644index 000000000..855a82c59--- /dev/null+++ b/crates/ov_cli/src/commands/skills.rs@@ -0,0 +1,2018 @@+use crate::client::HttpClient;+use crate::error::{Error, Result};+use crate::output::{OutputFormat, output_success};+use crate::theme;+use colored::Colorize;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::collections::BTreeSet;+use std::io::{self, IsTerminal, Write};+use std::path::{Component, Path, PathBuf};+use std::process::Command;+use tempfile::TempDir;+use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};+use url::Url;++enum PreparedSource {+ Raw(String),+ Path {+ path: PathBuf,+ _temp_dir: Option<TempDir>,+ origin: SourceOrigin,+ },+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct GitSource {+ clone_url: String,+ ref_name: Option<String>,+ subdir: Option<PathBuf>,+}++#[derive(Debug, Clone)]+enum SourceOrigin {+ Local { source: String },+ Git(GitSource),+}++#[derive(Debug)]+struct AddTarget {+ data: String,+ source: Option<SkillSourceRecord>,+ _temp_dir: Option<TempDir>,+}++#[derive(Debug, Clone)]+struct InstalledSkillSummary {+ name: String,+ description: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+struct SkillSourceRecord {+ #[serde(rename = "type")]+ source_type: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ source: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ path: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ clone_url: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ ref_name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ subdir: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ skill_name: Option<String>,+}++impl PreparedSource {+ fn path(&self) -> Option<&Path> {+ match self {+ Self::Path { path, .. } => Some(path.as_path()),+ Self::Raw(_) => None,+ }+ }+}++pub async fn add(+ client: &HttpClient,+ data: &str,+ skill_names: Vec<String>,+ list_only: bool,+ wait: bool,+ yes: bool,+ show_progress: bool,+ verbose: bool,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let source = prepare_source(data)?;+ if list_only {+ return list_source_skills(&source, output_format, compact);+ }++ let targets = resolve_add_targets(&source, &skill_names)?;+ if targets.is_empty() {+ return Err(Error::Client("No skills to install.".to_string()));+ }+ if targets.len() > 1 && !yes {+ let names = targets.iter().map(skill_target_label).collect::<Vec<_>>();+ if !confirm_action("Install", &names)? {+ output_message_result(+ serde_json::json!({ "cancelled": true, "skills": names }),+ "Aborted.".to_string(),+ output_format,+ compact,+ );+ return Ok(());+ }+ }++ let mut installed = Vec::new();++ for target in targets {+ let source_metadata = source_record_value(target.source.as_ref())?;+ let result = client+ .add_skill(+ &target.data,+ wait,+ None,+ show_progress,+ verbose,+ source_metadata,+ )+ .await?;+ installed.push(result);+ }++ if !wait && matches!(output_format, OutputFormat::Table) {+ eprintln!("Note: Skill processing may continue in the background.");+ eprintln!(+ "Use 'ov task status <task_id>' to check progress, or 'ov task list' to see all tasks."+ );+ }++ if installed.len() == 1 {+ output_success(installed.remove(0), output_format, compact);+ } else {+ let total = installed.len();+ output_success(+ serde_json::json!({+ "installed": installed,+ "total": total,+ }),+ output_format,+ compact,+ );+ }+ Ok(())+}++pub async fn list(+ client: &HttpClient,+ node_limit: i32,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let result = client.skills_list(node_limit).await?;+ output_success(result, output_format, compact);+ Ok(())+}++pub async fn show(+ client: &HttpClient,+ name: &str,+ level: Option<i32>,+ include_files: bool,+ include_source: bool,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let include_content = level.is_none() || level == Some(2);+ let mut result = client+ .skill_show(name, include_content, include_files, include_source, level)+ .await?;+ if let Some(level) = level {+ filter_skill_show_level(&mut result, level);+ }+ output_skill_show(&result, output_format, compact);+ Ok(())+}++pub async fn find(+ client: &HttpClient,+ query: &str,+ node_limit: i32,+ threshold: Option<f64>,+ level: Option<Vec<i32>>,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let result = client+ .skill_find(query, node_limit, threshold, level)+ .await?;+ output_success(result, output_format, compact);+ Ok(())+}++pub async fn update(+ client: &HttpClient,+ skill_names: Vec<String>,+ wait: bool,+ yes: bool,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let update_all = skill_names.is_empty();+ let names = resolve_installed_skill_names(client, skill_names).await?;+ if names.is_empty() {+ output_message_result(+ serde_json::json!({ "updated": [], "total": 0 }),+ "No skills to update.".to_string(),+ output_format,+ compact,+ );+ return Ok(());+ }+ if !yes && !confirm_action("Update", &names)? {+ output_message_result(+ serde_json::json!({ "cancelled": true, "skills": names }),+ "Aborted.".to_string(),+ output_format,+ compact,+ );+ return Ok(());+ }++ let mut updated = Vec::new();+ let mut skipped = Vec::new();+ for name in names {+ let update_target = match resolve_update_target(client, &name, !update_all).await {+ Ok(target) => target,+ Err(error) if update_all => {+ skipped.push(json!({+ "name": name,+ "reason": error.to_string(),+ }));+ continue;+ }+ Err(error) => return Err(error),+ };+ let source_metadata = source_record_value(update_target.source.as_ref())?;+ let result = client+ .skill_update(+ &name,+ &update_target.data,+ wait,+ None,+ false,+ false,+ source_metadata,+ )+ .await?;+ updated.push(result);+ }+ let total = updated.len();+ let skipped_total = skipped.len();+ output_success(+ serde_json::json!({+ "updated": updated,+ "total": total,+ "skipped": skipped,+ "skipped_total": skipped_total,+ }),+ output_format,+ compact,+ );+ Ok(())+}++pub async fn remove(+ client: &HttpClient,+ skill_names: Vec<String>,+ all: bool,+ yes: bool,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ if all && !skill_names.is_empty() {+ return Err(Error::Client(+ "Pass either skill names or --all, not both.".to_string(),+ ));+ }+ let requested_names = normalize_skill_names(skill_names)?;+ let names = if all {+ resolve_installed_skill_names(client, Vec::new()).await?+ } else if !requested_names.is_empty() {+ requested_names+ } else {+ if yes || !can_prompt() {+ return Err(Error::Client(+ "Specify at least one skill name, or pass --all.".to_string(),+ ));+ }+ match prompt_remove_skill_selection(client).await? {+ Some(selected) => selected,+ None => {+ output_message_result(+ serde_json::json!({ "cancelled": true, "skills": [] }),+ "Aborted.".to_string(),+ output_format,+ compact,+ );+ return Ok(());+ }+ }+ };+ if names.is_empty() {+ output_message_result(+ serde_json::json!({ "removed": [], "total": 0 }),+ "No skills to remove.".to_string(),+ output_format,+ compact,+ );+ return Ok(());+ }+ if !yes && !confirm_action("Remove", &names)? {+ output_message_result(+ serde_json::json!({ "cancelled": true, "skills": names }),+ "Aborted.".to_string(),+ output_format,+ compact,+ );+ return Ok(());+ }++ let removed_names = names.clone();+ let mut removed = Vec::new();+ for name in names {+ removed.push(client.skill_remove(&name).await?);+ }+ let total = removed.len();+ output_message_result(+ serde_json::json!({+ "removed": removed,+ "removed_names": removed_names,+ "total": total,+ }),+ format!(+ "Removed {} skill(s): {}.",+ total,+ format_name_list(&removed_names)+ ),+ output_format,+ compact,+ );+ Ok(())+}++pub async fn validate(+ _client: &HttpClient,+ path: &str,+ strict: bool,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let result = validate_skill_path(path, strict)?;+ if result+ .get("valid")+ .and_then(Value::as_bool)+ .is_some_and(|valid| !valid)+ {+ let errors = result+ .get("errors")+ .and_then(Value::as_array)+ .map(|items| {+ items+ .iter()+ .filter_map(|item| {+ item.as_str()+ .or_else(|| item.get("message").and_then(Value::as_str))+ })+ .collect::<Vec<_>>()+ .join("; ")+ })+ .filter(|text| !text.is_empty())+ .unwrap_or_else(|| "Skill validation failed".to_string());+ if matches!(output_format, OutputFormat::Json) {+ output_success(result, output_format, compact);+ }+ return Err(Error::Client(errors));+ }+ output_skill_validate_success(&result, output_format, compact);+ Ok(())+}++fn validate_skill_path(path: &str, strict: bool) -> Result<Value> {+ let path_obj = Path::new(path);+ if !path_obj.exists() {+ return Err(Error::Client(format!(+ "Skill path '{}' does not exist.",+ path+ )));+ }++ let skill_file = if path_obj.is_dir() {+ let skill_file = path_obj.join("SKILL.md");+ if !skill_file.is_file() {+ return Err(Error::Client(format!(+ "SKILL.md not found in '{}'.",+ path_obj.display()+ )));+ }+ skill_file+ } else if path_obj.is_file() {+ if path_obj.file_name().and_then(|name| name.to_str()) != Some("SKILL.md") {+ return Err(Error::Client(+ "Validate expects a SKILL.md file or a skill directory.".to_string(),+ ));+ }+ path_obj.to_path_buf()+ } else {+ return Err(Error::Client(format!(+ "Skill path '{}' is not a file or directory.",+ path+ )));+ };++ let content = std::fs::read_to_string(&skill_file).map_err(|e| {+ Error::Client(format!(+ "Failed to read skill file '{}': {}",+ skill_file.display(),+ e+ ))+ })?;+ let skill_dir_name = skill_file+ .parent()+ .and_then(|parent| parent.file_name())+ .and_then(|name| name.to_str())+ .unwrap_or("")+ .to_string();++ Ok(validate_skill_content(+ &content,+ strict,+ &skill_file.to_string_lossy(),+ &skill_dir_name,+ ))+}++fn validate_skill_content(+ content: &str,+ strict: bool,+ source_path: &str,+ skill_dir_name: &str,+) -> Value {+ let mut errors = Vec::new();+ let mut warnings = Vec::new();++ let parsed = match parse_skill_md(content) {+ Ok(parsed) => parsed,+ Err(message) => {+ return json!({+ "valid": false,+ "strict": strict,+ "message": "Skill validation failed.",+ "name": "",+ "description": "",+ "tags": [],+ "allowed_tools": [],+ "body_lines": 0,+ "source_path": source_path,+ "skill_dir_name": skill_dir_name,+ "errors": [validation_issue("yaml_format", &message, "data")],+ "warnings": [],+ });+ }+ };++ let name = yaml_mapping_get_str(&parsed.meta, "name")+ .unwrap_or("")+ .trim()+ .to_string();+ let description = yaml_mapping_get_str(&parsed.meta, "description")+ .unwrap_or("")+ .trim()+ .to_string();+ let tags = yaml_value_as_string_array(yaml_mapping_get(&parsed.meta, "tags"));+ let allowed_tools = yaml_value_as_string_array(+ yaml_mapping_get(&parsed.meta, "allowed_tools")+ .or_else(|| yaml_mapping_get(&parsed.meta, "allowed-tools")),+ );++ if name.is_empty() {+ errors.push(validation_issue(+ "name_required",+ "name is required",+ "name",+ ));+ }+ if description.is_empty() {+ errors.push(validation_issue(+ "description_required",+ "description is required",+ "description",+ ));+ }++ if !name.is_empty() {+ if !skill_dir_name.is_empty() && name != skill_dir_name {+ push_mode_issue(+ &mut errors,+ &mut warnings,+ strict,+ "name_matches_directory",+ &format!(+ "name '{}' does not match directory name '{}'",+ name, skill_dir_name+ ),+ "name",+ );+ }+ if name.chars().count() > 64 {+ push_mode_issue(+ &mut errors,+ &mut warnings,+ strict,+ "name_max_length",+ "name must not exceed 64 characters",+ "name",+ );+ }+ if !is_valid_skill_name(&name) {+ push_mode_issue(+ &mut errors,+ &mut warnings,+ strict,+ "name_allowed_characters",+ "name may only contain letters, numbers, underscores, and hyphens",+ "name",+ );+ }+ }++ if description.chars().count() > 1024 {+ push_mode_issue(+ &mut errors,+ &mut warnings,+ strict,+ "description_max_length",+ "description must not exceed 1024 characters",+ "description",+ );+ }++ let body_lines = parsed.body.lines().count();+ if strict && body_lines > 500 {+ warnings.push(validation_issue(+ "body_max_lines",+ "SKILL.md body exceeds 500 lines",+ "content",+ ));+ }++ json!({+ "valid": errors.is_empty(),+ "strict": strict,+ "message": if errors.is_empty() { "Skill validation succeeded." } else { "Skill validation failed." },+ "name": name,+ "description": description,+ "tags": tags,+ "allowed_tools": allowed_tools,+ "body_lines": body_lines,+ "source_path": source_path,+ "skill_dir_name": skill_dir_name,+ "errors": errors,+ "warnings": warnings,+ })+}++struct ParsedSkillMd {+ meta: serde_yaml::Mapping,+ body: String,+}++fn parse_skill_md(content: &str) -> std::result::Result<ParsedSkillMd, String> {+ let first_line_end = content+ .find('\n')+ .ok_or_else(|| "SKILL.md must have YAML frontmatter".to_string())?;+ if !is_frontmatter_delimiter(&content[..first_line_end]) {+ return Err("SKILL.md must have YAML frontmatter".to_string());+ }++ let frontmatter_start = first_line_end + 1;+ let mut line_start = frontmatter_start;+ let (frontmatter, body) = loop {+ let Some(relative_line_end) = content[line_start..].find('\n') else {+ return Err("SKILL.md must have closing YAML frontmatter delimiter".to_string());+ };+ let line_end = line_start + relative_line_end;+ if is_frontmatter_delimiter(&content[line_start..line_end]) {+ break (+ &content[frontmatter_start..line_start],+ &content[line_end + 1..],+ );+ }+ line_start = line_end + 1;+ };+ let meta: serde_yaml::Value = serde_yaml::from_str(frontmatter)+ .map_err(|e| format!("Invalid YAML frontmatter: {}", e))?;+ let Some(meta) = meta.as_mapping().cloned() else {+ return Err("Invalid YAML frontmatter".to_string());+ };+ Ok(ParsedSkillMd {+ meta,+ body: body.trim().to_string(),+ })+}++fn is_frontmatter_delimiter(line: &str) -> bool {+ let line = line.strip_suffix('\r').unwrap_or(line);+ line.strip_prefix("---")+ .is_some_and(|suffix| suffix.chars().all(char::is_whitespace))+}++fn yaml_mapping_get<'a>(+ mapping: &'a serde_yaml::Mapping,+ key: &str,+) -> Option<&'a serde_yaml::Value> {+ mapping.get(serde_yaml::Value::String(key.to_string()))+}++fn yaml_mapping_get_str<'a>(mapping: &'a serde_yaml::Mapping, key: &str) -> Option<&'a str> {+ yaml_mapping_get(mapping, key).and_then(serde_yaml::Value::as_str)+}++fn yaml_value_as_string_array(value: Option<&serde_yaml::Value>) -> Vec<String> {+ match value {+ Some(serde_yaml::Value::Sequence(items)) => items+ .iter()+ .filter_map(serde_yaml::Value::as_str)+ .map(ToString::to_string)+ .collect(),+ Some(value) => value+ .as_str()+ .map(|value| vec![value.to_string()])+ .unwrap_or_default(),+ None => Vec::new(),+ }+}++fn is_valid_skill_name(name: &str) -> bool {+ name.chars()+ .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')+}++fn validation_issue(rule: &str, message: &str, field: &str) -> Value {+ json!({+ "rule": rule,+ "message": message,+ "field": field,+ })+}++fn push_mode_issue(+ errors: &mut Vec<Value>,+ warnings: &mut Vec<Value>,+ strict: bool,+ rule: &str,+ message: &str,+ field: &str,+) {+ let issue = validation_issue(rule, message, field);+ if strict {+ errors.push(issue);+ } else {+ warnings.push(issue);+ }+}++fn output_skill_validate_success(result: &Value, output_format: OutputFormat, compact: bool) {+ if matches!(output_format, OutputFormat::Json) {+ output_success(result, output_format, compact);+ return;+ }++ let name = result.get("name").and_then(Value::as_str).unwrap_or("");+ let description = result+ .get("description")+ .and_then(Value::as_str)+ .unwrap_or("");+ let mut lines = vec![+ "Skill validation succeeded.".to_string(),+ format!("name: {}", name),+ format!("description: {}", description),+ ];++ if let Some(warnings) = result.get("warnings").and_then(Value::as_array)+ && !warnings.is_empty()+ {+ lines.push(String::new());+ lines.push("warnings:".to_string());+ for warning in warnings {+ let message = warning+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or("Validation warning");+ lines.push(format!("- {}", message));+ }+ }++ println!("{}", lines.join("\n"));+}++fn prepare_source(data: &str) -> Result<PreparedSource> {+ let path = Path::new(data);+ if path.exists() {+ return Ok(PreparedSource::Path {+ path: path.to_path_buf(),+ _temp_dir: None,+ origin: SourceOrigin::Local {+ source: data.to_string(),+ },+ });+ }+ if let Some(git_source) = parse_git_source(data) {+ return prepare_git_source(git_source);+ }+ Ok(PreparedSource::Raw(data.to_string()))+}++fn prepare_git_source(git_source: GitSource) -> Result<PreparedSource> {+ let temp_dir = tempfile::tempdir()?;+ let status = Command::new("git")+ .arg("clone")+ .arg("--depth")+ .arg("1")+ .args(+ git_source+ .ref_name+ .iter()+ .flat_map(|ref_name| ["--branch", ref_name.as_str()]),+ )+ .arg(&git_source.clone_url)+ .arg(temp_dir.path())+ .status()+ .map_err(|e| Error::Client(format!("Failed to run git clone: {}", e)))?;+ if !status.success() {+ return Err(Error::Client(format!(+ "Failed to clone skill source: {}",+ git_source.clone_url+ )));+ }+ let path = if let Some(subdir) = git_source.subdir.as_ref() {+ let normalized_subdir = normalize_git_subdir(subdir)?;+ let repo_root = std::fs::canonicalize(temp_dir.path()).map_err(|e| {+ Error::Client(format!(+ "Failed to resolve cloned repository root '{}': {}",+ temp_dir.path().display(),+ e+ ))+ })?;+ let requested_path = temp_dir.path().join(&normalized_subdir);+ let canonical_path = std::fs::canonicalize(&requested_path).map_err(|e| {+ Error::Client(format!(+ "Skill path '{}' was not found in cloned repository '{}': {}",+ normalized_subdir.display(),+ git_source.clone_url,+ e+ ))+ })?;+ if !canonical_path.starts_with(&repo_root) {+ return Err(Error::Client(format!(+ "Git skill subdir '{}' escapes cloned repository '{}'.",+ normalized_subdir.display(),+ git_source.clone_url+ )));+ }+ canonical_path+ } else {+ temp_dir.path().to_path_buf()+ };+ Ok(PreparedSource::Path {+ path,+ _temp_dir: Some(temp_dir),+ origin: SourceOrigin::Git(git_source),+ })+}++fn normalize_git_subdir(subdir: &Path) -> Result<PathBuf> {+ let mut normalized = PathBuf::new();+ for component in subdir.components() {+ match component {+ Component::Normal(part) => normalized.push(part),+ Component::CurDir => {}+ Component::ParentDir => {+ return Err(Error::Parse(format!(+ "Git source metadata contains unsafe subdir '{}': parent directory components are not allowed.",+ subdir.display()+ )));+ }+ Component::RootDir | Component::Prefix(_) => {+ return Err(Error::Parse(format!(+ "Git source metadata contains absolute subdir '{}', which is not allowed.",+ subdir.display()+ )));+ }+ }+ }++ if normalized.as_os_str().is_empty() {+ return Err(Error::Parse("Git source metadata missing subdir".to_string()));+ }++ Ok(normalized)+}++fn parse_git_source(data: &str) -> Option<GitSource> {+ if let Some(source) = parse_github_tree_source(data) {+ return Some(source);+ }+ let is_plain_git_source = data.starts_with("git@")+ || data.starts_with("ssh://")+ || data.starts_with("git://")+ || ((data.starts_with("https://") || data.starts_with("http://"))+ && (data.ends_with(".git")+ || data.contains("github.com/")+ || data.contains("gitlab.com/")+ || data.contains("bitbucket.org/")));+ is_plain_git_source.then(|| GitSource {+ clone_url: data.to_string(),+ ref_name: None,+ subdir: None,+ })+}++fn parse_github_tree_source(data: &str) -> Option<GitSource> {+ let url = Url::parse(data).ok()?;+ if url.host_str()? != "github.com" {+ return None;+ }++ let segments = url.path_segments()?.collect::<Vec<_>>();+ if segments.len() < 5 || segments.get(2) != Some(&"tree") {+ return None;+ }++ let owner = segments[0];+ let repo = segments[1].trim_end_matches(".git");+ let (branch, subdir_segments) = split_github_tree_ref_and_subdir(&segments)?;+ let subdir = subdir_segments+ .iter()+ .fold(PathBuf::new(), |mut path, segment| {+ path.push(segment);+ path+ });+ if owner.is_empty() || repo.is_empty() || branch.is_empty() || subdir.as_os_str().is_empty() {+ return None;+ }++ Some(GitSource {+ clone_url: format!("https://github.com/{owner}/{repo}.git"),+ ref_name: Some(branch),+ subdir: Some(subdir),+ })+}++fn split_github_tree_ref_and_subdir(segments: &[&str]) -> Option<(String, Vec<String>)> {+ if segments.len() < 5 {+ return None;+ }+ let default_branch = segments[3];+ let default_subdir = &segments[4..];+ if default_branch.is_empty() || default_subdir.is_empty() {+ return None;+ }++ if let Some(skill_root_index) = segments[4..]+ .iter()+ .position(|segment| *segment == "skills")+ {+ let split_at = 4 + skill_root_index;+ let branch = segments[3..split_at].join("/");+ let subdir = segments[split_at..]+ .iter()+ .map(|segment| (*segment).to_string())+ .collect::<Vec<_>>();+ if !branch.is_empty() && !subdir.is_empty() {+ return Some((branch, subdir));+ }+ }++ Some((+ default_branch.to_string(),+ default_subdir+ .iter()+ .map(|segment| (*segment).to_string())+ .collect::<Vec<_>>(),+ ))+}++fn resolve_add_targets(source: &PreparedSource, skill_names: &[String]) -> Result<Vec<AddTarget>> {+ if skill_names.is_empty() {+ return match source {+ PreparedSource::Raw(data) => Ok(vec![AddTarget {+ data: data.clone(),+ source: None,+ _temp_dir: None,+ }]),+ PreparedSource::Path { path, .. } => resolve_default_add_targets(source, path),+ };+ }++ let Some(root) = source.path() else {+ return Err(Error::Client(+ "--skill can only be used with a local or git skill source.".to_string(),+ ));+ };+ if !root.is_dir() {+ return Err(Error::Client(+ "--skill requires a directory source.".to_string(),+ ));+ }++ let requested = normalize_skill_names(skill_names.to_vec())?;+ if requested.iter().any(|name| name == "*") {+ if requested.len() > 1 {+ return Err(Error::Client(+ "Use --skill '*' by itself when installing all skills.".to_string(),+ ));+ }+ let targets = discover_skill_dirs(root)?;+ if targets.is_empty() {+ return Err(Error::Client(format!(+ "No skill directories found under '{}'.",+ root.display()+ )));+ }+ return targets+ .into_iter()+ .map(|path| add_target_from_path(source, root, path))+ .collect();+ }++ requested+ .into_iter()+ .map(|name| {+ resolve_named_skill_dir(root, &name)+ .and_then(|path| add_target_from_path(source, root, path))+ })+ .collect()+}++fn resolve_default_add_targets(source: &PreparedSource, path: &Path) -> Result<Vec<AddTarget>> {+ if !path.is_dir() {+ return Ok(vec![add_target_from_path(+ source,+ path,+ path.to_path_buf(),+ )?]);+ }+ if path.join("SKILL.md").is_file() {+ return Ok(vec![add_target_from_path(+ source,+ path,+ path.to_path_buf(),+ )?]);+ }++ let targets = discover_skill_dirs(path)?;+ if targets.is_empty() {+ return Err(Error::Client(format!(+ "SKILL.md not found in '{}'.",+ path.display()+ )));+ }+ targets+ .into_iter()+ .map(|target| add_target_from_path(source, path, target))+ .collect()+}++fn add_target_from_path(+ source: &PreparedSource,+ root: &Path,+ target: PathBuf,+) -> Result<AddTarget> {+ Ok(AddTarget {+ data: path_to_string(&target),+ source: source_record_for_target(source, root, &target)?,+ _temp_dir: None,+ })+}++fn source_record_for_target(+ source: &PreparedSource,+ root: &Path,+ target: &Path,+) -> Result<Option<SkillSourceRecord>> {+ let PreparedSource::Path { origin, .. } = source else {+ return Ok(None);+ };++ match origin {+ SourceOrigin::Local { source } => Ok(Some(SkillSourceRecord {+ source_type: "local".to_string(),+ source: Some(source.clone()),+ path: Some(path_to_string(target)),+ clone_url: None,+ ref_name: None,+ subdir: None,+ skill_name: None,+ })),+ SourceOrigin::Git(git_source) => {+ let subdir = git_subdir_for_target(git_source.subdir.as_ref(), root, target)?;+ Ok(Some(SkillSourceRecord {+ source_type: "git".to_string(),+ source: Some(git_source_source(git_source)),+ path: None,+ clone_url: Some(git_source.clone_url.clone()),+ ref_name: git_source.ref_name.clone(),+ subdir: subdir.map(|path| path_to_string(&path)),+ skill_name: None,+ }))+ }+ }+}++fn git_subdir_for_target(+ source_subdir: Option<&PathBuf>,+ root: &Path,+ target: &Path,+) -> Result<Option<PathBuf>> {+ let relative = target+ .strip_prefix(root)+ .ok()+ .filter(|path| !path.as_os_str().is_empty());+ let mut subdir = source_subdir.cloned().unwrap_or_default();+ if let Some(relative) = relative {+ subdir.push(relative);+ }+ if subdir.as_os_str().is_empty() {+ Ok(None)+ } else {+ Ok(Some(subdir))+ }+}++fn git_source_source(git_source: &GitSource) -> String {+ if git_source.clone_url.contains("github.com/")+ && let (Some(ref_name), Some(subdir)) = (&git_source.ref_name, &git_source.subdir)+ {+ let repo = git_source+ .clone_url+ .trim_end_matches(".git")+ .trim_start_matches("https://github.com/");+ return format!(+ "https://github.com/{}/tree/{}/{}",+ repo,+ ref_name,+ path_to_string(subdir)+ );+ }+ git_source.clone_url.clone()+}++fn list_source_skills(+ source: &PreparedSource,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let Some(root) = source.path() else {+ return Err(Error::Client(+ "--list can only be used with a local or git skill source.".to_string(),+ ));+ };+ if !root.is_dir() {+ return Err(Error::Client(+ "--list requires a directory skill source.".to_string(),+ ));+ }++ let dirs = discover_skill_dirs(root)?;+ let skills = dirs+ .iter()+ .map(|dir| skill_dir_summary(dir, root))+ .collect::<Result<Vec<_>>>()?;+ output_success(+ serde_json::json!({+ "source": path_to_string(root),+ "skills": skills,+ "total": skills.len(),+ }),+ output_format,+ compact,+ );+ Ok(())+}++fn skill_dir_summary(dir: &Path, root: &Path) -> Result<Value> {+ let skill_md = dir.join("SKILL.md");+ let content = std::fs::read_to_string(&skill_md).map_err(|e| {+ Error::Client(format!(+ "Failed to read skill file '{}': {}",+ skill_md.display(),+ e+ ))+ })?;+ let parsed = parse_skill_md(&content).ok();+ let name = parsed+ .as_ref()+ .and_then(|parsed| yaml_mapping_get_str(&parsed.meta, "name"))+ .map(ToString::to_string)+ .or_else(|| {+ dir.file_name()+ .and_then(|name| name.to_str())+ .map(ToString::to_string)+ })+ .unwrap_or_default();+ let description = parsed+ .as_ref()+ .and_then(|parsed| yaml_mapping_get_str(&parsed.meta, "description"))+ .unwrap_or("")+ .to_string();+ let relative_path = dir.strip_prefix(root).unwrap_or(dir);++ Ok(serde_json::json!({+ "name": name,+ "description": description,+ "path": path_to_string(relative_path),+ }))+}++fn skill_target_label(target: &AddTarget) -> String {+ let path = Path::new(&target.data);+ path.file_name()+ .and_then(|name| name.to_str())+ .unwrap_or(&target.data)+ .to_string()+}++async fn resolve_update_target(+ client: &HttpClient,+ name: &str,+ allow_prompt: bool,+) -> Result<AddTarget> {+ if let Some(record) = read_skill_source_record(client, name).await? {+ return update_target_from_record(&record, name, allow_prompt);+ }++ if allow_prompt {+ if let Some(target) = prompt_update_source(name)? {+ return Ok(target);+ }+ }++ Err(Error::Client(format!(+ "Skill '{}' has no recorded updateable source metadata. Reinstall it with 'ov skills add <source>' or run update interactively to provide a new source.",+ name+ )))+}++async fn read_skill_source_record(+ client: &HttpClient,+ name: &str,+) -> Result<Option<SkillSourceRecord>> {+ let result = client.skill_show(name, false, false, true, Some(0)).await?;+ let Some(source) = result.get("source") else {+ return Ok(None);+ };+ if !source+ .get("tracked")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ {+ return Ok(None);+ }+ let mut record: SkillSourceRecord = serde_json::from_value(source.clone())+ .map_err(|e| Error::Parse(format!("Invalid source metadata for '{}': {}", name, e)))?;+ record.skill_name = Some(name.to_string());+ Ok(Some(record))+}++fn update_target_from_record(+ record: &SkillSourceRecord,+ name: &str,+ allow_prompt: bool,+) -> Result<AddTarget> {+ match record.source_type.as_str() {+ "git" => {+ let prepared = prepare_source_from_git_record(record)?;+ let PreparedSource::Path {+ path, _temp_dir, ..+ } = prepared+ else {+ return Err(Error::Parse(format!(+ "Skill '{}' git source did not resolve to a path",+ name+ )));+ };+ Ok(AddTarget {+ data: path_to_string(&path),+ source: Some(record.clone()),+ _temp_dir,+ })+ }+ "local" => {+ if allow_prompt {+ if let Some(target) = prompt_update_source(name)? {+ return Ok(target);+ }+ return Err(Error::Client(format!(+ "Local source metadata for skill '{}' is not trusted. Provide a local path or git source to continue.",+ name+ )));+ }+ Err(Error::Client(format!(+ "Skill '{}' was installed from a local source, but server-recorded local paths are not trusted for non-interactive update. Re-run 'ov skills update {}' interactively to provide a local path or git source.",+ name, name+ )))+ }+ other => Err(Error::Parse(format!(+ "Unsupported source type '{}' for skill '{}'",+ other, name+ ))),+ }+}++fn prepare_source_from_git_record(record: &SkillSourceRecord) -> Result<PreparedSource> {+ let clone_url = record+ .clone_url+ .as_deref()+ .ok_or_else(|| Error::Parse("Git source metadata missing clone_url".to_string()))?;+ let subdir = record+ .subdir+ .as_ref()+ .map(PathBuf::from)+ .map(|path| normalize_git_subdir(&path))+ .transpose()?;+ let git_source = GitSource {+ clone_url: clone_url.to_string(),+ ref_name: record.ref_name.clone(),+ subdir,+ };+ prepare_git_source(git_source)+}++fn prompt_update_source(name: &str) -> Result<Option<AddTarget>> {+ if !io::stdin().is_terminal() || !io::stdout().is_terminal() {+ return Ok(None);+ }++ print!(+ "Source for skill '{}' is missing or untracked. Enter a local path or git source to update it (blank to abort): ",+ name+ );+ io::stdout().flush()?;++ let mut answer = String::new();+ io::stdin().read_line(&mut answer)?;+ let source_text = answer.trim();+ if source_text.is_empty() {+ return Ok(None);+ }+ let source = prepare_source(source_text)?;+ let targets = resolve_add_targets(&source, &[name.to_string()])?;+ let mut target = targets.into_iter().next().ok_or_else(|| {+ Error::Client(format!(+ "Skill '{}' was not found in source '{}'.",+ name, source_text+ ))+ })?;+ if let PreparedSource::Path { _temp_dir, .. } = source {+ target._temp_dir = _temp_dir;+ }+ Ok(Some(target))+}++fn source_record_value(source: Option<&SkillSourceRecord>) -> Result<Option<Value>> {+ source+ .map(serde_json::to_value)+ .transpose()+ .map_err(|e| Error::Parse(format!("Failed to serialize source metadata: {}", e)))+}++fn normalize_skill_names(names: Vec<String>) -> Result<Vec<String>> {+ let mut seen = BTreeSet::new();+ let mut out = Vec::new();+ for name in names {+ let trimmed = name.trim();+ if trimmed.is_empty() {+ return Err(Error::Client("Skill name cannot be empty.".to_string()));+ }+ if seen.insert(trimmed.to_string()) {+ out.push(trimmed.to_string());+ }+ }+ Ok(out)+}++fn discover_skill_dirs(root: &Path) -> Result<Vec<PathBuf>> {+ let mut dirs = Vec::new();+ if root.join("SKILL.md").is_file() {+ dirs.push(root.to_path_buf());+ }+ for entry in std::fs::read_dir(root)? {+ let entry = entry?;+ let path = entry.path();+ if path.is_dir() && path.join("SKILL.md").is_file() {+ dirs.push(path);+ }+ }+ dirs.sort();+ dirs.dedup();+ Ok(dirs)+}++fn resolve_named_skill_dir(root: &Path, name: &str) -> Result<PathBuf> {+ let child = root.join(name);+ if child.is_dir() && child.join("SKILL.md").is_file() {+ return Ok(child);+ }++ if root.join("SKILL.md").is_file()+ && root+ .file_name()+ .and_then(|value| value.to_str())+ .is_some_and(|root_name| root_name == name)+ {+ return Ok(root.to_path_buf());+ }++ Err(Error::Client(format!(+ "Skill '{}' was not found under '{}'.",+ name,+ root.display()+ )))+}++async fn resolve_installed_skill_names(+ client: &HttpClient,+ requested: Vec<String>,+) -> Result<Vec<String>> {+ let requested = normalize_skill_names(requested)?;+ if !requested.is_empty() {+ return Ok(requested);+ }++ Ok(list_installed_skills(client)+ .await?+ .into_iter()+ .map(|skill| skill.name)+ .collect())+}++async fn list_installed_skills(client: &HttpClient) -> Result<Vec<InstalledSkillSummary>> {+ let result = client.skills_list(10000).await?;+ let skills = result+ .get("skills")+ .and_then(Value::as_array)+ .ok_or_else(|| Error::Parse("skills list response missing skills array".to_string()))?+ .iter()+ .filter_map(|item| {+ let name = item.get("name").and_then(Value::as_str)?.to_string();+ let description = item+ .get("description")+ .and_then(Value::as_str)+ .unwrap_or("")+ .trim()+ .to_string();+ Some(InstalledSkillSummary { name, description })+ })+ .collect();+ Ok(skills)+}++async fn prompt_remove_skill_selection(client: &HttpClient) -> Result<Option<Vec<String>>> {+ let skills = list_installed_skills(client).await?;+ if skills.is_empty() {+ return Ok(Some(Vec::new()));+ }+ prompt_multi_select_skills("Select skill(s) to remove", &skills)+}++fn can_prompt() -> bool {+ io::stdin().is_terminal() && io::stdout().is_terminal()+}++fn prompt_multi_select_skills(+ prompt: &str,+ skills: &[InstalledSkillSummary],+) -> Result<Option<Vec<String>>> {+ use crossterm::{+ cursor,+ event::{self, Event, KeyCode, KeyModifiers},+ execute,+ terminal::{self, Clear, ClearType},+ };++ if skills.is_empty() {+ return Ok(Some(Vec::new()));+ }++ struct RawGuard {+ hide_cursor: bool,+ }++ impl RawGuard {+ fn enter() -> Result<Self> {+ terminal::enable_raw_mode()?;+ let mut stdout = io::stdout();+ if let Err(error) = execute!(stdout, cursor::Hide) {+ let _ = terminal::disable_raw_mode();+ return Err(error.into());+ }+ Ok(Self { hide_cursor: true })+ }+ }++ impl Drop for RawGuard {+ fn drop(&mut self) {+ let _ = terminal::disable_raw_mode();+ if self.hide_cursor {+ let _ = execute!(io::stdout(), cursor::Show);+ }+ }+ }++ let _raw_guard = RawGuard::enter()?;+ let mut current = 0usize;+ let mut checked = vec![false; skills.len()];+ let mut rendered_lines = 0usize;++ loop {+ clear_rendered_lines(rendered_lines)?;+ let lines = skill_multi_select_lines(prompt, skills, current, &checked);+ rendered_lines = lines.len();+ print!("{}", live_select_block(&lines));+ io::stdout().flush()?;++ if let Event::Key(key) = event::read()? {+ match key.code {+ KeyCode::Up => {+ current = if current == 0 {+ skills.len().saturating_sub(1)+ } else {+ current - 1+ };+ }+ KeyCode::Down => current = (current + 1) % skills.len(),+ KeyCode::Char(' ') => checked[current] = !checked[current],+ KeyCode::Char('a') | KeyCode::Char('A') => {+ let select_all = checked.iter().any(|value| !*value);+ checked.fill(select_all);+ }+ KeyCode::Enter | KeyCode::Char('\n') | KeyCode::Char('\r') => {+ clear_rendered_lines(rendered_lines)?;+ let selected = selected_skill_names(skills, current, &checked);+ return Ok(Some(selected));+ }+ KeyCode::Esc => {+ clear_rendered_lines(rendered_lines)?;+ return Ok(None);+ }+ KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {+ clear_rendered_lines(rendered_lines)?;+ return Err(Error::Client("Aborted.".to_string()));+ }+ _ => {}+ }+ }+ }++ fn clear_rendered_lines(lines: usize) -> Result<()> {+ if lines == 0 {+ return Ok(());+ }+ let mut stdout = io::stdout();+ execute!(+ stdout,+ cursor::MoveUp(lines as u16),+ cursor::MoveToColumn(0)+ )?;+ for line in 0..lines {+ execute!(+ stdout,+ cursor::MoveToColumn(0),+ Clear(ClearType::CurrentLine)+ )?;+ if line + 1 < lines {+ execute!(stdout, cursor::MoveDown(1))?;+ }+ }+ execute!(+ stdout,+ cursor::MoveUp(lines.saturating_sub(1) as u16),+ cursor::MoveToColumn(0)+ )?;+ Ok(())+ }+}++fn selected_skill_names(+ skills: &[InstalledSkillSummary],+ current: usize,+ checked: &[bool],+) -> Vec<String> {+ let mut selected = skills+ .iter()+ .zip(checked)+ .filter_map(|(skill, checked)| checked.then(|| skill.name.clone()))+ .collect::<Vec<_>>();+ if selected.is_empty()+ && let Some(skill) = skills.get(current)+ {+ selected.push(skill.name.clone());+ }+ selected+}++fn skill_multi_select_lines(+ prompt: &str,+ skills: &[InstalledSkillSummary],+ current: usize,+ checked: &[bool],+) -> Vec<String> {+ let terminal_width = crossterm::terminal::size()+ .map(|(columns, _)| columns as usize)+ .unwrap_or(100)+ .clamp(48, 140);+ let item_width = terminal_width.saturating_sub(8).max(32);+ let mut lines = Vec::new();+ lines.push(format!(+ "{} {}",+ theme::prompt("?").bold(),+ theme::strong(prompt)+ ));+ lines.push(format!(+ " {}",+ theme::muted("Up/Down move, Space toggle, Enter confirm, A toggle all, Esc cancel")+ ));+ lines.push(String::new());+ for (index, skill) in skills.iter().enumerate() {+ let active = index == current;+ let cursor = if active { ">" } else { " " };+ let check = if checked.get(index).copied().unwrap_or(false) {+ "[x]"+ } else {+ "[ ]"+ };+ let label = skill_selection_label(skill, item_width);+ let label = if active {+ theme::selection(label).bold().to_string()+ } else {+ theme::body(label).to_string()+ };+ lines.push(format!(" {cursor} {check} {label}"));+ }+ lines+}++fn skill_selection_label(skill: &InstalledSkillSummary, width: usize) -> String {+ let label = if skill.description.is_empty() {+ skill.name.clone()+ } else {+ format!("{} - {}", skill.name, skill.description)+ };+ truncate_display_width(&label, width)+}++fn truncate_display_width(text: &str, max_width: usize) -> String {+ if UnicodeWidthStr::width(text) <= max_width {+ return text.to_string();+ }++ let ellipsis = "...";+ let target_width = max_width.saturating_sub(ellipsis.len());+ let mut width = 0usize;+ let mut out = String::new();+ for ch in text.chars() {+ let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);+ if width + ch_width > target_width {+ break;+ }+ out.push(ch);+ width += ch_width;+ }+ out.push_str(ellipsis);+ out+}++fn live_select_block(lines: &[String]) -> String {+ if lines.is_empty() {+ return String::new();+ }++ let mut rendered = lines.join("\r\n");+ rendered.push_str("\r\n");+ rendered+}++fn confirm_action(action: &str, names: &[String]) -> Result<bool> {+ if !can_prompt() {+ return Err(Error::Client(format!(+ "{} requires confirmation. Pass --yes to skip the prompt.",+ action+ )));+ }++ print!(+ "{} {} skill(s): {}? [y/N]: ",+ action,+ names.len(),+ format_name_list(names)+ );+ io::stdout().flush()?;++ let mut answer = String::new();+ io::stdin().read_line(&mut answer)?;+ let answer = answer.trim().to_ascii_lowercase();+ Ok(answer == "y" || answer == "yes")+}++fn format_name_list(names: &[String]) -> String {+ const MAX_NAMES: usize = 5;+ if names.len() <= MAX_NAMES {+ return names.join(", ");+ }+ format!(+ "{}, and {} more",+ names[..MAX_NAMES].join(", "),+ names.len() - MAX_NAMES+ )+}++fn path_to_string(path: &Path) -> String {+ path.to_string_lossy().to_string()+}++fn output_skill_show(result: &Value, output_format: OutputFormat, compact: bool) {+ if matches!(output_format, OutputFormat::Table)+ && let Some(rendered) = render_skill_show_for_table(result)+ {+ println!(+ "{}",+ crate::output::append_profile_to_rendered(rendered, result)+ );+ return;+ }+ output_success(result, output_format, compact);+}++fn filter_skill_show_level(value: &mut Value, level: i32) {+ let Some(obj) = value.as_object_mut() else {+ return;+ };++ match level {+ 0 => {+ obj.remove("overview");+ obj.remove("content");+ }+ 1 => {+ obj.remove("abstract");+ obj.remove("content");+ }+ 2 => {+ obj.remove("abstract");+ obj.remove("overview");+ }+ _ => {}+ }+}++fn render_skill_show_for_table(value: &Value) -> Option<String> {+ let obj = value.as_object()?;+ if !obj.contains_key("skill_md_uri") && !obj.contains_key("abstract") {+ return None;+ }++ let mut lines = Vec::new();+ push_section(&mut lines, "metadata");+ push_kv(&mut lines, "name", obj.get("name"));+ push_kv(&mut lines, "description", obj.get("description"));+ push_kv(&mut lines, "uri", obj.get("uri"));+ push_kv(&mut lines, "root_uri", obj.get("root_uri"));+ push_kv(&mut lines, "skill_md_uri", obj.get("skill_md_uri"));+ push_kv(&mut lines, "tags", obj.get("tags"));+ push_kv(&mut lines, "allowed_tools", obj.get("allowed_tools"));++ if let Some(abstract_text) = obj.get("abstract").and_then(Value::as_str) {+ push_text_section(&mut lines, "L0 abstract", abstract_text);+ }+ if let Some(overview) = obj.get("overview").and_then(Value::as_str) {+ push_text_section(&mut lines, "L1 overview", overview);+ }+ if let Some(content) = obj.get("content").and_then(Value::as_str) {+ push_text_section(&mut lines, "L2 SKILL.md", content);+ }+ if let Some(files) = obj.get("files").and_then(Value::as_array) {+ push_section(&mut lines, "auxiliary files");+ if files.is_empty() {+ lines.push("(none)".to_string());+ } else {+ for file in files {+ let name = file+ .get("path")+ .or_else(|| file.get("name"))+ .and_then(Value::as_str)+ .unwrap_or("");+ let kind = file.get("kind").and_then(Value::as_str).unwrap_or("file");+ let uri = file.get("uri").and_then(Value::as_str).unwrap_or("");+ lines.push(format!("- {} [{}]", name, kind));+ if !uri.is_empty() {+ lines.push(format!(" uri: {}", uri));+ }+ }+ }+ }+ if let Some(source) = obj.get("source").and_then(Value::as_object) {+ push_section(&mut lines, "source");+ for (key, value) in source {+ push_kv(&mut lines, key, Some(value));+ }+ }++ Some(lines.join("\n"))+}++fn push_section(lines: &mut Vec<String>, title: &str) {+ if !lines.is_empty() {+ lines.push(String::new());+ }+ lines.push(format!("[{}]", title));+}++fn push_text_section(lines: &mut Vec<String>, title: &str, text: &str) {+ push_section(lines, title);+ lines.push(text.trim_end().to_string());+}++fn push_kv(lines: &mut Vec<String>, key: &str, value: Option<&Value>) {+ let Some(value) = value else {+ return;+ };+ if value.is_null() {+ return;+ }+ lines.push(format!("{}: {}", key, format_show_value(value)));+}++fn format_show_value(value: &Value) -> String {+ match value {+ Value::String(text) => text.clone(),+ Value::Array(items) => {+ if items.is_empty() {+ "[]".to_string()+ } else {+ items+ .iter()+ .map(format_show_value)+ .collect::<Vec<_>>()+ .join(", ")+ }+ }+ Value::Bool(value) => value.to_string(),+ Value::Number(value) => value.to_string(),+ Value::Object(_) => serde_json::to_string(value).unwrap_or_default(),+ Value::Null => String::new(),+ }+}++fn output_message_result(+ result: serde_json::Value,+ message: String,+ output_format: OutputFormat,+ compact: bool,+) {+ match output_format {+ OutputFormat::Json => output_success(result, output_format, compact),+ OutputFormat::Table => {+ println!(+ "{}",+ crate::output::append_profile_to_rendered(message, &result)+ );+ }+ }+}++#[cfg(test)]+mod tests {+ use super::{+ PreparedSource, SkillSourceRecord, SourceOrigin, filter_skill_show_level,+ parse_github_tree_source, parse_skill_md, prepare_source_from_git_record,+ render_skill_show_for_table, resolve_add_targets, update_target_from_record,+ };+ use serde_json::json;+ use std::path::Path;++ #[test]+ fn skill_show_table_renders_complete_skill_information() {+ let result = json!({+ "name": "demo-skill",+ "description": "Demo skill",+ "uri": "viking://agent/skills/demo-skill",+ "root_uri": "viking://agent/skills/demo-skill",+ "skill_md_uri": "viking://agent/skills/demo-skill/SKILL.md",+ "tags": ["test"],+ "allowed_tools": ["shell"],+ "abstract": "name: demo-skill\ndescription: Demo skill",+ "overview": "Overview text",+ "content": "# demo-skill\n\nUse it.",+ "files": [+ {+ "name": "SKILL.md",+ "path": "SKILL.md",+ "uri": "viking://agent/skills/demo-skill/SKILL.md",+ "kind": "definition",+ "is_dir": false+ },+ {+ "name": "helper.md",+ "path": "references/helper.md",+ "uri": "viking://agent/skills/demo-skill/references/helper.md",+ "kind": "auxiliary",+ "is_dir": false+ }+ ],+ "source": {+ "tracked": false,+ "message": "Skill source metadata is not tracked yet."+ }+ });++ let rendered = render_skill_show_for_table(&result).expect("skill show table");+ assert!(rendered.contains("[metadata]"));+ assert!(rendered.contains("name: demo-skill"));+ assert!(rendered.contains("[L0 abstract]"));+ assert!(rendered.contains("[L1 overview]"));+ assert!(rendered.contains("[L2 SKILL.md]"));+ assert!(rendered.contains("[auxiliary files]"));+ assert!(rendered.contains("references/helper.md [auxiliary]"));+ assert!(rendered.contains("[source]"));+ }++ #[test]+ fn skill_show_level_one_filters_other_levels_before_rendering() {+ let mut result = json!({+ "name": "demo-skill",+ "skill_md_uri": "viking://agent/skills/demo-skill/SKILL.md",+ "abstract": "L0 text",+ "overview": "L1 text",+ "content": "# L2 text"+ });++ filter_skill_show_level(&mut result, 1);++ let rendered = render_skill_show_for_table(&result).expect("skill show table");+ assert!(!rendered.contains("[L0 abstract]"));+ assert!(!rendered.contains("L0 text"));+ assert!(rendered.contains("[L1 overview]"));+ assert!(rendered.contains("L1 text"));+ assert!(!rendered.contains("[L2 SKILL.md]"));+ assert!(!rendered.contains("# L2 text"));+ }++ #[test]+ fn skill_validate_parser_accepts_delimiter_trailing_whitespace() {+ let parsed =+ parse_skill_md("--- \nname: demo-skill\ndescription: Demo skill\n--- \n\n# Demo\n")+ .expect("frontmatter delimiter with trailing whitespace should parse");++ assert_eq!(+ parsed+ .meta+ .get(serde_yaml::Value::String("name".to_string()))+ .and_then(serde_yaml::Value::as_str),+ Some("demo-skill")+ );+ assert_eq!(parsed.body, "# Demo");+ }++ #[test]+ fn github_tree_skill_url_resolves_to_repo_and_subdir() {+ let source = parse_github_tree_source(+ "https://github.com/anthropics/skills/tree/main/skills/algorithmic-art",+ )+ .expect("github tree source");++ assert_eq!(source.clone_url, "https://github.com/anthropics/skills.git");+ assert_eq!(source.ref_name.as_deref(), Some("main"));+ assert_eq!(+ source.subdir.as_deref(),+ Some(Path::new("skills/algorithmic-art"))+ );+ }++ #[test]+ fn github_tree_skill_url_supports_slash_branch_before_skills_dir() {+ let source = parse_github_tree_source(+ "https://github.com/acme/skills/tree/feature/foo/skills/demo-skill",+ )+ .expect("github tree source");++ assert_eq!(source.clone_url, "https://github.com/acme/skills.git");+ assert_eq!(source.ref_name.as_deref(), Some("feature/foo"));+ assert_eq!(+ source.subdir.as_deref(),+ Some(Path::new("skills/demo-skill"))+ );+ }++ #[test]+ fn update_target_rejects_api_source_record_without_prompt() {+ let record = SkillSourceRecord {+ source_type: "api".to_string(),+ source: Some("inline_content".to_string()),+ path: None,+ clone_url: None,+ ref_name: None,+ subdir: None,+ skill_name: Some("api-skill".to_string()),+ };++ let error = update_target_from_record(&record, "api-skill", false)+ .expect_err("api source should not be directly updateable");+ assert!(+ error+ .to_string()+ .contains("Unsupported source type 'api' for skill 'api-skill'")+ );+ }++ #[test]+ fn update_target_rejects_local_source_record_without_prompt() {+ let record = SkillSourceRecord {+ source_type: "local".to_string(),+ source: Some("/tmp/demo-skill".to_string()),+ path: Some("/tmp/demo-skill".to_string()),+ clone_url: None,+ ref_name: None,+ subdir: None,+ skill_name: Some("local-skill".to_string()),+ };++ let error = update_target_from_record(&record, "local-skill", false)+ .expect_err("local source should not be trusted for non-interactive update");+ assert!(error.to_string().contains("server-recorded local paths are not trusted"));+ }++ #[test]+ fn prepare_source_from_git_record_rejects_parent_dir_subdir() {+ let record = SkillSourceRecord {+ source_type: "git".to_string(),+ source: Some("https://github.com/acme/skills/tree/main/skills/demo".to_string()),+ path: None,+ clone_url: Some("https://github.com/acme/skills.git".to_string()),+ ref_name: Some("main".to_string()),+ subdir: Some("../outside".to_string()),+ skill_name: Some("demo".to_string()),+ };++ let error = prepare_source_from_git_record(&record)+ .err()+ .expect("parent dir subdir should be rejected before clone");+ assert!(error.to_string().contains("parent directory components are not allowed"));+ }++ #[test]+ fn prepare_source_from_git_record_rejects_absolute_subdir() {+ let record = SkillSourceRecord {+ source_type: "git".to_string(),+ source: Some("https://github.com/acme/skills/tree/main/skills/demo".to_string()),+ path: None,+ clone_url: Some("https://github.com/acme/skills.git".to_string()),+ ref_name: Some("main".to_string()),+ subdir: Some("/tmp/escape".to_string()),+ skill_name: Some("demo".to_string()),+ };++ let error = prepare_source_from_git_record(&record)+ .err()+ .expect("absolute subdir should be rejected before clone");+ assert!(error.to_string().contains("absolute subdir"));+ }++ #[test]+ fn default_add_targets_expand_skill_collection_directory() {+ let temp_dir = tempfile::tempdir().expect("tempdir");+ let root = temp_dir.path().join("skills");+ let skill_a = root.join("skill-a");+ let skill_b = root.join("skill-b");+ std::fs::create_dir_all(&skill_a).expect("skill-a dir");+ std::fs::create_dir_all(&skill_b).expect("skill-b dir");+ std::fs::write(+ skill_a.join("SKILL.md"),+ "---\nname: skill-a\ndescription: A\n---\n",+ )+ .expect("skill-a md");+ std::fs::write(+ skill_b.join("SKILL.md"),+ "---\nname: skill-b\ndescription: B\n---\n",+ )+ .expect("skill-b md");++ let source = PreparedSource::Path {+ path: root,+ _temp_dir: None,+ origin: SourceOrigin::Local {+ source: temp_dir.path().to_string_lossy().to_string(),+ },+ };+ let targets = resolve_add_targets(&source, &[]).expect("targets");++ assert_eq!(targets.len(), 2);+ assert!(+ targets+ .iter()+ .any(|target| target.data.ends_with("skill-a"))+ );+ assert!(+ targets+ .iter()+ .any(|target| target.data.ends_with("skill-b"))+ );+ }+}diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 06f9c547a..5ec672ca6 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -106,19 +106,26 @@ impl CliContext {#[command(arg_required_else_help = true)]struct Cli {/// Output format- #[arg(short, long, value_enum, default_value = "table", global = true)]+ #[arg(+ short,+ long,+ value_enum,+ default_value = "table",+ global = true,+ hide = true+ )]output: OutputFormat,/// Compact representation, defaults to true - compacts JSON output or uses simplified representation for Table output- #[arg(short, long, global = true, default_value = "true")]+ #[arg(short, long, global = true, default_value = "true", hide = true)]compact: bool,/// Account identifier to send as X-OpenViking-Account- #[arg(long, global = true)]+ #[arg(long, global = true, hide = true)]account: Option<String>,/// User identifier to send as X-OpenViking-User- #[arg(long, global = true)]+ #[arg(long, global = true, hide = true)]user: Option<String>,/// Use root API key for admin commands@@ -126,7 +133,7 @@ struct Cli {sudo: bool,/// Enable HTTP request profiling for this command- #[arg(long, global = true)]+ #[arg(long, global = true, hide = true)]profile: bool,/// Show upload progress (legacy pre-command placement; prefer command-local --progress)@@ -270,6 +277,11 @@ enum Commands {#[command(flatten)]upload_options: UploadCliOptions,},+ /// [Data] Manage installed skills+ Skills {+ #[command(subcommand)]+ action: SkillCommands,+ },/// [Data] List directory contents#[command(alias = "list")]Ls {@@ -845,6 +857,109 @@ enum SessionCommands {},}+#[derive(Subcommand)]+enum SkillCommands {+ /// Add skills from a source+ Add {+ /// Skill source+ source: String,+ /// Install only the named skill(s); use '*' to install all skills in a source+ #[arg(short = 's', long = "skill", value_name = "NAME", num_args = 1.., value_delimiter = ',')]+ skills: Vec<String>,+ /// List available skills in the source without installing+ #[arg(short = 'l', long = "list")]+ list: bool,+ /// Wait until processing is complete+ #[arg(short = 'w', long)]+ wait: bool,+ /// Skip confirmation prompt+ #[arg(short = 'y', long = "yes")]+ yes: bool,+ },+ /// List installed agent skills+ #[command(alias = "ls")]+ List {+ /// Maximum number of skills to list+ #[arg(+ short = 'n',+ long = "node-limit",+ alias = "limit",+ default_value = "1000"+ )]+ node_limit: i32,+ },+ /// Find installed agent skills semantically+ Find {+ /// Search query+ query: String,+ /// Maximum number of results+ #[arg(+ short = 'n',+ long = "node-limit",+ alias = "limit",+ default_value = "10"+ )]+ node_limit: i32,+ /// Score threshold+ #[arg(short, long)]+ threshold: Option<f64>,+ /// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)+ #[arg(short = 'L', long = "level", value_delimiter = ',')]+ level: Option<Vec<i32>>,+ },+ /// Show one installed skill+ Show {+ /// Skill name+ name: String,+ /// Detail level to show (0=abstract, 1=overview, 2=SKILL.md content)+ #[arg(short = 'L', long = "level", value_parser = clap::value_parser!(i32).range(0..=2))]+ level: Option<i32>,+ /// Include files under the skill directory+ #[arg(short = 'f', long = "files")]+ files: bool,+ /// Include source metadata when available+ #[arg(long = "source")]+ source: bool,+ /// Output format for this command+ #[arg(long = "format", value_parser = ["table", "json"])]+ format: Option<String>,+ /// Include full SKILL.md content (legacy alias for --level 2)+ #[arg(long, hide = true)]+ content: bool,+ },+ /// Update installed skills from their recorded source+ Update {+ /// Skill name(s) to update; omit to update all installed skills+ skills: Vec<String>,+ /// Wait until processing is complete+ #[arg(short = 'w', long)]+ wait: bool,+ /// Skip confirmation prompt+ #[arg(short = 'y', long = "yes")]+ yes: bool,+ },+ /// Remove installed skills+ #[command(alias = "rm", alias = "delete")]+ Remove {+ /// Skill name(s) to remove+ skills: Vec<String>,+ /// Remove all installed skills+ #[arg(long = "all")]+ all: bool,+ /// Skip confirmation prompt+ #[arg(short = 'y', long = "yes")]+ yes: bool,+ },+ /// Validate a local SKILL.md file or skill directory+ Validate {+ /// SKILL.md file or skill directory path+ path: String,+ /// Strict mode; warnings such as name mismatch are reported as errors+ #[arg(long = "strict")]+ strict: bool,+ },+}+#[derive(Subcommand)]enum WatchCommands {/// List watch tasks (auto-refresh subscriptions)@@ -1042,6 +1157,8 @@ impl Commands {| ConfigCommands::Delete(_)| ConfigCommands::List,),+ } | Commands::Skills {+ action: SkillCommands::Validate { .. },} | Commands::Version)}@@ -1317,6 +1434,7 @@ fn consumes_plain_help_value(token: &str) -> bool {| "--level"| "--level-limit"| "-s"+ | "--skill"| "--session"| "--sender"| "--message"@@ -1328,6 +1446,7 @@ fn consumes_plain_help_value(token: &str) -> bool {| "--token-budget"| "--interval"| "--active"+ | "--format") || token.starts_with("--output=")|| token.starts_with("--compact=")|| token.starts_with("--account=")@@ -1348,6 +1467,7 @@ fn consumes_plain_help_value(token: &str) -> bool {|| token.starts_with("--abs-limit=")|| token.starts_with("--level=")|| token.starts_with("--level-limit=")+ || token.starts_with("--skill=")|| token.starts_with("--session=")|| token.starts_with("--sender=")|| token.starts_with("--message=")@@ -1359,6 +1479,7 @@ fn consumes_plain_help_value(token: &str) -> bool {|| token.starts_with("--token-budget=")|| token.starts_with("--interval=")|| token.starts_with("--active=")+ || token.starts_with("--format=")}fn canonical_plain_help_token(token: &str) -> &str {@@ -1381,7 +1502,7 @@ fn allows_plain_help_as_user_input(command: &str) -> bool {fn is_plain_help_group(command: &str) -> bool {matches!(command,- "config" | "task" | "admin" | "system" | "session" | "privacy" | "observer"+ "config" | "task" | "admin" | "system" | "session" | "privacy" | "observer" | "skills")}@@ -1419,6 +1540,10 @@ fn pre_parse_requires_cli_config_file(args: &[OsString]) -> bool {.get(1).map(|token| is_privacy_subcommand(token)).unwrap_or(false),+ "skills" => tokens+ .get(1)+ .map(|token| is_skill_subcommand(token))+ .unwrap_or(false),"observer" => tokens.get(1).map(|token| is_observer_subcommand(token))@@ -1589,6 +1714,13 @@ fn is_watch_subcommand(token: &str) -> bool {)}+fn is_skill_subcommand(token: &str) -> bool {+ matches!(+ token,+ "add" | "list" | "ls" | "find" | "show" | "update" | "remove" | "rm" | "delete"+ )+}+fn is_admin_subcommand(token: &str) -> bool {matches!(token,@@ -2065,6 +2197,92 @@ async fn main() {ctx.with_upload_options(upload_options.merged_with_legacy(legacy_upload_options));handlers::handle_add_skill(data, wait, timeout, ctx).await}+ Commands::Skills { action } => match action {+ SkillCommands::Add {+ source,+ skills,+ list,+ wait,+ yes,+ } => {+ let client = ctx.get_client();+ commands::skills::add(+ &client,+ &source,+ skills,+ list,+ wait,+ yes,+ ctx.should_show_progress(),+ ctx.is_verbose(),+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ SkillCommands::List { node_limit } => {+ let client = ctx.get_client();+ commands::skills::list(&client, node_limit, ctx.output_format, ctx.compact).await+ }+ SkillCommands::Find {+ query,+ node_limit,+ threshold,+ level,+ } => {+ let client = ctx.get_client();+ commands::skills::find(+ &client,+ &query,+ node_limit,+ threshold,+ level,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ SkillCommands::Show {+ name,+ level,+ files,+ source,+ format,+ content,+ } => {+ let client = ctx.get_client();+ let output_format = format+ .as_deref()+ .map(OutputFormat::from)+ .unwrap_or(ctx.output_format);+ let level = if content { Some(2) } else { level };+ commands::skills::show(+ &client,+ &name,+ level,+ files,+ source,+ output_format,+ ctx.compact,+ )+ .await+ }+ SkillCommands::Update { skills, wait, yes } => {+ let client = ctx.get_client();+ commands::skills::update(&client, skills, wait, yes, ctx.output_format, ctx.compact)+ .await+ }+ SkillCommands::Remove { skills, all, yes } => {+ let client = ctx.get_client();+ commands::skills::remove(&client, skills, all, yes, ctx.output_format, ctx.compact)+ .await+ }+ SkillCommands::Validate { path, strict } => {+ let client = ctx.get_client();+ commands::skills::validate(&client, &path, strict, ctx.output_format, ctx.compact)+ .await+ }+ },Commands::Relations { uri } => handlers::handle_relations(uri, ctx).await,Commands::Link {from_uri,@@ -2354,10 +2572,10 @@ async fn main() {mod tests {use super::{Cli, CliContext, Commands, ConfigAddTarget, ConfigCommands, LanguageGateAction,- PrivacyCommands, UploadCliOptions, first_command_token, is_language_command_request,- language_command_can_run_picker, language_gate_action, language_required_message,- legacy_upload_option_error, plain_help_misuse, pre_parse_requires_cli_config_file,- preprocess_privacy_args,+ PrivacyCommands, SkillCommands, UploadCliOptions, first_command_token,+ is_language_command_request, language_command_can_run_picker, language_gate_action,+ language_required_message, legacy_upload_option_error, plain_help_misuse,+ pre_parse_requires_cli_config_file, preprocess_privacy_args,};use crate::config::{Config, DEFAULT_CUSTOM_URL};use crate::output::OutputFormat;@@ -2444,6 +2662,10 @@ mod tests {assert!(!switch.command.requires_cli_config_file());assert!(!switch_named.command.requires_cli_config_file());assert!(!version.command.requires_cli_config_file());++ let skills_validate = Cli::try_parse_from(["ov", "skills", "validate", "./skills/foo"])+ .expect("skills validate should parse");+ assert!(!skills_validate.command.requires_cli_config_file());}#[test]@@ -2667,6 +2889,15 @@ mod tests {&["ov", "observer", "retrieval"],&["ov", "observer", "filesystem"],&["ov", "observer", "system"],+ &["ov", "skills", "add"],+ &["ov", "skills", "list"],+ &["ov", "skills", "ls"],+ &["ov", "skills", "find"],+ &["ov", "skills", "show"],+ &["ov", "skills", "update"],+ &["ov", "skills", "remove"],+ &["ov", "skills", "rm"],+ &["ov", "skills", "delete"],];for args in cases {@@ -2714,6 +2945,8 @@ mod tests {&["ov", "config", "add", "ov-service", "--api-key-stdin"],&["ov", "config", "edit", "prod", "--activate"],&["ov", "config", "setup-cli"],+ &["ov", "skills", "validate", "./skills/foo"],+ &["ov", "skills", "validate", "./skills/foo", "--strict"],&["ov", "version"],&["ov", "language", "en"],&["ov", "lang", "en"],@@ -2803,6 +3036,160 @@ mod tests {}_ => panic!("expected add-skill command"),}++ assert!(Cli::try_parse_from(["ov", "skills", "add", "./skill", "--progress"]).is_err());+ assert!(Cli::try_parse_from(["ov", "skills", "update", "--progress"]).is_err());+ }++ #[test]+ fn cli_parses_skills_command_group() {+ let list = Cli::try_parse_from(["ov", "skills", "list", "--limit", "25"])+ .expect("skills list should parse");+ match list.command {+ Commands::Skills {+ action: SkillCommands::List { node_limit },+ } => assert_eq!(node_limit, 25),+ _ => panic!("expected skills list"),+ }++ let find = Cli::try_parse_from([+ "ov",+ "skills",+ "find",+ "review code",+ "--threshold",+ "0.4",+ "--level",+ "0,1",+ ])+ .expect("skills find should parse");+ match find.command {+ Commands::Skills {+ action:+ SkillCommands::Find {+ query,+ threshold,+ level,+ ..+ },+ } => {+ assert_eq!(query, "review code");+ assert_eq!(threshold, Some(0.4));+ assert_eq!(level, Some(vec![0, 1]));+ }+ _ => panic!("expected skills find"),+ }++ let update =+ Cli::try_parse_from(["ov", "skills", "update", "code-review", "--wait", "--yes"])+ .expect("skills update should parse");+ match update.command {+ Commands::Skills {+ action:+ SkillCommands::Update {+ skills, wait, yes, ..+ },+ } => {+ assert_eq!(skills, vec!["code-review"]);+ assert!(wait);+ assert!(yes);+ }+ _ => panic!("expected skills update"),+ }++ let add_selected = Cli::try_parse_from([+ "ov",+ "skills",+ "add",+ "https://github.com/acme/skills.git",+ "--skill",+ "foo",+ "bar",+ "--list",+ "--yes",+ ])+ .expect("skills add RFC flags should parse");+ match add_selected.command {+ Commands::Skills {+ action:+ SkillCommands::Add {+ source,+ skills,+ list,+ yes,+ ..+ },+ } => {+ assert_eq!(source, "https://github.com/acme/skills.git");+ assert_eq!(skills, vec!["foo", "bar"]);+ assert!(list);+ assert!(yes);+ }+ _ => panic!("expected skills add"),+ }++ let show = Cli::try_parse_from([+ "ov",+ "skills",+ "show",+ "code-review",+ "--level",+ "2",+ "--files",+ "--source",+ "--format",+ "json",+ ])+ .expect("skills show RFC flags should parse");+ match show.command {+ Commands::Skills {+ action:+ SkillCommands::Show {+ level,+ files,+ source,+ format,+ ..+ },+ } => {+ assert_eq!(level, Some(2));+ assert!(files);+ assert!(source);+ assert_eq!(format.as_deref(), Some("json"));+ }+ _ => panic!("expected skills show"),+ }++ let show_global_output =+ Cli::try_parse_from(["ov", "skills", "show", "code-review", "-o", "json"])+ .expect("skills show should accept global -o after the subcommand");+ assert_eq!(show_global_output.output, OutputFormat::Json);++ let remove = Cli::try_parse_from(["ov", "skills", "remove", "foo", "bar", "--yes"])+ .expect("skills remove --yes should parse");+ match remove.command {+ Commands::Skills {+ action: SkillCommands::Remove { skills, yes, all },+ } => {+ assert_eq!(skills, vec!["foo", "bar"]);+ assert!(yes);+ assert!(!all);+ }+ _ => panic!("expected skills remove"),+ }++ let validate =+ Cli::try_parse_from(["ov", "skills", "validate", "./skills/foo", "--strict"])+ .expect("skills validate --strict should parse");+ match validate.command {+ Commands::Skills {+ action: SkillCommands::Validate { path, strict },+ } => {+ assert_eq!(path, "./skills/foo");+ assert!(strict);+ }+ _ => panic!("expected skills validate"),+ }}#[test]@@ -2840,6 +3227,15 @@ mod tests {let add_resource = Cli::try_parse_from(["ov", "--progress", "add-resource", "./README.md"]).expect("legacy pre-command upload flags should parse for add-resource");assert!(legacy_upload_option_error(upload_options, &add_resource.command).is_none());++ let skills_add = Cli::try_parse_from(["ov", "--progress", "skills", "add", "./skill"])+ .expect("hidden legacy flag still parses before runtime validation");+ assert_eq!(+ legacy_upload_option_error(upload_options, &skills_add.command),+ Some(+ "--progress, --no-progress, and --verbose are only supported for add-resource and add-skill."+ )+ );}#[test]diff --git a/crates/ov_cli/src/tui/app.rs b/crates/ov_cli/src/tui/app.rsindex 5b6de11fb..43f99051a 100644--- a/crates/ov_cli/src/tui/app.rs+++ b/crates/ov_cli/src/tui/app.rs@@ -1,14 +1,15 @@use crate::client::HttpClient;-use super::tree::TreeState;use super::image_preview;+use super::tree::TreeState;+use std::io::Write;use std::{pin::Pin, time::Instant};use tempfile::NamedTempFile;-use std::io::Write;// Type alias for confirmation callback-type ConfirmationCallback = Box<dyn for<'a> FnOnce(&'a mut App) -> Pin<Box<dyn Future<Output = ()> + 'a>>>;+type ConfirmationCallback =+ Box<dyn for<'a> FnOnce(&'a mut App) -> Pin<Box<dyn Future<Output = ()> + 'a>>>;#[derive(Debug, Clone, Copy, PartialEq)]pub enum Panel {@@ -249,11 +250,15 @@ impl App {self.current_preview_image = Some(path);// Keep temp file aliveself.temp_image_file = Some(temp_file);- info_text.push_str(&format!("Size: {} bytes", bytes.len()));+ info_text+ .push_str(&format!("Size: {} bytes", bytes.len()));}}Err(e) => {- info_text.push_str(&format!("(Could not write temp file: {})", e));+ info_text.push_str(&format!(+ "(Could not write temp file: {})",+ e+ ));}}}@@ -263,7 +268,8 @@ impl App {}}Err(e) => {- info_text.push_str(&format!("(Could not create temp file for preview: {})", e));+ info_text+ .push_str(&format!("(Could not create temp file for preview: {})", e));}}}@@ -371,10 +377,7 @@ impl App {F: for<'a> FnOnce(&'a mut App) -> Pin<Box<dyn Future<Output = ()> + 'a>> + 'static,{self.status_message_locked = true;- self.confirmation = Some((- message,- Box::new(on_confirmed),- ));+ self.confirmation = Some((message, Box::new(on_confirmed)));}pub async fn load_vector_records(&mut self, uri_prefix: Option<String>) {@@ -481,7 +484,8 @@ impl App {/// Collect all currently expanded nodesfn collect_expanded_nodes(&self) -> Vec<String> {- self.tree.visible+ self.tree+ .visible.iter().filter(|r| r.expanded).map(|r| r.uri.clone())@@ -503,14 +507,18 @@ impl App {/// Find cursor position for a given URI, fallback to parent if not foundfn find_cursor_for_uri(&self, uri: &str) -> usize {- self.tree.visible.iter()+ self.tree+ .visible+ .iter().position(|r| r.uri == uri).unwrap_or_else(|| {let mut parent_path = uri.to_string();while parent_path != "viking://" && parent_path != "/" {if let Some(last_slash) = parent_path.rfind('/') {parent_path = parent_path[..last_slash].to_string();- if let Some(pos) = self.tree.visible.iter().position(|r| r.uri == parent_path) {+ if let Some(pos) =+ self.tree.visible.iter().position(|r| r.uri == parent_path)+ {return pos;}} else {@@ -522,7 +530,12 @@ impl App {}/// Reload the entire tree and restore state- async fn reload_tree_and_restore_state(&mut self, client: &HttpClient, expanded_nodes: &[String], target_uri: &str) {+ async fn reload_tree_and_restore_state(+ &mut self,+ client: &HttpClient,+ expanded_nodes: &[String],+ target_uri: &str,+ ) {self.tree.load_root(client, "viking://").await;// Restore expanded state for previously expanded nodes@@ -531,7 +544,8 @@ impl App {}// Ensure parent directories of target URI are expanded- self.ensure_parent_directories_expanded(client, target_uri).await;+ self.ensure_parent_directories_expanded(client, target_uri)+ .await;// Find and set cursor to target URIlet cursor = self.find_cursor_for_uri(target_uri);@@ -543,7 +557,9 @@ impl App {pub async fn reload_entire_tree(&mut self) {let client = self.client.clone();- let selected_node = self.tree.selected_uri()+ let selected_node = self+ .tree+ .selected_uri().map(|uri| uri.to_string()).unwrap_or_else(|| "viking://".to_string());@@ -551,7 +567,8 @@ impl App {let expanded_nodes = self.collect_expanded_nodes();// Reload tree and restore state- self.reload_tree_and_restore_state(&client, &expanded_nodes, &selected_node).await;+ self.reload_tree_and_restore_state(&client, &expanded_nodes, &selected_node)+ .await;self.set_status_message("Tree refreshed".to_string());}@@ -584,10 +601,16 @@ impl App {let current_cursor = self.tree.cursor;let target_uri = if current_cursor + 1 < self.tree.visible.len() {// Use next node if it exists- self.tree.visible.get(current_cursor + 1).map(|r| r.uri.clone())+ self.tree+ .visible+ .get(current_cursor + 1)+ .map(|r| r.uri.clone())} else if current_cursor > 0 {// Use previous node if next doesn't exist- self.tree.visible.get(current_cursor - 1).map(|r| r.uri.clone())+ self.tree+ .visible+ .get(current_cursor - 1)+ .map(|r| r.uri.clone())} else {// Fallback to parent if no siblingsif let Some(last_slash) = selected_uri.rfind('/') {@@ -611,7 +634,8 @@ impl App {// Reload tree and restore stateif let Some(uri) = &target_uri {- self.reload_tree_and_restore_state(&client, &expanded_nodes, uri).await;+ self.reload_tree_and_restore_state(&client, &expanded_nodes, uri)+ .await;}}Err(e) => {diff --git a/crates/ov_cli/src/tui/event.rs b/crates/ov_cli/src/tui/event.rsindex a80352bb1..37ecf837f 100644--- a/crates/ov_cli/src/tui/event.rs+++ b/crates/ov_cli/src/tui/event.rs@@ -99,7 +99,8 @@ async fn handle_tree_key(app: &mut App, key: KeyEvent) {}// Create confirmation- let message = format!("Delete {}? (y/n): {}",+ let message = format!(+ "Delete {}? (y/n): {}",if is_dir { "directory" } else { "file" },selected_uri);diff --git a/crates/ov_cli/src/tui/image_preview.rs b/crates/ov_cli/src/tui/image_preview.rsindex 371b5f2fe..ea66e301d 100644--- a/crates/ov_cli/src/tui/image_preview.rs+++ b/crates/ov_cli/src/tui/image_preview.rs@@ -1,9 +1,6 @@-use std::sync::{Arc, Mutex};+use crossterm::{ExecutableCommand, cursor::MoveTo};use std::path::Path;-use crossterm::{- ExecutableCommand,- cursor::MoveTo,-};+use std::sync::{Arc, Mutex};/// Preview area coordinates (in terminal cells)#[derive(Debug, Clone, Copy)]@@ -17,8 +14,14 @@ pub struct PreviewArea {/// Check if a file is an image based on extensionpub fn is_image_file(filename: &str) -> bool {let path = Path::new(filename);- let ext = path.extension().and_then(|e| e.to_str()).map(|e| e.to_lowercase());- matches!(ext.as_deref(), Some("png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "tiff" | "tif"))+ let ext = path+ .extension()+ .and_then(|e| e.to_str())+ .map(|e| e.to_lowercase());+ matches!(+ ext.as_deref(),+ Some("png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "tiff" | "tif")+ )}/// Image previewer using viuer (simpler, more reliable)@@ -78,11 +81,7 @@ impl ImagePreviewer {}/// Display an image at the specified area- pub fn display_image_at(- &mut self,- image_path: &str,- area: PreviewArea,- ) -> Result<(), String> {+ pub fn display_image_at(&mut self, image_path: &str, area: PreviewArea) -> Result<(), String> {// Check if file exists firstlet path = std::path::Path::new(image_path);if !path.exists() {@@ -93,13 +92,19 @@ impl ImagePreviewer {}self.log(&format!("Displaying image: {}", image_path));- self.log(&format!("Preview area: x={}, y={}, width={}, height={}", area.x, area.y, area.width, area.height));+ self.log(&format!(+ "Preview area: x={}, y={}, width={}, height={}",+ area.x, area.y, area.width, area.height+ ));// Calculate dimensions - viuer uses half-blocks, so height is in characters// Each character cell can display 2x1 pixels (approximate)let max_width = Some(area.width.saturating_sub(2) as u32);let max_height = Some(area.height.saturating_sub(2) as u32);- self.log(&format!("Target dimensions: width={:?}, height={:?}", max_width, max_height));+ self.log(&format!(+ "Target dimensions: width={:?}, height={:?}",+ max_width, max_height+ ));// Try with multiple terminal protocols to find what workslet configs = [@@ -171,25 +176,25 @@ impl ImagePreviewer {self.log("Trying viuer::print_from_file");for (i, config) in configs.iter().enumerate() {self.log(&format!("Trying viuer config {} (print_from_file)", i + 1));- self.log(&format!("Config details: width={:?}, height={:?}, use_kitty={}, use_iterm={}",- config.width, config.height, config.use_kitty, config.use_iterm));+ self.log(&format!(+ "Config details: width={:?}, height={:?}, use_kitty={}, use_iterm={}",+ config.width, config.height, config.use_kitty, config.use_iterm+ ));// Move cursor to the preview area positionself.log(&format!("Moving cursor to x={}, y={}", area.x, area.y));match std::io::stdout().execute(MoveTo(area.x, area.y)) {- Ok(_) => {- match viuer::print_from_file(image_path, config) {- Ok(_) => {- displayed = true;- self.log(&format!("Success with config {} (print_from_file)", i + 1));- break;- }- Err(e) => {- self.log(&format!("Config {} failed (print_from_file): {}", i + 1, e));- last_error_str = Some(format!("{}", e));- }+ Ok(_) => match viuer::print_from_file(image_path, config) {+ Ok(_) => {+ displayed = true;+ self.log(&format!("Success with config {} (print_from_file)", i + 1));+ break;}- }+ Err(e) => {+ self.log(&format!("Config {} failed (print_from_file): {}", i + 1, e));+ last_error_str = Some(format!("{}", e));+ }+ },Err(e) => {self.log(&format!("Failed to move cursor: {}", e));last_error_str = Some(format!("Cursor move failed: {}", e));@@ -209,19 +214,24 @@ impl ImagePreviewer {// Move cursor to the preview area positionmatch std::io::stdout().execute(MoveTo(area.x, area.y)) {- Ok(_) => {- match viuer::print(&img, config) {- Ok(_) => {- displayed = true;- self.log(&format!("Success with config {} (image crate)", i + 1));- break;- }- Err(e) => {- self.log(&format!("Config {} failed (image crate): {}", i + 1, e));- last_error_str = Some(format!("{}", e));- }+ Ok(_) => match viuer::print(&img, config) {+ Ok(_) => {+ displayed = true;+ self.log(&format!(+ "Success with config {} (image crate)",+ i + 1+ ));+ break;}- }+ Err(e) => {+ self.log(&format!(+ "Config {} failed (image crate): {}",+ i + 1,+ e+ ));+ last_error_str = Some(format!("{}", e));+ }+ },Err(e) => {self.log(&format!("Failed to move cursor: {}", e));last_error_str = Some(format!("Cursor move failed: {}", e));@@ -237,7 +247,10 @@ impl ImagePreviewer {}if !displayed {- return Err(format!("Failed to display image with all configs. Last error: {:?}", last_error_str));+ return Err(format!(+ "Failed to display image with all configs. Last error: {:?}",+ last_error_str+ ));}*self.current_image.lock().unwrap() = Some(image_path.to_string());diff --git a/crates/ov_cli/src/tui/mod.rs b/crates/ov_cli/src/tui/mod.rsindex d8b6facf1..7e4d52c14 100644--- a/crates/ov_cli/src/tui/mod.rs+++ b/crates/ov_cli/src/tui/mod.rs@@ -1,8 +1,8 @@mod app;mod event;+mod image_preview;mod tree;mod ui;-mod image_preview;use std::io;@@ -13,7 +13,7 @@ use crossterm::{};use ratatui::prelude::*;use ratatui::text::Line;-use ratatui::widgets::{Paragraph, Block, Borders};+use ratatui::widgets::{Block, Borders, Paragraph};use crate::client::HttpClient;use crate::error::Result;@@ -77,7 +77,8 @@ async fn run_loop(client: HttpClient, uri: &str) -> Result<()> {let mut captured_content_area = None;// Track if we had an image in the previous iteration- static PREV_HAD_IMAGE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+ static PREV_HAD_IMAGE: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);let had_image = PREV_HAD_IMAGE.load(std::sync::atomic::Ordering::Relaxed);let has_image = app.current_preview_image.is_some();@@ -100,8 +101,11 @@ async fn run_loop(client: HttpClient, uri: &str) -> Result<()> {.take(usize::from(frame.area().height.saturating_sub(2))).map(|s| Line::from(s.as_str())).collect();- let paragraph = Paragraph::new(text)- .block(Block::default().borders(Borders::ALL).title(" Debug Logs (Press L to hide) "));+ let paragraph = Paragraph::new(text).block(+ Block::default()+ .borders(Borders::ALL)+ .title(" Debug Logs (Press L to hide) "),+ );frame.render_widget(paragraph, frame.area());} else {// Normal UIdiff --git a/crates/ov_cli/src/tui/tree.rs b/crates/ov_cli/src/tui/tree.rsindex c9ce900a5..9c1008f04 100644--- a/crates/ov_cli/src/tui/tree.rs+++ b/crates/ov_cli/src/tui/tree.rs@@ -318,6 +318,9 @@ impl TreeState {}pub fn allow_deletion(&self, selected_uri: &str) -> bool {- selected_uri != "/" && !Self::ROOT_SCOPES.iter().any(|s| selected_uri == format!("viking://{}", s))+ selected_uri != "/"+ && !Self::ROOT_SCOPES+ .iter()+ .any(|s| selected_uri == format!("viking://{}", s))}}diff --git a/crates/ov_cli/src/tui/ui.rs b/crates/ov_cli/src/tui/ui.rsindex 863a09973..276207fbb 100644--- a/crates/ov_cli/src/tui/ui.rs+++ b/crates/ov_cli/src/tui/ui.rs@@ -256,7 +256,6 @@ fn render_vector_records(frame: &mut Frame, app: &App, area: ratatui::layout::Re}fn render_status_bar(frame: &mut Frame, app: &App, area: ratatui::layout::Rect) {-// Show error message only if presentif !app.error_message.is_empty() {let bar = Paragraph::new(app.error_message.clone())@@ -359,7 +358,6 @@ fn render_status_bar(frame: &mut Frame, app: &App, area: ratatui::layout::Rect).add_modifier(Modifier::BOLD),),Span::raw(":top/bottom "),-]);}@@ -368,14 +366,15 @@ fn render_status_bar(frame: &mut Frame, app: &App, area: ratatui::layout::Rect)"d",Style::default().fg(Color::Yellow)- .add_modifier(Modifier::BOLD)),+ .add_modifier(Modifier::BOLD),+ ),Span::raw(":delete "),-Span::styled("r",Style::default().fg(Color::Yellow)- .add_modifier(Modifier::BOLD)),+ .add_modifier(Modifier::BOLD),+ ),Span::raw(":refresh"),]);diff --git a/openviking/privacy/service.py b/openviking/privacy/service.pyindex 313431081..9dd293c6a 100644--- a/openviking/privacy/service.py+++ b/openviking/privacy/service.py@@ -44,6 +44,13 @@ class UserPrivacyConfigService:except Exception:return False+ async def delete(self, ctx: RequestContext, category: str, target_key: str) -> bool:+ root_uri = self.get_config_root(ctx, category, target_key)+ if not await self.exists(ctx, category, target_key):+ return False+ await self._viking_fs.rm(root_uri, recursive=True, ctx=ctx)+ return True+async def _ensure_root(self, ctx: RequestContext, category: str, target_key: str) -> None:root_uri = self.get_config_root(ctx, category, target_key)await self._viking_fs.mkdir(root_uri, exist_ok=True, ctx=ctx)diff --git a/openviking/server/app.py b/openviking/server/app.pyindex 02558009b..0a9ff03ce 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -43,6 +43,7 @@ from openviking.server.routers import (resources_router,search_router,sessions_router,+ skills_router,stats_router,system_router,tasks_router,@@ -525,6 +526,7 @@ def create_app(app.include_router(search_router)app.include_router(relations_router)app.include_router(privacy_configs_router)+ app.include_router(skills_router)app.include_router(sessions_router)app.include_router(stats_router)app.include_router(pack_router)diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.pyindex 5f18b4a5a..1d3508688 100644--- a/openviking/server/routers/__init__.py+++ b/openviking/server/routers/__init__.py@@ -16,6 +16,7 @@ from openviking.server.routers.relations import router as relations_routerfrom openviking.server.routers.resources import router as resources_routerfrom openviking.server.routers.search import router as search_routerfrom openviking.server.routers.sessions import router as sessions_router+from openviking.server.routers.skills import router as skills_routerfrom openviking.server.routers.stats import router as stats_routerfrom openviking.server.routers.system import router as system_routerfrom openviking.server.routers.tasks import router as tasks_router@@ -33,6 +34,7 @@ __all__ = ["search_router","relations_router","sessions_router",+ "skills_router","stats_router","pack_router","privacy_configs_router",diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.pyindex 77474a565..044976cfb 100644--- a/openviking/server/routers/resources.py+++ b/openviking/server/routers/resources.py@@ -2,7 +2,7 @@# SPDX-License-Identifier: AGPL-3.0"""Resource endpoints for OpenViking HTTP Server."""-from typing import Any, Optional+from typing import Any, Dict, Optionalfrom fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFilefrom pydantic import BaseModel, ConfigDict, model_validator@@ -13,6 +13,7 @@ from openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContext, Rolefrom openviking.server.local_input_guard import require_remote_resource_sourcefrom openviking.server.responses import response_from_result+from openviking.server.skill_source_metadata import persist_skill_source_metadatafrom openviking.server.telemetry import run_operationfrom openviking.server.temp_upload_store import TempUploadStorefrom openviking.server.upload_token_store import UploadTokenError, upload_token_store@@ -107,6 +108,7 @@ class AddSkillRequest(BaseModel):temp_file_id: Optional[str] = Nonewait: bool = Falsetimeout: Optional[float] = None+ source_metadata: Optional[Dict[str, Any]] = Nonetelemetry: TelemetryRequest = False@model_validator(mode="after")@@ -278,12 +280,27 @@ async def add_skill(data = request.dataallow_local_path_resolution = Falseresolved = None+ source_metadata = request.source_metadata or {+ "type": "api",+ "source": "inline_content",+ "operation": "add",+ }if request.temp_file_id:store = TempUploadStore.build(http_request.app.state.config)resolved = await store.resolve_for_consume(request.temp_file_id, _ctx)data = resolved.local_pathallow_local_path_resolution = True-+ if request.source_metadata is None:+ source_metadata = {+ "type": "api",+ "source": "temp_upload",+ "operation": "add",+ "upload_mode": resolved.mode,+ }+ if resolved.original_filename and request.source_metadata is None:+ source_metadata["original_filename"] = resolved.original_filename++ source_path_hint = resolved.original_filename if resolved else Nonestore = TempUploadStore.build(http_request.app.state.config) if resolved else Noneasync def _add() -> dict[str, Any]:@@ -294,7 +311,9 @@ async def add_skill(wait=request.wait,timeout=request.timeout,allow_local_path_resolution=allow_local_path_resolution,+ source_path_hint=source_path_hint,)+ await persist_skill_source_metadata(service, _ctx, result, source_metadata)except Exception:if resolved and store:await store.mark_failed(resolved, _ctx)diff --git a/openviking/server/routers/skills.py b/openviking/server/routers/skills.pynew file mode 100644index 000000000..9f89ea9c4--- /dev/null+++ b/openviking/server/routers/skills.py@@ -0,0 +1,677 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Agent-scope skill management endpoints for OpenViking HTTP Server."""++import re+import shutil+import uuid+from pathlib import Path+from typing import Any, Dict, Optional++import yaml+from fastapi import APIRouter, Depends, Request+from fastapi import Path as ApiPath+from pydantic import BaseModel, ConfigDict, model_validator++from openviking.core.namespace import canonical_user_root+from openviking.core.skill_loader import SkillLoader+from openviking.privacy.service import UserPrivacyConfigVersion+from openviking.server.auth import get_request_context+from openviking.server.dependencies import get_service+from openviking.server.identity import RequestContext+from openviking.server.models import Response+from openviking.server.skill_source_metadata import (+ SOURCE_METADATA_FILENAME,+ persist_skill_source_metadata,+ read_skill_source_metadata,+)+from openviking.server.telemetry import run_operation+from openviking.server.temp_upload_store import TempUploadStore+from openviking.telemetry import TelemetryRequest+from openviking.utils.skill_processor import validate_skill_name+from openviking_cli.exceptions import InvalidArgumentError, NotFoundError++router = APIRouter(prefix="/api/v1/skills", tags=["skills"])+++class UpdateSkillRequest(BaseModel):+ """Replace an existing agent skill with new skill content."""++ model_config = ConfigDict(extra="forbid")++ data: Any = None+ temp_file_id: Optional[str] = None+ wait: bool = False+ timeout: Optional[float] = None+ source_metadata: Optional[Dict[str, Any]] = None+ telemetry: TelemetryRequest = False++ @model_validator(mode="after")+ def check_data_or_temp_file_id(self):+ if self.data is None and not self.temp_file_id:+ raise ValueError("Either 'data' or 'temp_file_id' must be provided")+ return self+++class FindSkillsRequest(BaseModel):+ model_config = ConfigDict(extra="forbid")++ query: str+ limit: int = 10+ score_threshold: Optional[float] = None+ level: Optional[list[int]] = None+ telemetry: TelemetryRequest = False+++class ValidateSkillRequest(BaseModel):+ model_config = ConfigDict(extra="forbid")++ data: Any+ strict: bool = False+ source_path: Optional[str] = None+ skill_dir_name: Optional[str] = None+++def _agent_skills_root(ctx: RequestContext) -> str:+ return f"{canonical_user_root(ctx)}/skills"+++def _validate_skill_name(skill_name: str) -> str:+ return validate_skill_name(skill_name)+++def _skill_root_uri(ctx: RequestContext, skill_name: str) -> str:+ return f"{_agent_skills_root(ctx)}/{_validate_skill_name(skill_name)}"+++def _skill_md_uri(root_uri: str) -> str:+ return f"{root_uri.rstrip('/')}/SKILL.md"+++def _skill_name_from_uri(uri: str) -> str:+ return uri.rstrip("/").split("/")[-1]+++def _relative_skill_path(root_uri: str, uri: str) -> str:+ prefix = root_uri.rstrip("/") + "/"+ if uri.startswith(prefix):+ return uri[len(prefix) :]+ return _skill_name_from_uri(uri)+++def _skill_file_kind(path: str, is_dir: bool) -> str:+ if is_dir:+ return "directory"+ if path == "SKILL.md":+ return "definition"+ if path in {".abstract.md", ".overview.md"}:+ return "summary"+ return "auxiliary"+++def _parse_abstract_meta(abstract: str) -> Dict[str, Any]:+ try:+ parsed = yaml.safe_load(abstract or "") or {}+ except Exception:+ return {}+ return parsed if isinstance(parsed, dict) else {}+++def _skill_summary_from_meta(name: str, root_uri: str, meta: Dict[str, Any]) -> Dict[str, Any]:+ return {+ "name": name,+ "uri": root_uri,+ "root_uri": root_uri,+ "skill_md_uri": _skill_md_uri(root_uri),+ "description": meta.get("description", ""),+ "tags": meta.get("tags") or [],+ "allowed_tools": meta.get("allowed_tools") or meta.get("allowed-tools") or [],+ }+++_SKILL_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")+++def _validation_issue(rule: str, message: str, field: str = "") -> Dict[str, str]:+ issue = {"rule": rule, "message": message}+ if field:+ issue["field"] = field+ return issue+++def _parse_skill_for_validation(data: Any) -> Dict[str, Any]:+ if isinstance(data, dict):+ parsed = dict(data)+ parsed["content"] = parsed.get("content") or ""+ elif isinstance(data, str):+ frontmatter, body = SkillLoader._split_frontmatter(data)+ if not frontmatter:+ raise ValueError("SKILL.md must have YAML frontmatter")+ try:+ meta = yaml.safe_load(frontmatter)+ except Exception as exc:+ raise ValueError(f"Invalid YAML frontmatter: {exc}") from exc+ if not isinstance(meta, dict):+ raise ValueError("Invalid YAML frontmatter")+ parsed = dict(meta)+ parsed["content"] = body.strip()+ else:+ raise ValueError(f"Unsupported data type: {type(data)}")++ allowed_tools = parsed.get("allowed_tools")+ if not allowed_tools:+ allowed_tools = parsed.get("allowed-tools")+ if allowed_tools is not None:+ parsed["allowed_tools"] = (+ allowed_tools if isinstance(allowed_tools, list) else [allowed_tools]+ )+ parsed.pop("allowed-tools", None)++ tags = parsed.get("tags")+ if tags is not None and not isinstance(tags, list):+ parsed["tags"] = [tags]++ return parsed+++def _validate_skill_format(+ service,+ data: Any,+ *,+ strict: bool,+ skill_dir_name: Optional[str],+ source_path: Optional[str],+) -> Dict[str, Any]:+ errors: list[Dict[str, str]] = []+ warnings: list[Dict[str, str]] = []++ try:+ parsed = _parse_skill_for_validation(data)+ except Exception as exc:+ return {+ "valid": False,+ "strict": strict,+ "errors": [+ _validation_issue(+ "yaml_format",+ str(exc),+ "data",+ )+ ],+ "warnings": [],+ "source_path": source_path or "",+ }++ name = parsed.get("name")+ description = parsed.get("description")+ content = parsed.get("content") or ""++ if not isinstance(name, str) or not name.strip():+ errors.append(_validation_issue("name_required", "name is required", "name"))+ if not isinstance(description, str) or not description.strip():+ errors.append(+ _validation_issue("description_required", "description is required", "description")+ )++ def add_mode_issue(rule: str, message: str, field: str):+ issue = _validation_issue(rule, message, field)+ if strict:+ errors.append(issue)+ else:+ warnings.append(issue)++ if isinstance(name, str) and name.strip():+ normalized_name = name.strip()+ normalized_dir_name = (skill_dir_name or "").strip()+ if normalized_dir_name and normalized_name != normalized_dir_name:+ add_mode_issue(+ "name_matches_directory",+ f"name '{normalized_name}' does not match directory name '{normalized_dir_name}'",+ "name",+ )+ if len(normalized_name) > 64:+ add_mode_issue("name_max_length", "name must not exceed 64 characters", "name")+ if not _SKILL_NAME_PATTERN.match(normalized_name):+ add_mode_issue(+ "name_allowed_characters",+ "name may only contain letters, numbers, underscores, and hyphens",+ "name",+ )++ if isinstance(description, str) and len(description) > 1024:+ add_mode_issue(+ "description_max_length",+ "description must not exceed 1024 characters",+ "description",+ )++ body_lines = len(content.splitlines())+ if strict and body_lines > 500:+ warnings.append(+ _validation_issue(+ "body_max_lines",+ "SKILL.md body exceeds 500 lines",+ "content",+ )+ )++ return {+ "valid": not errors,+ "strict": strict,+ "name": name or "",+ "description": description or "",+ "tags": parsed.get("tags") or [],+ "allowed_tools": parsed.get("allowed_tools") or [],+ "body_lines": body_lines,+ "source_path": source_path or "",+ "skill_dir_name": skill_dir_name or "",+ "errors": errors,+ "warnings": warnings,+ }+++def _skill_summary_from_entry(entry: Dict[str, Any]) -> Dict[str, Any]:+ root_uri = entry.get("uri", "")+ name = entry.get("name") or _skill_name_from_uri(root_uri)+ return _skill_summary_from_meta(name, root_uri, _parse_abstract_meta(entry.get("abstract", "")))+++def _skill_summary_from_hit(hit: Dict[str, Any]) -> Dict[str, Any]:+ root_uri = hit.get("uri", "")+ name = _skill_name_from_uri(root_uri)+ summary = _skill_summary_from_meta(+ name, root_uri, _parse_abstract_meta(hit.get("abstract", ""))+ )+ summary["score"] = hit.get("score", 0.0)+ summary["match_reason"] = hit.get("match_reason", "")+ summary["level"] = hit.get("level", 0)+ summary["abstract"] = hit.get("abstract", "")+ return summary+++async def _require_skill(service, ctx: RequestContext, skill_name: str) -> str:+ root_uri = _skill_root_uri(ctx, skill_name)+ try:+ stat = await service.fs.stat(root_uri, ctx=ctx)+ except NotFoundError:+ raise+ except Exception as exc:+ raise NotFoundError(root_uri, "skill") from exc+ if not stat or not stat.get("isDir", False):+ raise NotFoundError(root_uri, "skill")+ return root_uri+++async def _list_skill_files(+ service,+ ctx: RequestContext,+ root_uri: str,+ *,+ node_limit: int = 10000,+ level_limit: int = 10,+) -> list[Dict[str, Any]]:+ entries: list[Dict[str, Any]] = []+ queue: list[tuple[str, int]] = [(root_uri, 0)]+ visited_dirs = {root_uri.rstrip("/")}++ while queue and len(entries) < node_limit:+ current_uri, depth = queue.pop(0)+ child_limit = max(node_limit - len(entries), 0)+ if child_limit <= 0:+ break+ children = await service.fs.ls(+ current_uri,+ ctx=ctx,+ output="agent",+ abs_limit=1024,+ show_all_hidden=True,+ node_limit=child_limit,+ )+ for entry in children:+ if not isinstance(entry, dict):+ continue+ entry_uri = entry.get("uri", "")+ if not entry_uri:+ continue+ entries.append(entry)+ if len(entries) >= node_limit:+ break+ if not entry.get("isDir", False) or depth + 1 >= level_limit:+ continue+ normalized_uri = entry_uri.rstrip("/")+ if normalized_uri in visited_dirs:+ continue+ visited_dirs.add(normalized_uri)+ queue.append((entry_uri, depth + 1))+ return entries+++def _parse_skill_data(+ service,+ data: Any,+ *,+ allow_local_path_resolution: bool,+ source_path_hint: Optional[str] = None,+) -> Dict[str, Any]:+ skill_processor = getattr(service.resources, "_skill_processor", None)+ if skill_processor is None:+ raise RuntimeError("SkillProcessor is required for skill validation")+ skill_dict, _, _, _ = skill_processor._parse_skill( # noqa: SLF001 - keep parser authority centralized.+ data,+ allow_local_path_resolution=allow_local_path_resolution,+ source_path_hint=source_path_hint,+ )+ return skill_dict+++def _validate_data_matches_name(+ service,+ data: Any,+ skill_name: str,+ *,+ allow_local_path_resolution: bool,+ source_path_hint: Optional[str] = None,+) -> Dict[str, Any]:+ parsed = _parse_skill_data(+ service,+ data,+ allow_local_path_resolution=allow_local_path_resolution,+ source_path_hint=source_path_hint,+ )+ expected_name = _validate_skill_name(skill_name)+ if parsed.get("name") != expected_name:+ raise InvalidArgumentError(+ f"Skill name mismatch: path name is '{expected_name}', content name is '{parsed.get('name')}'",+ details={"expected": expected_name, "actual": parsed.get("name")},+ )+ return parsed+++async def _restore_skill_privacy(+ service,+ ctx: RequestContext,+ skill_name: str,+ previous_privacy: Optional[UserPrivacyConfigVersion],+) -> None:+ privacy = service.privacy_configs+ if privacy is None:+ return+ if previous_privacy is None:+ await privacy.delete(ctx, "skill", skill_name)+ return+ await privacy.activate_version(+ ctx,+ "skill",+ skill_name,+ previous_privacy.version,+ updated_by=ctx.user.user_id,+ )+++async def list_skills(+ node_limit: int = 1000,+ _ctx: RequestContext = Depends(get_request_context),+):+ """List installed agent skills."""+ service = get_service()+ root_uri = _agent_skills_root(_ctx)+ try:+ entries = await service.fs.ls(+ root_uri,+ ctx=_ctx,+ output="agent",+ abs_limit=1024,+ node_limit=node_limit,+ )+ except NotFoundError:+ entries = []+ skills = [+ _skill_summary_from_entry(entry)+ for entry in entries+ if isinstance(entry, dict) and entry.get("isDir", False)+ ]+ return Response(+ status="ok", result={"root_uri": root_uri, "skills": skills, "total": len(skills)}+ )++[email protected]("/find")+async def find_skills(+ request: FindSkillsRequest,+ _ctx: RequestContext = Depends(get_request_context),+):+ """Find agent skills by semantic search."""+ service = get_service()+ root_uri = _agent_skills_root(_ctx)+ execution = await run_operation(+ operation="skills.find",+ telemetry=request.telemetry,+ fn=lambda: service.search.find(+ query=request.query,+ ctx=_ctx,+ target_uri=root_uri,+ limit=request.limit,+ score_threshold=request.score_threshold,+ level=request.level,+ ),+ )+ result = execution.result+ result_dict = result.to_dict() if hasattr(result, "to_dict") else dict(result or {})+ hits = [_skill_summary_from_hit(hit) for hit in result_dict.get("skills", [])]+ return Response(+ status="ok",+ result={"root_uri": root_uri, "skills": hits, "total": len(hits)},+ telemetry=execution.telemetry,+ ).model_dump(exclude_none=True)++[email protected]("/validate")+async def validate_skill(+ request: ValidateSkillRequest,+ _ctx: RequestContext = Depends(get_request_context),+):+ """Validate a SKILL.md payload using Agent Skills formatting rules."""+ del _ctx+ service = get_service()+ result = _validate_skill_format(+ service,+ request.data,+ strict=request.strict,+ skill_dir_name=request.skill_dir_name,+ source_path=request.source_path,+ )+ return Response(status="ok", result=result)++[email protected]("/{skill_name}")+async def get_skill(+ skill_name: str = ApiPath(..., description="Skill name"),+ include_content: Optional[bool] = None,+ include_files: bool = True,+ include_source: bool = False,+ level: Optional[int] = None,+ _ctx: RequestContext = Depends(get_request_context),+):+ """Show one installed agent skill."""+ if level is not None and level not in {0, 1, 2}:+ raise InvalidArgumentError(+ "Skill show level must be 0, 1, or 2",+ details={"field": "level", "allowed": [0, 1, 2]},+ )+ service = get_service()+ root_uri = await _require_skill(service, _ctx, skill_name)+ abstract = await service.fs.abstract(root_uri, ctx=_ctx)+ result = _skill_summary_from_meta(skill_name, root_uri, _parse_abstract_meta(abstract))+ if level is None or level == 0:+ result["abstract"] = abstract+ if level is None or level == 1:+ result["overview"] = await service.fs.overview(root_uri, ctx=_ctx)+ if level == 2 or include_content is True or (level is None and include_content is not False):+ result["content"] = await service.fs.read(_skill_md_uri(root_uri), ctx=_ctx)+ if include_files:+ entries = await _list_skill_files(service, _ctx, root_uri)+ result["files"] = [+ {+ "name": entry.get("name") or _skill_name_from_uri(entry.get("uri", "")),+ "uri": entry.get("uri", ""),+ "path": _relative_skill_path(root_uri, entry.get("uri", "")),+ "is_dir": entry.get("isDir", False),+ "kind": _skill_file_kind(+ _relative_skill_path(root_uri, entry.get("uri", "")),+ entry.get("isDir", False),+ ),+ }+ for entry in entries+ if isinstance(entry, dict)+ and _relative_skill_path(root_uri, entry.get("uri", "")) != SOURCE_METADATA_FILENAME+ ]+ if include_source:+ result["source"] = await read_skill_source_metadata(service, _ctx, root_uri)+ return Response(status="ok", result=result)++[email protected]("/{skill_name}")+async def update_skill(+ http_request: Request,+ request: UpdateSkillRequest,+ skill_name: str = ApiPath(..., description="Skill name"),+ _ctx: RequestContext = Depends(get_request_context),+):+ """Replace an existing agent skill with new content."""+ service = get_service()+ root_uri = await _require_skill(service, _ctx, skill_name)++ data = request.data+ allow_local_path_resolution = False+ resolved = None+ source_metadata = request.source_metadata or {+ "type": "api",+ "source": "inline_content",+ "operation": "update",+ }+ if request.temp_file_id:+ store = TempUploadStore.build(http_request.app.state.config)+ resolved = await store.resolve_for_consume(request.temp_file_id, _ctx)+ data = Path(resolved.local_path)+ allow_local_path_resolution = True+ if request.source_metadata is None:+ source_metadata = {+ "type": "api",+ "source": "temp_upload",+ "operation": "update",+ "upload_mode": resolved.mode,+ }+ if resolved.original_filename and request.source_metadata is None:+ source_metadata["original_filename"] = resolved.original_filename++ source_path_hint = resolved.original_filename if resolved else None+ store = TempUploadStore.build(http_request.app.state.config) if resolved else None++ async def _update() -> Dict[str, Any]:+ backup_uri = f"{_agent_skills_root(_ctx)}/.{skill_name}.update-backup-{uuid.uuid4().hex}"+ backup_created = False+ privacy_update_attempted = False+ previous_privacy = None+ preparation = None+ privacy = service.privacy_configs+ try:+ if privacy is not None:+ previous_privacy = await privacy.get_current(_ctx, "skill", skill_name)+ preparation = await service.resources._skill_processor.prepare_skill_processing( # noqa: SLF001+ data,+ ctx=_ctx,+ allow_local_path_resolution=allow_local_path_resolution,+ source_path_hint=source_path_hint,+ )+ expected_name = _validate_skill_name(skill_name)+ if preparation.skill_dict.get("name") != expected_name:+ raise InvalidArgumentError(+ f"Skill name mismatch: path name is '{expected_name}', content name is '{preparation.skill_dict.get('name')}'",+ details={+ "expected": expected_name,+ "actual": preparation.skill_dict.get("name"),+ },+ )+ await service.fs.mv(root_uri, backup_uri, ctx=_ctx)+ backup_created = True+ result = await service.resources.add_skill(+ data=preparation,+ ctx=_ctx,+ wait=request.wait,+ timeout=request.timeout,+ allow_local_path_resolution=False,+ source_path_hint=source_path_hint,+ apply_privacy=False,+ privacy_change_reason="auto-extracted from update_skill",+ )+ await persist_skill_source_metadata(service, _ctx, result, source_metadata)+ privacy_update_attempted = True+ await service.resources._skill_processor.apply_skill_privacy( # noqa: SLF001+ preparation.skill_dict,+ preparation.privacy_values,+ _ctx,+ change_reason="auto-extracted from update_skill",+ delete_if_empty=True,+ )+ except Exception:+ if backup_created:+ try:+ await service.fs.rm(root_uri, ctx=_ctx, recursive=True)+ except Exception:+ pass+ try:+ await service.fs.mv(backup_uri, root_uri, ctx=_ctx)+ except Exception:+ pass+ if privacy_update_attempted:+ try:+ await _restore_skill_privacy(service, _ctx, skill_name, previous_privacy)+ except Exception:+ pass+ if resolved and store:+ await store.mark_failed(resolved, _ctx)+ raise+ else:+ if backup_created:+ await service.fs.rm(backup_uri, ctx=_ctx, recursive=True)+ if resolved and store:+ await store.mark_consumed(resolved, _ctx)+ result["action"] = "update"+ return result+ finally:+ if preparation and preparation.cleanup_path:+ shutil.rmtree(preparation.cleanup_path, ignore_errors=True)+ if resolved:+ await resolved.cleanup()++ execution = await run_operation(+ operation="skills.update",+ telemetry=request.telemetry,+ fn=_update,+ )+ return Response(+ status="ok",+ result=execution.result,+ telemetry=execution.telemetry,+ ).model_dump(exclude_none=True)++[email protected]("/{skill_name}")+async def delete_skill(+ skill_name: str = ApiPath(..., description="Skill name"),+ _ctx: RequestContext = Depends(get_request_context),+):+ """Remove one installed agent skill."""+ service = get_service()+ root_uri = await _require_skill(service, _ctx, skill_name)+ result = await service.fs.rm(root_uri, ctx=_ctx, recursive=True)+ privacy_deleted = False+ privacy = service.privacy_configs+ if privacy is not None:+ privacy_deleted = await privacy.delete(_ctx, "skill", skill_name)+ response_result: Dict[str, Any] = {"name": skill_name, "uri": root_uri, "root_uri": root_uri}+ if isinstance(result, dict) and "estimated_deleted_count" in result:+ response_result["estimated_deleted_count"] = result["estimated_deleted_count"]+ response_result["privacy_deleted"] = privacy_deleted+ return Response(status="ok", result=response_result)diff --git a/openviking/server/skill_source_metadata.py b/openviking/server/skill_source_metadata.pynew file mode 100644index 000000000..62afc6b11--- /dev/null+++ b/openviking/server/skill_source_metadata.py@@ -0,0 +1,77 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Helpers for persisted skill source metadata."""++import json+from typing import Any, Dict, Optional++from openviking.server.identity import RequestContext++SOURCE_METADATA_FILENAME = ".source.json"+++def skill_source_metadata_uri(root_uri: str) -> str:+ return f"{root_uri.rstrip('/')}/{SOURCE_METADATA_FILENAME}"+++async def read_skill_source_metadata(+ service,+ ctx: RequestContext,+ root_uri: str,+) -> Dict[str, Any]:+ uri = skill_source_metadata_uri(root_uri)+ try:+ raw = await service.fs.read(uri, ctx=ctx)+ except Exception:+ return {+ "tracked": False,+ "message": "Skill source metadata is not tracked yet.",+ }++ try:+ metadata = json.loads(raw)+ except Exception:+ return {+ "tracked": False,+ "message": "Skill source metadata is invalid.",+ }++ if not isinstance(metadata, dict):+ return {+ "tracked": False,+ "message": "Skill source metadata is invalid.",+ }+ metadata["tracked"] = True+ metadata["metadata_uri"] = uri+ return metadata+++async def persist_skill_source_metadata(+ service,+ ctx: RequestContext,+ result: Dict[str, Any],+ source: Optional[Dict[str, Any]],+) -> None:+ if not source:+ return++ root_uri = result.get("root_uri") or result.get("uri")+ if not root_uri:+ return++ record = dict(source)+ skill_name = result.get("name") or record.get("skill_name")+ if skill_name:+ record["skill_name"] = skill_name++ uri = skill_source_metadata_uri(root_uri)+ content = json.dumps(record, ensure_ascii=False, indent=2, sort_keys=True)+ viking_fs = getattr(service, "viking_fs", None)+ if viking_fs is not None:+ await viking_fs.write(uri, content, ctx=ctx)+ return++ try:+ await service.fs.write(uri=uri, content=content, ctx=ctx, mode="replace", wait=True)+ except Exception:+ await service.fs.write(uri=uri, content=content, ctx=ctx, mode="create", wait=True)diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.pyindex bbaf70ea0..43e8ee231 100644--- a/openviking/service/reindex_executor.py+++ b/openviking/service/reindex_executor.py@@ -1154,7 +1154,7 @@ class ReindexExecutor:details={"uri": uri},)- skill_dict, _, _ = SkillProcessor(service.vikingdb_manager)._parse_skill(+ skill_dict, _, _, _ = SkillProcessor(service.vikingdb_manager)._parse_skill(skill_content,allow_local_path_resolution=False,)diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 7e26dd30e..e55b68f6c 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -40,7 +40,7 @@ from openviking.utils import is_git_repo_url, parse_code_hosting_urlfrom openviking.utils.media_processor import _smart_stemfrom openviking.utils.network_guard import ensure_public_remote_targetfrom openviking.utils.resource_processor import ResourceProcessor-from openviking.utils.skill_processor import SkillProcessor+from openviking.utils.skill_processor import SkillProcessingPreparation, SkillProcessorfrom openviking_cli.exceptions import (ConflictError,DeadlineExceededError,@@ -828,6 +828,9 @@ class ResourceService:wait: bool = False,timeout: Optional[float] = None,allow_local_path_resolution: bool = True,+ source_path_hint: Optional[str] = None,+ apply_privacy: bool = True,+ privacy_change_reason: str = "auto-extracted from add_skill",) -> Dict[str, Any]:"""Add skill to OpenViking.@@ -847,12 +850,24 @@ class ResourceService:request_wait_tracker.register_request(telemetry_id)try:- result = await self._skill_processor.process_skill(- data=data,- viking_fs=self._viking_fs,- ctx=ctx,- allow_local_path_resolution=allow_local_path_resolution,- )+ if isinstance(data, SkillProcessingPreparation):+ result = await self._skill_processor.process_prepared_skill(+ data,+ viking_fs=self._viking_fs,+ ctx=ctx,+ apply_privacy=apply_privacy,+ privacy_change_reason=privacy_change_reason,+ )+ else:+ result = await self._skill_processor.process_skill(+ data=data,+ viking_fs=self._viking_fs,+ ctx=ctx,+ allow_local_path_resolution=allow_local_path_resolution,+ source_path_hint=source_path_hint,+ apply_privacy=apply_privacy,+ privacy_change_reason=privacy_change_reason,+ )if isinstance(result, dict) and "root_uri" not in result and result.get("uri"):result["root_uri"] = result["uri"]diff --git a/openviking/utils/skill_processor.py b/openviking/utils/skill_processor.pyindex 92092db2e..dd7f1fcab 100644--- a/openviking/utils/skill_processor.py+++ b/openviking/utils/skill_processor.py@@ -6,10 +6,12 @@ Skill Processor for OpenViking.Handles skill parsing, LLM generation, and storage operations."""+import shutilimport tempfileimport timeimport zipfilefrom copy import deepcopy+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -37,6 +39,53 @@ from openviking_cli.utils.config import get_openviking_configlogger = get_logger(__name__)+MAX_SKILL_NAME_LENGTH = 64+++@dataclass+class SkillProcessingPreparation:+ skill_dict: Dict[str, Any]+ auxiliary_files: List[Path]+ base_path: Optional[Path]+ cleanup_path: Optional[Path]+ privacy_values: Dict[str, str]+++def validate_skill_name(name: Any) -> str:+ """Validate and normalize an Agent Skill name for storage/API addressing."""+ if name is None:+ raise InvalidArgumentError("Skill must have 'name' field", details={"field": "name"})+ if not isinstance(name, str):+ raise InvalidArgumentError(+ "Skill 'name' must be a non-empty string",+ details={"field": "name"},+ )++ normalized = name.strip()+ if not normalized:+ raise InvalidArgumentError(+ "Skill 'name' must be a non-empty string",+ details={"field": "name"},+ )+ if len(normalized) > MAX_SKILL_NAME_LENGTH:+ raise InvalidArgumentError(+ f"Skill name cannot exceed {MAX_SKILL_NAME_LENGTH} characters",+ details={+ "field": "name",+ "max_length": MAX_SKILL_NAME_LENGTH,+ "actual_length": len(normalized),+ },+ )+ if not all(ch.isascii() and (ch.isalnum() or ch in {"_", "-"}) for ch in normalized):+ raise InvalidArgumentError(+ f"Invalid skill name: {name}",+ details={+ "field": "name",+ "reason": "skill name may only contain ASCII letters, numbers, underscores, and hyphens",+ },+ )+ return normalized+class SkillProcessor:"""@@ -65,12 +114,15 @@ class SkillProcessor:viking_fs: VikingFS,ctx: RequestContext,allow_local_path_resolution: bool = True,+ source_path_hint: Optional[str] = None,+ apply_privacy: bool = True,+ privacy_change_reason: str = "auto-extracted from add_skill",) -> Dict[str, Any]:"""Process and store a skill.Args:- data: Skill data (directory path, file path, string, or dict)+ data: Skill data (directory, file path, string, or dict)viking_fs: VikingFS instance for storageuser: Username for context@@ -81,143 +133,233 @@ class SkillProcessor:if data is None:raise ValueError("Skill data cannot be None")- config = get_openviking_config()- telemetry = get_current_telemetry()-parse_start = time.perf_counter()- skill_dict, auxiliary_files, base_path = self._parse_skill(+ preparation = await self.prepare_skill_processing(data,+ ctx=ctx,allow_local_path_resolution=allow_local_path_resolution,+ source_path_hint=source_path_hint,)- self._validate_skill_dict(skill_dict)+ telemetry = get_current_telemetry()telemetry.set("skill.parse.duration_ms", round((time.perf_counter() - parse_start) * 1000, 3))+ return await self.process_prepared_skill(+ preparation,+ viking_fs=viking_fs,+ ctx=ctx,+ apply_privacy=apply_privacy,+ privacy_change_reason=privacy_change_reason,+ )- skill_dict = await self.sanitize_skill_privacy(skill_dict, ctx)- skill_abstract = self._build_skill_abstract(skill_dict)+ async def process_prepared_skill(+ self,+ preparation: SkillProcessingPreparation,+ viking_fs: VikingFS,+ ctx: RequestContext,+ *,+ apply_privacy: bool = True,+ privacy_change_reason: str = "auto-extracted from add_skill",+ ) -> Dict[str, Any]:+ config = get_openviking_config()+ cleanup_path = preparation.cleanup_path+ skill_dict = preparation.skill_dict+ auxiliary_files = preparation.auxiliary_files+ base_path = preparation.base_path+ telemetry = get_current_telemetry()+ try:+ if apply_privacy:+ skill_dict = await self.apply_skill_privacy(+ skill_dict,+ preparation.privacy_values,+ ctx,+ change_reason=privacy_change_reason,+ delete_if_empty=False,+ )+ skill_abstract = self._build_skill_abstract(skill_dict)++ skill_root_uri = f"{canonical_user_root(ctx)}/skills"+ context = Context(+ uri=f"{skill_root_uri}/{skill_dict['name']}",+ parent_uri=skill_root_uri,+ is_leaf=False,+ abstract=skill_abstract,+ context_type=ContextType.SKILL.value,+ user=ctx.user,+ account_id=ctx.account_id,+ owner_space=user_space_fragment(ctx),+ meta={+ "name": skill_dict["name"],+ "description": skill_dict.get("description", ""),+ "allowed_tools": skill_dict.get("allowed_tools", []),+ "tags": skill_dict.get("tags", []),+ "source_path": skill_dict.get("source_path", ""),+ },+ )+ context.set_vectorize(Vectorize(text=context.abstract))- skill_root_uri = f"{canonical_user_root(ctx)}/skills"- context = Context(- uri=f"{skill_root_uri}/{skill_dict['name']}",- parent_uri=skill_root_uri,- is_leaf=False,- abstract=skill_abstract,- context_type=ContextType.SKILL.value,- user=ctx.user,- account_id=ctx.account_id,- owner_space=user_space_fragment(ctx),- meta={- "name": skill_dict["name"],- "description": skill_dict.get("description", ""),- "allowed_tools": skill_dict.get("allowed_tools", []),- "tags": skill_dict.get("tags", []),- "source_path": skill_dict.get("source_path", ""),- },- )- context.set_vectorize(Vectorize(text=context.abstract))+ overview_start = time.perf_counter()+ overview = await self._generate_overview(skill_dict, config)+ telemetry.set(+ "skill.overview.duration_ms",+ round((time.perf_counter() - overview_start) * 1000, 3),+ )- overview_start = time.perf_counter()- overview = await self._generate_overview(skill_dict, config)- telemetry.set(- "skill.overview.duration_ms",- round((time.perf_counter() - overview_start) * 1000, 3),- )+ skill_dir_uri = context.uri- skill_dir_uri = context.uri+ write_start = time.perf_counter()+ await self._write_skill_content(+ viking_fs=viking_fs,+ skill_dict=skill_dict,+ skill_dir_uri=skill_dir_uri,+ abstract=skill_abstract,+ overview=overview,+ ctx=ctx,+ )- write_start = time.perf_counter()- await self._write_skill_content(- viking_fs=viking_fs,- skill_dict=skill_dict,- skill_dir_uri=skill_dir_uri,- abstract=skill_abstract,- overview=overview,- ctx=ctx,- )+ await self._write_auxiliary_files(+ viking_fs=viking_fs,+ auxiliary_files=auxiliary_files,+ base_path=base_path,+ skill_dir_uri=skill_dir_uri,+ ctx=ctx,+ )+ telemetry.set(+ "skill.write.duration_ms", round((time.perf_counter() - write_start) * 1000, 3)+ )- await self._write_auxiliary_files(- viking_fs=viking_fs,- auxiliary_files=auxiliary_files,- base_path=base_path,- skill_dir_uri=skill_dir_uri,- ctx=ctx,- )- telemetry.set(- "skill.write.duration_ms", round((time.perf_counter() - write_start) * 1000, 3)- )+ index_start = time.perf_counter()+ await self._index_skill(+ context=context,+ skill_dir_uri=skill_dir_uri,+ )+ telemetry.set(+ "skill.index.duration_ms", round((time.perf_counter() - index_start) * 1000, 3)+ )+ return {+ "status": "success",+ "root_uri": skill_dir_uri,+ "uri": skill_dir_uri,+ "name": skill_dict["name"],+ "auxiliary_files": len(auxiliary_files),+ }+ finally:+ if cleanup_path:+ shutil.rmtree(cleanup_path, ignore_errors=True)- index_start = time.perf_counter()- await self._index_skill(- context=context,- skill_dir_uri=skill_dir_uri,- )- telemetry.set(- "skill.index.duration_ms", round((time.perf_counter() - index_start) * 1000, 3)+ async def prepare_skill_processing(+ self,+ data: Any,+ ctx: RequestContext,+ allow_local_path_resolution: bool = True,+ source_path_hint: Optional[str] = None,+ ) -> SkillProcessingPreparation:+ skill_dict, auxiliary_files, base_path, cleanup_path = self._parse_skill(+ data,+ allow_local_path_resolution=allow_local_path_resolution,+ source_path_hint=source_path_hint,)- return {- "status": "success",- "root_uri": skill_dir_uri,- "uri": skill_dir_uri,- "name": skill_dict["name"],- "auxiliary_files": len(auxiliary_files),- }+ try:+ self._validate_skill_dict(skill_dict)+ skill_dict, privacy_values = await self.prepare_skill_privacy(skill_dict, ctx)+ return SkillProcessingPreparation(+ skill_dict=skill_dict,+ auxiliary_files=auxiliary_files,+ base_path=base_path,+ cleanup_path=cleanup_path,+ privacy_values=privacy_values,+ )+ except Exception:+ if cleanup_path:+ shutil.rmtree(cleanup_path, ignore_errors=True)+ raisedef _parse_skill(self,data: Any,allow_local_path_resolution: bool = True,- ) -> tuple[Dict[str, Any], List[Path], Optional[Path]]:+ source_path_hint: Optional[str] = None,+ ) -> tuple[Dict[str, Any], List[Path], Optional[Path], Optional[Path]]:"""Parse skill data from various formats."""if data is None:raise ValueError("Skill data cannot be None")auxiliary_files = []base_path = None-- if isinstance(data, str):- if allow_local_path_resolution:- path_obj = Path(data)- if path_obj.exists():- if zipfile.is_zipfile(path_obj):- temp_dir = Path(tempfile.mkdtemp())- with zipfile.ZipFile(path_obj, "r") as zipf:- safe_extract_zip(zipf, temp_dir)- data = temp_dir- else:- data = path_obj- else:- deny_direct_local_skill_input(data)-- if isinstance(data, Path):- if data.is_dir():- # Directory containing SKILL.md- skill_file = data / "SKILL.md"- if not skill_file.exists():- raise ValueError(f"SKILL.md not found in {data}")-- skill_dict = SkillLoader.load(str(skill_file))- base_path = data- for item in data.rglob("*"):- if item.is_file() and item.name != "SKILL.md":- auxiliary_files.append(item)- else:- # Single SKILL.md file- skill_dict = SkillLoader.load(str(data))- elif isinstance(data, str):- # Raw SKILL.md content- skill_dict = SkillLoader.parse(data)- elif isinstance(data, dict):- if is_mcp_format(data):- skill_dict = mcp_to_skill(data)+ cleanup_path = None++ try:+ if isinstance(data, str):+ if allow_local_path_resolution:+ path_obj = Path(data)+ if path_obj.exists():+ data, cleanup_path = self._resolve_skill_path(path_obj)+ else:+ deny_direct_local_skill_input(data)++ if isinstance(data, Path):+ data, cleanup_path = self._resolve_skill_path(data)++ if isinstance(data, Path):+ if data.is_dir():+ # Directory containing SKILL.md+ skill_file = data / "SKILL.md"+ if not skill_file.exists():+ raise ValueError(f"SKILL.md not found in {data}")++ skill_dict = SkillLoader.load(str(skill_file))+ base_path = data+ for item in data.rglob("*"):+ if item.is_file() and item.name != "SKILL.md":+ auxiliary_files.append(item)+ else:+ # Single skill markdown file+ skill_dict = SkillLoader.load(str(data))+ elif isinstance(data, str):+ # Raw SKILL.md content+ skill_dict = SkillLoader.parse(data)+ elif isinstance(data, dict):+ if is_mcp_format(data):+ skill_dict = mcp_to_skill(data)+ else:+ skill_dict = dataelse:- skill_dict = data- else:- raise ValueError(f"Unsupported data type: {type(data)}")+ raise ValueError(f"Unsupported data type: {type(data)}")++ skill_dict = self._normalize_skill_dict(skill_dict)+ if source_path_hint:+ skill_dict["source_path"] = source_path_hint+ self._validate_skill_dict(skill_dict)+ return skill_dict, auxiliary_files, base_path, cleanup_path+ except Exception:+ if cleanup_path:+ shutil.rmtree(cleanup_path, ignore_errors=True)+ raise- skill_dict = self._normalize_skill_dict(skill_dict)- self._validate_skill_dict(skill_dict)- return skill_dict, auxiliary_files, base_path+ @staticmethod+ def _resolve_skill_path(path_obj: Path) -> tuple[Path, Optional[Path]]:+ """Resolve uploaded/local skill path, including ZIP archives."""+ if path_obj.is_file() and (+ zipfile.is_zipfile(path_obj) or path_obj.suffix.lower() == ".zip"+ ):+ temp_dir = Path(tempfile.mkdtemp())+ try:+ with zipfile.ZipFile(path_obj, "r") as zipf:+ safe_extract_zip(zipf, temp_dir)+ except zipfile.BadZipFile as exc:+ shutil.rmtree(temp_dir, ignore_errors=True)+ raise InvalidArgumentError(+ f"Invalid skill ZIP archive: {path_obj}",+ details={"path": str(path_obj), "expected": "zip"},+ ) from exc++ if not (temp_dir / "SKILL.md").exists():+ children = [child for child in temp_dir.iterdir() if child.is_dir()]+ if len(children) == 1 and (children[0] / "SKILL.md").exists():+ return children[0], temp_dir+ return temp_dir, temp_dir++ return path_obj, None@staticmethoddef _normalize_list_field(value: Any) -> Any:@@ -249,14 +391,7 @@ class SkillProcessor:@staticmethoddef _validate_skill_dict(skill_dict: Dict[str, Any]) -> None:"""Validate normalized skill metadata before storage/indexing."""- name = skill_dict.get("name")- if name is None:- raise InvalidArgumentError("Skill must have 'name' field", details={"field": "name"})- if not isinstance(name, str) or not name.strip():- raise InvalidArgumentError(- "Skill 'name' must be a non-empty string",- details={"field": "name"},- )+ skill_dict["name"] = validate_skill_name(skill_dict.get("name"))@staticmethoddef _build_skill_abstract(skill_dict: Dict[str, Any]) -> str:@@ -276,16 +411,12 @@ class SkillProcessor:return yaml.safe_dump(abstract_meta, allow_unicode=True, sort_keys=False).strip()- async def sanitize_skill_privacy(- self, skill_dict: Dict[str, Any], ctx: RequestContext- ) -> Dict[str, Any]:- return await self._sanitize_skill_privacy(skill_dict, ctx)-- async def _sanitize_skill_privacy(+ async def prepare_skill_privacy(self, skill_dict: Dict[str, Any], ctx: RequestContext- ) -> Dict[str, Any]:+ ) -> tuple[Dict[str, Any], Dict[str, str]]:+ del ctxif not self._privacy_config_service:- return skill_dict+ return skill_dict, {}content = skill_dict.get("content", "")extraction_result = await extract_skill_privacy_values(@@ -294,19 +425,60 @@ class SkillProcessor:content=content,)if not extraction_result.values:- return skill_dict+ return skill_dict, {}sanitized = deepcopy(skill_dict)sanitized["content"] = extraction_result.sanitized_content- await self._privacy_config_service.upsert(- ctx=ctx,- category="skill",- target_key=sanitized["name"],- values=extraction_result.values,- updated_by=ctx.user.user_id,- change_reason="auto-extracted from add_skill",+ return sanitized, extraction_result.values++ async def apply_skill_privacy(+ self,+ skill_dict: Dict[str, Any],+ privacy_values: Dict[str, str],+ ctx: RequestContext,+ *,+ change_reason: str,+ delete_if_empty: bool,+ ) -> Dict[str, Any]:+ if not self._privacy_config_service:+ return skill_dict++ if privacy_values:+ await self._privacy_config_service.upsert(+ ctx=ctx,+ category="skill",+ target_key=skill_dict["name"],+ values=privacy_values,+ updated_by=ctx.user.user_id,+ change_reason=change_reason,+ )+ return skill_dict++ if delete_if_empty:+ await self._privacy_config_service.delete(ctx, "skill", skill_dict["name"])+ return skill_dict++ async def sanitize_skill_privacy(+ self, skill_dict: Dict[str, Any], ctx: RequestContext+ ) -> Dict[str, Any]:+ return await self._sanitize_skill_privacy(ctx=ctx, skill_dict=skill_dict)++ async def _sanitize_skill_privacy(+ self,+ skill_dict: Dict[str, Any],+ ctx: RequestContext,+ *,+ change_reason: str = "auto-extracted from add_skill",+ delete_if_empty: bool = False,+ ) -> Dict[str, Any]:+ sanitized, privacy_values = await self.prepare_skill_privacy(skill_dict, ctx)+ return await self.apply_skill_privacy(+ sanitized,+ privacy_values,+ ctx,+ change_reason=change_reason,+ delete_if_empty=delete_if_empty,)- return sanitizedasync def _generate_overview(self, skill_dict: Dict[str, Any], config) -> str:"""Generate L1 overview using VLM."""diff --git a/tests/server/test_api_local_input_security.py b/tests/server/test_api_local_input_security.pyindex af476767f..03883053b 100644--- a/tests/server/test_api_local_input_security.py+++ b/tests/server/test_api_local_input_security.py@@ -45,6 +45,33 @@ description: temp uploaded skillassert body["result"]["uri"].startswith("viking://user/default/skills/")+async def test_add_skill_accepts_temp_uploaded_non_skill_filename(+ client: httpx.AsyncClient,+ upload_temp_dir,+):+ skill_file = upload_temp_dir / "upload_123.md"+ skill_file.write_text(+ """---+name: uploaded-arbitrary-name+description: temp uploaded skill+---++# Uploaded Skill+"""+ )+ meta_file = upload_temp_dir / f"{skill_file.name}.ov_upload.meta"+ meta_file.write_text('{"original_filename": "original-skill.md"}', encoding="utf-8")++ resp = await client.post(+ "/api/v1/skills",+ json={"temp_file_id": skill_file.name, "wait": True},+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert body["result"]["uri"].startswith("viking://user/default/skills/")++async def test_add_skill_rejects_direct_local_path(client: httpx.AsyncClient):resp = await client.post("/api/v1/skills",diff --git a/tests/server/test_api_skills.py b/tests/server/test_api_skills.pynew file mode 100644index 000000000..83fac085d--- /dev/null+++ b/tests/server/test_api_skills.py@@ -0,0 +1,609 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++import sys+import types+import zipfile++import pytest+from starlette.responses import PlainTextResponse++[email protected](autouse=True)+def _stub_mcp_endpoint(monkeypatch):+ """Keep these router tests independent from the optional MCP package."""++ module = types.ModuleType("openviking.server.mcp_endpoint")++ def create_mcp_app():+ async def _endpoint(_request):+ return PlainTextResponse("mcp stub")++ return _endpoint++ module.create_mcp_app = create_mcp_app+ monkeypatch.setitem(sys.modules, "openviking.server.mcp_endpoint", module)+++def _skill_md(name: str, description: str, body: str = "Use this skill for testing.") -> str:+ return f"""---+name: {name}+description: {description}+tags:+ - test+---++# {name}++## Instructions+{body}+"""+++async def _add_skill(client, name: str = "api-skill", description: str = "API skill"):+ response = await client.post(+ "/api/v1/skills",+ json={"data": _skill_md(name, description), "wait": True},+ )+ assert response.status_code == 200, response.text+ return response.json()["result"]+++async def test_skills_api_list_empty_collection(client):+ response = await client.get("/api/v1/skills")+ assert response.status_code == 200, response.text+ listed = response.json()["result"]+ assert listed["skills"] == []+ assert listed["total"] == 0+++async def test_skills_api_list_show_find_and_delete(client):+ added = await _add_skill(client, "api-skill", "API skill for list and show")+ assert added["uri"].endswith("/skills/api-skill")++ privacy_response = await client.post(+ "/api/v1/privacy-configs/skill/api-skill",+ json={"values": {"api_key": "secret-1"}, "change_reason": "seed"},+ )+ assert privacy_response.status_code == 200, privacy_response.text++ list_response = await client.get("/api/v1/skills")+ assert list_response.status_code == 200, list_response.text+ listed = list_response.json()["result"]+ assert listed["total"] >= 1+ assert any(skill["name"] == "api-skill" for skill in listed["skills"])++ show_response = await client.get(+ "/api/v1/skills/api-skill",+ params={"level": 2, "include_files": True, "include_source": True},+ )+ assert show_response.status_code == 200, show_response.text+ shown = show_response.json()["result"]+ assert shown["name"] == "api-skill"+ assert shown["description"] == "API skill for list and show"+ assert shown["skill_md_uri"].endswith("/skills/api-skill/SKILL.md")+ assert "# api-skill" in shown["content"]+ assert any(file["name"] == "SKILL.md" for file in shown["files"])+ assert shown["source"]["tracked"] is True+ assert shown["source"]["type"] == "api"+ assert shown["source"]["source"] == "inline_content"+ assert shown["source"]["operation"] == "add"+ assert shown["source"]["skill_name"] == "api-skill"++ level_zero_response = await client.get(+ "/api/v1/skills/api-skill",+ params={"level": 0},+ )+ assert level_zero_response.status_code == 200, level_zero_response.text+ level_zero = level_zero_response.json()["result"]+ assert "abstract" in level_zero+ assert "overview" not in level_zero+ assert "content" not in level_zero++ level_one_response = await client.get(+ "/api/v1/skills/api-skill",+ params={"level": 1},+ )+ assert level_one_response.status_code == 200, level_one_response.text+ level_one = level_one_response.json()["result"]+ assert "abstract" not in level_one+ assert "overview" in level_one+ assert "content" not in level_one++ level_two_response = await client.get(+ "/api/v1/skills/api-skill",+ params={"level": 2},+ )+ assert level_two_response.status_code == 200, level_two_response.text+ level_two = level_two_response.json()["result"]+ assert "abstract" not in level_two+ assert "overview" not in level_two+ assert "# api-skill" in level_two["content"]++ default_response = await client.get("/api/v1/skills/api-skill")+ assert default_response.status_code == 200, default_response.text+ default_show = default_response.json()["result"]+ assert "abstract" in default_show+ assert "overview" in default_show+ assert "content" in default_show++ no_content_response = await client.get(+ "/api/v1/skills/api-skill",+ params={"include_content": False},+ )+ assert no_content_response.status_code == 200, no_content_response.text+ no_content = no_content_response.json()["result"]+ assert "abstract" in no_content+ assert "overview" in no_content+ assert "content" not in no_content++ level_one_with_content_response = await client.get(+ "/api/v1/skills/api-skill",+ params={"level": 1, "include_content": True},+ )+ assert level_one_with_content_response.status_code == 200, level_one_with_content_response.text+ level_one_with_content = level_one_with_content_response.json()["result"]+ assert "abstract" not in level_one_with_content+ assert "overview" in level_one_with_content+ assert "content" in level_one_with_content++ find_response = await client.post(+ "/api/v1/skills/find",+ json={"query": "list and show", "limit": 5},+ )+ assert find_response.status_code == 200, find_response.text+ found = find_response.json()["result"]+ assert "skills" in found+ assert "total" in found++ delete_response = await client.delete("/api/v1/skills/api-skill")+ assert delete_response.status_code == 200, delete_response.text+ deleted = delete_response.json()["result"]+ assert deleted["name"] == "api-skill"+ assert deleted["privacy_deleted"] is True++ missing_response = await client.get("/api/v1/skills/api-skill")+ assert missing_response.status_code == 404++ missing_privacy_response = await client.get("/api/v1/privacy-configs/skill/api-skill")+ assert missing_privacy_response.status_code == 404+++async def test_skills_api_update_requires_matching_name(client):+ await _add_skill(client, "update-skill", "Original description")++ mismatch_response = await client.put(+ "/api/v1/skills/update-skill",+ json={"data": _skill_md("other-skill", "Wrong name"), "wait": True},+ )+ assert mismatch_response.status_code == 400+ assert mismatch_response.json()["error"]["code"] == "INVALID_ARGUMENT"++ update_response = await client.put(+ "/api/v1/skills/update-skill",+ json={+ "data": _skill_md(+ "update-skill",+ "Updated description",+ "Updated instructions from the replacement payload.",+ ),+ "wait": True,+ },+ )+ assert update_response.status_code == 200, update_response.text+ assert update_response.json()["result"]["action"] == "update"++ show_response = await client.get(+ "/api/v1/skills/update-skill",+ params={"include_content": True, "include_source": True},+ )+ shown = show_response.json()["result"]+ assert shown["description"] == "Updated description"+ assert "Updated instructions" in shown["content"]+ assert shown["source"]["tracked"] is True+ assert shown["source"]["type"] == "api"+ assert shown["source"]["source"] == "inline_content"+ assert shown["source"]["operation"] == "update"+ assert shown["source"]["skill_name"] == "update-skill"+++async def test_skills_api_update_accepts_temp_uploaded_single_file_with_arbitrary_name(+ client,+ tmp_path,+):+ await _add_skill(client, "update-temp-file-skill", "Original description")++ skill_file = tmp_path / "custom-update-name.md"+ skill_file.write_text(+ _skill_md("update-temp-file-skill", "Updated from uploaded file"),+ encoding="utf-8",+ )++ with skill_file.open("rb") as handle:+ upload_response = await client.post(+ "/api/v1/resources/temp_upload",+ files={"file": ("custom-update-name.md", handle, "text/markdown")},+ )+ assert upload_response.status_code == 200, upload_response.text+ temp_file_id = upload_response.json()["result"]["temp_file_id"]++ update_response = await client.put(+ "/api/v1/skills/update-temp-file-skill",+ json={"temp_file_id": temp_file_id, "wait": True},+ )+ assert update_response.status_code == 200, update_response.text+ assert update_response.json()["result"]["action"] == "update"++ show_response = await client.get(+ "/api/v1/skills/update-temp-file-skill",+ params={"include_content": True, "include_source": True},+ )+ shown = show_response.json()["result"]+ assert shown["description"] == "Updated from uploaded file"+ assert shown["source"]["original_filename"] == "custom-update-name.md"+++async def test_skills_api_update_rolls_back_when_replace_fails(client, monkeypatch):+ await _add_skill(client, "rollback-skill", "Original description")++ async def _fail_persist(*_args, **_kwargs):+ raise RuntimeError("source metadata write failed")++ monkeypatch.setattr(+ "openviking.server.routers.skills.persist_skill_source_metadata",+ _fail_persist,+ )++ with pytest.raises(RuntimeError, match="source metadata write failed"):+ await client.put(+ "/api/v1/skills/rollback-skill",+ json={+ "data": _skill_md(+ "rollback-skill",+ "Updated description",+ "This update should be rolled back.",+ ),+ "wait": True,+ },+ )++ show_response = await client.get(+ "/api/v1/skills/rollback-skill",+ params={"include_content": True},+ )+ assert show_response.status_code == 200, show_response.text+ shown = show_response.json()["result"]+ assert shown["description"] == "Original description"+ assert "This update should be rolled back." not in shown["content"]+++async def test_skills_api_update_removes_privacy_when_replacement_has_no_secrets(client):+ await _add_skill(client, "privacy-update-skill", "Original description")++ privacy_response = await client.post(+ "/api/v1/privacy-configs/skill/privacy-update-skill",+ json={"values": {"api_key": "secret-1"}, "change_reason": "seed"},+ )+ assert privacy_response.status_code == 200, privacy_response.text++ update_response = await client.put(+ "/api/v1/skills/privacy-update-skill",+ json={+ "data": _skill_md(+ "privacy-update-skill",+ "Updated description",+ "No secret placeholders remain in this skill.",+ ),+ "wait": True,+ },+ )+ assert update_response.status_code == 200, update_response.text++ current_privacy_response = await client.get(+ "/api/v1/privacy-configs/skill/privacy-update-skill"+ )+ assert current_privacy_response.status_code == 404++ show_response = await client.get(+ "/api/v1/skills/privacy-update-skill",+ params={"include_content": True},+ )+ assert show_response.status_code == 200, show_response.text+ shown = show_response.json()["result"]+ assert "Configured but not referenced in content" not in shown["content"]+++async def test_skills_api_update_restores_previous_privacy_on_failure(client, monkeypatch):+ await _add_skill(client, "rollback-privacy-skill", "Original description")++ seeded_privacy = await client.post(+ "/api/v1/privacy-configs/skill/rollback-privacy-skill",+ json={"values": {"api_key": "secret-old"}, "change_reason": "seed"},+ )+ assert seeded_privacy.status_code == 200, seeded_privacy.text++ async def _fail_persist(*_args, **_kwargs):+ raise RuntimeError("source metadata write failed")++ monkeypatch.setattr(+ "openviking.server.routers.skills.persist_skill_source_metadata",+ _fail_persist,+ )++ with pytest.raises(RuntimeError, match="source metadata write failed"):+ await client.put(+ "/api/v1/skills/rollback-privacy-skill",+ json={+ "data": _skill_md(+ "rollback-privacy-skill",+ "Updated description",+ 'api_key: "secret-new"\n',+ ),+ "wait": True,+ },+ )++ privacy_response = await client.get("/api/v1/privacy-configs/skill/rollback-privacy-skill")+ assert privacy_response.status_code == 200, privacy_response.text+ assert privacy_response.json()["result"]["values"]["api_key"] == "secret-old"+++async def test_skills_api_update_restores_previous_privacy_after_privacy_write(client, monkeypatch):+ from openviking.utils.skill_processor import SkillProcessor++ await _add_skill(client, "rollback-privacy-after-write-skill", "Original description")++ seeded_privacy = await client.post(+ "/api/v1/privacy-configs/skill/rollback-privacy-after-write-skill",+ json={"values": {"api_key": "secret-old"}, "change_reason": "seed"},+ )+ assert seeded_privacy.status_code == 200, seeded_privacy.text++ original_prepare = SkillProcessor.prepare_skill_privacy+ original_apply = SkillProcessor.apply_skill_privacy++ async def _prepare_new_privacy(self, skill_dict, ctx):+ if skill_dict.get("name") == "rollback-privacy-after-write-skill":+ return skill_dict, {"api_key": "secret-new"}+ return await original_prepare(self, skill_dict, ctx)++ async def _apply_then_fail(+ self,+ skill_dict,+ privacy_values,+ ctx,+ *,+ change_reason,+ delete_if_empty,+ ):+ result = await original_apply(+ self,+ skill_dict,+ privacy_values,+ ctx,+ change_reason=change_reason,+ delete_if_empty=delete_if_empty,+ )+ if skill_dict.get("name") == "rollback-privacy-after-write-skill":+ raise RuntimeError("privacy post-write failure")+ return result++ monkeypatch.setattr(SkillProcessor, "prepare_skill_privacy", _prepare_new_privacy)+ monkeypatch.setattr(SkillProcessor, "apply_skill_privacy", _apply_then_fail)++ with pytest.raises(RuntimeError, match="privacy post-write failure"):+ await client.put(+ "/api/v1/skills/rollback-privacy-after-write-skill",+ json={+ "data": _skill_md(+ "rollback-privacy-after-write-skill",+ "Updated description",+ 'api_key: "secret-new"\n',+ ),+ "wait": True,+ },+ )++ privacy_response = await client.get(+ "/api/v1/privacy-configs/skill/rollback-privacy-after-write-skill"+ )+ assert privacy_response.status_code == 200, privacy_response.text+ assert privacy_response.json()["result"]["values"]["api_key"] == "secret-old"++ show_response = await client.get(+ "/api/v1/skills/rollback-privacy-after-write-skill",+ params={"include_content": True},+ )+ assert show_response.status_code == 200, show_response.text+ shown = show_response.json()["result"]+ assert shown["description"] == "Original description"+ assert "secret-new" not in shown["content"]+++async def test_skills_api_rejects_invalid_skill_names(client):+ invalid_names = [+ "team/sql-helper",+ "bad name",+ ".",+ "..",+ "a" * 65,+ ]++ for name in invalid_names:+ response = await client.post(+ "/api/v1/skills",+ json={"data": _skill_md(name, "Invalid name skill"), "wait": True},+ )+ assert response.status_code == 400, response.text+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"+++async def test_skills_api_show_reads_source_metadata_and_hides_internal_file(client):+ await _add_skill(client, "source-skill", "Source metadata skill")++ show_response = await client.get(+ "/api/v1/skills/source-skill",+ params={"include_files": True, "include_source": True},+ )+ assert show_response.status_code == 200, show_response.text+ shown = show_response.json()["result"]+ assert shown["source"]["tracked"] is True+ assert shown["source"]["type"] == "api"+ assert shown["source"]["source"] == "inline_content"+ assert shown["source"]["operation"] == "add"+ assert shown["source"]["skill_name"] == "source-skill"+ assert all(file["path"] != ".source.json" for file in shown["files"])+++async def test_skills_api_add_accepts_source_metadata_override(client):+ response = await client.post(+ "/api/v1/skills",+ json={+ "data": _skill_md("git-source-skill", "Git source skill"),+ "wait": True,+ "source_metadata": {+ "type": "git",+ "source": "https://github.com/anthropics/skills/tree/main/skills",+ "clone_url": "https://github.com/anthropics/skills.git",+ "ref_name": "main",+ "subdir": "skills/git-source-skill",+ },+ },+ )+ assert response.status_code == 200, response.text++ show_response = await client.get(+ "/api/v1/skills/git-source-skill",+ params={"include_source": True},+ )+ assert show_response.status_code == 200, show_response.text+ source = show_response.json()["result"]["source"]+ assert source["tracked"] is True+ assert source["type"] == "git"+ assert source["clone_url"] == "https://github.com/anthropics/skills.git"+ assert source["ref_name"] == "main"+ assert source["subdir"] == "skills/git-source-skill"+ assert source["skill_name"] == "git-source-skill"+++async def test_skills_api_update_accepts_binary_auxiliary_files(client, tmp_path):+ await _add_skill(client, "binary-skill", "Original binary skill")++ skill_dir = tmp_path / "binary-skill"+ skill_dir.mkdir()+ (skill_dir / "SKILL.md").write_text(+ _skill_md("binary-skill", "Updated binary skill"),+ encoding="utf-8",+ )+ (skill_dir / "preview.bin").write_bytes(b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01")++ archive = tmp_path / "binary-skill.zip"+ with zipfile.ZipFile(archive, "w") as zip_file:+ for path in skill_dir.rglob("*"):+ zip_file.write(path, path.relative_to(skill_dir).as_posix())++ with archive.open("rb") as handle:+ upload_response = await client.post(+ "/api/v1/resources/temp_upload",+ files={"file": ("binary-skill.zip", handle, "application/zip")},+ )+ assert upload_response.status_code == 200, upload_response.text+ temp_file_id = upload_response.json()["result"]["temp_file_id"]++ update_response = await client.put(+ "/api/v1/skills/binary-skill",+ json={"temp_file_id": temp_file_id, "wait": True},+ )+ assert update_response.status_code == 200, update_response.text+ root_uri = update_response.json()["result"]["root_uri"]++ download_response = await client.get(+ "/api/v1/content/download",+ params={"uri": f"{root_uri}/preview.bin"},+ )+ assert download_response.status_code == 200, download_response.text+ assert download_response.content.startswith(b"\xff\xd8\xff\xe0")++ replace_response = await client.put(+ "/api/v1/skills/binary-skill",+ json={"data": _skill_md("binary-skill", "Updated without auxiliary files"), "wait": True},+ )+ assert replace_response.status_code == 200, replace_response.text+ replaced_root_uri = replace_response.json()["result"]["root_uri"]++ stale_download_response = await client.get(+ "/api/v1/content/download",+ params={"uri": f"{replaced_root_uri}/preview.bin"},+ )+ assert stale_download_response.status_code == 404+++async def test_skills_api_validate_inline_skill(client):+ valid_response = await client.post(+ "/api/v1/skills/validate",+ json={+ "data": _skill_md("valid-skill", "Valid skill"),+ "skill_dir_name": "valid-skill",+ },+ )+ assert valid_response.status_code == 200, valid_response.text+ valid = valid_response.json()["result"]+ assert valid["valid"] is True+ assert valid["name"] == "valid-skill"+ assert valid["errors"] == []+ assert valid["warnings"] == []++ invalid_response = await client.post(+ "/api/v1/skills/validate",+ json={"data": "# Missing frontmatter"},+ )+ assert invalid_response.status_code == 200, invalid_response.text+ invalid = invalid_response.json()["result"]+ assert invalid["valid"] is False+ assert invalid["errors"]++ missing_description_response = await client.post(+ "/api/v1/skills/validate",+ json={"data": "---\nname: missing-description\n---\n# Body"},+ )+ assert missing_description_response.status_code == 200, missing_description_response.text+ missing_description = missing_description_response.json()["result"]+ assert missing_description["valid"] is False+ assert any(issue["rule"] == "description_required" for issue in missing_description["errors"])+++async def test_skills_api_validate_rfc_strict_and_loose_rules(client):+ mismatch = _skill_md("actual-name", "Valid description")++ loose_response = await client.post(+ "/api/v1/skills/validate",+ json={"data": mismatch, "skill_dir_name": "directory-name"},+ )+ assert loose_response.status_code == 200, loose_response.text+ loose = loose_response.json()["result"]+ assert loose["valid"] is True+ assert loose["errors"] == []+ assert any(issue["rule"] == "name_matches_directory" for issue in loose["warnings"])++ strict_response = await client.post(+ "/api/v1/skills/validate",+ json={"data": mismatch, "skill_dir_name": "directory-name", "strict": True},+ )+ assert strict_response.status_code == 200, strict_response.text+ strict = strict_response.json()["result"]+ assert strict["valid"] is False+ assert any(issue["rule"] == "name_matches_directory" for issue in strict["errors"])++ long_body = "\n".join(f"line {idx}" for idx in range(501))+ long_body_response = await client.post(+ "/api/v1/skills/validate",+ json={+ "data": _skill_md("long-body", "Valid description", long_body),+ "skill_dir_name": "long-body",+ "strict": True,+ },+ )+ assert long_body_response.status_code == 200, long_body_response.text+ long_body_result = long_body_response.json()["result"]+ assert long_body_result["valid"] is True+ assert any(issue["rule"] == "body_max_lines" for issue in long_body_result["warnings"])diff --git a/tests/unit/test_skill_processor_none.py b/tests/unit/test_skill_processor_none.pyindex 17337f9e0..f0eca7a2c 100644--- a/tests/unit/test_skill_processor_none.py+++ b/tests/unit/test_skill_processor_none.py@@ -7,6 +7,8 @@ skill data is None, instead of falling through to the generic'Unsupported data type' error."""+import shutil+import zipfilefrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -36,16 +38,17 @@ class TestParseSkillNoneData:def test_parse_skill_valid_dict_passes(self):"""A valid dict should not raise."""processor = SkillProcessor(vikingdb=None)- skill_dict, aux_files, base_path = processor._parse_skill(+ skill_dict, aux_files, base_path, cleanup_path = processor._parse_skill({"name": "test-skill", "description": "A test skill"})assert skill_dict["name"] == "test-skill"assert aux_files == []assert base_path is None+ assert cleanup_path is Nonedef test_parse_skill_normalizes_hyphenated_allowed_tools(self):processor = SkillProcessor(vikingdb=None)- skill_dict, _, _ = processor._parse_skill(+ skill_dict, _, _, _ = processor._parse_skill({"name": "test-skill","description": "A test skill",@@ -58,6 +61,57 @@ class TestParseSkillNoneData:assert "allowed-tools" not in skill_dictassert skill_dict["tags"] == ["test"]+ def test_parse_skill_zip_returns_cleanup_path(self, tmp_path):+ processor = SkillProcessor(vikingdb=None)+ archive = tmp_path / "skill.zip"+ with zipfile.ZipFile(archive, "w") as zipf:+ zipf.writestr(+ "zip-skill/SKILL.md",+ "---\nname: zip-skill\ndescription: Zip skill\n---\n\n# Zip Skill\n",+ )+ zipf.writestr("zip-skill/helper.txt", "helper")++ skill_dict, aux_files, base_path, cleanup_path = processor._parse_skill(archive)++ assert skill_dict["name"] == "zip-skill"+ assert cleanup_path is not None+ assert cleanup_path.exists()+ assert base_path is not None+ assert base_path.exists()+ assert len(aux_files) == 1+ shutil.rmtree(cleanup_path, ignore_errors=True)++ def test_parse_skill_accepts_single_file_with_non_standard_name(self, tmp_path):+ processor = SkillProcessor(vikingdb=None)+ skill_file = tmp_path / "custom-name.md"+ skill_file.write_text(+ "---\nname: custom-name\ndescription: Custom filename skill\n---\n\n# Skill\n",+ encoding="utf-8",+ )++ skill_dict, aux_files, base_path, cleanup_path = processor._parse_skill(skill_file)++ assert skill_dict["name"] == "custom-name"+ assert skill_dict["source_path"].endswith("custom-name.md")+ assert aux_files == []+ assert base_path is None+ assert cleanup_path is None++ def test_parse_skill_prefers_source_path_hint_for_single_file(self, tmp_path):+ processor = SkillProcessor(vikingdb=None)+ uploaded_path = tmp_path / "upload_123.md"+ uploaded_path.write_text(+ "---\nname: hinted-skill\ndescription: Hint source path\n---\n\n# Skill\n",+ encoding="utf-8",+ )++ skill_dict, _, _, _ = processor._parse_skill(+ uploaded_path,+ source_path_hint="hinted-skill.md",+ )++ assert skill_dict["source_path"] == "hinted-skill.md"+@pytest.mark.parametrize("skill_dict", [{}, {"description": "missing name"}])def test_validate_skill_dict_requires_name_field(self, skill_dict):"""Dict skill data should fail fast when required metadata is missing."""