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
fix(skills): now we allow viking://agent/skills again, and optimize CLI for skills (#2813)
MaojiaSheng0102a48c2a05
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 90e7d99ca..5bce37493 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -748,6 +748,7 @@ impl HttpClient {show_progress: bool,verbose: bool,source_metadata: Option<Value>,+ target_uri: Option<&str>,) -> Result<serde_json::Value> {let path_obj = Path::new(data);@@ -773,6 +774,9 @@ impl HttpClient {if let Some(source_metadata) = source_metadata.clone() {body["source_metadata"] = source_metadata;}+ if let Some(target_uri) = target_uri {+ body["target_uri"] = serde_json::Value::String(target_uri.to_string());+ }let dynamic_timeout =TimeoutConfig::for_resource_processing().calculate(zip_file.path())?;self.base@@ -794,6 +798,9 @@ impl HttpClient {if let Some(source_metadata) = source_metadata.clone() {body["source_metadata"] = source_metadata;}+ if let Some(target_uri) = target_uri {+ body["target_uri"] = serde_json::Value::String(target_uri.to_string());+ }let dynamic_timeout =TimeoutConfig::for_resource_processing().calculate(path_obj)?;self.base@@ -808,6 +815,9 @@ impl HttpClient {if let Some(source_metadata) = source_metadata.clone() {body["source_metadata"] = source_metadata;}+ if let Some(target_uri) = target_uri {+ body["target_uri"] = serde_json::Value::String(target_uri.to_string());+ }self.post("/api/v1/skills", &body).await}} else {@@ -819,12 +829,22 @@ impl HttpClient {if let Some(source_metadata) = source_metadata {body["source_metadata"] = source_metadata;}+ if let Some(target_uri) = target_uri {+ body["target_uri"] = serde_json::Value::String(target_uri.to_string());+ }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())];+ pub async fn skills_list(+ &self,+ node_limit: i32,+ target_uri: Option<&str>,+ ) -> Result<serde_json::Value> {+ let mut params = vec![("node_limit".to_string(), node_limit.to_string())];+ if let Some(target_uri) = target_uri {+ params.push(("target_uri".to_string(), target_uri.to_string()));+ }self.get("/api/v1/skills", ¶ms).await}@@ -835,6 +855,7 @@ impl HttpClient {include_files: bool,include_source: bool,level: Option<i32>,+ target_uri: Option<&str>,) -> Result<serde_json::Value> {let path = format!("/api/v1/skills/{}", name);let mut params = vec![@@ -845,6 +866,9 @@ impl HttpClient {if let Some(level) = level {params.push(("level".to_string(), level.to_string()));}+ if let Some(target_uri) = target_uri {+ params.push(("target_uri".to_string(), target_uri.to_string()));+ }self.get(&path, ¶ms).await}@@ -854,13 +878,17 @@ impl HttpClient {node_limit: i32,threshold: Option<f64>,level: Option<Vec<i32>>,+ target_uri: Option<&str>,) -> Result<serde_json::Value> {- let body = serde_json::json!({+ let mut body = serde_json::json!({"query": query,"limit": node_limit,"score_threshold": threshold,"level": level,});+ if let Some(target_uri) = target_uri {+ body["target_uri"] = serde_json::Value::String(target_uri.to_string());+ }self.post("/api/v1/skills/find", &body).await}@@ -927,9 +955,15 @@ impl HttpClient {show_progress: bool,verbose: bool,source_metadata: Option<Value>,+ target_uri: Option<&str>,) -> Result<serde_json::Value> {let endpoint = format!("/api/v1/skills/{}", name);let path_obj = Path::new(data);+ let attach_target_uri = |body: &mut Value| {+ if let Some(target_uri) = target_uri {+ body["target_uri"] = serde_json::Value::String(target_uri.to_string());+ }+ };if path_obj.exists() {if path_obj.is_dir() {@@ -952,6 +986,7 @@ impl HttpClient {if let Some(source_metadata) = source_metadata.clone() {body["source_metadata"] = source_metadata;}+ attach_target_uri(&mut body);self.put(&endpoint, &body).await} else if path_obj.is_file() {let temp_file_id = if show_progress {@@ -968,6 +1003,7 @@ impl HttpClient {if let Some(source_metadata) = source_metadata.clone() {body["source_metadata"] = source_metadata;}+ attach_target_uri(&mut body);self.put(&endpoint, &body).await} else {let mut body = serde_json::json!({@@ -978,6 +1014,7 @@ impl HttpClient {if let Some(source_metadata) = source_metadata.clone() {body["source_metadata"] = source_metadata;}+ attach_target_uri(&mut body);self.put(&endpoint, &body).await}} else {@@ -989,13 +1026,23 @@ impl HttpClient {if let Some(source_metadata) = source_metadata {body["source_metadata"] = source_metadata;}+ attach_target_uri(&mut body);self.put(&endpoint, &body).await}}- pub async fn skill_remove(&self, name: &str) -> Result<serde_json::Value> {+ pub async fn skill_remove(+ &self,+ name: &str,+ target_uri: Option<&str>,+ ) -> Result<serde_json::Value> {let path = format!("/api/v1/skills/{}", name);- self.delete(&path, &[]).await+ let params: Vec<(String, String)> = if let Some(target_uri) = target_uri {+ vec![("target_uri".to_string(), target_uri.to_string())]+ } else {+ Vec::new()+ };+ self.delete(&path, ¶ms).await}// ============ Task Methods ============diff --git a/crates/ov_cli/src/commands/resources.rs b/crates/ov_cli/src/commands/resources.rsindex 190078254..3520827a2 100644--- a/crates/ov_cli/src/commands/resources.rs+++ b/crates/ov_cli/src/commands/resources.rs@@ -63,13 +63,14 @@ pub async fn add_skill(data: &str,wait: bool,timeout: Option<f64>,+ parent: Option<&str>,show_progress: bool,verbose: bool,format: OutputFormat,compact: bool,) -> Result<()> {let result = client- .add_skill(data, wait, timeout, show_progress, verbose, None)+ .add_skill(data, wait, timeout, show_progress, verbose, None, parent).await?;if !wait && matches!(format, OutputFormat::Table) {diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex 9d6142acd..4cfb60bff 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -20,6 +20,8 @@ const SEARCH_RESULT_COLLECTION_KEYS: &[&str] =enum SearchRenderMode {Find,Search,+ SkillsList,+ SkillsFind,}#[derive(Debug, Clone, Copy)]@@ -42,6 +44,72 @@ impl SearchRenderContext {node_limit,}}++ fn skills_list() -> Self {+ Self {+ mode: SearchRenderMode::SkillsList,+ node_limit: 0,+ }+ }++ fn skills_find(node_limit: i32) -> Self {+ Self {+ mode: SearchRenderMode::SkillsFind,+ node_limit,+ }+ }++ fn hides_level_and_score(self) -> bool {+ matches!(+ self.mode,+ SearchRenderMode::SkillsList | SearchRenderMode::SkillsFind+ )+ }++ fn splits_name_and_description(self) -> bool {+ matches!(+ self.mode,+ SearchRenderMode::SkillsList | SearchRenderMode::SkillsFind+ )+ }++ fn item_noun(self) -> (&'static str, &'static str) {+ match self.mode {+ SearchRenderMode::SkillsList | SearchRenderMode::SkillsFind => ("skill", "skills"),+ _ => ("result", "results"),+ }+ }++ fn shows_ranking_line(self) -> bool {+ !matches!(self.mode, SearchRenderMode::SkillsList)+ }+}++pub(super) fn output_skills_list_results(result: &Value, output_format: OutputFormat, compact: bool) {+ let context = SearchRenderContext::skills_list();+ if let Some(rendered) =+ render_search_output_for_table_with_context(result, output_format, Some(context))+ {+ println!("{rendered}");+ } else {+ output_success(result, output_format, compact);+ }+}++pub(super) fn output_skills_find_results(+ result: &Value,+ output_format: OutputFormat,+ compact: bool,+ node_limit: i32,+) {+ let context = SearchRenderContext::skills_find(node_limit);+ if let Some(rendered) =+ render_search_output_for_table_with_context(result, output_format, Some(context))+ {+ println!("{rendered}");+ } else {+ output_success(result, output_format, compact);+ }}pub async fn find(@@ -181,14 +249,26 @@ fn render_search_results_for_table_with_context(.bold().to_string(),);- lines.push(theme::body(search_ranking_line(context, pass_count)).to_string());+ if context.is_none_or(|context| context.shows_ranking_line()) {+ lines.push(theme::body(search_ranking_line(context, pass_count)).to_string());+ }lines.push(String::new());+ let hide_level_and_score = context.is_some_and(|context| context.hides_level_and_score());+ let split_name_description =+ context.is_some_and(|context| context.splits_name_and_description());for (index, item) in items.iter().enumerate() {if index > 0 {lines.push(String::new());}- render_search_result_card(index + 1, item, text_width, &mut lines);+ render_search_result_card(+ index + 1,+ item,+ text_width,+ hide_level_and_score,+ split_name_description,+ &mut lines,+ );}append_profile_lines(profile, &mut lines);@@ -200,10 +280,13 @@ fn search_result_summary(context: Option<SearchRenderContext>,pass_count: Option<usize>,) -> String {+ let (singular, plural) = context+ .map(SearchRenderContext::item_noun)+ .unwrap_or(("result", "results"));let mut summary = format!("{} {}",item_count,- pluralize(item_count as u64, "result", "results")+ pluralize(item_count as u64, singular, plural));if matches!(@@ -231,10 +314,16 @@ fn search_ranking_line(context: Option<SearchRenderContext>, pass_count: Option<context.node_limit,pluralize(context.node_limit as u64, "result", "results")),+ SearchRenderMode::SkillsFind => format!(+ "limit {} final {}",+ context.node_limit,+ pluralize(context.node_limit as u64, "skill", "skills")+ ),SearchRenderMode::Search if pass_count.is_some_and(|count| count > 1) => {format!("limit {} per pass", context.node_limit)}SearchRenderMode::Search => format!("limit {} per search pass", context.node_limit),+ SearchRenderMode::SkillsList => return "Ranked by relevance".to_string(),};format!("Ranked by relevance · {suffix}")@@ -306,6 +395,8 @@ fn render_search_result_card(rank: usize,item: &Value,text_width: usize,+ hide_level_and_score: bool,+ split_name_and_description: bool,lines: &mut Vec<String>,) {let object = item.as_object();@@ -315,12 +406,14 @@ fn render_search_result_card(.to_string(),];- if let Some(level) = search_result_level(object) {- metadata.push(theme::value(level).bold().to_string());- }+ if !hide_level_and_score {+ if let Some(level) = search_result_level(object) {+ metadata.push(theme::value(level).bold().to_string());+ }- if let Some(score) = search_result_score(object) {- metadata.push(theme::warning(score).bold().to_string());+ if let Some(score) = search_result_score(object) {+ metadata.push(theme::warning(score).bold().to_string());+ }}lines.push(format!(@@ -335,6 +428,12 @@ fn render_search_result_card(}}+ if split_name_and_description+ && render_skill_name_and_description(object, text_width, lines)+ {+ return;+ }+let abstract_text = search_result_text(item, object);let wrapped = wrap_display_text(&abstract_text, text_width, SEARCH_MAX_ABSTRACT_LINES);if wrapped.is_empty() {@@ -349,6 +448,82 @@ fn render_search_result_card(}}+fn render_skill_name_and_description(+ object: Option<&serde_json::Map<String, Value>>,+ text_width: usize,+ lines: &mut Vec<String>,+) -> bool {+ let Some(object) = object else {+ return false;+ };++ let name = object+ .get("name")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty());+ let description = object+ .get("description")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .or_else(|| extract_field_from_abstract(object, "description"));+ let name = name.or_else(|| extract_field_from_abstract(object, "name"));++ if name.is_none() && description.is_none() {+ return false;+ }++ if let Some(name) = name {+ let label = theme::heading("name:").bold().to_string();+ let value = theme::body(name).to_string();+ lines.push(format!("{SEARCH_INDENT}{label} {value}"));+ }++ if let Some(description) = description {+ let label = theme::heading("description:").bold().to_string();+ let wrapped = wrap_display_text(description, text_width, SEARCH_MAX_ABSTRACT_LINES);+ if let Some((first, rest)) = wrapped.split_first() {+ lines.push(format!(+ "{SEARCH_INDENT}{label} {}",+ theme::body(first)+ ));+ for line in rest {+ lines.push(format!("{SEARCH_INDENT}{}", theme::body(line)));+ }+ } else {+ lines.push(format!(+ "{SEARCH_INDENT}{label} {}",+ theme::body(description)+ ));+ }+ }++ true+}++fn extract_field_from_abstract<'a>(+ object: &'a serde_json::Map<String, Value>,+ field: &str,+) -> Option<&'a str> {+ let raw = object+ .get("abstract")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())?;+ let needle = format!("{field}:");+ let start = raw.find(&needle)? + needle.len();+ let rest = raw[start..].trim_start();+ let end = ["name:", "description:", "tags:", "allowed_tools:"]+ .iter()+ .filter(|key| !key.eq_ignore_ascii_case(&format!("{field}:")))+ .filter_map(|key| rest.find(key))+ .min()+ .unwrap_or(rest.len());+ let value = rest[..end].trim().trim_end_matches(',');+ if value.is_empty() { None } else { Some(value) }+}+fn search_card_text_width() -> usize {if std::io::stdout().is_terminal()&& let Ok((columns, _)) = crossterm::terminal::size()@@ -414,7 +589,7 @@ fn search_result_uri(object: Option<&serde_json::Map<String, Value>>) -> Option<}fn search_result_text(item: &Value, object: Option<&serde_json::Map<String, Value>>) -> String {- for key in ["abstract", "snippet", "content", "text"] {+ for key in ["abstract", "description", "snippet", "content", "text"] {if let Some(text) = object.and_then(|object| object.get(key)).and_then(Value::as_str)diff --git a/crates/ov_cli/src/commands/skills.rs b/crates/ov_cli/src/commands/skills.rsindex 98880db80..d33c21b4c 100644--- a/crates/ov_cli/src/commands/skills.rs+++ b/crates/ov_cli/src/commands/skills.rs@@ -90,6 +90,7 @@ pub async fn add(verbose: bool,output_format: OutputFormat,compact: bool,+ parent: Option<&str>,) -> Result<()> {let source = prepare_source(data)?;if list_only {@@ -125,6 +126,7 @@ pub async fn add(show_progress,verbose,source_metadata,+ parent,).await?;installed.push(result);@@ -158,9 +160,10 @@ pub async fn list(node_limit: i32,output_format: OutputFormat,compact: bool,+ parent: Option<&str>,) -> Result<()> {- let result = client.skills_list(node_limit).await?;- output_success(result, output_format, compact);+ let result = client.skills_list(node_limit, parent).await?;+ super::search::output_skills_list_results(&result, output_format, compact);Ok(())}@@ -172,10 +175,18 @@ pub async fn show(include_source: bool,output_format: OutputFormat,compact: bool,+ parent: Option<&str>,) -> Result<()> {let include_content = level.is_none() || level == Some(2);let mut result = client- .skill_show(name, include_content, include_files, include_source, level)+ .skill_show(+ name,+ include_content,+ include_files,+ include_source,+ level,+ parent,+ ).await?;if let Some(level) = level {filter_skill_show_level(&mut result, level);@@ -192,11 +203,12 @@ pub async fn find(level: Option<Vec<i32>>,output_format: OutputFormat,compact: bool,+ parent: Option<&str>,) -> Result<()> {let result = client- .skill_find(query, node_limit, threshold, level)+ .skill_find(query, node_limit, threshold, level, parent).await?;- output_success(result, output_format, compact);+ super::search::output_skills_find_results(&result, output_format, compact, node_limit);Ok(())}@@ -207,6 +219,7 @@ pub async fn update(yes: bool,output_format: OutputFormat,compact: bool,+ parent: Option<&str>,) -> Result<()> {let update_all = skill_names.is_empty();let names = resolve_installed_skill_names(client, skill_names).await?;@@ -253,6 +266,7 @@ pub async fn update(false,false,source_metadata,+ parent,).await?;updated.push(result);@@ -279,6 +293,7 @@ pub async fn remove(yes: bool,output_format: OutputFormat,compact: bool,+ parent: Option<&str>,) -> Result<()> {if all && !skill_names.is_empty() {return Err(Error::Client(@@ -331,7 +346,7 @@ pub async fn remove(let removed_names = names.clone();let mut removed = Vec::new();for name in names {- removed.push(client.skill_remove(&name).await?);+ removed.push(client.skill_remove(&name, parent).await?);}let total = removed.len();output_message_result(@@ -1158,7 +1173,9 @@ 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 result = client+ .skill_show(name, false, false, true, Some(0), None)+ .await?;let Some(source) = result.get("source") else {return Ok(None);};@@ -1348,7 +1365,7 @@ async fn resolve_installed_skill_names(}async fn list_installed_skills(client: &HttpClient) -> Result<Vec<InstalledSkillSummary>> {- let result = client.skills_list(10000).await?;+ let result = client.skills_list(10000, None).await?;let skills = result.get("skills").and_then(Value::as_array)diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex e71f0ee2f..15b5dba17 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -238,6 +238,7 @@ pub async fn handle_add_skill(data: String,wait: bool,timeout: Option<f64>,+ parent: Option<String>,ctx: CliContext,) -> Result<()> {let client = ctx.get_client();@@ -246,6 +247,7 @@ pub async fn handle_add_skill(&data,wait,timeout,+ parent.as_deref(),ctx.should_show_progress(),ctx.is_verbose(),ctx.output_format,diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 164857cc6..9bbb3e730 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -340,6 +340,9 @@ enum Commands {/// Wait timeout in seconds#[arg(long, value_name = "seconds", help_heading = "Common options")]timeout: Option<f64>,+ /// Parent skill root URI (e.g. viking://agent/skills); defaults to user-private skills+ #[arg(short = 'p', long = "parent-auto-create", value_name = "uri", help_heading = "Skill options")]+ parent: Option<String>,#[command(flatten)]upload_options: UploadCliOptions,},@@ -1226,6 +1229,9 @@ enum SkillCommands {/// Skip confirmation prompt#[arg(short = 'y', long = "yes")]yes: bool,+ /// Parent skill root URI (e.g. viking://agent/skills); defaults to user-private skills+ #[arg(short = 'p', long = "parent-auto-create", value_name = "uri")]+ parent: Option<String>,},/// List installed agent skills#[command(alias = "ls")]@@ -1239,6 +1245,9 @@ enum SkillCommands {value_name = "n")]node_limit: i32,+ /// Restrict listing to a specific skill root URI (defaults to merged user + agent)+ #[arg(short = 'p', long = "uri", value_name = "uri")]+ parent: Option<String>,},/// Find installed agent skills semanticallyFind {@@ -1265,6 +1274,9 @@ enum SkillCommands {value_name = "0,1,2")]level: Option<Vec<i32>>,+ /// Restrict search to a specific skill root URI (defaults to merged user + agent)+ #[arg(short = 'p', long = "uri", value_name = "uri")]+ parent: Option<String>,},/// Show one installed skillShow {@@ -1291,6 +1303,9 @@ enum SkillCommands {/// Include full SKILL.md content (legacy alias for --level 2)#[arg(long, hide = true)]content: bool,+ /// Resolve the skill under a specific root URI (e.g. viking://agent/skills)+ #[arg(short = 'p', long = "uri", value_name = "uri")]+ parent: Option<String>,},/// Update installed skills from their recorded sourceUpdate {@@ -1303,6 +1318,9 @@ enum SkillCommands {/// Skip confirmation prompt#[arg(short = 'y', long = "yes")]yes: bool,+ /// Resolve the skill under a specific root URI (e.g. viking://agent/skills)+ #[arg(short = 'p', long = "parent-auto-create", value_name = "uri")]+ parent: Option<String>,},/// Remove installed skills#[command(alias = "rm", alias = "delete")]@@ -1316,6 +1334,9 @@ enum SkillCommands {/// Skip confirmation prompt#[arg(short = 'y', long = "yes")]yes: bool,+ /// Resolve the skill under a specific root URI (e.g. viking://agent/skills)+ #[arg(short = 'p', long = "parent-auto-create", value_name = "uri")]+ parent: Option<String>,},/// Validate a local SKILL.md file or skill directoryValidate {@@ -2640,11 +2661,12 @@ async fn main() {data,wait,timeout,+ parent,upload_options,} => {let ctx =ctx.with_upload_options(upload_options.merged_with_legacy(legacy_upload_options));- handlers::handle_add_skill(data, wait, timeout, ctx).await+ handlers::handle_add_skill(data, wait, timeout, parent, ctx).await}Commands::Skills { action } => match action {SkillCommands::Add {@@ -2653,6 +2675,7 @@ async fn main() {list,wait,yes,+ parent,} => {let client = ctx.get_client();commands::skills::add(@@ -2666,18 +2689,27 @@ async fn main() {ctx.is_verbose(),ctx.output_format,ctx.compact,+ parent.as_deref(),).await}- SkillCommands::List { node_limit } => {+ SkillCommands::List { node_limit, parent } => {let client = ctx.get_client();- commands::skills::list(&client, node_limit, ctx.output_format, ctx.compact).await+ commands::skills::list(+ &client,+ node_limit,+ ctx.output_format,+ ctx.compact,+ parent.as_deref(),+ )+ .await}SkillCommands::Find {query,node_limit,threshold,level,+ parent,} => {let client = ctx.get_client();commands::skills::find(@@ -2688,6 +2720,7 @@ async fn main() {level,ctx.output_format,ctx.compact,+ parent.as_deref(),).await}@@ -2698,6 +2731,7 @@ async fn main() {source,format,content,+ parent,} => {let client = ctx.get_client();let output_format = format@@ -2713,18 +2747,45 @@ async fn main() {source,output_format,ctx.compact,+ parent.as_deref(),).await}- SkillCommands::Update { skills, wait, yes } => {+ SkillCommands::Update {+ skills,+ wait,+ yes,+ parent,+ } => {let client = ctx.get_client();- commands::skills::update(&client, skills, wait, yes, ctx.output_format, ctx.compact)- .await+ commands::skills::update(+ &client,+ skills,+ wait,+ yes,+ ctx.output_format,+ ctx.compact,+ parent.as_deref(),+ )+ .await}- SkillCommands::Remove { skills, all, yes } => {+ SkillCommands::Remove {+ skills,+ all,+ yes,+ parent,+ } => {let client = ctx.get_client();- commands::skills::remove(&client, skills, all, yes, ctx.output_format, ctx.compact)- .await+ commands::skills::remove(+ &client,+ skills,+ all,+ yes,+ ctx.output_format,+ ctx.compact,+ parent.as_deref(),+ )+ .await}SkillCommands::Validate { path, strict } => {let client = ctx.get_client();diff --git a/docs/en/concepts/02-context-types.md b/docs/en/concepts/02-context-types.mdindex 71cc3925a..9001a880a 100644--- a/docs/en/concepts/02-context-types.md+++ b/docs/en/concepts/02-context-types.md@@ -8,7 +8,7 @@ Based on a simplified mapping of human cognitive patterns and engineering consid|------|---------|-----------|------------|| **Resource** | Knowledge and rules | Long-term, relatively static | User adds || **Memory** | Agent's cognition | Long-term, dynamically updated | Agent records |-| **Skill** | Callable capabilities | Long-term, static | Agent invokes |+| **Skill** | Declarable agent capability configuration (AgentDefinedContextType) | Long-term, static | User or system adds |## Resource@@ -81,9 +81,9 @@ results = await client.find()```-## Skill+## Skill (Capabilities / AgentDefinedContextType)-Skills are capabilities that Agents can invoke, such as current Skills, MCP, etc.+Skills are capabilities that Agents can invoke, belonging to the **AgentDefinedContextType** category. This includes traditional workflow definitions, communication endpoints, tool configurations, and payment capabilities. Their common characteristic is that they **define how an agent interacts with external systems**, with relatively static runtime definitions, but invocation experiences are updated in Memory.### Characteristics@@ -94,27 +94,52 @@ Skills are capabilities that Agents can invoke, such as current Skills, MCP, etc### Storage Location```-viking://user/skills/{skill-name}/+viking://user/skills/{skill-name}/ # Default storage path+├── .abstract.md # L0: Short description+├── SKILL.md # L1: Detailed overview+└── scripts # L2: Full definition++viking://agent/skills/{skill-name}/ # Override via --uri, public/shared (account global)├── .abstract.md # L0: Short description├── SKILL.md # L1: Detailed overview└── scripts # L2: Full definition```+### AgentDefinedContextType Subtypes++AgentDefinedContextType includes the following subtypes, all stored under the `viking://agent/` scope:++| Subtype | Location | Description |+|---------|----------|-------------|+| **Skill** | `agent/skills/` | Traditional workflow definitions, such as search and code generation |+| **Endpoint** | `agent/endpoints/` | Communication endpoint configuration (a2a, anp, etc.) (planned) |+| **Tool** | `agent/tools/` | Tool configuration (mcp, etc.) (planned) |+| **Payment** | `agent/payments/` | Payment capability configuration (ap2, etc.) (planned) |+### Usage```python-# Add skill+# Add skill (defaults to viking://user/skills/)await client.add_skill({"name": "search-web","description": "Search the web for information","content": "# search-web\n..."})-# Search skills+# Write to global agent skills root (public/shared) via -p override+ov skills add search-web -p viking://agent/skills++# Search user skillsresults = await client.find("web search",target_uri="viking://user/skills/")++# Search global agent skills+results = await client.find(+ "web search",+ target_uri="viking://agent/skills/"+)```## Unified Searchdiff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex 216471890..0e9e0057d 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -9,25 +9,25 @@ viking://{scope}/{path}```- **scheme**: Always `viking`-- **scope**: Top-level namespace (`resources`, `user`; `temp`, `queue`, and `upload` are internal)+- **scope**: Top-level namespace (`resources`, `user`, `agent`; `temp`, `queue`, and `upload` are internal)- **path**: Resource path within the scope## Scopes| Scope | Description | Lifecycle | Visibility ||-------|-------------|-----------|------------|-| **resources** | Independent resources | Long-term | Global |+| **resources** | Independent resources / objective knowledge | Long-term | Account global || **user** | User-level data, including sessions | Long-term / session lifetime | Current user |+| **agent** | Agent capabilities and configuration (skills, endpoints, tools, payments, etc.) | Long-term | Account global || **queue** | Processing queue | Temporary | Internal || **temp** | Temporary files | During parsing | Internal || **upload** | Temporary upload files | Temporary | Internal |Public API and CLI filesystem/content operations accept the public scopes-`resources` and `user` (plus the root URI `viking://`). `session` is retained+`resources`, `user`, and `agent`, plus the root URI `viking://`. `session` is retainedas a backward-compatible alias for user session paths; new session data livesunder `viking://user/{user_id}/sessions`.-`agent` is deprecated but remains as a read-only compatibility entry for legacy-agent data. `temp`, `queue`, and `upload` are internal implementation+`temp`, `queue`, and `upload` are internal implementationscopes and cannot be addressed directly through public API URI parameters.## Initial Directory Structure@@ -55,6 +55,12 @@ viking://│ ├── tools/│ └── history/│+├── agent/ # Agent capabilities and configuration (global)+│ ├── skills/ # Skill definitions+│ ├── endpoints/ # Communication endpoints (a2a, anp, etc.) (planned)+│ ├── tools/ # Tool configuration (mcp, etc.) (planned)+│ └── payments/ # Payment configuration (ap2, etc.) (planned)+│└── resources/{project}/ # Resource workspace```@@ -94,6 +100,20 @@ viking://user/{user_id}/peers/{peer_id}/memories/viking://user/{user_id}/peers/{peer_id}/resources/```+### Agent Capabilities and Configuration++```+viking://agent/skills/search-web # A specific skill definition+viking://agent/skills/ # All skill definitions+viking://agent/endpoints/ # Communication endpoints (a2a, anp, etc.) (planned)+viking://agent/tools/mcp/ # MCP tool configuration (planned)+viking://agent/payments/ap2/ # Payment configuration (planned)+```++`viking://agent/...` is a global shared scope, accessible to all users under the account,+without agent_id isolation. Legacy (0.3.x) data under `viking://agent/...` remains accessible+via a read-only compatibility entry, but new data should be written according to the new directory semantics.+The short `viking://user/...` form is relative to the current request identity.OpenViking expands it internally to explicit namespace paths such as`viking://user/{user_id}/...` before storage and retrieval.@@ -212,15 +232,21 @@ viking://│ ├── memories/│ └── resources/│+├── agent/ # Agent capabilities and configuration (account global)+│ ├── skills/ # Skill definitions+│ ├── endpoints/ # Communication endpoints (a2a, anp, etc.) (planned)+│ ├── tools/ # Tool configuration (mcp, etc.) (planned)+│ └── payments/ # Payment configuration (ap2, etc.) (planned)+│└── user/{user_id}/sessions/{session_id}/├── messages.jsonl├── tools/└── history/```-`viking://agent/...` is deprecated and only kept for read-only legacy agent-compatibility. New data should be written under-`viking://user/{user_id}/peers/{peer_id}/...`.+`viking://agent/...` is a global shared scope for agent capabilities, accessible to all users under the account,+without agent_id isolation. Legacy (0.3.x) data under `viking://agent/...` remains accessible+via a read-only compatibility entry, but new data should be written according to the new directory semantics.## URI Operations@@ -269,11 +295,17 @@ results = client.find(target_uri="viking://user/memories/")-# Search only in skills+# Search only in user skillsresults = client.find("web search",target_uri="viking://user/skills/")++# Search only in global agent skills+results = client.find(+ "web search",+ target_uri="viking://agent/skills/"+)```### File System Operations@@ -324,10 +356,20 @@ await client.add_resource(url, to="viking://resources/project/")# Add private resources to the current user's resource rootawait client.add_resource(path, parent="viking://user/resources/project/")-# Skills always go to the current user's skills root-await client.add_skill(skill) # Canonical root: viking://user/{user_id}/skills/+# Skills are added to the current user's skills root by default+await client.add_skill(skill) # canonical root: viking://user/skills/++# Write to the global agent skills root (public/shared) via -p override+ov skills add xxx -p viking://agent/skills/```+### Resources Scope Constraint++The `resources` scope is for objective knowledge only (documents, code, specifications, papers, etc.).+Storing non-knowledge data in `viking://resources/` is prohibited, including but not limited to:+tool configurations, communication endpoint definitions, payment configurations, skill definitions, etc.+Such data should use the `viking://agent/` scope.+## Related Documents- [Architecture Overview](./01-architecture.md) - System architecturediff --git a/docs/zh/concepts/02-context-types.md b/docs/zh/concepts/02-context-types.mdindex 9a14e1785..ae29df623 100644--- a/docs/zh/concepts/02-context-types.md+++ b/docs/zh/concepts/02-context-types.md@@ -8,7 +8,7 @@|------|------|----------|--------|| **Resource** | 知识和规则 | 长期,相对静态 | 用户添加 || **Memory** | Agent 的认知 | 长期,动态更新 | Agent 记录 |-| **Skill** | 可调用的能力 | 长期,静态 | Agent 调用 |+| **Skill** | 可声明的 agent 能动性配置(AgentDefinedContextType) | 长期,静态 | 用户或系统添加 |## Resource(资源)@@ -81,9 +81,9 @@ results = await client.find()```-## Skill(技能)+## Skill(技能 / AgentDefinedContextType)-技能是 Agent 可以调用的能力,比如目前的Skills、MCP等均属于此类。+技能(Skill)是 Agent 可以调用的能力,属于 AgentDefinedContextType 范畴。包括传统工作流定义、通信端点、工具配置和支付能力等。它们的共同特征是:**定义了 agent 如何与外部系统交互**,运行时定义相对静态,但调用经验会在 Memory 中更新。### 特点@@ -94,28 +94,52 @@ results = await client.find(### 存储位置```-viking://user/skills/{skill-name}/+viking://user/skills/{skill-name}/ # 默认存储路径├── .abstract.md # L0: 简短描述-├── SKILL.md # L1: 详细概览-└── scripts # L2: 完整定义+├── SKILL.md # L1: 详细概览+└── scripts # L2: 完整定义+viking://agent/skills/{skill-name}/ # 通过 --uri 覆盖,公开共享(account 全局)+├── .abstract.md # L0: 简短描述+├── SKILL.md # L1: 详细概览+└── scripts # L2: 完整定义```+### AgentDefinedContextType 子类型++AgentDefinedContextType 包含以下子类型,均存储于 `viking://agent/` 作用域:++| 子类型 | 位置 | 说明 |+|--------|------|------|+| **Skill** | `agent/skills/` | 传统工作流定义,如搜索、代码生成 |+| **Endpoint** | `agent/endpoints/` | 通信端点配置(a2a, anp 等)(规划中) |+| **Tool** | `agent/tools/` | 工具配置(mcp 等)(规划中) |+| **Payment** | `agent/payments/` | 支付能力配置(ap2 等)(规划中) |+### 使用```python-# 添加技能+# 添加技能(默认写入 viking://user/skills/)await client.add_skill({"name": "search-web","description": "搜索网络获取信息","content": "# search-web\n..."})-# 搜索技能+# 通过 -p 指定写入全局 agent 技能根(公开共享)+ov skills add search-web -p viking://agent/skills++# 搜索用户技能results = await client.find("网络搜索",target_uri="viking://user/skills/")++# 搜索全局 agent 技能+results = await client.find(+ "网络搜索",+ target_uri="viking://agent/skills/"+)```## 统一检索diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex fead3b01b..5994e65cb 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -9,23 +9,23 @@ viking://{scope}/{path}```- **scheme**: 始终为 `viking`-- **scope**: 顶级命名空间(`resources`、`user`;`temp`、`queue` 和 `upload` 为内部作用域)+- **scope**: 顶级命名空间(`resources`、`user`、`agent`;`temp`、`queue` 和 `upload` 为内部作用域)- **path**: 作用域内的资源路径## 作用域| 作用域 | 说明 | 生命周期 | 可见性 ||--------|------|----------|--------|-| **resources** | 独立资源 | 长期 | 全局 |+| **resources** | 独立资源/客观知识 | 长期 | account 全局 || **user** | 用户级数据,包括 session | 长期 / 会话生命周期 | 当前用户 |+| **agent** | agent 能力与配置(技能、端点、工具、支付等) | 长期 | account 全局 || **queue** | 处理队列 | 临时 | 内部 || **temp** | 临时文件 | 解析期间 | 内部 || **upload** | 临时上传文件 | 临时 | 内部 |-公开 API 和 CLI 的文件系统/内容操作接受公开作用域 `resources` 和 `user`,+公开 API 和 CLI 的文件系统/内容操作接受公开作用域 `resources`、`user` 和 `agent`,以及根 URI `viking://`。`session` 保留为 user session 路径的向后兼容别名;-新 session 数据位于 `viking://user/{user_id}/sessions`。`agent` 已废弃,但仍作为-legacy agent 数据的只读兼容入口。+新 session 数据位于 `viking://user/{user_id}/sessions`。`temp`、`queue` 和 `upload` 是内部实现作用域,不能通过公开 API 的 URI 参数直接访问。## 初始目录@@ -53,6 +53,12 @@ viking://│ ├── tools/│ └── history/│+├── agent/ # agent 能力与配置(全局)+│ ├── skills/ # 技能定义+│ ├── endpoints/ # 通信端点(a2a, anp 等)(规划中)+│ ├── tools/ # 工具配置(mcp 等)(规划中)+│ └── payments/ # 支付配置(ap2 等)(规划中)+│└── resources/{project}/ # 资源工作区```@@ -98,6 +104,20 @@ OpenViking 会在存储和检索前将它展开为显式命名空间路径,例`{user_id}` 和 `{peer_id}` 等身份路径片段必须是安全的单段标识,例如`alice` 或 `web-visitor-alice`。+### agent 能力与配置++```+viking://agent/skills/search-web # 某个技能定义+viking://agent/skills/ # 所有技能定义+viking://agent/endpoints/ # 通信端点(a2a, anp 等)(规划中)+viking://agent/tools/mcp/ # MCP 工具配置(规划中)+viking://agent/payments/ap2/ # 支付配置(规划中)+```++`viking://agent/...` 为全局共享作用域,account 下所有用户均可访问,+不通过 agent_id 隔离。旧版(0.3.x)遗留的 `viking://agent/...` 数据仍可通过+只读兼容入口访问,但新数据应按照新的目录语义写入。+### 会话数据```@@ -190,12 +210,18 @@ ov add-resource --parent-auto-create "viking://resources/reports/{calendar:ym}"```viking://-├── resources/ # 独立资源+├── resources/ # 独立资源(客观知识,禁止存储非知识类配置)│ └── {project}/│ ├── .abstract.md # 摘要│ ├── .overview.md # 概述│ └── {files...}│+├── agent/ # agent 能力与配置(全局共享,account 粒度)+│ ├── skills/ # 技能定义+│ ├── endpoints/ # 通信端点(a2a, anp 等)(规划中)+│ ├── tools/ # 工具配置(mcp 等)(规划中)+│ └── payments/ # 支付配置(ap2 等)(规划中)+│├── user/{user_id}/│ ├── profile.md # 用户基本信息│ ├── memories/@@ -204,7 +230,7 @@ viking://│ │ └── events/ # 每条独立│ ├── resources/│ │ └── {project}/-│ ├── skills/+│ ├── skills/ # 用户技能(与 viking://agent/skills/ 兼容)│ └── peers/{peer_id}/│ ├── memories/│ └── resources/@@ -215,8 +241,8 @@ viking://└── history/```-`viking://agent/...` 已废弃,仅保留 legacy agent 数据的只读兼容;新数据应写入-`viking://user/{user_id}/peers/{peer_id}/...`。+`viking://agent/...` 作用域为全局共享的 agent 能力根,account 下所有用户均可访问,+不通过 agent_id 隔离。旧版(0.3.x)遗留的 `viking://agent/...` 数据仍可通过只读兼容入口访问。## URI 操作@@ -320,10 +346,20 @@ await client.add_resource(url, to="viking://resources/project/")# 添加到当前用户私有资源根await client.add_resource(path, parent="viking://user/resources/project/")-# 技能始终添加到当前用户技能根-await client.add_skill(skill) # canonical root: viking://user/{user_id}/skills/+# 技能默认添加到当前用户技能根+await client.add_skill(skill) # canonical root: viking://user/skills/++# 通过 -p 指定写入全局 agent 技能根(公开共享)+ov skills add xxx -p viking://agent/skills/```+### resources 作用域约束++`resources` 作用域仅用于存储客观知识类数据(文档、代码、规范、论文等)。+禁止在 `viking://resources/` 下存储非知识类数据,包括但不限于:+工具配置、通信端点定义、支付配置、技能定义等。+此类数据应使用 `viking://agent/` 作用域。+## 相关文档- [架构概述](./01-architecture.md) - 系统整体架构diff --git a/openviking/async_client.py b/openviking/async_client.pyindex a0f427bfb..9a81ce5f8 100644--- a/openviking/async_client.py+++ b/openviking/async_client.py@@ -377,12 +377,16 @@ class AsyncOpenViking:wait: bool = False,timeout: float = None,telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:"""Add skill to OpenViking.Args:wait: Whether to wait for vectorization to completetimeout: Wait timeout in seconds+ target_uri: Optional target root URI override. Defaults to the+ user's private ``viking://user/{user_id}/skills`` directory.+ Pass ``viking://agent/skills`` to install a shared skill."""await self._ensure_initialized()return await self._client.add_skill(@@ -390,6 +394,111 @@ class AsyncOpenViking:wait=wait,timeout=timeout,telemetry=telemetry,+ target_uri=target_uri,+ )++ async def list_skills(+ self,+ node_limit: int = 1000,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """List installed skills."""+ await self._ensure_initialized()+ return await self._client.list_skills(+ node_limit=node_limit,+ target_uri=target_uri,+ )++ async def find_skills(+ self,+ query: str,+ limit: int = 10,+ score_threshold: Optional[float] = None,+ level: Optional[List[int]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Find skills by semantic search."""+ await self._ensure_initialized()+ return await self._client.find_skills(+ query=query,+ limit=limit,+ score_threshold=score_threshold,+ level=level,+ telemetry=telemetry,+ target_uri=target_uri,+ )++ async def get_skill(+ self,+ skill_name: str,+ include_content: Optional[bool] = None,+ include_files: bool = True,+ include_source: bool = False,+ level: Optional[int] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Get a skill by name."""+ await self._ensure_initialized()+ return await self._client.get_skill(+ skill_name=skill_name,+ include_content=include_content,+ include_files=include_files,+ include_source=include_source,+ level=level,+ target_uri=target_uri,+ )++ async def update_skill(+ self,+ skill_name: str,+ data: Any,+ wait: bool = False,+ timeout: Optional[float] = None,+ source_metadata: Optional[Dict[str, Any]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Update an existing skill."""+ await self._ensure_initialized()+ return await self._client.update_skill(+ skill_name=skill_name,+ data=data,+ wait=wait,+ timeout=timeout,+ source_metadata=source_metadata,+ telemetry=telemetry,+ target_uri=target_uri,+ )++ async def delete_skill(+ self,+ skill_name: str,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Delete a skill."""+ await self._ensure_initialized()+ return await self._client.delete_skill(+ skill_name=skill_name,+ target_uri=target_uri,+ )++ async def validate_skill(+ self,+ data: Any,+ strict: bool = False,+ source_path: Optional[str] = None,+ skill_dir_name: Optional[str] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Validate skill data."""+ await self._ensure_initialized()+ return await self._client.validate_skill(+ data=data,+ strict=strict,+ source_path=source_path,+ skill_dir_name=skill_dir_name,+ target_uri=target_uri,)# ============= Search methods =============diff --git a/openviking/client/local.py b/openviking/client/local.pyindex 1b0a04210..36f63c83c 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -7,8 +7,17 @@ Implements BaseClient interface using direct service calls (embedded mode).from typing import Any, Dict, List, Optional, Union-from openviking.core.peer_id import normalize_peer_id, normalize_peer_selector+from openviking.core.peer_id import normalize_peer_idfrom openviking.server.identity import RequestContext, Role+from openviking.server.routers.skills import (+ _list_skill_files,+ _list_skills_from_root,+ _merge_skills,+ _require_skill,+ _restore_skill_privacy,+ _skill_summary_from_hit,+ _validate_skill_format,+)from openviking.service import OpenVikingServicefrom openviking.service.task_tracker import get_task_trackerfrom openviking.telemetry import TelemetryRequest@@ -72,7 +81,6 @@ class LocalClient(BaseClient):path: Optional[str] = None,user: Optional[UserIdentifier] = None,actor_peer_id: Optional[str] = None,- agent_id: Optional[str] = None,):"""Initialize LocalClient.@@ -80,21 +88,16 @@ class LocalClient(BaseClient):path: Local storage path (overrides ov.conf storage path)user: Explicit account/user identity for embedded modeactor_peer_id: Optional view filter for the current user's peer collection.- agent_id: Legacy alias for actor_peer_id."""self._service = OpenVikingService(path=path,user=user or UserIdentifier.the_default_user(),)self._user = self._service.user- if actor_peer_id and agent_id:- raise ValueError("actor_peer_id cannot be used with legacy agent_id")- self._legacy_agent_id = normalize_peer_selector(None, agent_id=agent_id)self._ctx = RequestContext(user=self._user,role=Role.USER,- actor_peer_id=normalize_peer_selector(actor_peer_id, agent_id=agent_id),- legacy_agent_id=self._legacy_agent_id,+ actor_peer_id=normalize_peer_id(actor_peer_id),)@property@@ -164,6 +167,7 @@ class LocalClient(BaseClient):wait: bool = False,timeout: Optional[float] = None,telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:"""Add skill to OpenViking."""execution = await run_with_telemetry(@@ -174,6 +178,188 @@ class LocalClient(BaseClient):ctx=self._ctx,wait=wait,timeout=timeout,+ target_uri=target_uri,+ ),+ )+ return attach_telemetry_payload(+ execution.result,+ execution.telemetry,+ )++ async def list_skills(+ self,+ node_limit: int = 1000,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """List installed skills."""+ from openviking.core.namespace import canonical_user_root++ service = self._service+ ctx = self._ctx+ if target_uri:+ skills = await _list_skills_from_root(service, ctx, target_uri)+ return {"root_uri": target_uri, "skills": skills, "total": len(skills)}+ else:+ user_skills = await _list_skills_from_root(+ service, ctx, f"{canonical_user_root(ctx)}/skills"+ )+ agent_skills = await _list_skills_from_root(service, ctx, "viking://agent/skills")+ merged = [*user_skills, *agent_skills]+ return {+ "root_uris": [f"{canonical_user_root(ctx)}/skills", "viking://agent/skills"],+ "skills": merged,+ "total": len(merged),+ }++ async def find_skills(+ self,+ query: str,+ limit: int = 10,+ score_threshold: Optional[float] = None,+ level: Optional[List[int]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Find skills by semantic search."""+ from openviking.core.namespace import canonical_user_root++ service = self._service+ ctx = self._ctx++ async def _search_at(uri: str) -> list:+ result = await service.search.find(+ query=query,+ ctx=ctx,+ target_uri=uri,+ limit=limit,+ score_threshold=score_threshold,+ level=level,+ )+ result_dict = result.to_dict() if hasattr(result, "to_dict") else dict(result or {})+ return [_skill_summary_from_hit(hit) for hit in result_dict.get("skills", [])]++ if target_uri:+ execution = await run_with_telemetry(+ operation="skills.find",+ telemetry=telemetry,+ fn=lambda: _search_at(target_uri),+ )+ hits = execution.result+ return {+ "root_uri": target_uri,+ "skills": hits,+ "total": len(hits),+ }+ else:+ user_root = f"{canonical_user_root(ctx)}/skills"+ agent_root = "viking://agent/skills"++ user_execution = await run_with_telemetry(+ operation="skills.find",+ telemetry=telemetry,+ fn=lambda: _search_at(user_root),+ )+ user_hits = user_execution.result++ agent_hits = await _search_at(agent_root)++ merged = [*user_hits, *agent_hits]+ if merged and "score" in merged[0]:+ merged.sort(key=lambda x: x.get("score", 0), reverse=True)++ return {+ "root_uris": [user_root, agent_root],+ "skills": merged,+ "total": len(merged),+ }++ async def get_skill(+ self,+ skill_name: str,+ include_content: Optional[bool] = None,+ include_files: bool = True,+ include_source: bool = False,+ level: Optional[int] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Get a skill by name."""+ from openviking.server.routers.skills import (+ _parse_abstract_meta,+ _relative_skill_path,+ _skill_file_kind,+ _skill_summary_from_meta,+ SOURCE_METADATA_FILENAME,+ )+ from openviking.server.skill_source_metadata import read_skill_source_metadata++ 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 = self._service+ ctx = self._ctx+ root_uri = await _require_skill(service, ctx, skill_name, target_uri)++ 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):+ from openviking.server.routers.skills import _skill_md_uri++ 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,+ "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 result++ async def update_skill(+ self,+ skill_name: str,+ data: Any,+ wait: bool = False,+ timeout: Optional[float] = None,+ source_metadata: Optional[Dict[str, Any]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Update an existing skill."""+ service = self._service+ ctx = self._ctx++ # Verify the skill exists and determine its root URI+ root_uri = await _require_skill(service, ctx, skill_name, target_uri)+ skill_root_parent = root_uri.rsplit("/", 1)[0]++ execution = await run_with_telemetry(+ operation="skills.update",+ telemetry=telemetry,+ fn=lambda: self._update_skill_impl(+ skill_name, data, root_uri, skill_root_parent, wait, timeout, source_metadata),)return attach_telemetry_payload(@@ -181,6 +367,130 @@ class LocalClient(BaseClient):execution.telemetry,)+ async def _update_skill_impl(+ self,+ skill_name: str,+ data: Any,+ root_uri: str,+ skill_root_parent: str,+ wait: bool,+ timeout: Optional[float],+ source_metadata: Optional[Dict[str, Any]],+ ) -> Dict[str, Any]:+ import shutil+ import uuid++ from openviking.server.skill_source_metadata import persist_skill_source_metadata++ service = self._service+ ctx = self._ctx+ backup_uri = f"{skill_root_parent}/.{skill_name}.update-backup-{uuid.uuid4().hex}"+ backup_created = False+ privacy_update_attempted = False+ previous_privacy = None+ preparation = None+ privacy = service.privacy_configs+ effective_source_metadata = source_metadata or {+ "type": "embedded",+ "source": "inline_content",+ "operation": "update",+ }+ 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=False,+ )+ expected_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=wait,+ timeout=timeout,+ allow_local_path_resolution=False,+ apply_privacy=False,+ privacy_change_reason="auto-extracted from update_skill",+ target_uri=skill_root_parent,+ )+ await persist_skill_source_metadata(service, ctx, result, effective_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+ raise+ else:+ if backup_created:+ try:+ await service.fs.rm(backup_uri, ctx=ctx, recursive=True)+ except Exception:+ pass+ result["action"] = "update"+ return result+ finally:+ if preparation and preparation.cleanup_path:+ shutil.rmtree(preparation.cleanup_path, ignore_errors=True)++ async def delete_skill(+ self,+ skill_name: str,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Delete a skill."""+ service = self._service+ ctx = self._ctx+ root_uri = await _require_skill(service, ctx, skill_name, target_uri)+ result = await service.fs.rm(root_uri, ctx=ctx, recursive=True)+ return {"name": skill_name, "uri": root_uri, "root_uri": root_uri, "deleted": True}++ async def validate_skill(+ self,+ data: Any,+ strict: bool = False,+ source_path: Optional[str] = None,+ skill_dir_name: Optional[str] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Validate skill data."""+ result = _validate_skill_format(+ self._service,+ data,+ strict=strict,+ skill_dir_name=skill_dir_name,+ source_path=source_path,+ )+ return result+async def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:"""Wait for all processing to complete."""return await self._service.resources.wait_processed(timeout=timeout)@@ -720,15 +1030,7 @@ class LocalClient(BaseClient):}def _resolve_message_peer_id(self, role: str, peer_id: Optional[str]) -> Optional[str]:- if self._legacy_agent_id is None:- return normalize_peer_id(peer_id)- if peer_id is not None:- raise InvalidArgumentError(- "peer_id cannot be used when client is configured with legacy agent_id"- )- if role == "assistant":- return self._legacy_agent_id- return None+ return normalize_peer_id(peer_id)# ============= Pack =============diff --git a/openviking/core/namespace.py b/openviking/core/namespace.pyindex 5f5274673..fa62f3119 100644--- a/openviking/core/namespace.py+++ b/openviking/core/namespace.py@@ -193,9 +193,13 @@ def is_session_uri(uri: str) -> bool:return len(parts) >= 3 and parts[0] == "user" and parts[2] == "sessions"+AGENT_SHARED_ROOTS: tuple[str, ...] = ("viking://agent/skills",)++def visible_roots(ctx: RequestContext) -> list[str]:return ["viking://resources",+ *AGENT_SHARED_ROOTS,canonical_user_root(ctx),]diff --git a/openviking/core/peer_id.py b/openviking/core/peer_id.pyindex 7fc54ebb3..c1cdf1145 100644--- a/openviking/core/peer_id.py+++ b/openviking/core/peer_id.py@@ -17,37 +17,6 @@ def normalize_peer_id(raise ValueError(f"Invalid peer_id: {exc}") from exc-def peer_id_from_legacy_agent_uri(agent_uri: Optional[str]) -> Optional[str]:- """Resolve a legacy agent URI or ID into a peer_id."""- if not agent_uri:- return None- value = agent_uri.strip()- if not value:- return None- if value.startswith("viking://agent/"):- parts = [part for part in value[len("viking://agent/") :].strip("/").split("/") if part]- value = parts[0] if parts else ""- return normalize_peer_id(value)---def normalize_peer_selector(- peer_id: Optional[str],- *,- agent_id: Optional[str] = None,- agent_uri: Optional[str] = None,-) -> Optional[str]:- """Normalize peer_id with legacy agent_id/agent_uri compatibility."""- resolved_peer_id = normalize_peer_id(peer_id)- legacy_agent_id = normalize_peer_id(agent_id)- legacy_agent_uri_id = peer_id_from_legacy_agent_uri(agent_uri)- if legacy_agent_id and legacy_agent_uri_id and legacy_agent_id != legacy_agent_uri_id:- raise ValueError("legacy agent_id must match agent_uri")- legacy_peer_id = legacy_agent_id or legacy_agent_uri_id- if resolved_peer_id and legacy_peer_id:- raise ValueError("peer_id cannot be used with legacy agent_id/agent_uri")- return resolved_peer_id or legacy_peer_id--def safe_peer_id(peer_id: Optional[str]) -> Optional[str]:"""Return a usable peer_id, or None for empty/path-like values."""try:diff --git a/openviking/core/retrieval_targets.py b/openviking/core/retrieval_targets.pyindex 9a1305dbc..5b699b45d 100644--- a/openviking/core/retrieval_targets.py+++ b/openviking/core/retrieval_targets.py@@ -60,14 +60,12 @@ def default_target_directories(return []user_root = canonical_user_root(ctx)- legacy_agent_targets = _legacy_agent_targets(ctx.legacy_agent_id, context_type=context_type)if context_type == ContextType.MEMORY:if ctx.actor_peer_id:return _dedupe([f"{user_root}/memories",f"{user_root}/peers/{ctx.actor_peer_id}/memories",- *legacy_agent_targets,])return [user_root]@@ -78,12 +76,11 @@ def default_target_directories("viking://resources",f"{user_root}/resources",f"{user_root}/peers/{ctx.actor_peer_id}/resources",- *legacy_agent_targets,])return ["viking://resources", user_root]if context_type == ContextType.SKILL:- return _dedupe([*_default_skill_targets(ctx), *legacy_agent_targets])+ return _dedupe([*_default_skill_targets(ctx), *_default_agent_skill_targets()])if ctx.actor_peer_id:return _dedupe(["viking://resources", *_default_user_root_targets(ctx)])return [user_root, "viking://resources"]@@ -115,9 +112,9 @@ def _target_directories_for_uri(if _is_current_user_root(target_uri, ctx):return _default_user_root_targets(ctx)- legacy_agent_target = _resolve_legacy_agent_target(target_uri, ctx=ctx)- if legacy_agent_target is not None:- return legacy_agent_target+ # New agent scope: direct access for agent/skills/, agent/endpoints/, etc.+ if _is_agent_scope_uri(target_uri):+ return [target_uri]peer_target = _resolve_peer_target(target_uri, ctx=ctx)if peer_target is not None:@@ -130,6 +127,10 @@ def _target_directories_for_uri(return [target_uri]+def _default_agent_skill_targets() -> List[str]:+ return ["viking://agent/skills"]++def _default_user_root_targets(ctx: RequestContext) -> List[str]:user_root = canonical_user_root(ctx)if not ctx.actor_peer_id:@@ -140,7 +141,6 @@ def _default_user_root_targets(ctx: RequestContext) -> List[str]:f"{user_root}/resources",*_default_skill_targets(ctx),*_actor_peer_targets(ctx),- *_legacy_agent_targets(ctx.legacy_agent_id),])@@ -157,83 +157,9 @@ def _actor_peer_targets(ctx: RequestContext) -> List[str]:f"{peer_root}/memories",f"{peer_root}/resources",]---def _legacy_agent_targets(- agent_id: Optional[str],- *,- context_type: Optional[ContextType] = None,-) -> List[str]:- if not agent_id:- return []- agent_root = f"viking://agent/{agent_id}"- if context_type == ContextType.MEMORY:- return [f"{agent_root}/memories"]- if context_type == ContextType.RESOURCE:- return [f"{agent_root}/resources"]- if context_type == ContextType.SKILL:- return [f"{agent_root}/skills"]- return [- f"{agent_root}/memories",- f"{agent_root}/resources",- f"{agent_root}/skills",- ]---def _resolve_legacy_agent_target(- target_uri: str,- *,- ctx: RequestContext,-) -> Optional[List[str]]:- parts = uri_parts(target_uri)- if not parts or parts[0] != "agent":- return None- if len(parts) == 1:- agent_id = ctx.legacy_agent_id or ctx.actor_peer_id- if not agent_id:- return [target_uri]- return _legacy_agent_and_migrated_targets(agent_id, ctx)-- agent_id = _normalize_peer_id(parts[1])- if ctx.actor_peer_id and agent_id != ctx.actor_peer_id:- raise PermissionDeniedError("Actor peer cannot access another legacy agent context.")-- suffix = parts[2:]- if not suffix:- return _legacy_agent_and_migrated_targets(agent_id, ctx)- if suffix[0] == "memories":- return _dedupe(- [- target_uri,- _with_suffix(f"{canonical_user_root(ctx)}/peers/{agent_id}/memories", suffix[1:]),- ]- )- if suffix[0] == "resources":- return _dedupe(- [- target_uri,- _with_suffix(f"{canonical_user_root(ctx)}/peers/{agent_id}/resources", suffix[1:]),- ]- )- if suffix[0] == "skills":- return _dedupe(- [- target_uri,- _with_suffix(f"{canonical_user_root(ctx)}/skills", suffix[1:]),- ]- )- return [target_uri]---def _legacy_agent_and_migrated_targets(agent_id: str, ctx: RequestContext) -> List[str]:- return _dedupe(- [- *_legacy_agent_targets(agent_id),- f"{canonical_user_root(ctx)}/peers/{agent_id}/memories",- f"{canonical_user_root(ctx)}/peers/{agent_id}/resources",- *_default_skill_targets(ctx),- ]- )+def _is_agent_scope_uri(target_uri: str) -> bool:+ parts = target_uri[len("viking://"):].strip("/").split("/")+ return parts and parts[0] == "agent" and len(parts) >= 2 and parts[1] in {"skills", "endpoints", "tools", "payments"}def _with_suffix(root: str, suffix: List[str]) -> str:diff --git a/openviking/models/vlm/base.py b/openviking/models/vlm/base.pyindex 70117fe87..7aeb1b54f 100644--- a/openviking/models/vlm/base.py+++ b/openviking/models/vlm/base.py@@ -339,6 +339,27 @@ class VLMFactory:return get_all_provider_names()+def _annotate_vlm_error(exc: Exception, vlm_instance: "VLMBase") -> None:+ """Attach model and api_base info to an exception for better error diagnostics.++ The info is attached as attributes on the exception object so that upstream+ error mapping (e.g. error_mapping.py) can include them in the user-facing+ message, making it clear which model endpoint triggered the failure.+ """+ try:+ if not hasattr(exc, "_vlm_model"):+ model = getattr(vlm_instance, "model", None)+ if model:+ exc._vlm_model = model+ if not hasattr(exc, "_vlm_api_base"):+ api_base = getattr(vlm_instance, "api_base", None)+ if api_base:+ exc._vlm_api_base = api_base+ except Exception:+ # Never let annotation break the original error path+ pass++class FailoverVLM(VLMBase):"""VLM wrapper that provides failover to a backup VLM instance.@@ -401,6 +422,7 @@ class FailoverVLM(VLMBase):self._switcher.record_primary_success()return resultexcept Exception as e:+ _annotate_vlm_error(e, self.primary)last_error = eif self._switcher.record_primary_failure(e):# Switched to backup, continue to try backup@@ -415,6 +437,7 @@ class FailoverVLM(VLMBase):method = getattr(self.backup, method_name)return method(*args, **kwargs)except Exception as e:+ _annotate_vlm_error(e, self.backup)last_error = eself._logger.error(f"Backup VLM also failed with error: {e}")raise last_error@@ -443,6 +466,7 @@ class FailoverVLM(VLMBase):self._switcher.record_primary_success()return resultexcept Exception as e:+ _annotate_vlm_error(e, self.primary)last_error = eif self._switcher.record_primary_failure(e):# Switched to backup, continue to try backup@@ -457,6 +481,7 @@ class FailoverVLM(VLMBase):method = getattr(self.backup, method_name)return await method(*args, **kwargs)except Exception as e:+ _annotate_vlm_error(e, self.backup)last_error = eself._logger.error(f"Backup VLM also failed with error: {e}")raise last_error@@ -662,6 +687,7 @@ class MultiCredentialVLM(VLMBase):self._switcher.commit_success(idx)return resultexcept Exception as exc:+ _annotate_vlm_error(exc, vlm_instance)error_class = classify_api_error(exc)aggregated_errors.append((credential_id, error_class, exc, idx))@@ -708,6 +734,7 @@ class MultiCredentialVLM(VLMBase):self._switcher.commit_success(idx)return resultexcept Exception as exc:+ _annotate_vlm_error(exc, vlm_instance)error_class = classify_api_error(exc)aggregated_errors.append((credential_id, error_class, exc, idx))diff --git a/openviking/server/error_mapping.py b/openviking/server/error_mapping.pyindex 357478afc..da166e064 100644--- a/openviking/server/error_mapping.py+++ b/openviking/server/error_mapping.py@@ -298,12 +298,25 @@ def _upstream_code_for_status(status: int) -> str:return "UNKNOWN"+def _extract_vlm_info(exc: Exception | None) -> tuple[str | None, str | None]:+ """Extract model name and api_base from the exception chain, if annotated."""+ if exc is None:+ return None, None+ for item in _iter_exception_chain(exc):+ model = getattr(item, "_vlm_model", None)+ api_base = getattr(item, "_vlm_api_base", None)+ if model or api_base:+ return model, api_base+ return None, None++def _build_upstream_error(*,code: str,message: str,status: int | None = None,source: BaseException | None = None,+ vlm_context: BaseException | None = None,) -> OpenVikingError:labels = {"INVALID_ARGUMENT": "Upstream model request was rejected",@@ -326,6 +339,18 @@ def _build_upstream_error(details["upstream_status_code"] = statusif source is not None:details["upstream_error_type"] = type(source).__name__+ # Search for VLM model/api_base annotations. vlm_context is the outermost+ # exception (where failover wrappers attach the annotation); source may be+ # an inner exception from the chain.+ vlm_model, vlm_api_base = _extract_vlm_info(vlm_context)+ if not vlm_model and not vlm_api_base:+ vlm_model, vlm_api_base = _extract_vlm_info(source)+ if vlm_model:+ details["vlm_model"] = vlm_model+ display = f"{display}\n Model: {vlm_model}"+ if vlm_api_base:+ details["vlm_api_base"] = vlm_api_base+ display = f"{display}\n API base: {vlm_api_base}"return OpenVikingError(display, code=code, details=details)@@ -348,6 +373,7 @@ def _map_upstream_api_error(exc: Exception) -> OpenVikingError | None:status=status,source=source,message=_upstream_detail_message(exc),+ vlm_context=exc,)if not _looks_like_upstream_model_error(exc):@@ -356,11 +382,17 @@ def _map_upstream_api_error(exc: Exception) -> OpenVikingError | None:lowered = text.lower()if "invalid api key" in lowered or "unauthorized" in lowered:return _build_upstream_error(- code="UNAUTHENTICATED", message=_upstream_detail_message(exc), source=exc+ code="UNAUTHENTICATED",+ message=_upstream_detail_message(exc),+ source=exc,+ vlm_context=exc,)if "forbidden" in lowered:return _build_upstream_error(- code="PERMISSION_DENIED", message=_upstream_detail_message(exc), source=exc+ code="PERMISSION_DENIED",+ message=_upstream_detail_message(exc),+ source=exc,+ vlm_context=exc,)if any(marker in lowered@@ -374,7 +406,10 @@ def _map_upstream_api_error(exc: Exception) -> OpenVikingError | None:)):return _build_upstream_error(- code="RESOURCE_EXHAUSTED", message=_upstream_detail_message(exc), source=exc+ code="RESOURCE_EXHAUSTED",+ message=_upstream_detail_message(exc),+ source=exc,+ vlm_context=exc,)return Nonediff --git a/openviking/server/identity.py b/openviking/server/identity.pyindex 277d10b59..f66bd3eda 100644--- a/openviking/server/identity.py+++ b/openviking/server/identity.py@@ -97,10 +97,6 @@ class RequestContext:# Request-level view filter for the current user's peers collection. This does# not change tenant/user identity or session ownership.actor_peer_id: Optional[str] = None- # Set only when the request came through the legacy agent_id compatibility- # path. Search/find use it to include unmigrated viking://agent data without- # making pure actor_peer_id requests read legacy agent scopes by default.- legacy_agent_id: Optional[str] = None# Mirrors ResolvedIdentity.from_oauth. Routes that mint OAuth state# (OTP issuance, oauth-verify) reject callers with from_oauth=True to# prevent a stolen access token from laundering itself into a long-liveddiff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.pyindex b7df7bde2..bcf541ae9 100644--- a/openviking/server/routers/resources.py+++ b/openviking/server/routers/resources.py@@ -112,6 +112,7 @@ class AddSkillRequest(BaseModel):wait: bool = Falsetimeout: Optional[float] = Nonesource_metadata: Optional[Dict[str, Any]] = None+ target_uri: Optional[str] = Nonetelemetry: TelemetryRequest = False@model_validator(mode="after")@@ -312,6 +313,7 @@ async def add_skill(timeout=request.timeout,allow_local_path_resolution=allow_local_path_resolution,source_path_hint=source_path_hint,+ target_uri=request.target_uri,)await persist_skill_source_metadata(service, _ctx, result, source_metadata)except Exception:diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 8c1f06196..ee0b1ceb9 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -3,14 +3,12 @@"""Search endpoints for OpenViking HTTP Server."""import math-from dataclasses import replacefrom typing import Any, Dict, List, Literal, Optional, Unionfrom fastapi import APIRouter, Depends-from pydantic import BaseModel, ConfigDict, model_validator+from pydantic import BaseModel, ConfigDictfrom openviking.core.path_variables import resolve_path_variables-from openviking.core.peer_id import normalize_peer_selectorfrom openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundErrorfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_service@@ -87,21 +85,6 @@ def _resolve_uri_or_uris(uri: Union[str, List[str]]) -> Union[str, List[str]]:return resolve_path_variables(uri)-def _ctx_with_legacy_actor_peer(- ctx: RequestContext,- legacy_peer_id: Optional[str],-) -> RequestContext:- if legacy_peer_id is None:- return ctx- if ctx.actor_peer_id and ctx.actor_peer_id != legacy_peer_id:- raise InvalidArgumentError(- "actor_peer_id cannot be used with a different legacy agent_id/agent_uri"- )- if ctx.actor_peer_id == legacy_peer_id and ctx.legacy_agent_id == legacy_peer_id:- return ctx- return replace(ctx, actor_peer_id=legacy_peer_id, legacy_agent_id=legacy_peer_id)--class FindRequest(BaseModel):"""Request model for find."""@@ -110,8 +93,6 @@ class FindRequest(BaseModel):query: strtarget_uri: Union[str, List[str]] = ""context_type: Optional[Union[str, List[str]]] = None- agent_id: Optional[str] = None- agent_uri: Optional[str] = Nonelimit: int = 10node_limit: Optional[int] = Nonescore_threshold: Optional[float] = None@@ -124,15 +105,6 @@ class FindRequest(BaseModel):level: Optional[Union[int, str, List[int]]] = Nonetelemetry: TelemetryRequest = False- @model_validator(mode="after")- def normalize_request_peer_id(self) -> "FindRequest":- self.agent_id = normalize_peer_selector(- None,- agent_id=self.agent_id,- agent_uri=self.agent_uri,- )- return self-class SearchRequest(BaseModel):"""Request model for search with session."""@@ -142,8 +114,6 @@ class SearchRequest(BaseModel):query: strtarget_uri: Union[str, List[str]] = ""context_type: Optional[Union[str, List[str]]] = None- agent_id: Optional[str] = None- agent_uri: Optional[str] = Nonesession_id: Optional[str] = Nonelimit: int = 10node_limit: Optional[int] = None@@ -158,15 +128,6 @@ class SearchRequest(BaseModel):level: Optional[Union[int, str, List[int]]] = Nonetelemetry: TelemetryRequest = False- @model_validator(mode="after")- def normalize_request_peer_id(self) -> "SearchRequest":- self.agent_id = normalize_peer_selector(- None,- agent_id=self.agent_id,- agent_uri=self.agent_uri,- )- return self-class GrepRequest(BaseModel):"""Request model for grep."""@@ -194,7 +155,6 @@ async def find():"""Semantic search without session context."""service = get_service()- ctx = _ctx_with_legacy_actor_peer(_ctx, request.agent_id)actual_limit = _resolve_search_limit(request.limit, request.node_limit)effective_filter = _resolve_search_filter(request.filter,@@ -210,7 +170,7 @@ async def find(telemetry=request.telemetry,fn=lambda: service.search.find(query=request.query,- ctx=ctx,+ ctx=_ctx,target_uri=resolved_target_uri,limit=actual_limit,score_threshold=request.score_threshold,@@ -236,7 +196,6 @@ async def search():"""Semantic search with optional session context."""service = get_service()- ctx = _ctx_with_legacy_actor_peer(_ctx, request.agent_id)actual_limit = _resolve_search_limit(request.limit, request.node_limit)effective_filter = _resolve_search_filter(request.filter,@@ -251,11 +210,11 @@ async def search(async def _search():session = Noneif request.session_id:- session = service.sessions.session(ctx, request.session_id)+ session = service.sessions.session(_ctx, request.session_id)await session.load()return await service.search.search(query=request.query,- ctx=ctx,+ ctx=_ctx,target_uri=resolved_target_uri,session=session,limit=actual_limit,diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.pyindex bb86b4e56..adf3747bc 100644--- a/openviking/server/routers/sessions.py+++ b/openviking/server/routers/sessions.py@@ -8,7 +8,7 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Requesfrom pydantic import BaseModel, Field, model_validatorfrom openviking.core.path_variables import resolve_path_variables-from openviking.core.peer_id import normalize_peer_selector+from openviking.core.peer_id import normalize_peer_idfrom openviking.message.part import Part, TextPart, part_from_dictfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_service@@ -96,11 +96,7 @@ class AddMessageRequest(BaseModel):def validate_content_or_parts(self) -> "AddMessageRequest":if self.content is None and self.parts is None:raise ValueError("Either 'content' or 'parts' must be provided")- self.peer_id = normalize_peer_selector(- self.peer_id,- agent_id=self.agent_id,- agent_uri=self.agent_uri,- )+ self.peer_id = normalize_peer_id(self.peer_id)return selfdiff --git a/openviking/server/routers/skills.py b/openviking/server/routers/skills.pyindex 9f89ea9c4..3d7578715 100644--- a/openviking/server/routers/skills.py+++ b/openviking/server/routers/skills.py@@ -6,7 +6,7 @@ import reimport shutilimport uuidfrom pathlib import Path-from typing import Any, Dict, Optional+from typing import Any, Dict, Optional, Unionimport yamlfrom fastapi import APIRouter, Depends, Request@@ -14,6 +14,7 @@ from fastapi import Path as ApiPathfrom pydantic import BaseModel, ConfigDict, model_validatorfrom openviking.core.namespace import canonical_user_root+from openviking.core.path_variables import resolve_path_variablesfrom openviking.core.skill_loader import SkillLoaderfrom openviking.privacy.service import UserPrivacyConfigVersionfrom openviking.server.auth import get_request_context@@ -45,6 +46,7 @@ class UpdateSkillRequest(BaseModel):timeout: Optional[float] = Nonesource_metadata: Optional[Dict[str, Any]] = Nonetelemetry: TelemetryRequest = False+ target_uri: Optional[str] = None@model_validator(mode="after")def check_data_or_temp_file_id(self):@@ -61,6 +63,7 @@ class FindSkillsRequest(BaseModel):score_threshold: Optional[float] = Nonelevel: Optional[list[int]] = Nonetelemetry: TelemetryRequest = False+ target_uri: Optional[str] = Noneclass ValidateSkillRequest(BaseModel):@@ -70,18 +73,110 @@ class ValidateSkillRequest(BaseModel):strict: bool = Falsesource_path: Optional[str] = Noneskill_dir_name: Optional[str] = None+ target_uri: Optional[str] = None+++def _agent_skills_root(ctx: RequestContext, target_uri: Optional[str] = None) -> str:+ user_root = f"{canonical_user_root(ctx)}/skills"+ if not target_uri:+ return user_root+ resolved_uri = resolve_path_variables(target_uri).rstrip("/")+ if resolved_uri == "viking://agent/skills" or resolved_uri.startswith(+ "viking://agent/skills/"+ ):+ return "viking://agent/skills"+ if resolved_uri == user_root or resolved_uri.startswith(f"{user_root}/"):+ return user_root+ raise InvalidArgumentError(+ f"Unsupported skill target URI: {target_uri}",+ details={+ "field": "target_uri",+ "allowed": [user_root, "viking://agent/skills"],+ },+ )-def _agent_skills_root(ctx: RequestContext) -> str:- return f"{canonical_user_root(ctx)}/skills"+async def _list_skills_from_root(service, ctx: RequestContext, root_uri: str) -> list[Dict[str, Any]]:+ """List skills from a specific root URI.++ Filters out directory entries that do not look like a valid skill — i.e.+ their abstract metadata does not yield a valid ``name`` (matching the same+ rules ``add_skill`` enforces via ``validate_skill_name``). If the abstract+ is missing or unreadable we fall back to checking whether a SKILL.md file+ exists under the entry; only then is the directory accepted. This keeps+ nested directories like ``<skill>/scripts`` out of the listing.+ """+ try:+ entries = await service.fs.ls(+ root_uri,+ ctx=ctx,+ output="agent",+ abs_limit=1024,+ node_limit=1000,+ )+ except NotFoundError:+ return []++ results: list[Dict[str, Any]] = []+ for entry in entries:+ if not (isinstance(entry, dict) and entry.get("isDir", False)):+ continue+ if not await _entry_looks_like_skill(service, ctx, entry):+ continue+ results.append(_skill_summary_from_entry(entry))+ return results+++async def _entry_looks_like_skill(+ service, ctx: RequestContext, entry: Dict[str, Any]+) -> bool:+ """Decide whether a directory entry from ``ls`` represents a real skill."""+ entry_uri = entry.get("uri", "")+ if not entry_uri:+ return False++ meta = _parse_abstract_meta(entry.get("abstract", ""))+ if meta:+ try:+ validate_skill_name(meta.get("name"))+ except Exception:+ return False+ description = meta.get("description")+ if not isinstance(description, str) or not description.strip():+ return False+ return True++ # Abstract is missing or unparsable — fall back to checking that the+ # directory actually contains a SKILL.md file before listing it. Any+ # error (including NotFound) means we cannot confirm it is a skill.+ try:+ skill_md_stat = await service.fs.stat(_skill_md_uri(entry_uri), ctx=ctx)+ except Exception:+ return False+ if not skill_md_stat or skill_md_stat.get("isDir", False):+ return False+ return True+++def _merge_skills(skills_list: list[list[Dict[str, Any]]]) -> list[Dict[str, Any]]:+ """Merge skills from multiple sources, user skills take precedence."""+ seen_names = set()+ result = []+ for skills in skills_list:+ for skill in skills:+ name = skill.get("name")+ if name not in seen_names:+ seen_names.add(name)+ result.append(skill)+ return resultdef _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_root_uri(ctx: RequestContext, skill_name: str, target_uri: Optional[str] = None) -> str:+ return f"{_agent_skills_root(ctx, target_uri)}/{_validate_skill_name(skill_name)}"def _skill_md_uri(root_uri: str) -> str:@@ -119,6 +214,7 @@ def _parse_abstract_meta(abstract: str) -> Dict[str, Any]:def _skill_summary_from_meta(name: str, root_uri: str, meta: Dict[str, Any]) -> Dict[str, Any]:return {+ "type": "skill","name": name,"uri": root_uri,"root_uri": root_uri,@@ -277,10 +373,11 @@ def _skill_summary_from_entry(entry: Dict[str, Any]) -> Dict[str, Any]:def _skill_summary_from_hit(hit: Dict[str, Any]) -> Dict[str, Any]:- root_uri = hit.get("uri", "")- name = _skill_name_from_uri(root_uri)+ hit_uri = hit.get("uri", "")+ root_uri = _skill_root_from_hit_uri(hit_uri)+ name = _skill_name_from_uri(root_uri) if root_uri else _skill_name_from_uri(hit_uri)summary = _skill_summary_from_meta(- name, root_uri, _parse_abstract_meta(hit.get("abstract", ""))+ name, root_uri or hit_uri, _parse_abstract_meta(hit.get("abstract", "")))summary["score"] = hit.get("score", 0.0)summary["match_reason"] = hit.get("match_reason", "")@@ -289,17 +386,59 @@ def _skill_summary_from_hit(hit: Dict[str, Any]) -> Dict[str, Any]:return summary-async def _require_skill(service, ctx: RequestContext, skill_name: str) -> str:- root_uri = _skill_root_uri(ctx, skill_name)+def _skill_root_from_hit_uri(hit_uri: str) -> str:+ """Strip a trailing chunk filename (e.g. ``.abstract.md``) from a hit URI.++ Search results point at the indexed chunk file (typically ``.abstract.md``+ sitting alongside ``SKILL.md`` inside the skill directory). The summary+ consumed by the CLI expects the URI to identify the skill directory itself,+ so we trim a single trailing filename when one is present.+ """+ if not hit_uri:+ return ""+ trimmed = hit_uri.rstrip("/")+ last_segment = trimmed.rsplit("/", 1)[-1]+ if "." in last_segment:+ parent = trimmed.rsplit("/", 1)[0]+ if parent:+ return parent+ return trimmed+++async def _require_skill(service, ctx: RequestContext, skill_name: str, target_uri: Optional[str] = None) -> str:+ if target_uri:+ resolved_uri = resolve_path_variables(target_uri)+ root_uri = _skill_root_uri(ctx, skill_name, resolved_uri)+ try:+ stat = await service.fs.stat(root_uri, ctx=ctx)+ if stat and stat.get("isDir", False):+ return root_uri+ except NotFoundError:+ pass+ except Exception as exc:+ raise NotFoundError(root_uri, "skill") from exc++ user_root_uri = _skill_root_uri(ctx, skill_name)+ try:+ stat = await service.fs.stat(user_root_uri, ctx=ctx)+ if stat and stat.get("isDir", False):+ return user_root_uri+ except NotFoundError:+ pass+ except Exception as exc:+ raise NotFoundError(user_root_uri, "skill") from exc++ agent_root_uri = _skill_root_uri(ctx, skill_name, "viking://agent/skills")try:- stat = await service.fs.stat(root_uri, ctx=ctx)+ stat = await service.fs.stat(agent_root_uri, ctx=ctx)+ if stat and stat.get("isDir", False):+ return agent_root_uriexcept NotFoundError:- raise+ passexcept 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+ raise NotFoundError(agent_root_uri, "skill") from exc++ raise NotFoundError(_skill_root_uri(ctx, skill_name), "skill")async def _list_skill_files(@@ -411,29 +550,35 @@ async def _restore_skill_privacy(@router.get("")async def list_skills(node_limit: int = 1000,+ target_uri: Optional[str] = None,_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,+ if target_uri:+ resolved_uri = resolve_path_variables(target_uri)+ skills = await _list_skills_from_root(service, _ctx, resolved_uri)+ return Response(+ status="ok", result={"root_uri": resolved_uri, "skills": skills, "total": len(skills)}+ )+ else:+ user_skills = await _list_skills_from_root(+ service, _ctx, f"{canonical_user_root(_ctx)}/skills"+ )+ agent_skills = await _list_skills_from_root(service, _ctx, "viking://agent/skills")+ # Intentionally concatenate without deduplication: when the same skill+ # name exists in both the user-private and the account-shared agent+ # scope, both entries should be visible so the caller can tell them+ # apart by ``root_uri``.+ merged_skills = [*user_skills, *agent_skills]+ return Response(+ status="ok",+ result={+ "root_uris": [f"{canonical_user_root(_ctx)}/skills", "viking://agent/skills"],+ "skills": merged_skills,+ "total": len(merged_skills),+ },)- 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)}- )@router.post("/find")@@ -443,27 +588,79 @@ async def find_skills():"""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)+ target_uri = request.target_uri+ if target_uri:+ resolved_uri = resolve_path_variables(target_uri)+ execution = await run_operation(+ operation="skills.find",+ telemetry=request.telemetry,+ fn=lambda: service.search.find(+ query=request.query,+ ctx=_ctx,+ target_uri=resolved_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": resolved_uri, "skills": hits, "total": len(hits)},+ telemetry=execution.telemetry,+ ).model_dump(exclude_none=True)+ else:+ user_root = f"{canonical_user_root(_ctx)}/skills"+ agent_root = "viking://agent/skills"++ user_execution = await run_operation(+ operation="skills.find",+ telemetry=request.telemetry,+ fn=lambda: service.search.find(+ query=request.query,+ ctx=_ctx,+ target_uri=user_root,+ limit=request.limit,+ score_threshold=request.score_threshold,+ level=request.level,+ ),+ )+ user_result = user_execution.result+ user_result_dict = user_result.to_dict() if hasattr(user_result, "to_dict") else dict(user_result or {})+ user_hits = [_skill_summary_from_hit(hit) for hit in user_result_dict.get("skills", [])]++ agent_execution = await run_operation(+ operation="skills.find",+ telemetry=request.telemetry,+ fn=lambda: service.search.find(+ query=request.query,+ ctx=_ctx,+ target_uri=agent_root,+ limit=request.limit,+ score_threshold=request.score_threshold,+ level=request.level,+ ),+ )+ agent_result = agent_execution.result+ agent_result_dict = agent_result.to_dict() if hasattr(agent_result, "to_dict") else dict(agent_result or {})+ agent_hits = [_skill_summary_from_hit(hit) for hit in agent_result_dict.get("skills", [])]++ merged_hits = [*user_hits, *agent_hits]+ # Sort merged hits by score descending if available+ if merged_hits and "score" in merged_hits[0]:+ merged_hits.sort(key=lambda x: x.get("score", 0), reverse=True)++ return Response(+ status="ok",+ result={+ "root_uris": [user_root, agent_root],+ "skills": merged_hits,+ "total": len(merged_hits),+ },+ telemetry=user_execution.telemetry,+ ).model_dump(exclude_none=True)@router.post("/validate")@@ -487,6 +684,7 @@ async def validate_skill(@router.get("/{skill_name}")async def get_skill(skill_name: str = ApiPath(..., description="Skill name"),+ target_uri: Optional[str] = None,include_content: Optional[bool] = None,include_files: bool = True,include_source: bool = False,@@ -500,7 +698,7 @@ async def get_skill(details={"field": "level", "allowed": [0, 1, 2]},)service = get_service()- root_uri = await _require_skill(service, _ctx, skill_name)+ root_uri = await _require_skill(service, _ctx, skill_name, target_uri)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:@@ -540,7 +738,7 @@ async def update_skill():"""Replace an existing agent skill with new content."""service = get_service()- root_uri = await _require_skill(service, _ctx, skill_name)+ root_uri = await _require_skill(service, _ctx, skill_name, request.target_uri)data = request.dataallow_local_path_resolution = False@@ -569,7 +767,9 @@ async def update_skill(store = TempUploadStore.build(http_request.app.state.config) if resolved else Noneasync def _update() -> Dict[str, Any]:- backup_uri = f"{_agent_skills_root(_ctx)}/.{skill_name}.update-backup-{uuid.uuid4().hex}"+ # Derive backup root from the actual skill root URI to keep backup in the same scope.+ skill_root_parent = root_uri.rsplit("/", 1)[0]+ backup_uri = f"{skill_root_parent}/.{skill_name}.update-backup-{uuid.uuid4().hex}"backup_created = Falseprivacy_update_attempted = Falseprevious_privacy = None@@ -604,6 +804,7 @@ async def update_skill(source_path_hint=source_path_hint,apply_privacy=False,privacy_change_reason="auto-extracted from update_skill",+ target_uri=skill_root_parent,)await persist_skill_source_metadata(service, _ctx, result, source_metadata)privacy_update_attempted = True@@ -660,11 +861,12 @@ async def update_skill(@router.delete("/{skill_name}")async def delete_skill(skill_name: str = ApiPath(..., description="Skill name"),+ target_uri: Optional[str] = None,_ctx: RequestContext = Depends(get_request_context),):"""Remove one installed agent skill."""service = get_service()- root_uri = await _require_skill(service, _ctx, skill_name)+ root_uri = await _require_skill(service, _ctx, skill_name, target_uri)result = await service.fs.rm(root_uri, ctx=_ctx, recursive=True)privacy_deleted = Falseprivacy = service.privacy_configsdiff --git a/openviking/service/legacy_migration.py b/openviking/service/legacy_migration.pyindex 7350dac6e..aa267257a 100644--- a/openviking/service/legacy_migration.py+++ b/openviking/service/legacy_migration.py@@ -20,6 +20,13 @@ from openviking_cli.exceptions import FailedPreconditionErrorfrom openviking_cli.session.user_id import UserIdentifier, validate_user_id+# Reserved sub-directories of viking://agent/ that belong to the new public+# scope layout (skills, endpoints, tools, payments). They must not be treated+# as legacy ``agent_id`` directories by either the migration planner or the+# cleanup planner.+_AGENT_RESERVED_SUBDIRS = frozenset({"skills", "endpoints", "tools", "payments"})++@dataclass(frozen=True)class TreeCopy:source_path: str@@ -210,7 +217,15 @@ class LegacyDataMigration:for account_id in sorted(await self._physical_account_ids()):agent_path = f"/local/{account_id}/agent"if await self._exists(agent_path):- plan.targets.append(self._cleanup_target(account_id, agent_path, "agent"))+ for entry in await self._ls(agent_path):+ if not entry["is_dir"]:+ continue+ if entry["name"] in _AGENT_RESERVED_SUBDIRS:+ continue+ legacy_path = f"{agent_path}/{entry['name']}"+ plan.targets.append(+ self._cleanup_target(account_id, legacy_path, "agent")+ )session_path = f"/local/{account_id}/session"if await self._exists(session_path):@@ -414,6 +429,8 @@ class LegacyDataMigration:if not agent_entry["is_dir"]:continueagent_id = agent_entry["name"]+ if agent_id in _AGENT_RESERVED_SUBDIRS:+ continueuser_root = f"{agent_root}/{agent_id}/user"for user_entry in await self._ls(user_root):if not user_entry["is_dir"]:@@ -436,6 +453,8 @@ class LegacyDataMigration:if not agent_entry["is_dir"]:continueagent_id = agent_entry["name"]+ if agent_id in _AGENT_RESERVED_SUBDIRS:+ continuesource_agent_path = f"{agent_root}/{agent_id}"if not user_ids:plan.warnings.append(diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.pyindex e3fd0c1b3..34835f6f6 100644--- a/openviking/service/reindex_executor.py+++ b/openviking/service/reindex_executor.py@@ -195,8 +195,21 @@ class ReindexExecutor:if classification.is_user_namespace_root:return "user_namespace"if parts[0] == "agent":+ if len(parts) >= 2 and parts[1] in {"skills", "endpoints", "tools", "payments"}:+ if classification.is_skill_namespace:+ return "skill_namespace"+ if classification.is_skill_root:+ return "skill"+ if classification.is_skill:+ raise OpenVikingError(+ f"Unsupported reindex URI: {uri}",+ code="UNSUPPORTED_URI",+ details={"uri": uri},+ )+ return "resource"raise OpenVikingError(- "viking://agent is deprecated; use viking://user instead.",+ "viking://agent/{agent_id}/... is no longer supported; "+ "use viking://agent/skills/... or viking://user/... instead.",code="UNSUPPORTED_URI",details={"uri": uri},)diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 3d6b5e0c7..c06d298a9 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -1037,6 +1037,7 @@ class ResourceService:source_path_hint: Optional[str] = None,apply_privacy: bool = True,privacy_change_reason: str = "auto-extracted from add_skill",+ target_uri: Optional[str] = None,) -> Dict[str, Any]:"""Add skill to OpenViking.@@ -1044,6 +1045,7 @@ class ResourceService:data: Skill data (directory path, file path, string, or dict)wait: Whether to wait for vectorization to completetimeout: Wait timeout in seconds+ target_uri: Optional root URI override (e.g. ``viking://agent/skills``).Returns:Processing result@@ -1063,6 +1065,7 @@ class ResourceService:ctx=ctx,apply_privacy=apply_privacy,privacy_change_reason=privacy_change_reason,+ target_uri=target_uri,)else:result = await self._skill_processor.process_skill(@@ -1073,6 +1076,7 @@ class ResourceService:source_path_hint=source_path_hint,apply_privacy=apply_privacy,privacy_change_reason=privacy_change_reason,+ target_uri=target_uri,)if isinstance(result, dict) and "root_uri" not in result and result.get("uri"):result["root_uri"] = result["uri"]diff --git a/openviking/session/skill/session_skill_context_provider.py b/openviking/session/skill/session_skill_context_provider.pyindex 52e85e068..3870fa941 100644--- a/openviking/session/skill/session_skill_context_provider.py+++ b/openviking/session/skill/session_skill_context_provider.py@@ -97,48 +97,61 @@ class SessionSkillContextProvider(SessionExtractContextProvider):if not self._ctx or not self._viking_fs:return pre_fetch_messages- skill_root_uri = f"{canonical_user_root(self._ctx)}/skills"- try:- entries = await self._viking_fs.ls(- skill_root_uri,- output="agent",- abs_limit=256,- show_all_hidden=False,- node_limit=1000,- ctx=self._ctx,- )- listed_skills = []- for entry in entries:- if not entry.get("isDir", False):- continue- skill_root = (- entry.get("uri") or f"{skill_root_uri.rstrip('/')}/{entry.get('name', '')}"+ user_skill_root = f"{canonical_user_root(self._ctx)}/skills"+ agent_skill_root = "viking://agent/skills"+ skill_roots = [user_skill_root, agent_skill_root]++ listed_skills: List[Dict[str, Any]] = []+ seen_names: set[str] = set()+ errors: Dict[str, str] = {}+ for skill_root_uri in skill_roots:+ try:+ entries = await self._viking_fs.ls(+ skill_root_uri,+ output="agent",+ abs_limit=256,+ show_all_hidden=False,+ node_limit=1000,+ ctx=self._ctx,)- skill_name = entry.get("name") or skill_root.rstrip("/").split("/")[-1]- listed_skills.append(- {- "skill_name": skill_name,- "uri": f"{skill_root.rstrip('/')}/SKILL.md",- "abstract": entry.get("abstract", ""),- }- )- add_tool_call_pair_to_messages(- messages=pre_fetch_messages,- call_id=0,- tool_name="ls",- params={"uri": skill_root_uri},- result=listed_skills- if listed_skills- else "Directory is empty. You can create a new skill if the conversation shows a reusable workflow.",- )- except Exception as exc:- add_tool_call_pair_to_messages(- messages=pre_fetch_messages,- call_id=0,- tool_name="ls",- params={"uri": skill_root_uri},- result={"error": str(exc)},+ for entry in entries:+ if not entry.get("isDir", False):+ continue+ skill_root = (+ entry.get("uri")+ or f"{skill_root_uri.rstrip('/')}/{entry.get('name', '')}"+ )+ skill_name = entry.get("name") or skill_root.rstrip("/").split("/")[-1]+ if skill_name in seen_names:+ continue+ seen_names.add(skill_name)+ listed_skills.append(+ {+ "skill_name": skill_name,+ "uri": f"{skill_root.rstrip('/')}/SKILL.md",+ "abstract": entry.get("abstract", ""),+ }+ )+ except Exception as exc:+ errors[skill_root_uri] = str(exc)++ if listed_skills:+ tool_result: Any = listed_skills+ elif errors:+ tool_result = {"error": errors}+ else:+ tool_result = (+ "Directory is empty. You can create a new skill if the conversation "+ "shows a reusable workflow.")++ add_tool_call_pair_to_messages(+ messages=pre_fetch_messages,+ call_id=0,+ tool_name="ls",+ params={"uri": skill_roots},+ result=tool_result,+ )return pre_fetch_messagesasync def execute_tool(self, tool_call) -> Any:diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.pyindex 1ea9df3ca..0b9e58aca 100644--- a/openviking/storage/viking_fs.py+++ b/openviking/storage/viking_fs.py@@ -366,11 +366,22 @@ class VikingFS:"or current-user content path instead.",resource=normalized_uri,)- if parts and parts[0] in {"agent", "session"}:+ if parts and parts[0] == "session":raise PermissionDeniedError(f"Writing {normalized_uri} is not supported; use user-owned namespaces instead.",resource=normalized_uri,)+ if parts and parts[0] == "agent":+ if len(parts) >= 2 and parts[1] not in {"skills", "endpoints", "tools", "payments"}:+ raise PermissionDeniedError(+ f"viking://agent/{{agent_id}} is deprecated. Use viking://user/.../peers/{{agent_id}} instead.",+ resource=normalized_uri,+ )+ if len(parts) < 2:+ raise PermissionDeniedError(+ "Writing to viking://agent root is not supported.",+ resource=normalized_uri,+ )# ========== AGFS Basic Commands ==========@@ -2239,7 +2250,8 @@ class VikingFS:real_ctx = self._ctx_or_default(ctx)account_id = real_ctx.account_idnormalized_uri, legacy_parts = self._normalized_uri_parts(uri)- if legacy_parts and legacy_parts[0] == "agent":+ if legacy_parts and legacy_parts[0] == "agent" and self._is_legacy_agent_id_uri(uri):+ # Old format: viking://agent/{agent_id}/... — direct mapping for read-only compatsafe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in legacy_parts]@@ -2279,17 +2291,17 @@ class VikingFS:_, parts = self._normalized_uri_parts(uri)return parts == ["session"]- def _is_legacy_agent_uri(self, uri: str) -> bool:+ def _is_legacy_agent_id_uri(self, uri: str) -> bool:_, parts = self._normalized_uri_parts(uri)- return bool(parts and parts[0] == "agent")+ return bool(+ parts and parts[0] == "agent"+ and len(parts) >= 2+ and parts[1] not in {"skills", "endpoints", "tools", "payments"}+ )def _read_paths(self, uri: str, ctx: Optional[RequestContext] = None) -> List[str]:"""Return read candidates for a URI, including legacy alias fallbacks."""paths = [self._uri_to_path(uri, ctx=ctx)]- for alias_uri in self._legacy_agent_alias_uris(uri, ctx=ctx):- alias_path = self._uri_to_path(alias_uri, ctx=ctx)- if alias_path not in paths:- paths.append(alias_path)if self._is_legacy_session_uri(uri):for candidate in (@@ -2300,35 +2312,6 @@ class VikingFS:paths.append(candidate)return paths- def _legacy_agent_alias_uris(- self,- uri: str,- ctx: Optional[RequestContext] = None,- ) -> List[str]:- """Return migrated user/peer URI aliases for a legacy viking://agent URI."""- _, parts = self._normalized_uri_parts(uri)- if not parts or parts[0] != "agent":- return []-- user_root = canonical_user_root(self._ctx_or_default(ctx))- if len(parts) == 1:- return [f"{user_root}/peers"]-- agent_id = parts[1]- suffix = parts[2:]- if not suffix:- return [f"{user_root}/peers/{agent_id}"]-- if suffix[0] in {"memories", "resources"}:- return [f"{user_root}/peers/{agent_id}/{'/'.join(suffix)}"]- if suffix[0] == "skills":- skill_suffix = suffix[1:]- skill_uri = f"{user_root}/skills"- if skill_suffix:- skill_uri = f"{skill_uri}/{'/'.join(skill_suffix)}"- return [skill_uri]- return []-async def _read_path_visible(self,request_uri: str,@@ -2351,7 +2334,20 @@ class VikingFS:ctx: Optional[RequestContext],) -> str:normalized_request, request_parts = self._normalized_uri_parts(request_uri)- if not request_parts or request_parts[0] not in {"agent", "session"}:+ # Only legacy namespaces need alias remapping:+ # - Old format viking://agent/{agent_id}/...+ # - viking://session/...+ is_legacy_namespace = (+ request_parts+ and (+ request_parts[0] == "session"+ or (+ request_parts[0] == "agent"+ and self._is_legacy_agent_id_uri(request_uri)+ )+ )+ )+ if not is_legacy_namespace:return self._path_to_uri(entry_path, ctx=ctx)base = base_path.rstrip("/")rel_path = entry_path[len(base) :].strip("/") if entry_path.startswith(base) else ""@@ -2512,7 +2508,7 @@ class VikingFS:return await self._session_root_items(uri, real_ctx)primary_path = self._uri_to_path(uri, ctx=ctx)- merge_paths = self._is_legacy_agent_uri(uri)+ merge_paths = self._is_legacy_session_uri(uri)found_path = Falselast_not_found: Optional[Exception] = Noneby_uri: Dict[str, tuple[Dict[str, Any], str]] = {}@@ -2620,15 +2616,15 @@ class VikingFS:if scope == "_system":return Falseif scope == "agent":- return self._is_legacy_agent_accessible(parts, ctx)+ # New format: agent/skills/..., agent/endpoints/... — globally readable (account scope)+ if len(parts) >= 2 and parts[1] in {"skills", "endpoints", "tools", "payments"}:+ return True+ # Old format: agent/{agent_id}/... — actor_peer_id match for read-only access+ if not ctx.actor_peer_id or len(parts) < 2:+ return True+ return parts[1] == ctx.actor_peer_idreturn namespace_is_accessible(normalized_uri, ctx)- @staticmethod- def _is_legacy_agent_accessible(parts: List[str], ctx: RequestContext) -> bool:- if not ctx.actor_peer_id or len(parts) < 2:- return True- return parts[1] == ctx.actor_peer_id-def _handle_agfs_read(self, result: Union[bytes, Any, None]) -> bytes:"""Handle AGFSClient read return types consistently."""if isinstance(result, bytes):diff --git a/openviking/sync_client.py b/openviking/sync_client.pyindex 877f2c5e3..1c2d1b6da 100644--- a/openviking/sync_client.py+++ b/openviking/sync_client.py@@ -243,10 +243,127 @@ class SyncOpenViking:wait: bool = False,timeout: float = None,telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:"""Add skill to OpenViking."""return run_async(- self._async_client.add_skill(data, wait=wait, timeout=timeout, telemetry=telemetry)+ self._async_client.add_skill(+ data,+ wait=wait,+ timeout=timeout,+ telemetry=telemetry,+ target_uri=target_uri,+ )+ )++ def list_skills(+ self,+ node_limit: int = 1000,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """List installed skills."""+ return run_async(+ self._async_client.list_skills(+ node_limit=node_limit,+ target_uri=target_uri,+ )+ )++ def find_skills(+ self,+ query: str,+ limit: int = 10,+ score_threshold: Optional[float] = None,+ level: Optional[List[int]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Find skills by semantic search."""+ return run_async(+ self._async_client.find_skills(+ query=query,+ limit=limit,+ score_threshold=score_threshold,+ level=level,+ telemetry=telemetry,+ target_uri=target_uri,+ )+ )++ def get_skill(+ self,+ skill_name: str,+ include_content: Optional[bool] = None,+ include_files: bool = True,+ include_source: bool = False,+ level: Optional[int] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Get a skill by name."""+ return run_async(+ self._async_client.get_skill(+ skill_name=skill_name,+ include_content=include_content,+ include_files=include_files,+ include_source=include_source,+ level=level,+ target_uri=target_uri,+ )+ )++ def update_skill(+ self,+ skill_name: str,+ data: Any,+ wait: bool = False,+ timeout: Optional[float] = None,+ source_metadata: Optional[Dict[str, Any]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Update an existing skill."""+ return run_async(+ self._async_client.update_skill(+ skill_name=skill_name,+ data=data,+ wait=wait,+ timeout=timeout,+ source_metadata=source_metadata,+ telemetry=telemetry,+ target_uri=target_uri,+ )+ )++ def delete_skill(+ self,+ skill_name: str,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Delete a skill."""+ return run_async(+ self._async_client.delete_skill(+ skill_name=skill_name,+ target_uri=target_uri,+ )+ )++ def validate_skill(+ self,+ data: Any,+ strict: bool = False,+ source_path: Optional[str] = None,+ skill_dir_name: Optional[str] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Validate skill data."""+ return run_async(+ self._async_client.validate_skill(+ data=data,+ strict=strict,+ source_path=source_path,+ skill_dir_name=skill_dir_name,+ target_uri=target_uri,+ ))def search(diff --git a/openviking/utils/skill_processor.py b/openviking/utils/skill_processor.pyindex 66d63116c..8a163bbfd 100644--- a/openviking/utils/skill_processor.py+++ b/openviking/utils/skill_processor.py@@ -118,6 +118,7 @@ class SkillProcessor:source_path_hint: Optional[str] = None,apply_privacy: bool = True,privacy_change_reason: str = "auto-extracted from add_skill",+ target_uri: Optional[str] = None,) -> Dict[str, Any]:"""Process and store a skill.@@ -126,6 +127,8 @@ class SkillProcessor:data: Skill data (directory, file path, string, or dict)viking_fs: VikingFS instance for storageuser: Username for context+ target_uri: Optional root URI override (e.g. ``viking://agent/skills``).+ When omitted, defaults to ``{user_root}/skills``.Returns:Processing result with status and metadata@@ -151,6 +154,7 @@ class SkillProcessor:ctx=ctx,apply_privacy=apply_privacy,privacy_change_reason=privacy_change_reason,+ target_uri=target_uri,)async def process_prepared_skill(@@ -161,6 +165,7 @@ class SkillProcessor:*,apply_privacy: bool = True,privacy_change_reason: str = "auto-extracted from add_skill",+ target_uri: Optional[str] = None,) -> Dict[str, Any]:config = get_openviking_config()cleanup_path = preparation.cleanup_path@@ -179,10 +184,10 @@ class SkillProcessor:)skill_abstract = self._build_skill_abstract(skill_dict)- skill_root_uri = f"{canonical_user_root(ctx)}/skills"+ effective_root_uri = self._resolve_skill_root_uri(ctx, target_uri)context = Context(- uri=f"{skill_root_uri}/{skill_dict['name']}",- parent_uri=skill_root_uri,+ uri=f"{effective_root_uri}/{skill_dict['name']}",+ parent_uri=effective_root_uri,is_leaf=False,abstract=skill_abstract,context_type=ContextType.SKILL.value,@@ -389,6 +394,35 @@ class SkillProcessor:return normalized+ @staticmethod+ def _resolve_skill_root_uri(+ ctx: RequestContext, target_uri: Optional[str]+ ) -> str:+ """Resolve the skill storage root URI.++ Defaults to the per-user private skills root. Callers may pass+ ``viking://agent/skills`` (or a future agent-scope subpath) to publish+ the skill under the account-global ``/agent`` scope.+ """+ if target_uri:+ normalized = target_uri.rstrip("/")+ if normalized.startswith("viking://agent/skills"):+ return "viking://agent/skills"+ user_root = f"{canonical_user_root(ctx)}/skills"+ if normalized == user_root.rstrip("/"):+ return user_root+ raise InvalidArgumentError(+ f"Unsupported skill root URI: {target_uri}",+ details={+ "field": "target_uri",+ "allowed": [+ f"{canonical_user_root(ctx)}/skills",+ "viking://agent/skills",+ ],+ },+ )+ return f"{canonical_user_root(ctx)}/skills"+@staticmethoddef _validate_skill_dict(skill_dict: Dict[str, Any]) -> None:"""Validate normalized skill metadata before storage/indexing."""diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.pyindex d68baa77b..c66836b3b 100644--- a/openviking_cli/client/base.py+++ b/openviking_cli/client/base.py@@ -56,10 +56,81 @@ class BaseClient(ABC):wait: bool = False,timeout: Optional[float] = None,telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:"""Add skill to OpenViking."""...+ @abstractmethod+ async def list_skills(+ self,+ node_limit: int = 1000,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """List skills."""+ ...++ @abstractmethod+ async def find_skills(+ self,+ query: str,+ limit: int = 10,+ score_threshold: Optional[float] = None,+ level: Optional[List[int]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Find skills by semantic search."""+ ...++ @abstractmethod+ async def get_skill(+ self,+ skill_name: str,+ include_content: Optional[bool] = None,+ include_files: bool = True,+ include_source: bool = False,+ level: Optional[int] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Get a skill by name."""+ ...++ @abstractmethod+ async def update_skill(+ self,+ skill_name: str,+ data: Any,+ wait: bool = False,+ timeout: Optional[float] = None,+ source_metadata: Optional[Dict[str, Any]] = None,+ telemetry: TelemetryRequest = False,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Update an existing skill."""+ ...++ @abstractmethod+ async def delete_skill(+ self,+ skill_name: str,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Delete a skill."""+ ...++ @abstractmethod+ async def validate_skill(+ self,+ data: Any,+ strict: bool = False,+ source_path: Optional[str] = None,+ skill_dir_name: Optional[str] = None,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Validate skill data."""+ ...+@abstractmethodasync def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:"""Wait for all processing to complete."""diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.pyindex aac1a1858..81fb24ae5 100644--- a/openviking_cli/utils/uri.py+++ b/openviking_cli/utils/uri.py@@ -22,7 +22,7 @@ class VikingURI:- user: User scope (viking://user/...), including sessions underviking://user/{user_id}/sessions/{session_id}- session: Legacy alias for user sessions (viking://session/{session_id}/...)- - agent: Legacy read-only agent scope (viking://agent/{agent_id}/...)+ - agent: Agent capabilities scope (viking://agent/skills/..., viking://agent/endpoints/...)- queue: Queue scope (viking://queue/...)Examples:@@ -37,9 +37,10 @@ class VikingURI:LISTABLE_SCOPES = {"resources","user",+ "agent",}PUBLIC_SCOPES = frozenset(LISTABLE_SCOPES)- LEGACY_SCOPES = frozenset({"agent", "session"})+ LEGACY_SCOPES = frozenset({"session"})INTERNAL_SCOPES = frozenset({"temp", "queue", "upload"})# All valid scopes that can be addressed by the URI parser/storage internals.# Public API handlers must not use this as their external whitelist.diff --git a/pyproject.toml b/pyproject.tomlindex 61c51b5ab..f3d6e2463 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -17,7 +17,7 @@ requires-python = ">=3.10"authors = [{name = "ByteDance", email = "[email protected]"}]-license = { text = "AGPL-3.0" }+license = "AGPL-3.0"classifiers = ["Development Status :: 3 - Alpha","Intended Audience :: Developers",diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex c7414e670..b4419be71 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -463,8 +463,11 @@ class AsyncHTTPClient:wait: bool = False,timeout: Optional[float] = None,telemetry: Any = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:request_data = {"wait": wait, "timeout": timeout, "telemetry": telemetry}+ if target_uri is not None:+ request_data["target_uri"] = target_uriif isinstance(data, str):path_obj = Path(data)if path_obj.exists():@@ -485,8 +488,15 @@ class AsyncHTTPClient:response = await self._http.post("/api/v1/skills", json=request_data)return self._handle_response_data(response).get("result", {})- async def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:- response = await self._http.get("/api/v1/skills", params={"node_limit": node_limit})+ async def list_skills(+ self,+ node_limit: int = 1000,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ params: Dict[str, Any] = {"node_limit": node_limit}+ if target_uri is not None:+ params["target_uri"] = target_uri+ response = await self._http.get("/api/v1/skills", params=params)return self._handle_response(response)async def find_skills(@@ -496,6 +506,7 @@ class AsyncHTTPClient:score_threshold: Optional[float] = None,level: Optional[List[int]] = None,telemetry: Any = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:payload = {"query": query,@@ -504,6 +515,8 @@ class AsyncHTTPClient:"level": level,"telemetry": telemetry,}+ if target_uri is not None:+ payload["target_uri"] = target_uriresponse = await self._http.post("/api/v1/skills/find", json=payload)return self._handle_response_data(response).get("result", {})@@ -513,12 +526,15 @@ class AsyncHTTPClient:strict: bool = False,source_path: Optional[str] = None,skill_dir_name: Optional[str] = None,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:payload: Dict[str, Any] = {"data": data, "strict": strict}if source_path is not None:payload["source_path"] = source_pathif skill_dir_name is not None:payload["skill_dir_name"] = skill_dir_name+ if target_uri is not None:+ payload["target_uri"] = target_uriresponse = await self._http.post("/api/v1/skills/validate", json=payload)return self._handle_response(response)@@ -529,6 +545,7 @@ class AsyncHTTPClient:include_files: bool = True,include_source: bool = False,level: Optional[int] = None,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:params: Dict[str, Any] = {"include_files": include_files,@@ -538,6 +555,8 @@ class AsyncHTTPClient:params["include_content"] = include_contentif level is not None:params["level"] = level+ if target_uri is not None:+ params["target_uri"] = target_uriresponse = await self._http.get(f"/api/v1/skills/{skill_name}", params=params)return self._handle_response(response)@@ -549,6 +568,7 @@ class AsyncHTTPClient:timeout: Optional[float] = None,source_metadata: Optional[Dict[str, Any]] = None,telemetry: Any = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:request_data: Dict[str, Any] = {"wait": wait,@@ -556,6 +576,8 @@ class AsyncHTTPClient:"source_metadata": source_metadata,"telemetry": telemetry,}+ if target_uri is not None:+ request_data["target_uri"] = target_uriif isinstance(data, str):path_obj = Path(data)if path_obj.exists():@@ -576,8 +598,15 @@ class AsyncHTTPClient:response = await self._http.put(f"/api/v1/skills/{skill_name}", json=request_data)return self._handle_response_data(response).get("result", {})- async def delete_skill(self, skill_name: str) -> Dict[str, Any]:- response = await self._http.delete(f"/api/v1/skills/{skill_name}")+ async def delete_skill(+ self,+ skill_name: str,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ params: Dict[str, Any] = {}+ if target_uri is not None:+ params["target_uri"] = target_uri+ response = await self._http.delete(f"/api/v1/skills/{skill_name}", params=params)return self._handle_response(response)async def list_watches(@@ -1401,13 +1430,26 @@ class SyncHTTPClient:wait: bool = False,timeout: Optional[float] = None,telemetry: Any = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:return run_async(- self._async_client.add_skill(data, wait=wait, timeout=timeout, telemetry=telemetry)+ self._async_client.add_skill(+ data,+ wait=wait,+ timeout=timeout,+ telemetry=telemetry,+ target_uri=target_uri,+ ))- def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:- return run_async(self._async_client.list_skills(node_limit=node_limit))+ def list_skills(+ self,+ node_limit: int = 1000,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ return run_async(+ self._async_client.list_skills(node_limit=node_limit, target_uri=target_uri)+ )def find_skills(self,@@ -1416,6 +1458,7 @@ class SyncHTTPClient:score_threshold: Optional[float] = None,level: Optional[List[int]] = None,telemetry: Any = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:return run_async(self._async_client.find_skills(@@ -1424,6 +1467,7 @@ class SyncHTTPClient:score_threshold=score_threshold,level=level,telemetry=telemetry,+ target_uri=target_uri,))@@ -1433,6 +1477,7 @@ class SyncHTTPClient:strict: bool = False,source_path: Optional[str] = None,skill_dir_name: Optional[str] = None,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:return run_async(self._async_client.validate_skill(@@ -1440,6 +1485,7 @@ class SyncHTTPClient:strict=strict,source_path=source_path,skill_dir_name=skill_dir_name,+ target_uri=target_uri,))@@ -1450,6 +1496,7 @@ class SyncHTTPClient:include_files: bool = True,include_source: bool = False,level: Optional[int] = None,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:return run_async(self._async_client.get_skill(@@ -1458,6 +1505,7 @@ class SyncHTTPClient:include_files=include_files,include_source=include_source,level=level,+ target_uri=target_uri,))@@ -1469,6 +1517,7 @@ class SyncHTTPClient:timeout: Optional[float] = None,source_metadata: Optional[Dict[str, Any]] = None,telemetry: Any = False,+ target_uri: Optional[str] = None,) -> Dict[str, Any]:return run_async(self._async_client.update_skill(@@ -1478,11 +1527,18 @@ class SyncHTTPClient:timeout=timeout,source_metadata=source_metadata,telemetry=telemetry,+ target_uri=target_uri,))- def delete_skill(self, skill_name: str) -> Dict[str, Any]:- return run_async(self._async_client.delete_skill(skill_name))+ def delete_skill(+ self,+ skill_name: str,+ target_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ return run_async(+ self._async_client.delete_skill(skill_name, target_uri=target_uri)+ )def list_watches(self,diff --git a/tests/cli/conftest.py b/tests/cli/conftest.pyindex 21c99344d..f0116cd28 100644--- a/tests/cli/conftest.py+++ b/tests/cli/conftest.py@@ -147,83 +147,99 @@ def _extract_user_key(users: list[object], user_id: str) -> str:def _resolve_api_key() -> str:+ """Resolve a user API key suitable for data-plane operations.++ Root keys (OPENVIKING_API_KEY/OPENVIKING_ROOT_API_KEY) cannot be used for+ data-plane operations like add-skill/ls/read. When only a root key is+ available we need to provision a regular user via admin APIs.++ Returns an empty string if we cannot obtain a valid user key; callers+ should skip tests in that case.+ """+ # Priority 1: Explicit test user key is already a user key - use directlyexplicit_user_key = os.getenv("OPENVIKING_CLI_TEST_API_KEY") or os.getenv("OPENVIKING_USER_API_KEY", "")if explicit_user_key:return explicit_user_key++ # Priority 2: If we don't have a root key, we can't provision users; return+ # CONFIGURED_API_KEY as-is (it might be a pre-provisioned user key)if not ROOT_API_KEY:return CONFIGURED_API_KEY+ # Priority 3: Use root key to provision/get a user key via admin API.+ # Retry a few times to handle server startup race conditions.account_id = CLI_ACCOUNT or "test-account"user_id = CLI_USER or "test-user"- try:- list_resp = httpx.get(- f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",- headers=_admin_headers(),- timeout=10.0,- )- if list_resp.status_code == 404:- create_resp = httpx.post(- f"{BASE_URL}/api/v1/admin/accounts",- headers=_admin_headers(),- json={"account_id": account_id, "admin_user_id": user_id},- timeout=10.0,- )- if create_resp.status_code in (200, 201):- user_key = create_resp.json().get("result", {}).get("user_key")- if isinstance(user_key, str) and user_key:- return user_key- return CONFIGURED_API_KEY-- if list_resp.status_code != 200:- return CONFIGURED_API_KEY-- users = list_resp.json().get("result", [])- if isinstance(users, list):- user_key = _extract_user_key(users, user_id)- if user_key:- return user_key- user_exists = any(- (isinstance(user, dict) and user.get("user_id") == user_id)- or (isinstance(user, str) and user == user_id)- for user in users- )- else:- user_exists = False- if not user_exists:- register_resp = httpx.post(+ for attempt in range(5):+ try:+ list_resp = httpx.get(f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",headers=_admin_headers(),- json={"user_id": user_id, "role": "admin"},timeout=10.0,)- if register_resp.status_code in (200, 201):- user_key = register_resp.json().get("result", {}).get("user_key")- if isinstance(user_key, str) and user_key:- return user_key- return CONFIGURED_API_KEY-- httpx.put(- f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/role",- headers=_admin_headers(),- json={"role": "admin"},- timeout=10.0,- )- key_resp = httpx.post(- f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/key",- headers=_admin_headers(),- json={},- timeout=10.0,- )- if key_resp.status_code == 200:- user_key = key_resp.json().get("result", {}).get("user_key")- if isinstance(user_key, str) and user_key:- return user_key- except Exception:- pass- return CONFIGURED_API_KEY+ if list_resp.status_code == 404:+ create_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts",+ headers=_admin_headers(),+ json={"account_id": account_id, "admin_user_id": user_id},+ timeout=10.0,+ )+ if create_resp.status_code in (200, 201):+ user_key = create_resp.json().get("result", {}).get("user_key")+ if isinstance(user_key, str) and user_key:+ return user_key+ elif list_resp.status_code == 200:+ users = list_resp.json().get("result", [])+ if isinstance(users, list):+ user_key = _extract_user_key(users, user_id)+ if user_key:+ return user_key+ user_exists = any(+ (isinstance(user, dict) and user.get("user_id") == user_id)+ or (isinstance(user, str) and user == user_id)+ for user in users+ )+ else:+ user_exists = False++ if not user_exists:+ register_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",+ headers=_admin_headers(),+ json={"user_id": user_id, "role": "admin"},+ timeout=10.0,+ )+ if register_resp.status_code in (200, 201):+ user_key = register_resp.json().get("result", {}).get("user_key")+ if isinstance(user_key, str) and user_key:+ return user_key+ else:+ httpx.put(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/role",+ headers=_admin_headers(),+ json={"role": "admin"},+ timeout=10.0,+ )+ key_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/key",+ headers=_admin_headers(),+ json={},+ timeout=10.0,+ )+ if key_resp.status_code == 200:+ user_key = key_resp.json().get("result", {}).get("user_key")+ if isinstance(user_key, str) and user_key:+ return user_key+ except Exception:+ pass+ time.sleep(2)++ # Failed to provision a user key after retries - return empty string+ # rather than falling back to root key (which doesn't work for data plane)+ return ""API_KEY = _resolve_api_key()@@ -321,10 +337,11 @@ CLI_COMPATIBLE = _check_cli_compatible()def pytest_collection_modifyitems(config, items):+ skip_reason = Noneif not CLI_COMPATIBLE:- reason = "openviking CLI not available"+ skip_reason = "openviking CLI not available"if CLI_BIN is None:- reason = "openviking CLI binary not found. Install via: curl -fsSL http://openviking.tos-cn-beijing.volces.com/cli/install.sh | bash"+ skip_reason = "openviking CLI binary not found. Install via: curl -fsSL http://openviking.tos-cn-beijing.volces.com/cli/install.sh | bash"else:try:result = subprocess.run(@@ -335,10 +352,14 @@ def pytest_collection_modifyitems(config, items):env=_env(),)if "GLIBC" in result.stderr:- reason = "openviking CLI binary is not compatible with this system (GLIBC version mismatch)"+ skip_reason = "openviking CLI binary is not compatible with this system (GLIBC version mismatch)"except Exception:pass- skip_cli = pytest.mark.skip(reason=reason)+ elif not API_KEY:+ skip_reason = "Could not obtain a valid user API key for data-plane operations"++ if skip_reason:+ skip_cli = pytest.mark.skip(reason=skip_reason)for item in items:if item.get_closest_marker("cli_remote"):item.add_marker(skip_cli)@@ -367,6 +388,33 @@ def _parse_cli_json(stdout):return None+def is_cli_auth_error(result: dict) -> bool:+ """Check if a CLI result indicates an authentication error.++ Matches both raw API errors (UNAUTHENTICATED/Unauthorized) and the+ user-friendly Rust CLI error card ("Authentication Error" / "rejected the API key").+ """+ stderr = (result.get("stderr") or "").lower()+ stdout = (result.get("stdout") or "").lower()+ combined = stderr + " " + stdout+ auth_markers = [+ "unauthenticated",+ "authentication error",+ "rejected the api key",+ "unauthorized",+ "forbidden",+ "invalid api key",+ "api key invalid",+ ]+ return any(marker in combined for marker in auth_markers)+++def skip_if_auth_error(result: dict) -> None:+ """Skip the test if the result indicates an authentication error."""+ if is_cli_auth_error(result):+ pytest.skip("Upstream API authentication unavailable")++def _inject_global_args(args):global_args = []if CLI_ACCOUNT:@@ -397,38 +445,105 @@ def ov(args, timeout=120):}-def ov_add_resource(path, to_uri, *extra_args):- return ov(- [- "add-resource",- path,- "--to",- to_uri,- *extra_args,- "--wait",- "--timeout",- ADD_RESOURCE_WAIT_TIMEOUT,- "-o",- "json",- ],- timeout=ADD_RESOURCE_COMMAND_TIMEOUT,+def _is_retryable_api_error(result: dict) -> bool:+ """Check if a CLI error is retryable (resource busy, conflict, network issue)."""+ if is_cli_auth_error(result):+ return False+ stderr = (result.get("stderr") or "").lower()+ stdout = (result.get("stdout") or "").lower()+ combined = stderr + " " + stdout+ retryable_markers = [+ "conflict",+ "resource is busy",+ "busy",+ "network error",+ "connection error",+ "could not reach openviking",+ "timeout",+ "temporarily unavailable",+ ]+ return any(marker in combined for marker in retryable_markers)+++def _retry_cli_call(args, *, attempts=15, interval=10, timeout=120):+ """Generic CLI call retry helper for write operations.++ Retries on CONFLICT/busy/network errors, skips on auth errors,+ returns immediately on non-retryable errors.+ """+ r = None+ for _attempt in range(attempts):+ r = ov(args, timeout=timeout)+ if r["exit_code"] == 0:+ return r+ skip_if_auth_error(r)+ if _is_retryable_api_error(r):+ time.sleep(interval)+ continue+ # Non-retryable error, return immediately+ return r+ return r+++def ov_add_resource(path, to_uri, *extra_args, attempts=15, interval=10):+ """Add a resource with retries for CONFLICT/busy/network errors."""+ args = [+ "add-resource",+ path,+ "--to",+ to_uri,+ *extra_args,+ "--wait",+ "--timeout",+ ADD_RESOURCE_WAIT_TIMEOUT,+ "-o",+ "json",+ ]+ return _retry_cli_call(+ args, attempts=attempts, interval=interval, timeout=ADD_RESOURCE_COMMAND_TIMEOUT)+def ov_add_skill(path, *extra_args, attempts=15, interval=10):+ """Add a skill with retries for CONFLICT/busy/network errors."""+ args = [+ "add-skill",+ path,+ *extra_args,+ "--wait",+ "-o",+ "json",+ ]+ return _retry_cli_call(args, attempts=attempts, interval=interval, timeout=120)+++def ov_mkdir(uri, *extra_args, attempts=15, interval=5):+ """Create a directory with retries for CONFLICT/busy/network errors."""+ args = ["mkdir", uri, *extra_args, "-o", "json"]+ return _retry_cli_call(args, attempts=attempts, interval=interval, timeout=120)++def ov_retry(args, *, attempts=5, interval=5, timeout=120, retry_if=None):r = Nonefor attempt in range(attempts):r = ov(args, timeout=timeout)if r["exit_code"] == 0:return r- if retry_if is not None and not retry_if(r):+ skip_if_auth_error(r)+ # Determine if we should retry+ should_retry = True+ if retry_if is not None:+ should_retry = retry_if(r)+ else:+ should_retry = _is_retryable_api_error(r)+ if not should_retry:return rif attempt < attempts - 1:time.sleep(interval)return r-def ov_rm(uri, *, recursive=True, attempts=5, interval=3):+def ov_rm(uri, *, recursive=True, attempts=15, interval=5):args = ["rm", uri, "-o", "json"]if recursive:args.insert(2, "-r")@@ -494,39 +609,36 @@ def _find_file_in_pack(pack_uri, retries=10, interval=5):@pytest.fixture(scope="session", autouse=True)def ensure_resources_dir():- r = ov(["mkdir", "viking://resources", "-o", "json"], timeout=120)- if r["exit_code"] != 0 and "already exists" not in r["stderr"].lower():+ r = ov_mkdir("viking://resources")+ if r["exit_code"] != 0:+ if "already exists" in (r.get("stderr") or "").lower():+ return+ skip_if_auth_error(r)r2 = ov(["stat", "viking://resources", "-o", "json"])if r2["exit_code"] != 0:- pass+ skip_if_auth_error(r2)+ pytest.fail(f"Failed to create resources dir: {r['stderr'][:300]}")@pytest.fixture(scope="session")def ensure_user_skills_dir():uri = "viking://user/skills"- for _attempt in range(5):- r = ov(["mkdir", uri, "-o", "json"], timeout=120)- if r["exit_code"] == 0 or "already exists" in (r.get("stderr") or "").lower():- return-- stat_r = ov(["stat", uri, "-o", "json"], timeout=120)- if stat_r["exit_code"] == 0:- return-- time.sleep(5)- assert r["exit_code"] == 0, f"mkdir {uri} failed after retries: {r['stderr']}"+ r = ov_mkdir(uri)+ if r["exit_code"] == 0 or "already exists" in (r.get("stderr") or "").lower():+ return+ skip_if_auth_error(r)+ stat_r = ov(["stat", uri, "-o", "json"], timeout=120)+ if stat_r["exit_code"] == 0:+ return+ skip_if_auth_error(stat_r)+ pytest.fail(f"mkdir {uri} failed after retries: {r['stderr'][:300]}")@pytest.fixture(scope="session")def test_dir_uri(ensure_resources_dir):uri = f"viking://resources/cli_test_{uuid.uuid4().hex[:8]}"- r = None- for _attempt in range(5):- r = ov(["mkdir", uri, "-o", "json"], timeout=120)- if r["exit_code"] == 0:- break- time.sleep(5)- assert r["exit_code"] == 0, f"mkdir failed after retries: {r['stderr']}"+ r = ov_mkdir(uri)+ assert r["exit_code"] == 0, f"mkdir failed after retries: {r['stderr'][:300]}"yield uriov_rm(uri, attempts=10, interval=5)@@ -538,15 +650,7 @@ def test_pack_uri(test_dir_uri):temp_path = f.nametry:pack_uri = f"{test_dir_uri}/test_pack"- r = None- for _attempt in range(10):- r = ov_add_resource(temp_path, pack_uri)- if r["exit_code"] == 0:- break- if "CONFLICT" in (r.get("stderr") or "") or "busy" in (r.get("stderr") or "").lower():- time.sleep(10)- else:- time.sleep(5)+ r = ov_add_resource(temp_path, pack_uri)assert r["exit_code"] == 0, f"add-resource failed after retries: {r['stderr']}"finally:os.unlink(temp_path)diff --git a/tests/cli/test_cli_content.py b/tests/cli/test_cli_content.pyindex f7f7244d6..a552fdbb5 100644--- a/tests/cli/test_cli_content.py+++ b/tests/cli/test_cli_content.py@@ -4,7 +4,6 @@import osimport tempfile-import timeimport uuidimport pytest@@ -79,18 +78,7 @@ class TestContentReindex:f.write("# Reindex Test\n\nThis is an independent resource for reindex testing.")temp_path = f.nametry:- r = None- for _attempt in range(10):- r = ov_add_resource(temp_path, reindex_pack)- if r["exit_code"] == 0:- break- if (- "CONFLICT" in (r.get("stderr") or "")- or "busy" in (r.get("stderr") or "").lower()- ):- time.sleep(10)- else:- time.sleep(5)+ r = ov_add_resource(temp_path, reindex_pack)assert r["exit_code"] == 0, f"add-resource for reindex failed: {r['stderr'][:300]}"finally:os.unlink(temp_path)diff --git a/tests/cli/test_cli_filesystem.py b/tests/cli/test_cli_filesystem.pyindex edc261bc2..688dfab18 100644--- a/tests/cli/test_cli_filesystem.py+++ b/tests/cli/test_cli_filesystem.py@@ -7,7 +7,7 @@ import tempfileimport uuidimport pytest-from conftest import ov, ov_add_resource, ov_mv, ov_rm+from conftest import ov, ov_add_resource, ov_mkdir, ov_mv, ov_rmpytestmark = pytest.mark.cli_remote@@ -88,7 +88,7 @@ class TestFsStat:class TestFsMkdir:def test_mkdir(self, test_dir_uri):sub_dir = f"{test_dir_uri}/mkdir_test"- r = ov(["mkdir", sub_dir, "-o", "json"])+ r = ov_mkdir(sub_dir)assert r["exit_code"] == 0, (f"ov mkdir should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -99,7 +99,7 @@ class TestFsMkdir:def test_mkdir_with_description(self, test_dir_uri):sub_dir = f"{test_dir_uri}/mkdir_desc"- r = ov(["mkdir", sub_dir, "--description", "CLI test directory", "-o", "json"])+ r = ov_mkdir(sub_dir, "--description", "CLI test directory")assert r["exit_code"] == 0, (f"ov mkdir with description should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -109,7 +109,7 @@ class TestFsMkdir:class TestFsRm:def test_rm_directory(self, test_dir_uri):sub_dir = f"{test_dir_uri}/rm_test"- ov(["mkdir", sub_dir, "-o", "json"])+ ov_mkdir(sub_dir)r = ov_rm(sub_dir)assert r["exit_code"] == 0, (f"ov rm should exit 0, got {r['exit_code']}: {r['stderr'][:300]}"diff --git a/tests/cli/test_cli_resources.py b/tests/cli/test_cli_resources.pyindex dee82c81e..869f4f05c 100644--- a/tests/cli/test_cli_resources.py+++ b/tests/cli/test_cli_resources.py@@ -4,11 +4,10 @@import osimport tempfile-import timeimport uuidimport pytest-from conftest import ov, ov_add_resource+from conftest import ov_add_resourcepytestmark = pytest.mark.cli_remote@@ -20,19 +19,7 @@ class TestAddResource:temp_path = f.nametry:to_uri = f"{test_dir_uri}/res_{uuid.uuid4().hex[:6]}"- r = None- for _attempt in range(5):- r = ov_add_resource(temp_path, to_uri)- if r["exit_code"] == 0:- break- if "CONFLICT" in (r.get("stderr") or "") or "Network error" in (- r.get("stderr") or ""- ):- time.sleep(10)- else:- time.sleep(5)- if r["exit_code"] != 0 and "Network error" in (r.get("stderr") or ""):- pytest.skip("OpenViking server unreachable")+ r = ov_add_resource(temp_path, to_uri)assert r["exit_code"] == 0, (f"add-resource should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -52,56 +39,13 @@ class TestAddResource:finally:os.unlink(temp_path)--class TestAddSkill:- def test_add_skill_from_file(self):- with tempfile.NamedTemporaryFile(suffix=".md", delete=False, mode="w") as f:- f.write(- "---\nname: cli_test_skill\ndescription: A test skill for CLI automation\n---\n# CLI Test Skill\n\nThis is a test skill for CLI automation."- )- temp_path = f.name- try:- r = None- for _attempt in range(5):- r = ov(["add-skill", temp_path, "--wait", "-o", "json"], timeout=120)- if r["exit_code"] == 0:- break- if "UNAUTHENTICATED" in (r.get("stderr") or ""):- pytest.skip("Upstream API authentication unavailable")- time.sleep(5)- assert r["exit_code"] == 0, (- f"add-skill from file should exit 0, got {r['exit_code']}: {r['stderr'][:300]}"- )- data = r["json"]- assert data is not None, "add-skill should return JSON"- assert data.get("ok") is True, f"Expected ok=true, got {data.get('ok')}"- assert "result" in data, "'result' field should exist"- result = data["result"]- assert "root_uri" in result, (- f"add-skill result should contain root_uri, got keys: {sorted(result.keys())}"- )- finally:- os.unlink(temp_path)-def test_add_resource_with_reason(self, test_dir_uri):with tempfile.NamedTemporaryFile(suffix=".txt", delete=False, mode="w") as f:f.write("CLI test: add resource with reason")temp_path = f.nametry:to_uri = f"{test_dir_uri}/reason_{uuid.uuid4().hex[:6]}"- r = None- for _attempt in range(5):- r = ov_add_resource(temp_path, to_uri, "--reason", "CLI test reason")- if r["exit_code"] == 0:- break- if "CONFLICT" in (r.get("stderr") or "") or "Network error" in (- r.get("stderr") or ""- ):- time.sleep(10)- else:- time.sleep(5)- if r["exit_code"] != 0 and "Network error" in (r.get("stderr") or ""):- pytest.skip("OpenViking server unreachable")+ r = ov_add_resource(temp_path, to_uri, "--reason", "CLI test reason")assert r["exit_code"] == 0, (f"add-resource with reason should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")diff --git a/tests/cli/test_cli_search.py b/tests/cli/test_cli_search.pyindex 5d4f3a3e9..c181f55d4 100644--- a/tests/cli/test_cli_search.py+++ b/tests/cli/test_cli_search.py@@ -2,10 +2,8 @@# SPDX-License-Identifier: AGPL-3.0"""CLI search operation tests (find, search, grep, glob)."""-import time-import pytest-from conftest import ov+from conftest import ov, skip_if_auth_errorpytestmark = pytest.mark.cli_remote@@ -13,8 +11,7 @@ pytestmark = pytest.mark.cli_remoteclass TestSearchFind:def test_find_basic(self):r = ov(["find", "test", "-o", "json", "-n", "5"], timeout=180)- if r["exit_code"] != 0 and "UNAUTHENTICATED" in (r.get("stderr") or ""):- pytest.skip("Upstream API authentication unavailable")+ skip_if_auth_error(r)assert r["exit_code"] == 0, (f"ov find should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -30,8 +27,7 @@ class TestSearchFind:def test_find_with_uri(self, test_dir_uri):r = ov(["find", "test", "-u", test_dir_uri, "-o", "json", "-n", "5"], timeout=180)- if r["exit_code"] != 0 and "UNAUTHENTICATED" in (r.get("stderr") or ""):- pytest.skip("Upstream API authentication unavailable")+ skip_if_auth_error(r)assert r["exit_code"] == 0, (f"ov find with uri should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -42,8 +38,7 @@ class TestSearchFind:class TestSearchSearch:def test_search_basic(self):r = ov(["search", "test", "-o", "json", "-n", "5"], timeout=180)- if r["exit_code"] != 0 and "UNAUTHENTICATED" in (r.get("stderr") or ""):- pytest.skip("Upstream API authentication unavailable")+ skip_if_auth_error(r)assert r["exit_code"] == 0, (f"ov search should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -57,8 +52,7 @@ class TestSearchSearch:["search", "test", "--session-id", test_session_id, "-o", "json", "-n", "5"],timeout=180,)- if r["exit_code"] != 0 and "UNAUTHENTICATED" in (r.get("stderr") or ""):- pytest.skip("Upstream API authentication unavailable")+ skip_if_auth_error(r)assert r["exit_code"] == 0, (f"ov search with session should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")diff --git a/tests/cli/test_cli_skills.py b/tests/cli/test_cli_skills.pyindex ad2ef9c55..7f7f670f6 100644--- a/tests/cli/test_cli_skills.py+++ b/tests/cli/test_cli_skills.py@@ -4,11 +4,10 @@import osimport tempfile-import timeimport uuidimport pytest-from conftest import ov+from conftest import ov, ov_add_skillpytestmark = pytest.mark.cli_remote@@ -23,14 +22,7 @@ class TestSkillAdd:)temp_path = f.nametry:- r = None- for _attempt in range(5):- r = ov(["add-skill", temp_path, "--wait", "-o", "json"], timeout=120)- if r["exit_code"] == 0:- break- if "UNAUTHENTICATED" in (r.get("stderr") or ""):- pytest.skip("Upstream API authentication unavailable")- time.sleep(5)+ r = ov_add_skill(temp_path)assert r["exit_code"] == 0, (f"add-skill from file should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -45,31 +37,6 @@ class TestSkillAdd:finally:os.unlink(temp_path)- def test_add_skill_with_reason(self):- skill_name = f"cli_test_skill_reason_{uuid.uuid4().hex[:6]}"- with tempfile.NamedTemporaryFile(suffix=".md", delete=False, mode="w") as f:- f.write(- f"---\nname: {skill_name}\ndescription: A test skill with reason\n---\n"- f"# {skill_name}\n\nThis is a test skill with reason."- )- temp_path = f.name- try:- r = None- for _attempt in range(5):- r = ov(["add-skill", temp_path, "--wait", "-o", "json"], timeout=120)- if r["exit_code"] == 0:- break- if "UNAUTHENTICATED" in (r.get("stderr") or ""):- pytest.skip("Upstream API authentication unavailable")- time.sleep(5)- assert r["exit_code"] == 0, (- f"add-skill should exit 0, got {r['exit_code']}: {r['stderr'][:300]}"- )- data = r["json"]- assert data is not None and data.get("ok") is True, "Expected ok=true"- finally:- os.unlink(temp_path)-class TestSkillList:def test_list_skills(self, ensure_user_skills_dir):diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.pyindex 7f8312532..6eb9e7094 100644--- a/tests/unit/test_namespace_uri_classification.py+++ b/tests/unit/test_namespace_uri_classification.py@@ -115,7 +115,10 @@ def test_session_uri_helpers_use_user_namespace():assert is_session_uri("viking://user/alice/sessions/s1")assert is_session_uri("viking://user/sessions/s1")assert is_session_uri("viking://session/s1")- assert "viking://session" not in visible_roots(ctx)+ roots = visible_roots(ctx)+ assert "viking://session" not in roots+ assert "viking://agent" not in roots+ assert "viking://agent/skills" in rootsdef test_current_user_short_content_roots_are_canonicalized_from_content_segments():