Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(openviking): Add User-Level Skill Privacy Configuration Capability (#1745)

DuTaobb515b1007d7
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 687de73c2..b69fb4fd4 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -1032,6 +1032,75 @@ impl HttpClient {
Ok(count)
}
+
+ // ============ Privacy Config Methods ============
+
+ pub async fn privacy_list_categories(&self) -> Result<serde_json::Value> {
+ self.get("/api/v1/privacy-configs", &[]).await
+ }
+
+ pub async fn privacy_list_targets(&self, category: &str) -> Result<serde_json::Value> {
+ let path = format!("/api/v1/privacy-configs/{}", category);
+ self.get(&path, &[]).await
+ }
+
+ pub async fn privacy_get_current(
+ &self,
+ category: &str,
+ target_key: &str,
+ ) -> Result<serde_json::Value> {
+ let path = format!("/api/v1/privacy-configs/{}/{}", category, target_key);
+ self.get(&path, &[]).await
+ }
+
+ pub async fn privacy_upsert(
+ &self,
+ category: &str,
+ target_key: &str,
+ body: &serde_json::Value,
+ ) -> Result<serde_json::Value> {
+ let path = format!("/api/v1/privacy-configs/{}/{}", category, target_key);
+ self.post(&path, body).await
+ }
+
+ pub async fn privacy_list_versions(
+ &self,
+ category: &str,
+ target_key: &str,
+ ) -> Result<serde_json::Value> {
+ let path = format!(
+ "/api/v1/privacy-configs/{}/{}/versions",
+ category, target_key
+ );
+ self.get(&path, &[]).await
+ }
+
+ pub async fn privacy_get_version(
+ &self,
+ category: &str,
+ target_key: &str,
+ version: i32,
+ ) -> Result<serde_json::Value> {
+ let path = format!(
+ "/api/v1/privacy-configs/{}/{}/versions/{}",
+ category, target_key, version
+ );
+ self.get(&path, &[]).await
+ }
+
+ pub async fn privacy_activate(
+ &self,
+ category: &str,
+ target_key: &str,
+ version: i32,
+ ) -> Result<serde_json::Value> {
+ let path = format!(
+ "/api/v1/privacy-configs/{}/{}/activate",
+ category, target_key
+ );
+ let body = serde_json::json!({ "version": version });
+ self.post(&path, &body).await
+ }
}
#[cfg(test)]
diff --git a/crates/ov_cli/src/commands/mod.rs b/crates/ov_cli/src/commands/mod.rs
index dfde8b48f..b48d32933 100644
--- a/crates/ov_cli/src/commands/mod.rs
+++ b/crates/ov_cli/src/commands/mod.rs
@@ -5,6 +5,7 @@ pub mod crypto;
pub mod filesystem;
pub mod observer;
pub mod pack;
+pub mod privacy;
pub mod relations;
pub mod resources;
pub mod search;
diff --git a/crates/ov_cli/src/commands/privacy.rs b/crates/ov_cli/src/commands/privacy.rs
new file mode 100644
index 000000000..0224d8a46
--- /dev/null
+++ b/crates/ov_cli/src/commands/privacy.rs
@@ -0,0 +1,365 @@
+use crate::client::HttpClient;
+use crate::error::{Error, Result};
+use crate::output::{OutputFormat, output_success};
+use serde_json::{Map, Value};
+use std::collections::{HashMap, HashSet};
+
+fn parse_kv_pairs(pairs: &[String]) -> Result<HashMap<String, String>> {
+ let mut parsed: HashMap<String, String> = HashMap::new();
+ for pair in pairs {
+ let (key, value) = pair.split_once('=').ok_or_else(|| {
+ Error::Client(format!("Invalid --key format: {} (expected key=value)", pair))
+ })?;
+ let key = key.trim();
+ if key.is_empty() {
+ return Err(Error::Client("--key key cannot be empty".to_string()));
+ }
+ parsed.insert(key.to_string(), value.to_string());
+ }
+ Ok(parsed)
+}
+
+fn parse_values_json(
+ values_json: Option<&str>,
+ values_file: Option<&str>,
+) -> Result<Option<Map<String, Value>>> {
+ let parsed = match (values_json, values_file) {
+ (Some(_), Some(_)) => {
+ return Err(Error::Client(
+ "Specify exactly one of --values-json or --values-file".to_string(),
+ ));
+ }
+ (Some(raw), None) => Some(raw.to_string()),
+ (None, Some(path)) => Some(
+ std::fs::read_to_string(path)
+ .map_err(|e| Error::Client(format!("Failed to read --values-file: {}", e)))?,
+ ),
+ (None, None) => None,
+ };
+
+ let Some(raw) = parsed else {
+ return Ok(None);
+ };
+
+ let value: Value = serde_json::from_str(&raw)
+ .map_err(|e| Error::Client(format!("Invalid JSON for values: {}", e)))?;
+ let obj = value
+ .as_object()
+ .ok_or_else(|| Error::Client("values JSON must be an object".to_string()))?
+ .clone();
+ Ok(Some(obj))
+}
+
+fn to_kv_row(key: &str, value: &Value) -> Value {
+ serde_json::json!({
+ "key": key,
+ "value": match value {
+ Value::String(s) => Value::String(s.clone()),
+ _ => Value::String(value.to_string()),
+ }
+ })
+}
+
+fn to_kv_rows(map: &Map<String, Value>) -> Vec<Value> {
+ let mut items: Vec<(&String, &Value)> = map.iter().collect();
+ items.sort_by(|(a, _), (b, _)| a.cmp(b));
+ items
+ .into_iter()
+ .map(|(k, v)| to_kv_row(k, v))
+ .collect()
+}
+
+fn split_kv_rows_by_keys(map: &Map<String, Value>, selected_keys: &HashSet<String>) -> (Vec<Value>, Vec<Value>) {
+ let mut items: Vec<(&String, &Value)> = map.iter().collect();
+ items.sort_by(|(a, _), (b, _)| a.cmp(b));
+
+ let mut selected_rows: Vec<Value> = Vec::new();
+ let mut other_rows: Vec<Value> = Vec::new();
+ for (key, value) in items {
+ if selected_keys.contains(key.as_str()) {
+ selected_rows.push(to_kv_row(key, value));
+ } else {
+ other_rows.push(to_kv_row(key, value));
+ }
+ }
+ (selected_rows, other_rows)
+}
+
+fn string_width(s: &str) -> usize {
+ s.chars().count()
+}
+
+fn pad_right(s: &str, width: usize) -> String {
+ let w = string_width(s);
+ if w >= width {
+ return s.to_string();
+ }
+ format!("{}{}", s, " ".repeat(width - w))
+}
+
+fn extract_kv_cells(rows: &[Value]) -> Vec<(String, String)> {
+ let mut cells: Vec<(String, String)> = Vec::new();
+ for row in rows {
+ let Some(obj) = row.as_object() else {
+ continue;
+ };
+ let key = obj
+ .get("key")
+ .map(|v| match v {
+ Value::String(s) => s.clone(),
+ _ => v.to_string(),
+ })
+ .unwrap_or_default();
+ let value = obj
+ .get("value")
+ .map(|v| match v {
+ Value::String(s) => s.clone(),
+ _ => v.to_string(),
+ })
+ .unwrap_or_default();
+ cells.push((key, value));
+ }
+ cells
+}
+
+fn render_kv_ascii_table(rows: &[Value]) -> String {
+ let cells = extract_kv_cells(rows);
+ let mut key_width = string_width("key");
+ let mut value_width = string_width("value");
+ for (k, v) in &cells {
+ key_width = key_width.max(string_width(k));
+ value_width = value_width.max(string_width(v));
+ }
+
+ let border = format!(
+ "+{}+{}+",
+ "-".repeat(key_width + 2),
+ "-".repeat(value_width + 2)
+ );
+
+ let mut out = String::new();
+ out.push_str(&border);
+ out.push('\n');
+ out.push_str(&format!(
+ "| {} | {} |\n",
+ pad_right("key", key_width),
+ pad_right("value", value_width)
+ ));
+ out.push_str(&border);
+ out.push('\n');
+
+ for (k, v) in cells {
+ out.push_str(&format!(
+ "| {} | {} |\n",
+ pad_right(&k, key_width),
+ pad_right(&v, value_width)
+ ));
+ }
+
+ out.push_str(&border);
+ out
+}
+
+fn output_section_table(title: &str, rows: Vec<Value>, _compact: bool) {
+ println!("[{}]", title);
+ println!("{}", render_kv_ascii_table(&rows));
+}
+
+fn output_meta_current_tables(meta: &Map<String, Value>, values: &Map<String, Value>, compact: bool) {
+ output_section_table("meta", to_kv_rows(meta), compact);
+ println!();
+ output_section_table("current", to_kv_rows(values), compact);
+}
+
+fn output_version_like_tables(result: &Value, compact: bool) -> Result<()> {
+ let mut meta = result
+ .as_object()
+ .ok_or_else(|| Error::Parse("Expected object response".to_string()))?
+ .clone();
+ let values = meta
+ .remove("values")
+ .and_then(|v| v.as_object().cloned())
+ .ok_or_else(|| Error::Parse("Expected values object in response".to_string()))?;
+
+ output_meta_current_tables(&meta, &values, compact);
+ Ok(())
+}
+
+pub async fn categories(client: &HttpClient, output_format: OutputFormat, compact: bool) -> Result<()> {
+ let result = client.privacy_list_categories().await?;
+ output_success(&result, output_format, compact);
+ Ok(())
+}
+
+pub async fn list_targets(
+ client: &HttpClient,
+ category: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let result = client.privacy_list_targets(category).await?;
+ output_success(&result, output_format, compact);
+ Ok(())
+}
+
+pub async fn get_current(
+ client: &HttpClient,
+ category: &str,
+ target_key: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let result = client.privacy_get_current(category, target_key).await?;
+ if matches!(output_format, OutputFormat::Table) {
+ let meta = result
+ .get("meta")
+ .and_then(Value::as_object)
+ .ok_or_else(|| Error::Parse("Expected meta object in response".to_string()))?
+ .clone();
+ let values = result
+ .get("current")
+ .and_then(|v| v.get("values"))
+ .and_then(Value::as_object)
+ .ok_or_else(|| Error::Parse("Expected current.values object in response".to_string()))?
+ .clone();
+ output_meta_current_tables(&meta, &values, compact);
+ return Ok(());
+ }
+
+ output_success(&result, output_format, compact);
+ Ok(())
+}
+
+pub async fn list_versions(
+ client: &HttpClient,
+ category: &str,
+ target_key: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let result = client.privacy_list_versions(category, target_key).await?;
+ output_success(&result, output_format, compact);
+ Ok(())
+}
+
+pub async fn get_version(
+ client: &HttpClient,
+ category: &str,
+ target_key: &str,
+ version: i32,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let result = client.privacy_get_version(category, target_key, version).await?;
+ if matches!(output_format, OutputFormat::Table) {
+ return output_version_like_tables(&result, compact);
+ }
+
+ output_success(&result, output_format, compact);
+ Ok(())
+}
+
+pub async fn activate(
+ client: &HttpClient,
+ category: &str,
+ target_key: &str,
+ version: i32,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let result = client.privacy_activate(category, target_key, version).await?;
+ if matches!(output_format, OutputFormat::Table) {
+ return output_version_like_tables(&result, compact);
+ }
+
+ output_success(&result, output_format, compact);
+ Ok(())
+}
+
+pub async fn upsert(
+ client: &HttpClient,
+ category: &str,
+ target_key: &str,
+ values_json: Option<&str>,
+ values_file: Option<&str>,
+ key_pairs: &[String],
+ change_reason: &str,
+ labels_json: Option<&str>,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let parsed_values = parse_values_json(values_json, values_file)?;
+ let mut final_values: Map<String, Value> = parsed_values.clone().unwrap_or_default();
+
+ let key_overrides = parse_kv_pairs(key_pairs)?;
+ let mut requested_keys: HashSet<String> = HashSet::new();
+ if let Some(values_from_json) = parsed_values.as_ref() {
+ requested_keys.extend(values_from_json.keys().cloned());
+ }
+ requested_keys.extend(key_overrides.keys().cloned());
+
+ if !key_overrides.is_empty() {
+ let current = client.privacy_get_current(category, target_key).await?;
+ let mut base_values = current
+ .get("current")
+ .and_then(|v| v.get("values"))
+ .and_then(Value::as_object)
+ .ok_or_else(|| {
+ Error::Parse("privacy get current response missing current.values object".to_string())
+ })?
+ .clone();
+
+ if let Some(values_from_json) = parsed_values {
+ for (key, value) in values_from_json {
+ base_values.insert(key, value);
+ }
+ }
+ for (key, value) in key_overrides {
+ base_values.insert(key, Value::String(value));
+ }
+ final_values = base_values;
+ }
+
+ if final_values.is_empty() {
+ return Err(Error::Client(
+ "No values provided; use --values-json/--values-file or --key-{key} <value>"
+ .to_string(),
+ ));
+ }
+
+ let labels_value = if let Some(raw) = labels_json {
+ let parsed: Value = serde_json::from_str(raw)
+ .map_err(|e| Error::Client(format!("Invalid JSON for --labels-json: {}", e)))?;
+ if !parsed.is_object() {
+ return Err(Error::Client("--labels-json must be a JSON object".to_string()));
+ }
+ Some(parsed)
+ } else {
+ None
+ };
+
+ let mut payload = serde_json::json!({
+ "values": Value::Object(final_values),
+ "change_reason": change_reason,
+ });
+ if let Some(labels) = labels_value {
+ payload["labels"] = labels;
+ }
+
+ let result = client.privacy_upsert(category, target_key, &payload).await?;
+ if matches!(output_format, OutputFormat::Table) {
+ let values = result
+ .get("values")
+ .and_then(Value::as_object)
+ .ok_or_else(|| Error::Parse("Expected values object in upsert response".to_string()))?
+ .clone();
+ let (updated_rows, unchanged_rows) = split_kv_rows_by_keys(&values, &requested_keys);
+ output_section_table("updated", updated_rows, compact);
+ println!();
+ output_section_table("unchanged", unchanged_rows, compact);
+ return Ok(());
+ }
+
+ output_success(&result, output_format, compact);
+ Ok(())
+}
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 2d51ccb49..252c9389e 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -4,6 +4,7 @@ use crate::config::merge_csv_options;
use crate::error::{Error, Result};
use crate::tui;
use crate::CliContext;
+use crate::PrivacyCommands;
pub async fn handle_add_resource(
mut path: String,
@@ -379,6 +380,90 @@ pub async fn handle_add_memory(content: String, ctx: CliContext) -> Result<()> {
commands::session::add_memory(&client, &content, ctx.output_format, ctx.compact).await
}
+pub async fn handle_privacy(cmd: PrivacyCommands, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ match cmd {
+ PrivacyCommands::Categories => {
+ commands::privacy::categories(&client, ctx.output_format, ctx.compact).await
+ }
+ PrivacyCommands::List { category } => {
+ commands::privacy::list_targets(&client, &category, ctx.output_format, ctx.compact)
+ .await
+ }
+ PrivacyCommands::Get {
+ category,
+ target_key,
+ } => commands::privacy::get_current(
+ &client,
+ &category,
+ &target_key,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await,
+ PrivacyCommands::Upsert {
+ category,
+ target_key,
+ values_json,
+ values_file,
+ key,
+ change_reason,
+ labels_json,
+ } => {
+ commands::privacy::upsert(
+ &client,
+ &category,
+ &target_key,
+ values_json.as_deref(),
+ values_file.as_deref(),
+ &key,
+ &change_reason,
+ labels_json.as_deref(),
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ PrivacyCommands::Versions {
+ category,
+ target_key,
+ } => commands::privacy::list_versions(
+ &client,
+ &category,
+ &target_key,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await,
+ PrivacyCommands::Version {
+ category,
+ target_key,
+ version,
+ } => commands::privacy::get_version(
+ &client,
+ &category,
+ &target_key,
+ version,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await,
+ PrivacyCommands::Activate {
+ category,
+ target_key,
+ version,
+ } => commands::privacy::activate(
+ &client,
+ &category,
+ &target_key,
+ version,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await,
+ }
+}
+
use crate::ConfigCommands;
use crate::config::Config;
use crate::output;
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 529063878..1f9373310 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -8,6 +8,7 @@ mod tui;
mod utils;
use clap::{ArgAction, Parser, Subcommand};
+use std::ffi::OsString;
use config::Config;
use error::Result;
use output::OutputFormat;
@@ -421,6 +422,11 @@ enum Commands {
/// or JSON array of such objects for multiple messages.
content: String,
},
+ /// [Data] Privacy config management commands
+ Privacy {
+ #[command(subcommand)]
+ action: PrivacyCommands,
+ },
/// [Experimental][Data] List relations of a resource
Relations {
/// Viking URI
@@ -636,6 +642,71 @@ enum SessionCommands {
},
}
+#[derive(Subcommand)]
+enum PrivacyCommands {
+ /// List privacy config categories
+ Categories,
+ /// List targets by category
+ List {
+ /// Privacy config category
+ category: String,
+ },
+ /// Get current active config for target
+ Get {
+ /// Privacy config category
+ category: String,
+ /// Privacy config target key
+ target_key: String,
+ },
+ /// Upsert privacy config values
+ Upsert {
+ /// Privacy config category
+ category: String,
+ /// Privacy config target key
+ target_key: String,
+ /// JSON object string for values
+ #[arg(long, conflicts_with = "values_file")]
+ values_json: Option<String>,
+ /// JSON file path for values
+ #[arg(long = "values-file", conflicts_with = "values_json")]
+ values_file: Option<String>,
+ /// Existing key updates in key=value format (repeatable)
+ #[arg(long = "key")]
+ key: Vec<String>,
+ /// Change reason
+ #[arg(long, default_value = "")]
+ change_reason: String,
+ /// Optional labels JSON object string
+ #[arg(long = "labels-json")]
+ labels_json: Option<String>,
+ },
+ /// List versions for target
+ Versions {
+ /// Privacy config category
+ category: String,
+ /// Privacy config target key
+ target_key: String,
+ },
+ /// Get one version by number
+ Version {
+ /// Privacy config category
+ category: String,
+ /// Privacy config target key
+ target_key: String,
+ /// Version number
+ version: i32,
+ },
+ /// Activate a version
+ Activate {
+ /// Privacy config category
+ category: String,
+ /// Privacy config target key
+ target_key: String,
+ /// Version number
+ version: i32,
+ },
+}
+
#[derive(Subcommand)]
enum AdminCommands {
/// Create a new account with its first admin user
@@ -710,9 +781,120 @@ enum ConfigCommands {
Validate,
}
+fn find_command_index(args: &[OsString]) -> Option<usize> {
+ let mut i = 1;
+ while i < args.len() {
+ let token = args[i].to_string_lossy();
+ match token.as_ref() {
+ "--output" | "-o" | "--compact" | "--account" | "--user" | "--agent-id" => {
+ i += 2;
+ }
+ "--sudo" => {
+ i += 1;
+ }
+ _ if token.starts_with('-') => {
+ i += 1;
+ }
+ _ => return Some(i),
+ }
+ }
+ None
+}
+
+fn is_privacy_subcommand(token: &str) -> bool {
+ matches!(
+ token,
+ "categories" | "list" | "get" | "upsert" | "versions" | "version" | "activate"
+ )
+}
+
+fn preprocess_privacy_get_shortcut(args: Vec<OsString>) -> Vec<OsString> {
+ let Some(cmd_idx) = find_command_index(&args) else {
+ return args;
+ };
+ if args[cmd_idx].to_string_lossy() != "privacy" {
+ return args;
+ }
+ let Some(next) = args.get(cmd_idx + 1) else {
+ return args;
+ };
+ let next_token = next.to_string_lossy();
+ if next_token.starts_with('-') || is_privacy_subcommand(&next_token) {
+ return args;
+ }
+
+ let mut out = Vec::with_capacity(args.len() + 1);
+ out.extend(args[..=cmd_idx].iter().cloned());
+ out.push(OsString::from("get"));
+ out.extend(args[cmd_idx + 1..].iter().cloned());
+ out
+}
+
+fn preprocess_privacy_upsert_key_flags(args: Vec<OsString>) -> Vec<OsString> {
+ let Some(cmd_idx) = find_command_index(&args) else {
+ return args;
+ };
+ if args[cmd_idx].to_string_lossy() != "privacy" {
+ return args;
+ }
+ if args.get(cmd_idx + 1).map(|s| s.to_string_lossy().to_string()) != Some("upsert".to_string()) {
+ return args;
+ }
+
+ let mut converted: Vec<OsString> = Vec::with_capacity(args.len());
+ let mut i = 0;
+
+ while i < args.len() {
+ let arg_lossy = args[i].to_string_lossy();
+
+ if i > cmd_idx + 1 && arg_lossy == "--" {
+ i += 1;
+ continue;
+ }
+
+ if i > cmd_idx + 1 && arg_lossy.starts_with("--key-") {
+ let suffix = &arg_lossy[6..];
+ if suffix.is_empty() {
+ converted.push(args[i].clone());
+ i += 1;
+ continue;
+ }
+
+ if let Some((key, value)) = suffix.split_once('=') {
+ converted.push(OsString::from("--key"));
+ converted.push(OsString::from(format!("{}={}", key, value)));
+ i += 1;
+ continue;
+ }
+
+ if i + 1 < args.len() {
+ let next_val = args[i + 1].to_string_lossy();
+ converted.push(OsString::from("--key"));
+ converted.push(OsString::from(format!("{}={}", suffix, next_val)));
+ i += 2;
+ continue;
+ }
+
+ converted.push(args[i].clone());
+ i += 1;
+ continue;
+ }
+
+ converted.push(args[i].clone());
+ i += 1;
+ }
+
+ converted
+}
+
+fn preprocess_privacy_args(args: Vec<OsString>) -> Vec<OsString> {
+ let args = preprocess_privacy_get_shortcut(args);
+ preprocess_privacy_upsert_key_flags(args)
+}
+
#[tokio::main]
async fn main() {
- let cli = Cli::parse();
+ let cli = Cli::parse_from(preprocess_privacy_args(std::env::args_os().collect()));
let output_format = cli.output;
let compact = cli.compact;
@@ -810,6 +992,7 @@ async fn main() {
Commands::Observer { action } => handlers::handle_observer(action, ctx).await,
Commands::Session { action } => handlers::handle_session(action, ctx).await,
Commands::Admin { action } => handlers::handle_admin(action, ctx).await,
+ Commands::Privacy { action } => handlers::handle_privacy(action, ctx).await,
Commands::Ls {
uri,
simple,
@@ -966,11 +1149,12 @@ async fn main() {
#[cfg(test)]
mod tests {
- use super::{Cli, CliContext};
+ use super::{Cli, CliContext, Commands, PrivacyCommands, preprocess_privacy_args};
use crate::config::Config;
use crate::handlers;
use crate::output::OutputFormat;
use clap::Parser;
+ use std::ffi::OsString;
#[test]
fn cli_parses_global_identity_override_flags() {
@@ -1090,4 +1274,90 @@ mod tests {
assert_eq!(params, vec!["--after 7d", "--before 2026-03-12"]);
}
+
+ #[test]
+ fn preprocess_key_dynamic_flag_to_static_form() {
+ let args = vec![
+ OsString::from("ov"),
+ OsString::from("privacy"),
+ OsString::from("upsert"),
+ OsString::from("skill"),
+ OsString::from("demo"),
+ OsString::from("--key-api_key"),
+ OsString::from("secret-v1"),
+ ];
+
+ let converted = preprocess_privacy_args(args);
+ let converted_strs: Vec<String> = converted
+ .into_iter()
+ .map(|s| s.to_string_lossy().to_string())
+ .collect();
+
+ assert_eq!(
+ converted_strs,
+ vec![
+ "ov",
+ "privacy",
+ "upsert",
+ "skill",
+ "demo",
+ "--key",
+ "api_key=secret-v1",
+ ]
+ );
+ }
+
+ #[test]
+ fn cli_parses_privacy_upsert_with_key_dynamic_flag() {
+ let cli = Cli::parse_from(preprocess_privacy_args(vec![
+ OsString::from("ov"),
+ OsString::from("privacy"),
+ OsString::from("upsert"),
+ OsString::from("skill"),
+ OsString::from("demo"),
+ OsString::from("--key-api_key"),
+ OsString::from("secret-v2"),
+ ]));
+
+ match cli.command {
+ Commands::Privacy { action } => match action {
+ PrivacyCommands::Upsert {
+ category,
+ target_key,
+ key,
+ ..
+ } => {
+ assert_eq!(category, "skill");
+ assert_eq!(target_key, "demo");
+ assert_eq!(key, vec!["api_key=secret-v2"]);
+ }
+ _ => panic!("expected privacy upsert"),
+ },
+ _ => panic!("expected privacy command"),
+ }
+ }
+
+ #[test]
+ fn cli_parses_privacy_shortcut_as_get() {
+ let cli = Cli::parse_from(preprocess_privacy_args(vec![
+ OsString::from("ov"),
+ OsString::from("privacy"),
+ OsString::from("skill"),
+ OsString::from("demo"),
+ ]));
+
+ match cli.command {
+ Commands::Privacy { action } => match action {
+ PrivacyCommands::Get {
+ category,
+ target_key,
+ } => {
+ assert_eq!(category, "skill");
+ assert_eq!(target_key, "demo");
+ }
+ _ => panic!("expected privacy get"),
+ },
+ _ => panic!("expected privacy command"),
+ }
+ }
}
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index 80ddeeac0..bccb43e2e 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -372,6 +372,18 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default
| POST | `/api/v1/sessions/{id}/used` | Record contexts / skills actually used |
| GET | `/api/v1/sessions/{id}/archives/{archive_id}` | Get a specific session archive |
+### Privacy Configs
+
+| Method | Path | Description |
+|--------|------|-------------|
+| GET | `/api/v1/privacy-configs` | List privacy config categories |
+| GET | `/api/v1/privacy-configs/{category}` | List targets under a category |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}` | Get active config (`meta + current`) |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}` | Upsert and activate |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions` | List version numbers |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions/{version}` | Get version snapshot |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}/activate` | Activate a version |
+
### Tasks
| Method | Path | Description |
@@ -419,5 +431,6 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default
- [Sessions](05-sessions.md) - Session management
- [Skills](04-skills.md) - Skill management
- [System](07-system.md) - System and monitoring API
+- [Privacy Configs](10-privacy.md) - Privacy config version management and activation
- [Metrics](09-metrics.md) - Prometheus metrics export and scraping guide
- [Admin](08-admin.md) - Multi-tenant management API
diff --git a/docs/en/api/10-privacy.md b/docs/en/api/10-privacy.md
new file mode 100644
index 000000000..c34101e13
--- /dev/null
+++ b/docs/en/api/10-privacy.md
@@ -0,0 +1,391 @@
+# Privacy Configs
+
+Privacy configs manage sensitive values by `category + target_key` (for example, a skill's `api_key` and `base_url`).
+
+Each update creates a version snapshot. You can query history and switch the active version.
+
+## Endpoint Summary
+
+| Method | Path | Description |
+|--------|------|-------------|
+| GET | `/api/v1/privacy-configs` | List privacy config categories |
+| GET | `/api/v1/privacy-configs/{category}` | List targets under a category |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}` | Get active config (`meta + current`) |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}` | Upsert and activate a new/current version |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions` | List version numbers |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions/{version}` | Get a specific version snapshot |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}/activate` | Activate a specific version |
+
+Detailed sections are below.
+
+---
+
+## Common Use Cases
+
+- Store sensitive settings for a skill
+- Rotate keys by writing a new version
+- Roll back to an old version
+- Restore placeholders in skill content at read time
+
+---
+
+## Data Structures
+
+### current (active version snapshot)
+
+```json
+{
+ "version": 3,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "***",
+ "base_url": "https://example.com"
+ },
+ "created_at": "2026-04-27T10:00:00+08:00",
+ "created_by": "alice",
+ "change_reason": "rotate key"
+}
+```
+
+### meta
+
+```json
+{
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "active_version": 3,
+ "latest_version": 5,
+ "created_at": "2026-04-21T10:00:00+08:00",
+ "updated_at": "2026-04-27T10:00:00+08:00",
+ "updated_by": "alice",
+ "last_accessed_at": "2026-04-27T10:00:00+08:00",
+ "labels": {
+ "env": "prod"
+ }
+}
+```
+
+---
+
+## API Reference
+
+### list_privacy_categories()
+
+List categories that have privacy configs for the current user.
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs
+```
+
+```bash
+curl -X GET http://localhost:1933/api/v1/privacy-configs \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": ["skill"],
+ "time": 0.01
+}
+```
+
+---
+
+### list_privacy_targets()
+
+List target keys under a category.
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}
+```
+
+```bash
+curl -X GET http://localhost:1933/api/v1/privacy-configs/skill \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": ["byted-viking-search-knowledgebase"],
+ "time": 0.01
+}
+```
+
+---
+
+### get_privacy_current()
+
+Get active config for a target (`meta + current`).
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}/{target_key}
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "meta": {
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "active_version": 3,
+ "latest_version": 5
+ },
+ "current": {
+ "version": 3,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "***",
+ "base_url": "https://example.com"
+ }
+ }
+ },
+ "time": 0.01
+}
+```
+
+> Returns `NOT_FOUND` if the target does not exist.
+
+---
+
+### upsert_privacy_config()
+
+Write a new version and set it as active.
+
+**Behavior**
+
+- `values` is written as a full snapshot for that version
+- New keys are allowed and persisted
+- If `values` is identical to the current version, no new version is created
+
+**HTTP API**
+
+```
+POST /api/v1/privacy-configs/{category}/{target_key}
+```
+
+**Request Body**
+
+| Field | Type | Required | Default | Description |
+|-------|------|----------|---------|-------------|
+| values | object | Yes | - | Privacy key-value pairs |
+| change_reason | string | No | "" | Reason for change |
+| labels | object | No | null | Labels stored in meta |
+
+```bash
+curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase" \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice" \
+ -d '{
+ "values": {
+ "api_key": "secret-2",
+ "base_url": "https://example.com",
+ "region": "cn"
+ },
+ "change_reason": "rotate key",
+ "labels": {
+ "env": "prod"
+ }
+ }'
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "version": 4,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "secret-2",
+ "base_url": "https://example.com",
+ "region": "cn"
+ },
+ "change_reason": "rotate key"
+ },
+ "time": 0.02
+}
+```
+
+---
+
+### list_privacy_versions()
+
+List all version numbers for a target.
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}/{target_key}/versions
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase/versions" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": [1, 2, 3, 4],
+ "time": 0.01
+}
+```
+
+> Returns `NOT_FOUND` if the target does not exist.
+
+---
+
+### get_privacy_version()
+
+Get one version snapshot.
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}/{target_key}/versions/{version}
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase/versions/2" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "version": 2,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "secret-1",
+ "base_url": "https://example.com"
+ }
+ },
+ "time": 0.01
+}
+```
+
+> Returns `NOT_FOUND` if target/version does not exist.
+
+---
+
+### activate_privacy_version()
+
+Switch active version.
+
+**HTTP API**
+
+```
+POST /api/v1/privacy-configs/{category}/{target_key}/activate
+```
+
+**Request Body**
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| version | int | Yes | Version number to activate |
+
+```bash
+curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase/activate" \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice" \
+ -d '{"version": 2}'
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "version": 2,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "secret-1",
+ "base_url": "https://example.com"
+ }
+ },
+ "time": 0.01
+}
+```
+
+> Returns `NOT_FOUND` if target/version does not exist.
+
+---
+
+## CLI Quick Operations
+
+```bash
+# Categories and targets
+openviking privacy categories
+openviking privacy list skill
+
+# Active config (shortcut supported)
+openviking privacy get skill byted-viking-search-knowledgebase
+openviking privacy skill byted-viking-search-knowledgebase
+
+# Upsert with full JSON snapshot
+openviking privacy upsert skill byted-viking-search-knowledgebase \
+ --values-json '{"api_key":"secret-2","base_url":"https://example.com"}'
+
+# Partial key update (CLI merges with current first)
+openviking privacy upsert skill byted-viking-search-knowledgebase \
+ --key-api_key secret-3
+
+# Version query and activation
+openviking privacy versions skill byted-viking-search-knowledgebase
+openviking privacy version skill byted-viking-search-knowledgebase 2
+openviking privacy activate skill byted-viking-search-knowledgebase 2
+```
+
+---
+
+## Related Documentation
+
+- [Skills](04-skills.md) - Skill write/read APIs
+- [File System](03-filesystem.md) - `read`/`write`/`ls`
+- [System](07-system.md) - System status and observability
diff --git a/docs/en/concepts/01-architecture.md b/docs/en/concepts/01-architecture.md
index af91be90d..f7e2c0388 100644
--- a/docs/en/concepts/01-architecture.md
+++ b/docs/en/concepts/01-architecture.md
@@ -177,3 +177,4 @@ curl http://localhost:1933/api/v1/search/find \
- [Data Encryption](./10-encryption.md) - At-rest encryption and key architecture
- [Multi-Tenant](./11-multi-tenant.md) - Account / user / agent isolation model
- [Metrics](./12-metrics.md) - `/metrics` usage and key metric explanations
+- [Privacy Configs and Skill Privacy Extraction/Restore](./13-privacy.md) - Versioning, placeholder extraction, and read-time restore
diff --git a/docs/en/concepts/13-privacy.md b/docs/en/concepts/13-privacy.md
new file mode 100644
index 000000000..1b5bbec16
--- /dev/null
+++ b/docs/en/concepts/13-privacy.md
@@ -0,0 +1,155 @@
+# Privacy Configs and Skill Privacy Extraction/Restore
+
+This page explains OpenViking privacy configs and how they work with skill write-time extraction and read-time restore.
+
+## Goal
+
+Privacy configs separate sensitive values (such as `api_key`, `token`, `base_url`) from skill body content so plaintext is not permanently stored in `SKILL.md`, while keeping full version management and rollback.
+
+Core goals:
+
+- Auto-extract sensitive values at write time and replace with placeholders
+- Auto-restore values from the active config at read time
+- Provide version query, switching, and auditability
+
+---
+
+## Core Objects and Storage Layout
+
+Privacy configs are keyed by `category + target_key`.
+
+- `category`: config category (currently skill uses `skill`)
+- `target_key`: target identifier (usually the skill name)
+
+Storage layout in user space:
+
+```
+viking://user/{user_space}/privacy/{category}/{target_key}/
+├── .meta.json # metadata (active_version/latest_version/labels, etc.)
+├── current.json # active version snapshot
+└── history/
+ ├── version_1.json
+ ├── version_2.json
+ └── ...
+```
+
+`current.json` and `history/version_x.json` are full `values` snapshots.
+
+---
+
+## Version Semantics
+
+### upsert
+
+- Each upsert treats incoming `values` as the candidate snapshot
+- If `values` is identical to current `values`, no new version is created
+- Otherwise a new version is created and activated
+- New keys are allowed (no unknown-key rejection)
+
+### activate
+
+- Sets a historical version as active (writes back to `current.json`)
+- Updates `active_version` in `.meta.json`
+
+---
+
+## Skill Privacy Extraction (Write Path)
+
+When adding a skill via `add_skill`, OpenViking runs extraction + placeholderization.
+
+```
+add_skill
+ -> SkillProcessor._sanitize_skill_privacy
+ -> extract_skill_privacy_values (LLM extracts values)
+ -> placeholderize_skill_content_with_blocks (replace plaintext with placeholders)
+ -> privacy.upsert(category="skill", target_key=skill_name, values=...)
+ -> write placeholderized SKILL.md
+```
+
+### Key Points
+
+1. **Extraction source**: model returns JSON; `values` is used as privacy key-value pairs.
+2. **Content replacement**: matched plaintext is replaced by placeholders:
+ - `{{ov_privacy:skill:{skill_name}:{field_name}}}`
+3. **Block mapping captured**:
+ - `original_content_blocks`
+ - `replacement_content_blocks`
+4. **Persisted content**: stored `SKILL.md` contains placeholders, not plaintext values.
+
+---
+
+## Skill Restore on Read (Load Path)
+
+When reading `SKILL.md`, `FSService.read` attempts placeholder restoration automatically.
+
+```
+fs.read(uri)
+ -> get_skill_name_from_uri(uri)
+ -> privacy.get_current(category="skill", target_key=skill_name)
+ -> restore_skill_content(content, skill_name, current.values)
+```
+
+### URI Matching
+
+Current matching is suffix-based: `/skills/{name}/SKILL.md`, so it supports:
+
+- `viking://agent/skills/{name}/SKILL.md`
+- `viking://agent/{agent_id}/skills/{name}/SKILL.md`
+
+### restore Rules
+
+`restore_skill_content` behavior:
+
+1. **Placeholder exists in content and value exists and is non-empty**
+ -> replace directly.
+
+2. **Placeholder exists in content but value is missing/empty**
+ -> keep placeholder; add item to `unresolved_entries`.
+
+3. **Config key is non-empty but not referenced by any placeholder in content**
+ -> add to extra-config notice (`Configured but not referenced in content`).
+
+4. If `unresolved_entries` or extra-config entries exist, append notice block:
+ - `[OpenViking Privacy Notice]`
+ - `Related configured privacy values: ...`
+ - `Not replaced (missing config): ...` (if any)
+ - `Configured but not referenced in content: ...` (if any)
+
+> Current implementation only runs restore when a `current` privacy config exists for that skill. If no current config exists, no notice is appended.
+
+---
+
+## Relationship with CLI/API
+
+- Management plane: Privacy API/CLI for versions (query, write, rollback)
+- Content plane: `read` automatically restores placeholders
+- Separation of concerns: content files hold placeholders; privacy service holds sensitive values and versions
+
+Common commands:
+
+```bash
+openviking privacy categories
+openviking privacy list skill
+openviking privacy skill <target_key>
+openviking privacy upsert skill <target_key> --values-json '{"api_key":"..."}'
+openviking privacy activate skill <target_key> <version>
+openviking read viking://agent/default/skills/<target_key>/SKILL.md
+```
+
+---
+
+## Benefits
+
+- Reduces plaintext sensitive data exposure in skill content
+- Versioning supports key rotation and fast rollback
+- Transparent to callers: `read` returns restored executable skill text
+- Notice block improves troubleshooting when config is incomplete or over-provisioned
+
+---
+
+## Related Documentation
+
+- [Skills](../api/04-skills.md) - Skill write/read API
+- [Privacy API](../api/10-privacy.md) - Privacy config endpoints
+- [Context Extraction](./06-extraction.md) - Main extraction pipeline
+- [Architecture Overview](./01-architecture.md) - Layering and module relationships
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 572a54ba0..91888aba3 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -369,6 +369,18 @@ openviking -o json ls viking://resources/
| POST | `/api/v1/sessions/{id}/used` | 记录实际使用的上下文 / 技能 |
| GET | `/api/v1/sessions/{id}/archives/{archive_id}` | 获取特定会话归档 |
+### 隐私配置
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| GET | `/api/v1/privacy-configs` | 列出隐私配置分类 |
+| GET | `/api/v1/privacy-configs/{category}` | 列出分类下目标 |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}` | 获取当前生效配置(meta + current) |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}` | 写入新版本并激活 |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions` | 列出版本号 |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions/{version}` | 获取指定版本详情 |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}/activate` | 激活指定版本 |
+
### 任务
| 方法 | 路径 | 说明 |
@@ -416,5 +428,6 @@ openviking -o json ls viking://resources/
- [会话管理](05-sessions.md) - 会话管理
- [技能](04-skills.md) - 技能管理
- [系统](07-system.md) - 系统和监控 API
+- [隐私配置](10-privacy.md) - 隐私配置版本管理与切换
- [指标与 Metrics](09-metrics.md) - Prometheus 指标导出与抓取说明
- [管理员](08-admin.md) - 多租户管理 API
diff --git a/docs/zh/api/10-privacy.md b/docs/zh/api/10-privacy.md
new file mode 100644
index 000000000..771189db6
--- /dev/null
+++ b/docs/zh/api/10-privacy.md
@@ -0,0 +1,391 @@
+# 隐私配置(Privacy Configs)
+
+隐私配置用于按 `category + target_key` 管理敏感字段版本(如 skill 的 `api_key`、`base_url`)。
+
+每次更新都会生成版本快照,可查询历史版本并切换生效版本。
+
+## 典型场景
+
+- 为某个 skill 保存密钥等敏感配置
+- 轮换密钥(新版本)
+- 回滚到历史版本
+- 在读取 skill 内容时按占位符自动恢复配置值
+
+---
+
+## 接口总览
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| GET | `/api/v1/privacy-configs` | 列出隐私配置分类 |
+| GET | `/api/v1/privacy-configs/{category}` | 列出分类下目标 |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}` | 获取当前生效配置(meta + current) |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}` | 写入新版本并激活 |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions` | 列出版本号 |
+| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions/{version}` | 获取指定版本详情 |
+| POST | `/api/v1/privacy-configs/{category}/{target_key}/activate` | 激活指定版本 |
+
+下面按接口逐一展开说明。
+
+---
+
+## 数据结构
+
+### current(当前生效版本)
+
+```json
+{
+ "version": 3,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "***",
+ "base_url": "https://example.com"
+ },
+ "created_at": "2026-04-27T10:00:00+08:00",
+ "created_by": "alice",
+ "change_reason": "rotate key"
+}
+```
+
+### meta(元信息)
+
+```json
+{
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "active_version": 3,
+ "latest_version": 5,
+ "created_at": "2026-04-21T10:00:00+08:00",
+ "updated_at": "2026-04-27T10:00:00+08:00",
+ "updated_by": "alice",
+ "last_accessed_at": "2026-04-27T10:00:00+08:00",
+ "labels": {
+ "env": "prod"
+ }
+}
+```
+
+---
+
+## API 参考
+
+### list_privacy_categories()
+
+列出当前用户下已有隐私配置的分类。
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs
+```
+
+```bash
+curl -X GET http://localhost:1933/api/v1/privacy-configs \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": ["skill"],
+ "time": 0.01
+}
+```
+
+---
+
+### list_privacy_targets()
+
+列出分类下的 target_key。
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}
+```
+
+```bash
+curl -X GET http://localhost:1933/api/v1/privacy-configs/skill \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": ["byted-viking-search-knowledgebase"],
+ "time": 0.01
+}
+```
+
+---
+
+### get_privacy_current()
+
+获取 target 当前生效配置(`meta + current`)。
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}/{target_key}
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "meta": {
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "active_version": 3,
+ "latest_version": 5
+ },
+ "current": {
+ "version": 3,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "***",
+ "base_url": "https://example.com"
+ }
+ }
+ },
+ "time": 0.01
+}
+```
+
+> 若 target 不存在,返回 `NOT_FOUND`。
+
+---
+
+### upsert_privacy_config()
+
+写入新版本并将其设为当前生效版本。
+
+**行为说明**
+
+- `values` 按整包快照写入(本次传入内容成为新版本的 `values`)
+- 传入新 key 会直接写入(允许新增)
+- 若与当前版本完全一致,则复用当前版本号,不新建版本
+
+**HTTP API**
+
+```
+POST /api/v1/privacy-configs/{category}/{target_key}
+```
+
+**请求体**
+
+| 字段 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| values | object | 是 | - | 隐私配置键值 |
+| change_reason | string | 否 | "" | 变更原因 |
+| labels | object | 否 | null | 元信息标签 |
+
+```bash
+curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase" \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice" \
+ -d '{
+ "values": {
+ "api_key": "secret-2",
+ "base_url": "https://example.com",
+ "region": "cn"
+ },
+ "change_reason": "rotate key",
+ "labels": {
+ "env": "prod"
+ }
+ }'
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "version": 4,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "secret-2",
+ "base_url": "https://example.com",
+ "region": "cn"
+ },
+ "change_reason": "rotate key"
+ },
+ "time": 0.02
+}
+```
+
+---
+
+### list_privacy_versions()
+
+列出 target 的所有版本号。
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}/{target_key}/versions
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase/versions" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": [1, 2, 3, 4],
+ "time": 0.01
+}
+```
+
+> 若 target 不存在,返回 `NOT_FOUND`。
+
+---
+
+### get_privacy_version()
+
+获取某个历史版本详情。
+
+**HTTP API**
+
+```
+GET /api/v1/privacy-configs/{category}/{target_key}/versions/{version}
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase/versions/2" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice"
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "version": 2,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "secret-1",
+ "base_url": "https://example.com"
+ }
+ },
+ "time": 0.01
+}
+```
+
+> 若 target/version 不存在,返回 `NOT_FOUND`。
+
+---
+
+### activate_privacy_version()
+
+切换当前生效版本。
+
+**HTTP API**
+
+```
+POST /api/v1/privacy-configs/{category}/{target_key}/activate
+```
+
+**请求体**
+
+| 字段 | 类型 | 必填 | 说明 |
+|------|------|------|------|
+| version | int | 是 | 要激活的版本号 |
+
+```bash
+curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-search-knowledgebase/activate" \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -H "X-OpenViking-User: alice" \
+ -d '{"version": 2}'
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "version": 2,
+ "category": "skill",
+ "target_key": "byted-viking-search-knowledgebase",
+ "values": {
+ "api_key": "secret-1",
+ "base_url": "https://example.com"
+ }
+ },
+ "time": 0.01
+}
+```
+
+> 若 target/version 不存在,返回 `NOT_FOUND`。
+
+---
+
+## CLI 快速操作
+
+```bash
+# 分类/目标
+openviking privacy categories
+openviking privacy list skill
+
+# 当前生效配置(支持快捷形式)
+openviking privacy get skill byted-viking-search-knowledgebase
+openviking privacy skill byted-viking-search-knowledgebase
+
+# 更新(整包 JSON)
+openviking privacy upsert skill byted-viking-search-knowledgebase \
+ --values-json '{"api_key":"secret-2","base_url":"https://example.com"}'
+
+# 仅更新部分 key(先读取 current 再合并)
+openviking privacy upsert skill byted-viking-search-knowledgebase \
+ --key-api_key secret-3
+
+# 版本查询与切换
+openviking privacy versions skill byted-viking-search-knowledgebase
+openviking privacy version skill byted-viking-search-knowledgebase 2
+openviking privacy activate skill byted-viking-search-knowledgebase 2
+```
+
+---
+
+## 相关文档
+
+- [技能](04-skills.md) - 技能写入与读取
+- [文件系统](03-filesystem.md) - `read`/`write`/`ls` 等
+- [系统](07-system.md) - 服务状态与可观测性
diff --git a/docs/zh/concepts/01-architecture.md b/docs/zh/concepts/01-architecture.md
index d060a3352..a2e95ac39 100644
--- a/docs/zh/concepts/01-architecture.md
+++ b/docs/zh/concepts/01-architecture.md
@@ -176,3 +176,4 @@ curl http://localhost:1933/api/v1/search/find \
- [数据加密](./10-encryption.md) - 静态数据加密与密钥架构
- [多租户](./11-multi-tenant.md) - account / user / agent 隔离模型
- [指标](./12-metrics.md) - `/metrics` 使用方式与关键指标说明
+- [用户隐私配置](./13-privacy.md) - 隐私版本管理、自动提取Skill隐私配置
diff --git a/docs/zh/concepts/13-privacy.md b/docs/zh/concepts/13-privacy.md
new file mode 100644
index 000000000..0bd475943
--- /dev/null
+++ b/docs/zh/concepts/13-privacy.md
@@ -0,0 +1,155 @@
+# 隐私配置与 Skill 隐私提取/加载
+
+本文介绍 OpenViking 的隐私配置能力,以及它与 Skill 写入(提取)和读取(加载还原)的协作机制。
+
+## 目标
+
+隐私配置用于把敏感值(如 `api_key`、`token`、`base_url`)从技能正文中分离出来,避免明文长期存储在 `SKILL.md` 中,同时保留版本化管理与回滚能力。
+
+核心目标:
+
+- 写入时自动抽取敏感值并占位符化
+- 读取时按当前生效配置自动还原
+- 支持版本查询、切换与审计
+
+---
+
+## 核心对象与存储结构
+
+隐私配置按二级键组织:`category + target_key`。
+
+- `category`:配置类别(当前 Skill 使用 `skill`)
+- `target_key`:目标标识(通常是 skill 名)
+
+用户空间下的存储路径:
+
+```
+viking://user/{user_space}/privacy/{category}/{target_key}/
+├── .meta.json # 元信息(active_version/latest_version/labels 等)
+├── current.json # 当前生效版本快照
+└── history/
+ ├── version_1.json
+ ├── version_2.json
+ └── ...
+```
+
+`current.json` 与 `history/version_x.json` 都是完整快照(`values` 整包)。
+
+---
+
+## 版本语义
+
+### upsert(写入)
+
+- 每次 upsert 都以传入 `values` 作为“新快照候选”
+- 如果与当前版本 `values` 完全一致,则不新建版本,直接返回当前版本
+- 否则创建新版本并自动设为当前生效版本
+- 允许新增 key(不会因“未知 key”报错)
+
+### activate(激活)
+
+- 将历史版本设置为当前生效版本(写回 `current.json`)
+- 更新 `.meta.json` 中的 `active_version`
+
+---
+
+## Skill 隐私提取(写入链路)
+
+当通过 `add_skill` 写入 Skill 时,会走隐私提取与占位符化流程。
+
+```
+add_skill
+ -> SkillProcessor._sanitize_skill_privacy
+ -> extract_skill_privacy_values (LLM 抽取 values)
+ -> placeholderize_skill_content_with_blocks (明文替换为占位符)
+ -> privacy.upsert(category="skill", target_key=skill_name, values=...)
+ -> 写入占位符化后的 SKILL.md
+```
+
+### 关键点
+
+1. **抽取结果来源**:模型返回 JSON,读取 `values` 字段作为隐私键值。
+2. **内容替换**:原文中命中的敏感片段会替换为占位符:
+ - `{{ov_privacy:skill:{skill_name}:{field_name}}}`
+3. **保留块映射**:会同时记录:
+ - `original_content_blocks`
+ - `replacement_content_blocks`
+4. **写盘结果**:`SKILL.md` 持久化的是占位符内容,不是明文值。
+
+---
+
+## Skill 加载还原(读取链路)
+
+读取 `SKILL.md` 时,`FSService.read` 会尝试自动还原占位符。
+
+```
+fs.read(uri)
+ -> get_skill_name_from_uri(uri)
+ -> privacy.get_current(category="skill", target_key=skill_name)
+ -> restore_skill_content(content, skill_name, current.values)
+```
+
+### URI 匹配
+
+当前支持通过后缀识别 Skill:`/skills/{name}/SKILL.md`,可兼容:
+
+- `viking://agent/skills/{name}/SKILL.md`
+- `viking://agent/{agent_id}/skills/{name}/SKILL.md`
+
+### restore 规则
+
+`restore_skill_content` 的行为如下:
+
+1. **content 中有占位符,且 privacy value 存在且非空**
+ -> 直接替换为对应值。
+
+2. **content 中有占位符,但 privacy value 缺失或为空**
+ -> 保留占位符不替换,并记入 `unresolved_entries`。
+
+3. **privacy 中存在 key 且非空,但 content 中没有对应占位符**
+ -> 记入“额外配置”提示(`Configured but not referenced in content`)。
+
+4. 当存在 `unresolved_entries` 或“额外配置”时,会在内容末尾追加:
+ - `[OpenViking Privacy Notice]`
+ - `Related configured privacy values: ...`
+ - `Not replaced (missing config): ...`(如有)
+ - `Configured but not referenced in content: ...`(如有)
+
+> 注意:当前实现中,仅当该 skill 已有 `current` 配置时才会进入 restore。若没有当前配置,不会追加 notice。
+
+---
+
+## 与 CLI/API 的关系
+
+- 管理面:通过 Privacy API/CLI 管理版本(查询、写入、回滚)
+- 内容面:通过 `read` 自动恢复占位符
+- 两者解耦:内容文件负责占位符,隐私服务负责敏感值与版本
+
+常用命令:
+
+```bash
+openviking privacy categories
+openviking privacy list skill
+openviking privacy skill <target_key>
+openviking privacy upsert skill <target_key> --values-json '{"api_key":"..."}'
+openviking privacy activate skill <target_key> <version>
+openviking read viking://agent/default/skills/<target_key>/SKILL.md
+```
+
+---
+
+## 设计收益
+
+- 降低明文敏感信息在技能正文中的暴露风险
+- 通过版本化支持密钥轮换与快速回滚
+- 对上层调用透明:`read` 即可拿到还原后的可执行技能文本
+- 对不完整配置提供可观测提示,便于排障
+
+---
+
+## 相关文档
+
+- [技能](../api/04-skills.md) - Skill 写入与读取 API
+- [隐私配置 API](../api/10-privacy.md) - 隐私配置端点说明
+- [上下文提取](./06-extraction.md) - 内容提取主流程
+- [架构概述](./01-architecture.md) - 系统分层与模块关系
diff --git a/openviking/core/directories.py b/openviking/core/directories.py
index 3621c553c..34d0ae496 100644
--- a/openviking/core/directories.py
+++ b/openviking/core/directories.py
@@ -79,6 +79,11 @@ PRESET_DIRECTORIES: Dict[str, DirectoryDefinition] = {
),
],
),
+ DirectoryDefinition(
+ path="privacy",
+ abstract="User privacy config root. Stores user-scoped sensitive configuration snapshots by category and target key.",
+ overview="Use this directory to access privacy-managed configuration values such as skill secrets. Concrete category and target-key subdirectories are created lazily by the privacy config service.",
+ ),
],
),
"agent": DirectoryDefinition(
diff --git a/openviking/privacy/__init__.py b/openviking/privacy/__init__.py
new file mode 100644
index 000000000..e01fb95f7
--- /dev/null
+++ b/openviking/privacy/__init__.py
@@ -0,0 +1,31 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Privacy config utilities for OpenViking."""
+
+from openviking.privacy.models import UserPrivacyConfigMeta, UserPrivacyConfigVersion
+from openviking.privacy.service import UserPrivacyConfigService
+from openviking.privacy.skill_extractor import (
+ SkillPrivacyExtractionResult,
+ extract_skill_privacy_values,
+)
+from openviking.privacy.skill_placeholder import (
+ SkillPrivacyPlaceholderizationResult,
+ build_placeholder,
+ placeholderize_skill_content,
+ placeholderize_skill_content_with_blocks,
+)
+from openviking.privacy.skill_restore import get_skill_name_from_uri, restore_skill_content
+
+__all__ = [
+ "UserPrivacyConfigMeta",
+ "UserPrivacyConfigVersion",
+ "UserPrivacyConfigService",
+ "SkillPrivacyExtractionResult",
+ "extract_skill_privacy_values",
+ "SkillPrivacyPlaceholderizationResult",
+ "build_placeholder",
+ "placeholderize_skill_content_with_blocks",
+ "placeholderize_skill_content",
+ "get_skill_name_from_uri",
+ "restore_skill_content",
+]
diff --git a/openviking/privacy/helpers.py b/openviking/privacy/helpers.py
new file mode 100644
index 000000000..957ea70d4
--- /dev/null
+++ b/openviking/privacy/helpers.py
@@ -0,0 +1,44 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Helpers for user privacy config paths and version handling."""
+
+import json
+import re
+from typing import Any
+
+_VERSION_RE = re.compile(r"^version_(\d+)\.json$")
+
+
+def config_root_uri(user_space: str, category: str, target_key: str) -> str:
+ return f"viking://user/{user_space}/privacy/{category}/{target_key}"
+
+
+def current_uri(user_space: str, category: str, target_key: str) -> str:
+ return f"{config_root_uri(user_space, category, target_key)}/current.json"
+
+
+def meta_uri(user_space: str, category: str, target_key: str) -> str:
+ return f"{config_root_uri(user_space, category, target_key)}/.meta.json"
+
+
+def history_dir_uri(user_space: str, category: str, target_key: str) -> str:
+ return f"{config_root_uri(user_space, category, target_key)}/history"
+
+
+def version_uri(user_space: str, category: str, target_key: str, version: int) -> str:
+ return f"{history_dir_uri(user_space, category, target_key)}/{version_filename(version)}"
+
+
+def version_filename(version: int) -> str:
+ return f"version_{version:03d}.json"
+
+
+def parse_version_filename(name: str) -> int | None:
+ match = _VERSION_RE.match(name)
+ if not match:
+ return None
+ return int(match.group(1))
+
+
+def canonicalize_values(values: dict[str, Any]) -> str:
+ return json.dumps(values, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
diff --git a/openviking/privacy/models.py b/openviking/privacy/models.py
new file mode 100644
index 000000000..8fe7e3090
--- /dev/null
+++ b/openviking/privacy/models.py
@@ -0,0 +1,84 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Models for user privacy configuration storage."""
+
+from dataclasses import dataclass, field
+from typing import Any, Dict
+
+
+@dataclass
+class UserPrivacyConfigMeta:
+ """Metadata persisted in .meta.json for a privacy config target."""
+
+ category: str = ""
+ target_key: str = ""
+ active_version: int = 0
+ latest_version: int = 0
+ created_at: str = ""
+ updated_at: str = ""
+ updated_by: str = ""
+ last_accessed_at: str = ""
+ labels: Dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "category": self.category,
+ "target_key": self.target_key,
+ "active_version": self.active_version,
+ "latest_version": self.latest_version,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ "updated_by": self.updated_by,
+ "last_accessed_at": self.last_accessed_at,
+ "labels": dict(self.labels),
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "UserPrivacyConfigMeta":
+ return cls(
+ category=data.get("category", ""),
+ target_key=data.get("target_key", ""),
+ active_version=int(data.get("active_version", 0) or 0),
+ latest_version=int(data.get("latest_version", 0) or 0),
+ created_at=data.get("created_at", ""),
+ updated_at=data.get("updated_at", ""),
+ updated_by=data.get("updated_by", ""),
+ last_accessed_at=data.get("last_accessed_at", ""),
+ labels=dict(data.get("labels", {})),
+ )
+
+
+@dataclass
+class UserPrivacyConfigVersion:
+ """Version snapshot for one privacy config target."""
+
+ version: int = 0
+ category: str = ""
+ target_key: str = ""
+ values: Dict[str, Any] = field(default_factory=dict)
+ created_at: str = ""
+ created_by: str = ""
+ change_reason: str = ""
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "version": self.version,
+ "category": self.category,
+ "target_key": self.target_key,
+ "values": dict(self.values),
+ "created_at": self.created_at,
+ "created_by": self.created_by,
+ "change_reason": self.change_reason,
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "UserPrivacyConfigVersion":
+ return cls(
+ version=int(data.get("version", 0) or 0),
+ category=data.get("category", ""),
+ target_key=data.get("target_key", ""),
+ values=dict(data.get("values", {})),
+ created_at=data.get("created_at", ""),
+ created_by=data.get("created_by", ""),
+ change_reason=data.get("change_reason", ""),
+ )
diff --git a/openviking/privacy/service.py b/openviking/privacy/service.py
new file mode 100644
index 000000000..592a37341
--- /dev/null
+++ b/openviking/privacy/service.py
@@ -0,0 +1,212 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""User privacy config storage service."""
+
+import json
+from typing import Any, Optional
+
+from openviking_cli.exceptions import NotFoundError
+
+from openviking.privacy.helpers import (
+ canonicalize_values,
+ config_root_uri,
+ current_uri,
+ history_dir_uri,
+ meta_uri,
+ parse_version_filename,
+ version_uri,
+)
+from openviking.privacy.models import UserPrivacyConfigMeta, UserPrivacyConfigVersion
+from openviking.server.identity import RequestContext
+from openviking.storage.viking_fs import VikingFS
+from openviking.utils.time_utils import get_current_timestamp
+
+
+class UserPrivacyConfigService:
+ """Manage user-scoped privacy configs with version history."""
+
+ def __init__(self, viking_fs: VikingFS):
+ self._viking_fs = viking_fs
+
+ def _user_space(self, ctx: RequestContext) -> str:
+ return ctx.user.user_space_name()
+
+ def get_config_root(self, ctx: RequestContext, category: str, target_key: str) -> str:
+ return config_root_uri(self._user_space(ctx), category, target_key)
+
+ async def exists(self, ctx: RequestContext, category: str, target_key: str) -> bool:
+ try:
+ await self._viking_fs.stat(self.get_config_root(ctx, category, target_key), ctx=ctx)
+ return True
+ except Exception:
+ return False
+
+ async def _ensure_root(self, ctx: RequestContext, category: str, target_key: str) -> None:
+ root_uri = self.get_config_root(ctx, category, target_key)
+ await self._viking_fs.mkdir(root_uri, exist_ok=True, ctx=ctx)
+ await self._viking_fs.mkdir(history_dir_uri(self._user_space(ctx), category, target_key), exist_ok=True, ctx=ctx)
+
+ async def get_meta(
+ self, ctx: RequestContext, category: str, target_key: str
+ ) -> Optional[UserPrivacyConfigMeta]:
+ try:
+ content = await self._viking_fs.read_file(
+ meta_uri(self._user_space(ctx), category, target_key), ctx=ctx
+ )
+ except Exception:
+ return None
+ return UserPrivacyConfigMeta.from_dict(json.loads(content))
+
+ async def _save_meta(
+ self, ctx: RequestContext, category: str, target_key: str, meta: UserPrivacyConfigMeta
+ ) -> None:
+ meta.updated_at = get_current_timestamp()
+ await self._viking_fs.write_file(
+ meta_uri(self._user_space(ctx), category, target_key),
+ json.dumps(meta.to_dict(), ensure_ascii=False),
+ ctx=ctx,
+ )
+
+ async def get_current(
+ self, ctx: RequestContext, category: str, target_key: str
+ ) -> Optional[UserPrivacyConfigVersion]:
+ try:
+ content = await self._viking_fs.read_file(
+ current_uri(self._user_space(ctx), category, target_key), ctx=ctx
+ )
+ except Exception:
+ return None
+ return UserPrivacyConfigVersion.from_dict(json.loads(content))
+
+ async def get_version(
+ self, ctx: RequestContext, category: str, target_key: str, version: int
+ ) -> Optional[UserPrivacyConfigVersion]:
+ try:
+ content = await self._viking_fs.read_file(
+ version_uri(self._user_space(ctx), category, target_key, version), ctx=ctx
+ )
+ except Exception:
+ return None
+ return UserPrivacyConfigVersion.from_dict(json.loads(content))
+
+ async def list_categories(self, ctx: RequestContext) -> list[str]:
+ uri = f"viking://user/{self._user_space(ctx)}/privacy"
+ try:
+ entries = await self._viking_fs.ls(uri, ctx=ctx)
+ except Exception:
+ return []
+ return sorted(entry["name"] for entry in entries if entry.get("name"))
+
+ async def list_targets(self, ctx: RequestContext, category: str) -> list[str]:
+ uri = f"viking://user/{self._user_space(ctx)}/privacy/{category}"
+ try:
+ entries = await self._viking_fs.ls(uri, ctx=ctx)
+ except Exception:
+ return []
+ return sorted(entry["name"] for entry in entries if entry.get("name"))
+
+ async def list_versions(self, ctx: RequestContext, category: str, target_key: str) -> list[int]:
+ try:
+ entries = await self._viking_fs.ls(
+ history_dir_uri(self._user_space(ctx), category, target_key), ctx=ctx
+ )
+ except Exception:
+ return []
+ versions = []
+ for entry in entries:
+ version = parse_version_filename(entry.get("name", ""))
+ if version is not None:
+ versions.append(version)
+ return sorted(versions)
+
+ async def upsert(
+ self,
+ ctx: RequestContext,
+ category: str,
+ target_key: str,
+ values: dict[str, Any],
+ updated_by: str = "",
+ change_reason: str = "",
+ labels: Optional[dict[str, Any]] = None,
+ ) -> UserPrivacyConfigVersion:
+ await self._ensure_root(ctx, category, target_key)
+ now = get_current_timestamp()
+ meta = await self.get_meta(ctx, category, target_key)
+ current = await self.get_current(ctx, category, target_key)
+
+ if current and canonicalize_values(current.values) == canonicalize_values(values):
+ if meta is None:
+ meta = UserPrivacyConfigMeta(
+ category=category,
+ target_key=target_key,
+ active_version=current.version,
+ latest_version=current.version,
+ created_at=now,
+ )
+ meta.updated_by = updated_by
+ meta.last_accessed_at = now
+ if labels is not None:
+ meta.labels = dict(labels)
+ await self._save_meta(ctx, category, target_key, meta)
+ return current
+
+ version_number = 1 if meta is None else meta.latest_version + 1
+ version = UserPrivacyConfigVersion(
+ version=version_number,
+ category=category,
+ target_key=target_key,
+ values=dict(values),
+ created_at=now,
+ created_by=updated_by,
+ change_reason=change_reason,
+ )
+
+ await self._viking_fs.write_file(
+ version_uri(self._user_space(ctx), category, target_key, version_number),
+ json.dumps(version.to_dict(), ensure_ascii=False),
+ ctx=ctx,
+ )
+ await self._viking_fs.write_file(
+ current_uri(self._user_space(ctx), category, target_key),
+ json.dumps(version.to_dict(), ensure_ascii=False),
+ ctx=ctx,
+ )
+
+ if meta is None:
+ meta = UserPrivacyConfigMeta(
+ category=category,
+ target_key=target_key,
+ created_at=now,
+ )
+ meta.active_version = version_number
+ meta.latest_version = version_number
+ meta.updated_by = updated_by
+ meta.last_accessed_at = now
+ if labels is not None:
+ meta.labels = dict(labels)
+ await self._save_meta(ctx, category, target_key, meta)
+ return version
+
+ async def activate_version(
+ self,
+ ctx: RequestContext,
+ category: str,
+ target_key: str,
+ version: int,
+ updated_by: str = "",
+ ) -> UserPrivacyConfigVersion:
+ meta = await self.get_meta(ctx, category, target_key)
+ snapshot = await self.get_version(ctx, category, target_key, version)
+ if meta is None or snapshot is None:
+ raise NotFoundError(f"{category}/{target_key}/versions/{version}", "privacy config")
+
+ await self._viking_fs.write_file(
+ current_uri(self._user_space(ctx), category, target_key),
+ json.dumps(snapshot.to_dict(), ensure_ascii=False),
+ ctx=ctx,
+ )
+ meta.active_version = version
+ meta.updated_by = updated_by
+ meta.last_accessed_at = get_current_timestamp()
+ await self._save_meta(ctx, category, target_key, meta)
+ return snapshot
diff --git a/openviking/privacy/skill_extractor.py b/openviking/privacy/skill_extractor.py
new file mode 100644
index 000000000..af2c4b8aa
--- /dev/null
+++ b/openviking/privacy/skill_extractor.py
@@ -0,0 +1,56 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Extract sensitive values from skill content."""
+
+from dataclasses import dataclass, field
+
+from openviking.privacy.skill_placeholder import placeholderize_skill_content_with_blocks
+from openviking.prompts import render_prompt
+from openviking_cli.utils.config import get_openviking_config
+from openviking_cli.utils.llm import parse_json_from_response
+
+
+@dataclass
+class SkillPrivacyExtractionResult:
+ values: dict[str, str]
+ original_content: str
+ sanitized_content: str
+ original_content_blocks: list[str] = field(default_factory=list)
+ replacement_content_blocks: list[str] = field(default_factory=list)
+
+
+async def extract_skill_privacy_values(
+ *,
+ skill_name: str,
+ skill_description: str,
+ content: str,
+) -> SkillPrivacyExtractionResult:
+ prompt = render_prompt(
+ "skill.privacy_extraction",
+ {
+ "skill_name": skill_name,
+ "skill_description": skill_description,
+ "skill_content": content,
+ },
+ )
+ response = await get_openviking_config().vlm.get_completion_async(prompt)
+ data = parse_json_from_response(response) or {}
+
+ values: dict[str, str] = {}
+ if isinstance(data, dict):
+ raw_values = data.get("values", {})
+ if isinstance(raw_values, dict):
+ values = {
+ str(key): "" if value is None else str(value)
+ for key, value in raw_values.items()
+ if str(key).strip()
+ }
+
+ placeholder_result = placeholderize_skill_content_with_blocks(content, skill_name, values)
+ return SkillPrivacyExtractionResult(
+ values=values,
+ original_content=content,
+ sanitized_content=placeholder_result.sanitized_content,
+ original_content_blocks=placeholder_result.original_content_blocks,
+ replacement_content_blocks=placeholder_result.replacement_content_blocks,
+ )
diff --git a/openviking/privacy/skill_placeholder.py b/openviking/privacy/skill_placeholder.py
new file mode 100644
index 000000000..293346266
--- /dev/null
+++ b/openviking/privacy/skill_placeholder.py
@@ -0,0 +1,47 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Placeholder helpers for skill privacy values."""
+
+from dataclasses import dataclass, field
+
+
+@dataclass
+class SkillPrivacyPlaceholderizationResult:
+ sanitized_content: str
+ original_content_blocks: list[str] = field(default_factory=list)
+ replacement_content_blocks: list[str] = field(default_factory=list)
+
+
+def build_placeholder(skill_name: str, field_name: str) -> str:
+ return f"{{{{ov_privacy:skill:{skill_name}:{field_name}}}}}"
+
+
+def placeholderize_skill_content_with_blocks(
+ content: str, skill_name: str, values: dict[str, str]
+) -> SkillPrivacyPlaceholderizationResult:
+ sanitized = content
+ original_content_blocks: list[str] = []
+ replacement_content_blocks: list[str] = []
+ replacements = sorted(values.items(), key=lambda item: len(str(item[1])), reverse=True)
+
+ for field_name, raw_value in replacements:
+ if not raw_value:
+ continue
+ raw_value_str = str(raw_value)
+ placeholder = build_placeholder(skill_name, field_name)
+ if raw_value_str in sanitized:
+ original_content_blocks.append(raw_value_str)
+ replacement_content_blocks.append(placeholder)
+ sanitized = sanitized.replace(raw_value_str, placeholder)
+
+ return SkillPrivacyPlaceholderizationResult(
+ sanitized_content=sanitized,
+ original_content_blocks=original_content_blocks,
+ replacement_content_blocks=replacement_content_blocks,
+ )
+
+
+def placeholderize_skill_content(
+ content: str, skill_name: str, values: dict[str, str]
+) -> str:
+ return placeholderize_skill_content_with_blocks(content, skill_name, values).sanitized_content
diff --git a/openviking/privacy/skill_restore.py b/openviking/privacy/skill_restore.py
new file mode 100644
index 000000000..04473adfd
--- /dev/null
+++ b/openviking/privacy/skill_restore.py
@@ -0,0 +1,69 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Read-time restore helpers for skill privacy placeholders."""
+
+import re
+
+from openviking.privacy.skill_placeholder import build_placeholder
+
+
+def get_skill_name_from_uri(uri: str) -> str | None:
+ normalized = uri.strip().rstrip("/")
+ marker = "/skills/"
+ suffix = "/SKILL.md"
+ if marker not in normalized or not normalized.endswith(suffix):
+ return None
+ start = normalized.rfind(marker)
+ if start < 0:
+ return None
+ middle = normalized[start + len(marker) : -len(suffix)]
+ if not middle or "/" in middle:
+ return None
+ return middle
+
+
+def _extract_placeholder_keys(content: str, skill_name: str) -> list[str]:
+ pattern = re.compile(r"\{\{ov_privacy:skill:" + re.escape(skill_name) + r":([^}:]+)\}\}")
+ keys: list[str] = []
+ seen: set[str] = set()
+ for match in pattern.finditer(content):
+ key = match.group(1)
+ if key not in seen:
+ seen.add(key)
+ keys.append(key)
+ return keys
+
+
+def restore_skill_content(content: str, skill_name: str, values: dict[str, str]) -> str:
+ restored = content
+ unresolved_entries: list[str] = []
+ placeholder_keys = _extract_placeholder_keys(content, skill_name)
+ placeholder_key_set = set(placeholder_keys)
+
+ for field_name in placeholder_keys:
+ placeholder = build_placeholder(skill_name, field_name)
+ raw_value = values.get(field_name)
+ if raw_value is None or str(raw_value) == "":
+ shown_value = "<missing>" if raw_value is None else '""'
+ unresolved_entries.append(f"{field_name}={shown_value}")
+ continue
+ restored = restored.replace(placeholder, str(raw_value))
+
+ extra_config_entries = [
+ f"{key}={value}"
+ for key, value in values.items()
+ if key not in placeholder_key_set and value is not None and str(value) != ""
+ ]
+
+ if unresolved_entries or extra_config_entries:
+ restored += "\n\n[Privacy Config Notice]\n"
+ if unresolved_entries:
+ restored += "Missing config: " + ", ".join(unresolved_entries) + "\n"
+ if extra_config_entries:
+ restored += (
+ "Configured but not referenced in content: "
+ + ", ".join(extra_config_entries)
+ + "\n"
+ )
+
+ return restored
diff --git a/openviking/prompts/templates/skill/privacy_extraction.yaml b/openviking/prompts/templates/skill/privacy_extraction.yaml
new file mode 100644
index 000000000..588e15dbc
--- /dev/null
+++ b/openviking/prompts/templates/skill/privacy_extraction.yaml
@@ -0,0 +1,75 @@
+metadata:
+ id: "skill.privacy_extraction"
+ name: "Skill Privacy Extraction"
+ description: "Extract user-maintained private config items from skill content as structured JSON"
+ version: "1.1.0"
+ language: "en"
+ category: "skill"
+
+variables:
+ - name: "skill_name"
+ type: "string"
+ description: "Skill name"
+ required: true
+ - name: "skill_description"
+ type: "string"
+ description: "Skill description"
+ required: true
+ - name: "skill_content"
+ type: "string"
+ description: "Complete skill content"
+ required: true
+
+template: |
+ Analyze the following skill content and extract user-private configuration items that should be maintained in the privacy config store.
+
+ ## Skill Information
+ **Name**: {{ skill_name }}
+ **Description**: {{ skill_description }}
+
+ ## Complete Content
+ {{ skill_content }}
+
+ ## Extraction Goal
+ Identify configuration items that are private, security-sensitive, environment-specific, tenant-specific, or user-maintained, even if the skill content does not contain a concrete value yet.
+
+ ## Extraction Rules
+ - Extract both:
+ - configuration items with explicit concrete values already present in the content
+ - configuration items that are clearly required or expected to be provided by the user, even if the value is missing, described only in prose, or shown only as a placeholder/example
+ - Focus especially on secrets, credentials, endpoints, and user-maintained connection settings, including but not limited to:
+ - api_key
+ - token
+ - ak
+ - sk
+ - access_key
+ - secret_key
+ - client_secret
+ - base_url
+ - endpoint
+ - host
+ - project
+ - resource_id
+ - collection_name
+ - collection
+ - database
+ - username
+ - password
+ - If a config item is clearly required but no real value is present, still include the field and set its value to an empty string.
+ - Prefer normalized snake_case field names when the document uses human-readable labels. For example:
+ - "Access Key" -> "access_key"
+ - "Secret Key" -> "secret_key"
+ - Do not invent concrete secret values.
+ - Ignore ordinary business input parameters that are not user-maintained configuration, such as one-time query inputs like query, limit, or request payload examples.
+ - If no user-maintained private config items are present, return an empty object.
+
+ ## Output Format
+ Return JSON only, in exactly this shape:
+ {
+ "values": {
+ "field_name": "raw value or empty string"
+ }
+ }
+
+llm_config:
+ temperature: 0.0
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 13ade23ac..bb1de92a7 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -35,6 +35,7 @@ from openviking.server.routers import (
metrics_router,
observer_router,
pack_router,
+ privacy_configs_router,
relations_router,
resources_router,
search_router,
@@ -402,6 +403,7 @@ def create_app(
app.include_router(content_router)
app.include_router(search_router)
app.include_router(relations_router)
+ app.include_router(privacy_configs_router)
app.include_router(sessions_router)
app.include_router(stats_router)
app.include_router(pack_router)
diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.py
index 95fe50a1b..54b2d22b0 100644
--- a/openviking/server/routers/__init__.py
+++ b/openviking/server/routers/__init__.py
@@ -11,6 +11,7 @@ from openviking.server.routers.maintenance import router as maintenance_router
from openviking.server.routers.metrics import router as metrics_router
from openviking.server.routers.observer import router as observer_router
from openviking.server.routers.pack import router as pack_router
+from openviking.server.routers.privacy_configs import router as privacy_configs_router
from openviking.server.routers.relations import router as relations_router
from openviking.server.routers.resources import router as resources_router
from openviking.server.routers.search import router as search_router
@@ -32,6 +33,7 @@ __all__ = [
"sessions_router",
"stats_router",
"pack_router",
+ "privacy_configs_router",
"debug_router",
"metrics_router",
"observer_router",
diff --git a/openviking/server/routers/privacy_configs.py b/openviking/server/routers/privacy_configs.py
new file mode 100644
index 000000000..dda361186
--- /dev/null
+++ b/openviking/server/routers/privacy_configs.py
@@ -0,0 +1,153 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Privacy config endpoints for OpenViking HTTP Server."""
+
+from typing import Any, Dict, Optional
+
+from fastapi import APIRouter, Depends, Path
+from pydantic import BaseModel, ConfigDict
+
+from openviking.server.auth import get_request_context
+from openviking_cli.exceptions import NotFoundError
+from openviking.server.dependencies import get_service
+from openviking.server.identity import RequestContext
+from openviking.server.models import Response
+
+router = APIRouter(prefix="/api/v1/privacy-configs", tags=["privacy-configs"])
+
+
+async def _require_privacy_target(
+ privacy,
+ ctx: RequestContext,
+ category: str,
+ target_key: str,
+) -> None:
+ if privacy is None or not await privacy.exists(ctx, category, target_key):
+ raise NotFoundError(f"{category}/{target_key}", "privacy config")
+
+
+class UpsertPrivacyConfigRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ values: Dict[str, Any]
+ change_reason: str = ""
+ labels: Optional[Dict[str, Any]] = None
+
+
+class ActivatePrivacyConfigVersionRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ version: int
+
+
+async def list_privacy_categories(
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ service = get_service()
+ privacy = service.privacy_configs
+ result = [] if privacy is None else await privacy.list_categories(_ctx)
+ return Response(status="ok", result=result)
+
+
[email protected]("/{category}")
+async def list_privacy_targets(
+ category: str = Path(..., description="Privacy config category"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ service = get_service()
+ privacy = service.privacy_configs
+ result = [] if privacy is None else await privacy.list_targets(_ctx, category)
+ return Response(status="ok", result=result)
+
+
[email protected]("/{category}/{target_key}")
+async def get_privacy_current(
+ category: str = Path(..., description="Privacy config category"),
+ target_key: str = Path(..., description="Privacy config target key"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ service = get_service()
+ privacy = service.privacy_configs
+ await _require_privacy_target(privacy, _ctx, category, target_key)
+ meta = await privacy.get_meta(_ctx, category, target_key)
+ current = await privacy.get_current(_ctx, category, target_key)
+ return Response(
+ status="ok",
+ result={
+ "meta": None if meta is None else meta.to_dict(),
+ "current": None if current is None else current.to_dict(),
+ },
+ )
+
+
[email protected]("/{category}/{target_key}/versions")
+async def list_privacy_versions(
+ category: str = Path(..., description="Privacy config category"),
+ target_key: str = Path(..., description="Privacy config target key"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ service = get_service()
+ privacy = service.privacy_configs
+ await _require_privacy_target(privacy, _ctx, category, target_key)
+ versions = await privacy.list_versions(_ctx, category, target_key)
+ return Response(status="ok", result=versions)
+
+
[email protected]("/{category}/{target_key}/versions/{version}")
+async def get_privacy_version(
+ category: str = Path(..., description="Privacy config category"),
+ target_key: str = Path(..., description="Privacy config target key"),
+ version: int = Path(..., description="Privacy config version"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ service = get_service()
+ privacy = service.privacy_configs
+ await _require_privacy_target(privacy, _ctx, category, target_key)
+ snapshot = await privacy.get_version(_ctx, category, target_key, version)
+ if snapshot is None:
+ raise NotFoundError(f"{category}/{target_key}/versions/{version}", "privacy config")
+ return Response(status="ok", result=snapshot.to_dict())
+
+
[email protected]("/{category}/{target_key}")
+async def upsert_privacy_config(
+ request: UpsertPrivacyConfigRequest,
+ category: str = Path(..., description="Privacy config category"),
+ target_key: str = Path(..., description="Privacy config target key"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ service = get_service()
+ privacy = service.privacy_configs
+ result = None
+ if privacy is not None:
+ result = await privacy.upsert(
+ ctx=_ctx,
+ category=category,
+ target_key=target_key,
+ values=request.values,
+ updated_by=_ctx.user.user_id,
+ change_reason=request.change_reason,
+ labels=request.labels,
+ )
+ return Response(status="ok", result=None if result is None else result.to_dict())
+
+
[email protected]("/{category}/{target_key}/activate")
+async def activate_privacy_version(
+ request: ActivatePrivacyConfigVersionRequest,
+ category: str = Path(..., description="Privacy config category"),
+ target_key: str = Path(..., description="Privacy config target key"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ service = get_service()
+ privacy = service.privacy_configs
+ await _require_privacy_target(privacy, _ctx, category, target_key)
+ result = await privacy.activate_version(
+ ctx=_ctx,
+ category=category,
+ target_key=target_key,
+ version=request.version,
+ updated_by=_ctx.user.user_id,
+ )
+ return Response(status="ok", result=result.to_dict())
diff --git a/openviking/service/core.py b/openviking/service/core.py
index ae9851ab2..63293dd84 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -11,6 +11,7 @@ from typing import Any, Optional
from openviking.core.directories import DirectoryInitializer
from openviking.crypto.config import bootstrap_encryption
+from openviking.privacy import UserPrivacyConfigService
from openviking.resource.watch_scheduler import WatchScheduler
from openviking.server.identity import RequestContext, Role
from openviking.service.debug_service import DebugService
@@ -79,6 +80,7 @@ class OpenVikingService:
self._directory_initializer: Optional[DirectoryInitializer] = None
self._watch_scheduler: Optional[WatchScheduler] = None
self._encryptor: Optional[Any] = None
+ self._privacy_config_service: Optional[UserPrivacyConfigService] = None
# Sub-services
self._fs_service = FSService()
@@ -212,6 +214,11 @@ class OpenVikingService:
"""Get SessionService instance."""
return self._session_service
+ @property
+ def privacy_configs(self) -> Optional[UserPrivacyConfigService]:
+ """Get UserPrivacyConfigService instance."""
+ return self._privacy_config_service
+
@property
def debug(self) -> DebugService:
"""Get DebugService instance."""
@@ -296,11 +303,16 @@ class OpenVikingService:
user_count,
)
+ self._privacy_config_service = UserPrivacyConfigService(self._viking_fs)
+
# Initialize processors
self._resource_processor = ResourceProcessor(
vikingdb=self._vikingdb_manager,
)
- self._skill_processor = SkillProcessor(vikingdb=self._vikingdb_manager)
+ self._skill_processor = SkillProcessor(
+ vikingdb=self._vikingdb_manager,
+ privacy_config_service=self._privacy_config_service,
+ )
self._session_compressor = create_session_compressor(vikingdb=self._vikingdb_manager)
# Start LockManager if initialized
@@ -316,7 +328,10 @@ class OpenVikingService:
logger.info("WatchScheduler started")
# Wire up sub-services
- self._fs_service.set_viking_fs(self._viking_fs)
+ self._fs_service.set_dependencies(
+ viking_fs=self._viking_fs,
+ privacy_config_service=self._privacy_config_service,
+ )
self._relation_service.set_viking_fs(self._viking_fs)
self._pack_service.set_viking_fs(self._viking_fs)
self._search_service.set_viking_fs(self._viking_fs)
@@ -368,6 +383,7 @@ class OpenVikingService:
self._skill_processor = None
self._session_compressor = None
self._directory_initializer = None
+ self._privacy_config_service = None
self._initialized = False
logger.info("OpenVikingService closed")
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index cb2ef9eeb..eb01841c9 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -9,6 +9,7 @@ Provides file system operations: ls, mkdir, rm, mv, tree, stat, read, abstract,
from typing import Any, Dict, List, Optional
from openviking.core.directories import get_context_type_for_uri
+from openviking.privacy import UserPrivacyConfigService, get_skill_name_from_uri, restore_skill_content
from openviking.core.uri_validation import validate_optional_viking_uri, validate_viking_uri
from openviking.server.identity import RequestContext
from openviking.storage.content_write import ContentWriteCoordinator
@@ -23,12 +24,22 @@ logger = get_logger(__name__)
class FSService:
"""File system operations service."""
- def __init__(self, viking_fs: Optional[VikingFS] = None):
+ def __init__(
+ self,
+ viking_fs: Optional[VikingFS] = None,
+ privacy_config_service: Optional[UserPrivacyConfigService] = None,
+ ):
self._viking_fs = viking_fs
+ self._privacy_config_service = privacy_config_service
- def set_viking_fs(self, viking_fs: VikingFS) -> None:
- """Set VikingFS instance (for deferred initialization)."""
+ def set_dependencies(
+ self,
+ viking_fs: VikingFS,
+ privacy_config_service: Optional[UserPrivacyConfigService] = None,
+ ) -> None:
+ """Set service dependencies (for deferred initialization)."""
self._viking_fs = viking_fs
+ self._privacy_config_service = privacy_config_service
def _ensure_initialized(self) -> VikingFS:
"""Ensure VikingFS is initialized."""
@@ -188,7 +199,22 @@ class FSService:
"""Read file content."""
viking_fs = self._ensure_initialized()
uri = validate_viking_uri(uri)
- return await viking_fs.read_file(uri, offset=offset, limit=limit, ctx=ctx)
+ content = await viking_fs.read_file(uri, ctx=ctx)
+ skill_name = get_skill_name_from_uri(uri)
+ if skill_name and self._privacy_config_service:
+ current = await self._privacy_config_service.get_current(
+ ctx=ctx,
+ category="skill",
+ target_key=skill_name,
+ )
+ if current:
+ content = restore_skill_content(content, skill_name, current.values)
+
+ if offset == 0 and limit == -1:
+ return content
+ lines = content.splitlines(keepends=True)
+ sliced = lines[offset:] if limit == -1 else lines[offset : offset + limit]
+ return "".join(sliced)
async def abstract(self, uri: str, ctx: RequestContext) -> str:
"""Read L0 abstract (.abstract.md)."""
diff --git a/openviking/utils/skill_processor.py b/openviking/utils/skill_processor.py
index abf7c4460..1a600a71f 100644
--- a/openviking/utils/skill_processor.py
+++ b/openviking/utils/skill_processor.py
@@ -9,6 +9,7 @@ Handles skill parsing, LLM generation, and storage operations.
import tempfile
import time
import zipfile
+from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -16,6 +17,10 @@ from openviking.core.context import Context, ContextType, Vectorize
from openviking.core.mcp_converter import is_mcp_format, mcp_to_skill
from openviking.core.namespace import agent_space_fragment, canonical_agent_root
from openviking.core.skill_loader import SkillLoader
+from openviking.privacy import (
+ UserPrivacyConfigService,
+ extract_skill_privacy_values,
+)
from openviking.server.identity import RequestContext
from openviking.server.local_input_guard import deny_direct_local_skill_input
from openviking.storage import VikingDBManager
@@ -42,9 +47,14 @@ class SkillProcessor:
5. Index to vector store
"""
- def __init__(self, vikingdb: VikingDBManager):
+ def __init__(
+ self,
+ vikingdb: VikingDBManager,
+ privacy_config_service: Optional[UserPrivacyConfigService] = None,
+ ):
"""Initialize skill processor."""
self.vikingdb = vikingdb
+ self._privacy_config_service = privacy_config_service
async def process_skill(
self,
@@ -80,6 +90,8 @@ class SkillProcessor:
"skill.parse.duration_ms", round((time.perf_counter() - parse_start) * 1000, 3)
)
+ skill_dict = await self._sanitize_skill_privacy(skill_dict, ctx)
+
context = Context(
uri=f"{canonical_agent_root(ctx)}/skills/{skill_dict['name']}",
parent_uri=f"{canonical_agent_root(ctx)}/skills",
@@ -198,6 +210,33 @@ class SkillProcessor:
return skill_dict, auxiliary_files, base_path
+ async def _sanitize_skill_privacy(
+ self, skill_dict: Dict[str, Any], ctx: RequestContext
+ ) -> Dict[str, Any]:
+ if not self._privacy_config_service:
+ return skill_dict
+
+ content = skill_dict.get("content", "")
+ extraction_result = await extract_skill_privacy_values(
+ skill_name=skill_dict.get("name", ""),
+ skill_description=skill_dict.get("description", ""),
+ content=content,
+ )
+ if not extraction_result.values:
+ return skill_dict
+
+ sanitized = deepcopy(skill_dict)
+ sanitized["content"] = extraction_result.sanitized_content
+ await self._privacy_config_service.upsert(
+ ctx=ctx,
+ category="skill",
+ target_key=sanitized["name"],
+ values=extraction_result.values,
+ updated_by=ctx.user.user_id,
+ change_reason="auto-extracted from add_skill",
+ )
+ return sanitized
+
async def _generate_overview(self, skill_dict: Dict[str, Any], config) -> str:
"""Generate L1 overview using VLM."""
from openviking.prompts import render_prompt
diff --git a/tests/server/conftest.py b/tests/server/conftest.py
index 577420d56..0bb79148c 100644
--- a/tests/server/conftest.py
+++ b/tests/server/conftest.py
@@ -74,6 +74,8 @@ def _install_fake_vlm(monkeypatch):
"""Use a fake VLM so server tests never hit external LLM APIs."""
async def _fake_get_completion(self, prompt, thinking=False):
+ if "extract user-private configuration items" in prompt:
+ return '{"values": {"api_key": "secret-xyz", "base_url": "https://example.com"}}'
return "# Test Summary\n\nFake summary for testing.\n\n## Details\nTest content."
async def _fake_get_vision_completion(self, prompt, images, thinking=False):
diff --git a/tests/server/test_api_privacy_configs.py b/tests/server/test_api_privacy_configs.py
new file mode 100644
index 000000000..9eb818566
--- /dev/null
+++ b/tests/server/test_api_privacy_configs.py
@@ -0,0 +1,122 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import httpx
+
+
+async def test_privacy_config_api_roundtrip(client: httpx.AsyncClient):
+ upsert = await client.post(
+ "/api/v1/privacy-configs/skill/demo-skill",
+ json={
+ "values": {"api_key": "secret-1"},
+ "change_reason": "seed",
+ },
+ )
+ assert upsert.status_code == 200
+ body = upsert.json()
+ assert body["status"] == "ok"
+ assert body["result"]["version"] == 1
+
+ get_current = await client.get("/api/v1/privacy-configs/skill/demo-skill")
+ assert get_current.status_code == 200
+ current_body = get_current.json()
+ assert current_body["result"]["current"]["values"]["api_key"] == "secret-1"
+ assert current_body["result"]["meta"]["active_version"] == 1
+
+ second = await client.post(
+ "/api/v1/privacy-configs/skill/demo-skill",
+ json={
+ "values": {"api_key": "secret-2"},
+ "change_reason": "rotate",
+ },
+ )
+ assert second.status_code == 200
+ assert second.json()["result"]["version"] == 2
+
+ versions = await client.get("/api/v1/privacy-configs/skill/demo-skill/versions")
+ assert versions.status_code == 200
+ assert versions.json()["result"] == [1, 2]
+
+ activate = await client.post(
+ "/api/v1/privacy-configs/skill/demo-skill/activate",
+ json={"version": 1},
+ )
+ assert activate.status_code == 200
+ assert activate.json()["result"]["version"] == 1
+
+ final_current = await client.get("/api/v1/privacy-configs/skill/demo-skill")
+ assert final_current.json()["result"]["current"]["values"]["api_key"] == "secret-1"
+
+
+async def test_privacy_config_update_allows_new_keys(client: httpx.AsyncClient):
+ create = await client.post(
+ "/api/v1/privacy-configs/skill/demo-skill-unknown-key",
+ json={
+ "values": {"api_key": "secret-1"},
+ "change_reason": "seed",
+ },
+ )
+ assert create.status_code == 200
+
+ update = await client.post(
+ "/api/v1/privacy-configs/skill/demo-skill-unknown-key",
+ json={
+ "values": {"api_key": "secret-2", "new_key": "x"},
+ "change_reason": "extend-keys",
+ },
+ )
+ assert update.status_code == 200
+ body = update.json()
+ assert body["status"] == "ok"
+ assert body["result"]["values"]["api_key"] == "secret-2"
+ assert body["result"]["values"]["new_key"] == "x"
+
+
+async def test_privacy_config_get_version_not_found(client: httpx.AsyncClient):
+ create = await client.post(
+ "/api/v1/privacy-configs/skill/demo-skill-version-not-found",
+ json={
+ "values": {"api_key": "secret-1"},
+ "change_reason": "seed",
+ },
+ )
+ assert create.status_code == 200
+
+ missing = await client.get(
+ "/api/v1/privacy-configs/skill/demo-skill-version-not-found/versions/10"
+ )
+ assert missing.status_code == 404
+ body = missing.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "NOT_FOUND"
+
+
+async def test_privacy_config_target_not_found(client: httpx.AsyncClient):
+ missing_target = "demo-skill-target-not-found"
+
+ detail = await client.get(f"/api/v1/privacy-configs/skill/{missing_target}")
+ assert detail.status_code == 404
+ detail_body = detail.json()
+ assert detail_body["status"] == "error"
+ assert detail_body["error"]["code"] == "NOT_FOUND"
+
+ versions = await client.get(f"/api/v1/privacy-configs/skill/{missing_target}/versions")
+ assert versions.status_code == 404
+ versions_body = versions.json()
+ assert versions_body["status"] == "error"
+ assert versions_body["error"]["code"] == "NOT_FOUND"
+
+ version_detail = await client.get(f"/api/v1/privacy-configs/skill/{missing_target}/versions/1")
+ assert version_detail.status_code == 404
+ version_detail_body = version_detail.json()
+ assert version_detail_body["status"] == "error"
+ assert version_detail_body["error"]["code"] == "NOT_FOUND"
+
+ activate = await client.post(
+ f"/api/v1/privacy-configs/skill/{missing_target}/activate",
+ json={"version": 1},
+ )
+ assert activate.status_code == 404
+ activate_body = activate.json()
+ assert activate_body["status"] == "error"
+ assert activate_body["error"]["code"] == "NOT_FOUND"
diff --git a/tests/server/test_privacy_config_service.py b/tests/server/test_privacy_config_service.py
new file mode 100644
index 000000000..19d45a888
--- /dev/null
+++ b/tests/server/test_privacy_config_service.py
@@ -0,0 +1,183 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import pytest
+
+from openviking.privacy.skill_extractor import extract_skill_privacy_values
+from openviking.server.identity import RequestContext, Role
+from openviking_cli.session.user_id import UserIdentifier
+
+
+async def test_privacy_config_service_versions(service):
+ ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_user"), role=Role.ROOT)
+ await service.initialize_user_directories(ctx)
+
+ privacy = service.privacy_configs
+ first = await privacy.upsert(
+ ctx=ctx,
+ category="skill",
+ target_key="demo-skill",
+ values={"api_key": "secret-1"},
+ updated_by=ctx.user.user_id,
+ )
+ same = await privacy.upsert(
+ ctx=ctx,
+ category="skill",
+ target_key="demo-skill",
+ values={"api_key": "secret-1"},
+ updated_by=ctx.user.user_id,
+ )
+ second = await privacy.upsert(
+ ctx=ctx,
+ category="skill",
+ target_key="demo-skill",
+ values={"api_key": "secret-2"},
+ updated_by=ctx.user.user_id,
+ )
+
+ assert first.version == 1
+ assert same.version == 1
+ assert second.version == 2
+ assert await privacy.list_versions(ctx, "skill", "demo-skill") == [1, 2]
+
+ restored = await privacy.activate_version(ctx, "skill", "demo-skill", 1, updated_by=ctx.user.user_id)
+ current = await privacy.get_current(ctx, "skill", "demo-skill")
+ assert restored.version == 1
+ assert current.version == 1
+ assert current.values["api_key"] == "secret-1"
+
+
+async def test_skill_read_restores_placeholder(service):
+ ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_restore"), role=Role.ROOT)
+ await service.initialize_user_directories(ctx)
+ await service.initialize_agent_directories(ctx)
+
+ await service.resources.add_skill(
+ data={
+ "name": "restore-skill",
+ "description": "skill with secret",
+ "content": 'api_key: "secret-xyz"\nbase_url: "https://example.com"\n',
+ },
+ ctx=ctx,
+ wait=False,
+ )
+
+ stored = await service.viking_fs.read_file("viking://agent/skills/restore-skill/SKILL.md", ctx=ctx)
+ restored = await service.fs.read("viking://agent/skills/restore-skill/SKILL.md", ctx=ctx)
+
+ assert "secret-xyz" not in stored
+ assert "{{ov_privacy:skill:restore-skill:api_key}}" in stored
+ assert "secret-xyz" in restored
+ assert "https://example.com" in restored
+
+
+async def test_skill_read_restores_placeholder_with_agent_segment(service):
+ ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_restore_agent_segment"), role=Role.ROOT)
+ await service.initialize_user_directories(ctx)
+ await service.initialize_agent_directories(ctx)
+
+ await service.resources.add_skill(
+ data={
+ "name": "restore-skill-agent-segment",
+ "description": "skill with secret",
+ "content": 'api_key: "secret-abc"\nbase_url: "https://example.com"\n',
+ },
+ ctx=ctx,
+ wait=False,
+ )
+
+ restored = await service.fs.read(
+ "viking://agent/default/skills/restore-skill-agent-segment/SKILL.md",
+ ctx=ctx,
+ )
+
+ assert "secret-abc" in restored
+ assert "https://example.com" in restored
+
+
+async def test_skill_privacy_extraction_returns_content_blocks():
+ content = 'api_key: "secret-xyz"\nbase_url: "https://example.com"\n'
+ result = await extract_skill_privacy_values(
+ skill_name="extract-block-skill",
+ skill_description="skill with secret",
+ content=content,
+ )
+
+ assert result.values["api_key"] == "secret-xyz"
+ assert result.values["base_url"] == "https://example.com"
+ assert result.original_content == content
+ assert result.original_content_blocks == ["https://example.com", "secret-xyz"]
+ assert result.replacement_content_blocks == [
+ "{{ov_privacy:skill:extract-block-skill:base_url}}",
+ "{{ov_privacy:skill:extract-block-skill:api_key}}",
+ ]
+ assert result.sanitized_content == (
+ 'api_key: "{{ov_privacy:skill:extract-block-skill:api_key}}"\n'
+ 'base_url: "{{ov_privacy:skill:extract-block-skill:base_url}}"\n'
+ )
+
+
+async def test_skill_read_appends_notice_for_unreplaced_placeholders(service):
+ ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_partial_restore"), role=Role.ROOT)
+ await service.initialize_user_directories(ctx)
+ await service.initialize_agent_directories(ctx)
+
+ skill_uri = "viking://agent/skills/partial-restore-skill"
+ await service.viking_fs.mkdir(skill_uri, exist_ok=True, ctx=ctx)
+ await service.viking_fs.write_file(
+ f"{skill_uri}/SKILL.md",
+ (
+ 'api_key: "{{ov_privacy:skill:partial-restore-skill:api_key}}"\n'
+ 'region: "{{ov_privacy:skill:partial-restore-skill:region}}"\n'
+ ),
+ ctx=ctx,
+ )
+
+ await service.privacy_configs.upsert(
+ ctx=ctx,
+ category="skill",
+ target_key="partial-restore-skill",
+ values={"api_key": "secret-xyz"},
+ updated_by=ctx.user.user_id,
+ )
+
+ restored = await service.fs.read(f"{skill_uri}/SKILL.md", ctx=ctx)
+
+ assert 'api_key: "secret-xyz"' in restored
+ assert '{{ov_privacy:skill:partial-restore-skill:region}}' in restored
+ assert "[Privacy Config Notice]" in restored
+ assert "Missing config: region=<missing>" in restored
+
+
+async def test_skill_read_appends_notice_for_extra_configured_keys(service):
+ ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_extra_config"), role=Role.ROOT)
+ await service.initialize_user_directories(ctx)
+ await service.initialize_agent_directories(ctx)
+
+ skill_uri = "viking://agent/skills/extra-config-skill"
+ await service.viking_fs.mkdir(skill_uri, exist_ok=True, ctx=ctx)
+ await service.viking_fs.write_file(
+ f"{skill_uri}/SKILL.md",
+ 'api_key: "{{ov_privacy:skill:extra-config-skill:api_key}}"\n',
+ ctx=ctx,
+ )
+
+ await service.privacy_configs.upsert(
+ ctx=ctx,
+ category="skill",
+ target_key="extra-config-skill",
+ values={"api_key": "secret-xyz", "region": "cn"},
+ updated_by=ctx.user.user_id,
+ )
+
+ restored = await service.fs.read(f"{skill_uri}/SKILL.md", ctx=ctx)
+
+ assert 'api_key: "secret-xyz"' in restored
+ assert "[Privacy Config Notice]" in restored
+ assert "Configured but not referenced in content: region=cn" in restored