Skip to content

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

fix: auth and system cmds (#1545)

MaojiaShengb13410546b07
diff --git a/crates/ov_cli/src/commands/system.rs b/crates/ov_cli/src/commands/system.rs
index f41fc7c6d..96dea7803 100644
--- a/crates/ov_cli/src/commands/system.rs
+++ b/crates/ov_cli/src/commands/system.rs
@@ -38,23 +38,20 @@ pub async fn health(
.get("healthy")
.and_then(|v| v.as_bool())
.unwrap_or(false);
- let _status = response.get("status").and_then(|v| v.as_str());
- let version = response.get("version").and_then(|v| v.as_str());
- let user_id = response.get("user_id").and_then(|v| v.as_str());
// For table output, print in a readable format
if matches!(output_format, OutputFormat::Table) || matches!(output_format, OutputFormat::Json) {
output_success(&response, output_format, compact);
} else {
- // Simple text output
- print!("healthy {}", if healthy { "true" } else { "false" });
- if let Some(v) = version {
- print!(" version {}", v);
+ // Simple text output - print healthy first, then other fields line by line
+ println!("healthy {}", if healthy { "true" } else { "false" });
+ if let Some(obj) = response.as_object() {
+ for (key, value) in obj {
+ if key != "healthy" {
+ println!("{} {}", key, value);
+ }
+ }
}
- if let Some(u) = user_id {
- print!(" user_id {}", u);
- }
- println!();
}
Ok(healthy)
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
new file mode 100644
index 000000000..62c0c6ef1
--- /dev/null
+++ b/crates/ov_cli/src/handlers.rs
@@ -0,0 +1,747 @@
+use crate::client;
+use crate::commands;
+use crate::config::merge_csv_options;
+use crate::error::{Error, Result};
+use crate::tui;
+use crate::CliContext;
+
+pub async fn handle_add_resource(
+ mut path: String,
+ to: Option<String>,
+ parent: Option<String>,
+ reason: String,
+ instruction: String,
+ wait: bool,
+ timeout: Option<f64>,
+ strict_mode: bool,
+ ignore_dirs: Option<String>,
+ include: Option<String>,
+ exclude: Option<String>,
+ no_directly_upload_media: bool,
+ watch_interval: f64,
+ ctx: CliContext,
+) -> Result<()> {
+ let is_url =
+ path.starts_with("http://") || path.starts_with("https://") || path.starts_with("git@");
+
+ if !is_url {
+ use std::path::Path;
+
+ // Unescape path: replace backslash followed by space with just space
+ let unescaped_path = path.replace("\\ ", " ");
+ let path_obj = Path::new(&unescaped_path);
+ if !path_obj.exists() {
+ eprintln!("Error: Path '{}' does not exist.", path);
+
+ // Check if there might be unquoted spaces
+ use std::env;
+ let args: Vec<String> = env::args().collect();
+
+ if let Some(add_resource_pos) =
+ args.iter().position(|s| s == "add-resource" || s == "add")
+ {
+ if args.len() > add_resource_pos + 2 {
+ let extra_args = &args[add_resource_pos + 2..];
+ let suggested_path = format!("{} {}", path, extra_args.join(" "));
+ eprintln!(
+ "\nIt looks like you may have forgotten to quote a path with spaces."
+ );
+ eprintln!("Suggested command: ov add-resource \"{}\"", suggested_path);
+ }
+ }
+
+ std::process::exit(1);
+ }
+ path = unescaped_path;
+ }
+
+ // Check that only one of --to or --parent is set
+ if to.is_some() && parent.is_some() {
+ eprintln!("Error: Cannot specify both --to and --parent at the same time.");
+ std::process::exit(1);
+ }
+
+ let strict = strict_mode;
+ let directly_upload_media = !no_directly_upload_media;
+
+ let effective_ignore_dirs =
+ merge_csv_options(ctx.config.upload.ignore_dirs.clone(), ignore_dirs);
+ let effective_include = merge_csv_options(ctx.config.upload.include.clone(), include);
+ let effective_exclude = merge_csv_options(ctx.config.upload.exclude.clone(), exclude);
+
+ let effective_timeout = if wait {
+ timeout.unwrap_or(60.0).max(ctx.config.timeout)
+ } else {
+ ctx.config.timeout
+ };
+ let client = client::HttpClient::new(
+ &ctx.config.url,
+ ctx.config.api_key.clone(),
+ ctx.config.agent_id.clone(),
+ ctx.config.account.clone(),
+ ctx.config.user.clone(),
+ effective_timeout,
+ );
+ commands::resources::add_resource(
+ &client,
+ &path,
+ to,
+ parent,
+ reason,
+ instruction,
+ wait,
+ timeout,
+ strict,
+ effective_ignore_dirs,
+ effective_include,
+ effective_exclude,
+ directly_upload_media,
+ watch_interval,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_add_skill(
+ data: String,
+ wait: bool,
+ timeout: Option<f64>,
+ ctx: CliContext,
+) -> Result<()> {
+ let client = ctx.get_client();
+ commands::resources::add_skill(
+ &client,
+ &data,
+ wait,
+ timeout,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_relations(uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::relations::list_relations(&client, &uri, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_link(
+ from_uri: String,
+ to_uris: Vec<String>,
+ reason: String,
+ ctx: CliContext,
+) -> Result<()> {
+ let client = ctx.get_client();
+ commands::relations::link(
+ &client,
+ &from_uri,
+ &to_uris,
+ &reason,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_unlink(from_uri: String, to_uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::relations::unlink(&client, &from_uri, &to_uri, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_export(uri: String, to: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::pack::export(&client, &uri, &to, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_import(
+ file_path: String,
+ target_uri: String,
+ force: bool,
+ no_vectorize: bool,
+ ctx: CliContext,
+) -> Result<()> {
+ let client = ctx.get_client();
+ commands::pack::import(
+ &client,
+ &file_path,
+ &target_uri,
+ force,
+ no_vectorize,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+use crate::SystemCommands;
+
+pub async fn handle_system(cmd: SystemCommands, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ match cmd {
+ SystemCommands::Wait { timeout } => {
+ commands::system::wait(&client, timeout, ctx.output_format, ctx.compact).await
+ }
+ SystemCommands::Status => {
+ commands::system::status(&client, ctx.output_format, ctx.compact).await
+ }
+ SystemCommands::Health => {
+ let _ = commands::system::health(&client, ctx.output_format, ctx.compact).await?;
+ Ok(())
+ }
+ SystemCommands::Crypto { action } => commands::crypto::handle_crypto(action).await,
+ }
+}
+
+use crate::ObserverCommands;
+
+pub async fn handle_observer(cmd: ObserverCommands, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ match cmd {
+ ObserverCommands::Queue => {
+ commands::observer::queue(&client, ctx.output_format, ctx.compact).await
+ }
+ ObserverCommands::Vikingdb => {
+ commands::observer::vikingdb(&client, ctx.output_format, ctx.compact).await
+ }
+ ObserverCommands::Models => {
+ commands::observer::models(&client, ctx.output_format, ctx.compact).await
+ }
+ ObserverCommands::Transaction => {
+ commands::observer::transaction(&client, ctx.output_format, ctx.compact).await
+ }
+ ObserverCommands::Retrieval => {
+ commands::observer::retrieval(&client, ctx.output_format, ctx.compact).await
+ }
+ ObserverCommands::System => {
+ commands::observer::system(&client, ctx.output_format, ctx.compact).await
+ }
+ }
+}
+
+use crate::SessionCommands;
+
+pub async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ match cmd {
+ SessionCommands::New => {
+ commands::session::new_session(&client, ctx.output_format, ctx.compact).await
+ }
+ SessionCommands::List => {
+ commands::session::list_sessions(&client, ctx.output_format, ctx.compact).await
+ }
+ SessionCommands::Get { session_id } => {
+ commands::session::get_session(&client, &session_id, ctx.output_format, ctx.compact)
+ .await
+ }
+ SessionCommands::GetSessionContext {
+ session_id,
+ token_budget,
+ } => {
+ commands::session::get_session_context(
+ &client,
+ &session_id,
+ token_budget,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ SessionCommands::GetSessionArchive {
+ session_id,
+ archive_id,
+ } => {
+ commands::session::get_session_archive(
+ &client,
+ &session_id,
+ &archive_id,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ SessionCommands::Delete { session_id } => {
+ commands::session::delete_session(&client, &session_id, ctx.output_format, ctx.compact)
+ .await
+ }
+ SessionCommands::AddMessage {
+ session_id,
+ role,
+ content,
+ } => {
+ commands::session::add_message(
+ &client,
+ &session_id,
+ &role,
+ &content,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ SessionCommands::Commit { session_id } => {
+ commands::session::commit_session(&client, &session_id, ctx.output_format, ctx.compact)
+ .await
+ }
+ }
+}
+
+use crate::AdminCommands;
+
+pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ match cmd {
+ AdminCommands::CreateAccount {
+ account_id,
+ admin_user_id,
+ } => {
+ commands::admin::create_account(
+ &client,
+ &account_id,
+ &admin_user_id,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ AdminCommands::ListAccounts => {
+ commands::admin::list_accounts(&client, ctx.output_format, ctx.compact).await
+ }
+ AdminCommands::DeleteAccount { account_id } => {
+ commands::admin::delete_account(&client, &account_id, ctx.output_format, ctx.compact)
+ .await
+ }
+ AdminCommands::RegisterUser {
+ account_id,
+ user_id,
+ role,
+ } => {
+ commands::admin::register_user(
+ &client,
+ &account_id,
+ &user_id,
+ &role,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ AdminCommands::ListUsers { account_id } => {
+ commands::admin::list_users(&client, &account_id, ctx.output_format, ctx.compact).await
+ }
+ AdminCommands::RemoveUser {
+ account_id,
+ user_id,
+ } => {
+ commands::admin::remove_user(
+ &client,
+ &account_id,
+ &user_id,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ AdminCommands::SetRole {
+ account_id,
+ user_id,
+ role,
+ } => {
+ commands::admin::set_role(
+ &client,
+ &account_id,
+ &user_id,
+ &role,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ AdminCommands::RegenerateKey {
+ account_id,
+ user_id,
+ } => {
+ commands::admin::regenerate_key(
+ &client,
+ &account_id,
+ &user_id,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ }
+}
+
+pub async fn handle_add_memory(content: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::session::add_memory(&client, &content, ctx.output_format, ctx.compact).await
+}
+
+use crate::ConfigCommands;
+use crate::config::Config;
+use crate::output;
+
+pub async fn handle_config(cmd: ConfigCommands, _ctx: CliContext) -> Result<()> {
+ match cmd {
+ ConfigCommands::Show => {
+ let config = Config::load()?;
+ output::output_success(
+ &serde_json::to_value(config).unwrap(),
+ output::OutputFormat::Json,
+ true,
+ );
+ Ok(())
+ }
+ ConfigCommands::Validate => match Config::load() {
+ Ok(_) => {
+ println!("Configuration is valid");
+ Ok(())
+ }
+ Err(e) => Err(Error::Config(e.to_string())),
+ },
+ }
+}
+
+pub async fn handle_read(uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::content::read(&client, &uri, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_abstract(uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::content::abstract_content(&client, &uri, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_overview(uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::content::overview(&client, &uri, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_write(
+ uri: String,
+ content: Option<String>,
+ from_file: Option<String>,
+ append: bool,
+ wait: bool,
+ timeout: Option<f64>,
+ ctx: CliContext,
+) -> Result<()> {
+ let client = ctx.get_client();
+ let payload = match (content, from_file) {
+ (Some(value), None) => value,
+ (None, Some(path)) => std::fs::read_to_string(path)
+ .map_err(|e| Error::Client(format!("Failed to read --from-file: {}", e)))?,
+ _ => {
+ return Err(Error::Client(
+ "Specify exactly one of --content or --from-file".into(),
+ ));
+ }
+ };
+ commands::content::write(
+ &client,
+ &uri,
+ &payload,
+ append,
+ wait,
+ timeout,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_reindex(uri: String, regenerate: bool, wait: bool, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::content::reindex(
+ &client,
+ &uri,
+ regenerate,
+ wait,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_get(uri: String, local_path: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::content::get(&client, &uri, &local_path).await
+}
+
+pub async fn handle_find(
+ query: String,
+ uri: String,
+ node_limit: i32,
+ threshold: Option<f64>,
+ after: Option<String>,
+ before: Option<String>,
+ ctx: CliContext,
+) -> Result<()> {
+ let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
+ if let Some(t) = threshold {
+ params.push(format!("--threshold {}", t));
+ }
+ append_time_filter_params(&mut params, after.as_deref(), before.as_deref());
+ params.push(format!("\"{}\"", query));
+ print_command_echo("ov find", &params.join(" "), ctx.config.echo_command);
+ let client = ctx.get_client();
+ commands::search::find(
+ &client,
+ &query,
+ &uri,
+ node_limit,
+ threshold,
+ after.as_deref(),
+ before.as_deref(),
+ None,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_search(
+ query: String,
+ uri: String,
+ session_id: Option<String>,
+ node_limit: i32,
+ threshold: Option<f64>,
+ after: Option<String>,
+ before: Option<String>,
+ ctx: CliContext,
+) -> Result<()> {
+ let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
+ if let Some(s) = &session_id {
+ params.push(format!("--session-id {}", s));
+ }
+ if let Some(t) = threshold {
+ params.push(format!("--threshold {}", t));
+ }
+ append_time_filter_params(&mut params, after.as_deref(), before.as_deref());
+ params.push(format!("\"{}\"", query));
+ print_command_echo("ov search", &params.join(" "), ctx.config.echo_command);
+ let client = ctx.get_client();
+ commands::search::search(
+ &client,
+ &query,
+ &uri,
+ session_id,
+ node_limit,
+ threshold,
+ after.as_deref(),
+ before.as_deref(),
+ None,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub fn append_time_filter_params(
+ params: &mut Vec<String>,
+ after: Option<&str>,
+ before: Option<&str>,
+) {
+ if let Some(value) = after {
+ params.push(format!("--after {}", value));
+ }
+ if let Some(value) = before {
+ params.push(format!("--before {}", value));
+ }
+}
+
+/// Print command with specified parameters for debugging
+pub fn print_command_echo(command: &str, params: &str, echo_enabled: bool) {
+ if echo_enabled {
+ println!("cmd: {} {}", command, params);
+ }
+}
+
+pub async fn handle_ls(
+ uri: String,
+ simple: bool,
+ recursive: bool,
+ abs_limit: i32,
+ show_all_hidden: bool,
+ node_limit: i32,
+ ctx: CliContext,
+) -> Result<()> {
+ let mut params = vec![
+ uri.clone(),
+ format!("-l {}", abs_limit),
+ format!("-n {}", node_limit),
+ ];
+ if simple {
+ params.push("-s".to_string());
+ }
+ if recursive {
+ params.push("-r".to_string());
+ }
+ if show_all_hidden {
+ params.push("-a".to_string());
+ }
+ print_command_echo("ov ls", &params.join(" "), ctx.config.echo_command);
+
+ let client = ctx.get_client();
+ let api_output = if ctx.compact { "agent" } else { "original" };
+ commands::filesystem::ls(
+ &client,
+ &uri,
+ simple,
+ recursive,
+ api_output,
+ abs_limit,
+ show_all_hidden,
+ node_limit,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_tree(
+ uri: String,
+ abs_limit: i32,
+ show_all_hidden: bool,
+ node_limit: i32,
+ level_limit: i32,
+ ctx: CliContext,
+) -> Result<()> {
+ let mut params = vec![
+ uri.clone(),
+ format!("-l {}", abs_limit),
+ format!("-n {}", node_limit),
+ format!("-L {}", level_limit),
+ ];
+ if show_all_hidden {
+ params.push("-a".to_string());
+ }
+ print_command_echo("ov tree", &params.join(" "), ctx.config.echo_command);
+
+ let client = ctx.get_client();
+ let api_output = if ctx.compact { "agent" } else { "original" };
+ commands::filesystem::tree(
+ &client,
+ &uri,
+ api_output,
+ abs_limit,
+ show_all_hidden,
+ node_limit,
+ level_limit,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_mkdir(uri: String, description: Option<String>, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::filesystem::mkdir(
+ &client,
+ &uri,
+ description.as_deref(),
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_rm(uri: String, recursive: bool, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::filesystem::rm(&client, &uri, recursive, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_mv(from_uri: String, to_uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::filesystem::mv(&client, &from_uri, &to_uri, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_stat(uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::filesystem::stat(&client, &uri, ctx.output_format, ctx.compact).await
+}
+
+pub async fn handle_grep(
+ uri: String,
+ exclude_uri: Option<String>,
+ pattern: String,
+ ignore_case: bool,
+ node_limit: i32,
+ level_limit: i32,
+ ctx: CliContext,
+) -> Result<()> {
+ // Prevent grep from root directory to avoid excessive server load and timeouts
+ if uri == "viking://" || uri == "viking:///" {
+ eprintln!(
+ "Error: Cannot grep from root directory 'viking://'.\n\
+ Grep from root would search across all scopes (resources, user, agent, session, queue, temp),\n\
+ which may cause server timeout or excessive load.\n\
+ Please specify a more specific scope, e.g.:\n\
+ ov grep --uri=viking://resources '{}'\n\
+ ov grep --uri=viking://user '{}'",
+ pattern, pattern
+ );
+ std::process::exit(1);
+ }
+
+ let mut params = vec![
+ format!("--uri={}", uri),
+ format!("-n {}", node_limit),
+ format!("-L {}", level_limit),
+ ];
+ if let Some(excluded) = &exclude_uri {
+ params.push(format!("-x {}", excluded));
+ }
+ if ignore_case {
+ params.push("-i".to_string());
+ }
+ params.push(format!("\"{}\"", pattern));
+ print_command_echo("ov grep", &params.join(" "), ctx.config.echo_command);
+ let client = ctx.get_client();
+ commands::search::grep(
+ &client,
+ &uri,
+ exclude_uri,
+ &pattern,
+ ignore_case,
+ node_limit,
+ level_limit,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_glob(pattern: String, uri: String, node_limit: i32, ctx: CliContext) -> Result<()> {
+ let params = vec![
+ format!("--uri={}", uri),
+ format!("-n {}", node_limit),
+ format!("\"{}\"", pattern),
+ ];
+ print_command_echo("ov glob", &params.join(" "), ctx.config.echo_command);
+ let client = ctx.get_client();
+ commands::search::glob(
+ &client,
+ &pattern,
+ &uri,
+ node_limit,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
+pub async fn handle_health(ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+
+ // Reuse the system health command
+ let _ = commands::system::health(&client, ctx.output_format, ctx.compact).await?;
+
+ Ok(())
+}
+
+pub async fn handle_tui(uri: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ tui::run_tui(client, &uri).await
+}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index e5f178eb2..4eb1a58d0 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -2,13 +2,14 @@ mod client;
mod commands;
mod config;
mod error;
+mod handlers;
mod output;
mod tui;
mod utils;
use clap::{ArgAction, Parser, Subcommand};
-use config::{Config, merge_csv_options};
-use error::{Error, Result};
+use config::Config;
+use error::Result;
use output::OutputFormat;
/// CLI context shared across commands
@@ -175,26 +176,6 @@ enum Commands {
#[arg(long)]
timeout: Option<f64>,
},
- /// [Data] Export context as .ovpack
- Export {
- /// Source URI
- uri: String,
- /// Output .ovpack file path
- to: String,
- },
- /// [Data] Import .ovpack into target URI
- Import {
- /// Input .ovpack file path
- file_path: String,
- /// Target parent URI
- target_uri: String,
- /// Overwrite when conflicts exist
- #[arg(long)]
- force: bool,
- /// Disable vectorization after import
- #[arg(long)]
- no_vectorize: bool,
- },
/// [Data] List directory contents
#[command(alias = "list")]
Ls {
@@ -341,7 +322,7 @@ enum Commands {
#[arg(long = "before")]
before: Option<String>,
},
- /// [Data] Run context-aware retrieval
+ /// [Experimental][Data] Run context-aware retrieval
Search {
/// Search query
query: String,
@@ -480,20 +461,15 @@ enum Commands {
#[arg(long)]
timeout: Option<f64>,
},
- /// [Status] Show OpenViking component status
+ /// [Status] All OpenViking Server components status
Status,
- /// [Status] Quick health check
- Health,
- /// [Status] System utility commands
- System {
- #[command(subcommand)]
- action: SystemCommands,
- },
- /// [Status] Observer status commands
+ /// [Status] Observe OpenViking Server components status
Observer {
#[command(subcommand)]
action: ObserverCommands,
},
+ /// [Status] Quick health check
+ Health,
/// [Status] Configuration management
Config {
#[command(subcommand)]
@@ -508,6 +484,31 @@ enum Commands {
#[command(subcommand)]
action: AdminCommands,
},
+ /// [Admin] System utility commands
+ System {
+ #[command(subcommand)]
+ action: SystemCommands,
+ },
+ /// [Admin][Data] Export context as .ovpack
+ Export {
+ /// Source URI
+ uri: String,
+ /// Output .ovpack file path
+ to: String,
+ },
+ /// [Admin][Data] Import .ovpack into target URI
+ Import {
+ /// Input .ovpack file path
+ file_path: String,
+ /// Target parent URI
+ target_uri: String,
+ /// Overwrite when conflicts exist
+ #[arg(long)]
+ force: bool,
+ /// Disable vectorization after import
+ #[arg(long)]
+ no_vectorize: bool,
+ },
/// [Admin] Reindex content at URI (regenerates .abstract.md and .overview.md)
Reindex {
/// Viking URI
@@ -707,7 +708,7 @@ async fn main() {
no_directly_upload_media,
watch_interval,
} => {
- handle_add_resource(
+ handlers::handle_add_resource(
path,
to,
parent,
@@ -729,21 +730,21 @@ async fn main() {
data,
wait,
timeout,
- } => handle_add_skill(data, wait, timeout, ctx).await,
- Commands::Relations { uri } => handle_relations(uri, ctx).await,
+ } => handlers::handle_add_skill(data, wait, timeout, ctx).await,
+ Commands::Relations { uri } => handlers::handle_relations(uri, ctx).await,
Commands::Link {
from_uri,
to_uris,
reason,
- } => handle_link(from_uri, to_uris, reason, ctx).await,
- Commands::Unlink { from_uri, to_uri } => handle_unlink(from_uri, to_uri, ctx).await,
- Commands::Export { uri, to } => handle_export(uri, to, ctx).await,
+ } => handlers::handle_link(from_uri, to_uris, reason, ctx).await,
+ Commands::Unlink { from_uri, to_uri } => handlers::handle_unlink(from_uri, to_uri, ctx).await,
+ Commands::Export { uri, to } => handlers::handle_export(uri, to, ctx).await,
Commands::Import {
file_path,
target_uri,
force,
no_vectorize,
- } => handle_import(file_path, target_uri, force, no_vectorize, ctx).await,
+ } => handlers::handle_import(file_path, target_uri, force, no_vectorize, ctx).await,
Commands::Wait { timeout } => {
let client = ctx.get_client();
commands::system::wait(&client, timeout, ctx.output_format, ctx.compact).await
@@ -752,11 +753,11 @@ async fn main() {
let client = ctx.get_client();
commands::observer::system(&client, ctx.output_format, ctx.compact).await
}
- Commands::Health => handle_health(ctx).await,
- Commands::System { action } => handle_system(action, ctx).await,
- Commands::Observer { action } => handle_observer(action, ctx).await,
- Commands::Session { action } => handle_session(action, ctx).await,
- Commands::Admin { action } => handle_admin(action, ctx).await,
+ Commands::Health => handlers::handle_health(ctx).await,
+ Commands::System { action } => handlers::handle_system(action, ctx).await,
+ 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::Ls {
uri,
simple,
@@ -764,20 +765,20 @@ async fn main() {
abs_limit,
all,
node_limit,
- } => handle_ls(uri, simple, recursive, abs_limit, all, node_limit, ctx).await,
+ } => handlers::handle_ls(uri, simple, recursive, abs_limit, all, node_limit, ctx).await,
Commands::Tree {
uri,
abs_limit,
all,
node_limit,
level_limit,
- } => handle_tree(uri, abs_limit, all, node_limit, level_limit, ctx).await,
- Commands::Mkdir { uri, description } => handle_mkdir(uri, description, ctx).await,
- Commands::Rm { uri, recursive } => handle_rm(uri, recursive, ctx).await,
- Commands::Mv { from_uri, to_uri } => handle_mv(from_uri, to_uri, ctx).await,
- Commands::Stat { uri } => handle_stat(uri, ctx).await,
- Commands::AddMemory { content } => handle_add_memory(content, ctx).await,
- Commands::Tui { uri } => handle_tui(uri, ctx).await,
+ } => handlers::handle_tree(uri, abs_limit, all, node_limit, level_limit, ctx).await,
+ Commands::Mkdir { uri, description } => handlers::handle_mkdir(uri, description, ctx).await,
+ Commands::Rm { uri, recursive } => handlers::handle_rm(uri, recursive, ctx).await,
+ Commands::Mv { from_uri, to_uri } => handlers::handle_mv(from_uri, to_uri, ctx).await,
+ Commands::Stat { uri } => handlers::handle_stat(uri, ctx).await,
+ Commands::AddMemory { content } => handlers::handle_add_memory(content, ctx).await,
+ Commands::Tui { uri } => handlers::handle_tui(uri, ctx).await,
Commands::Chat {
message,
session,
@@ -809,7 +810,7 @@ async fn main() {
};
cmd.run().await
}
- Commands::Config { action } => handle_config(action, ctx).await,
+ Commands::Config { action } => handlers::handle_config(action, ctx).await,
Commands::Version => {
println!("CLI: {}", env!("OPENVIKING_CLI_VERSION"));
@@ -827,9 +828,9 @@ async fn main() {
}
Ok(())
}
- Commands::Read { uri } => handle_read(uri, ctx).await,
- Commands::Abstract { uri } => handle_abstract(uri, ctx).await,
- Commands::Overview { uri } => handle_overview(uri, ctx).await,
+ Commands::Read { uri } => handlers::handle_read(uri, ctx).await,
+ Commands::Abstract { uri } => handlers::handle_abstract(uri, ctx).await,
+ Commands::Overview { uri } => handlers::handle_overview(uri, ctx).await,
Commands::Write {
uri,
content,
@@ -837,13 +838,13 @@ async fn main() {
append,
wait,
timeout,
- } => handle_write(uri, content, from_file, append, wait, timeout, ctx).await,
+ } => handlers::handle_write(uri, content, from_file, append, wait, timeout, ctx).await,
Commands::Reindex {
uri,
regenerate,
wait,
- } => handle_reindex(uri, regenerate, wait, ctx).await,
- Commands::Get { uri, local_path } => handle_get(uri, local_path, ctx).await,
+ } => handlers::handle_reindex(uri, regenerate, wait, ctx).await,
+ Commands::Get { uri, local_path } => handlers::handle_get(uri, local_path, ctx).await,
Commands::Find {
query,
uri,
@@ -851,7 +852,7 @@ async fn main() {
threshold,
after,
before,
- } => handle_find(query, uri, node_limit, threshold, after, before, ctx).await,
+ } => handlers::handle_find(query, uri, node_limit, threshold, after, before, ctx).await,
Commands::Search {
query,
uri,
@@ -861,7 +862,7 @@ async fn main() {
after,
before,
} => {
- handle_search(
+ handlers::handle_search(
query, uri, session_id, node_limit, threshold, after, before, ctx,
)
.await
@@ -874,7 +875,7 @@ async fn main() {
node_limit,
level_limit,
} => {
- handle_grep(
+ handlers::handle_grep(
uri,
exclude_uri,
pattern,
@@ -890,7 +891,7 @@ async fn main() {
pattern,
uri,
node_limit,
- } => handle_glob(pattern, uri, node_limit, ctx).await,
+ } => handlers::handle_glob(pattern, uri, node_limit, ctx).await,
};
if let Err(e) = result {
@@ -899,739 +900,11 @@ async fn main() {
}
}
-async fn handle_add_resource(
- mut path: String,
- to: Option<String>,
- parent: Option<String>,
- reason: String,
- instruction: String,
- wait: bool,
- timeout: Option<f64>,
- strict_mode: bool,
- ignore_dirs: Option<String>,
- include: Option<String>,
- exclude: Option<String>,
- no_directly_upload_media: bool,
- watch_interval: f64,
- ctx: CliContext,
-) -> Result<()> {
- let is_url =
- path.starts_with("http://") || path.starts_with("https://") || path.starts_with("git@");
-
- if !is_url {
- use std::path::Path;
-
- // Unescape path: replace backslash followed by space with just space
- let unescaped_path = path.replace("\\ ", " ");
- let path_obj = Path::new(&unescaped_path);
- if !path_obj.exists() {
- eprintln!("Error: Path '{}' does not exist.", path);
-
- // Check if there might be unquoted spaces
- use std::env;
- let args: Vec<String> = env::args().collect();
-
- if let Some(add_resource_pos) =
- args.iter().position(|s| s == "add-resource" || s == "add")
- {
- if args.len() > add_resource_pos + 2 {
- let extra_args = &args[add_resource_pos + 2..];
- let suggested_path = format!("{} {}", path, extra_args.join(" "));
- eprintln!(
- "\nIt looks like you may have forgotten to quote a path with spaces."
- );
- eprintln!("Suggested command: ov add-resource \"{}\"", suggested_path);
- }
- }
-
- std::process::exit(1);
- }
- path = unescaped_path;
- }
-
- // Check that only one of --to or --parent is set
- if to.is_some() && parent.is_some() {
- eprintln!("Error: Cannot specify both --to and --parent at the same time.");
- std::process::exit(1);
- }
-
- let strict = strict_mode;
- let directly_upload_media = !no_directly_upload_media;
-
- let effective_ignore_dirs =
- merge_csv_options(ctx.config.upload.ignore_dirs.clone(), ignore_dirs);
- let effective_include = merge_csv_options(ctx.config.upload.include.clone(), include);
- let effective_exclude = merge_csv_options(ctx.config.upload.exclude.clone(), exclude);
-
- let effective_timeout = if wait {
- timeout.unwrap_or(60.0).max(ctx.config.timeout)
- } else {
- ctx.config.timeout
- };
- let client = client::HttpClient::new(
- &ctx.config.url,
- ctx.config.api_key.clone(),
- ctx.config.agent_id.clone(),
- ctx.config.account.clone(),
- ctx.config.user.clone(),
- effective_timeout,
- );
- commands::resources::add_resource(
- &client,
- &path,
- to,
- parent,
- reason,
- instruction,
- wait,
- timeout,
- strict,
- effective_ignore_dirs,
- effective_include,
- effective_exclude,
- directly_upload_media,
- watch_interval,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_add_skill(
- data: String,
- wait: bool,
- timeout: Option<f64>,
- ctx: CliContext,
-) -> Result<()> {
- let client = ctx.get_client();
- commands::resources::add_skill(
- &client,
- &data,
- wait,
- timeout,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_relations(uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::relations::list_relations(&client, &uri, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_link(
- from_uri: String,
- to_uris: Vec<String>,
- reason: String,
- ctx: CliContext,
-) -> Result<()> {
- let client = ctx.get_client();
- commands::relations::link(
- &client,
- &from_uri,
- &to_uris,
- &reason,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_unlink(from_uri: String, to_uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::relations::unlink(&client, &from_uri, &to_uri, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_export(uri: String, to: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::pack::export(&client, &uri, &to, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_import(
- file_path: String,
- target_uri: String,
- force: bool,
- no_vectorize: bool,
- ctx: CliContext,
-) -> Result<()> {
- let client = ctx.get_client();
- commands::pack::import(
- &client,
- &file_path,
- &target_uri,
- force,
- no_vectorize,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_system(cmd: SystemCommands, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- match cmd {
- SystemCommands::Wait { timeout } => {
- commands::system::wait(&client, timeout, ctx.output_format, ctx.compact).await
- }
- SystemCommands::Status => {
- commands::system::status(&client, ctx.output_format, ctx.compact).await
- }
- SystemCommands::Health => {
- let _ = commands::system::health(&client, ctx.output_format, ctx.compact).await?;
- Ok(())
- }
- SystemCommands::Crypto { action } => commands::crypto::handle_crypto(action).await,
- }
-}
-
-async fn handle_observer(cmd: ObserverCommands, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- match cmd {
- ObserverCommands::Queue => {
- commands::observer::queue(&client, ctx.output_format, ctx.compact).await
- }
- ObserverCommands::Vikingdb => {
- commands::observer::vikingdb(&client, ctx.output_format, ctx.compact).await
- }
- ObserverCommands::Models => {
- commands::observer::models(&client, ctx.output_format, ctx.compact).await
- }
- ObserverCommands::Transaction => {
- commands::observer::transaction(&client, ctx.output_format, ctx.compact).await
- }
- ObserverCommands::Retrieval => {
- commands::observer::retrieval(&client, ctx.output_format, ctx.compact).await
- }
- ObserverCommands::System => {
- commands::observer::system(&client, ctx.output_format, ctx.compact).await
- }
- }
-}
-
-async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- match cmd {
- SessionCommands::New => {
- commands::session::new_session(&client, ctx.output_format, ctx.compact).await
- }
- SessionCommands::List => {
- commands::session::list_sessions(&client, ctx.output_format, ctx.compact).await
- }
- SessionCommands::Get { session_id } => {
- commands::session::get_session(&client, &session_id, ctx.output_format, ctx.compact)
- .await
- }
- SessionCommands::GetSessionContext {
- session_id,
- token_budget,
- } => {
- commands::session::get_session_context(
- &client,
- &session_id,
- token_budget,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- SessionCommands::GetSessionArchive {
- session_id,
- archive_id,
- } => {
- commands::session::get_session_archive(
- &client,
- &session_id,
- &archive_id,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- SessionCommands::Delete { session_id } => {
- commands::session::delete_session(&client, &session_id, ctx.output_format, ctx.compact)
- .await
- }
- SessionCommands::AddMessage {
- session_id,
- role,
- content,
- } => {
- commands::session::add_message(
- &client,
- &session_id,
- &role,
- &content,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- SessionCommands::Commit { session_id } => {
- commands::session::commit_session(&client, &session_id, ctx.output_format, ctx.compact)
- .await
- }
- }
-}
-
-async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- match cmd {
- AdminCommands::CreateAccount {
- account_id,
- admin_user_id,
- } => {
- commands::admin::create_account(
- &client,
- &account_id,
- &admin_user_id,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- AdminCommands::ListAccounts => {
- commands::admin::list_accounts(&client, ctx.output_format, ctx.compact).await
- }
- AdminCommands::DeleteAccount { account_id } => {
- commands::admin::delete_account(&client, &account_id, ctx.output_format, ctx.compact)
- .await
- }
- AdminCommands::RegisterUser {
- account_id,
- user_id,
- role,
- } => {
- commands::admin::register_user(
- &client,
- &account_id,
- &user_id,
- &role,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- AdminCommands::ListUsers { account_id } => {
- commands::admin::list_users(&client, &account_id, ctx.output_format, ctx.compact).await
- }
- AdminCommands::RemoveUser {
- account_id,
- user_id,
- } => {
- commands::admin::remove_user(
- &client,
- &account_id,
- &user_id,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- AdminCommands::SetRole {
- account_id,
- user_id,
- role,
- } => {
- commands::admin::set_role(
- &client,
- &account_id,
- &user_id,
- &role,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- AdminCommands::RegenerateKey {
- account_id,
- user_id,
- } => {
- commands::admin::regenerate_key(
- &client,
- &account_id,
- &user_id,
- ctx.output_format,
- ctx.compact,
- )
- .await
- }
- }
-}
-
-async fn handle_add_memory(content: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::session::add_memory(&client, &content, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_config(cmd: ConfigCommands, _ctx: CliContext) -> Result<()> {
- match cmd {
- ConfigCommands::Show => {
- let config = Config::load()?;
- output::output_success(
- &serde_json::to_value(config).unwrap(),
- output::OutputFormat::Json,
- true,
- );
- Ok(())
- }
- ConfigCommands::Validate => match Config::load() {
- Ok(_) => {
- println!("Configuration is valid");
- Ok(())
- }
- Err(e) => Err(Error::Config(e.to_string())),
- },
- }
-}
-
-async fn handle_read(uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::content::read(&client, &uri, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_abstract(uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::content::abstract_content(&client, &uri, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_overview(uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::content::overview(&client, &uri, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_write(
- uri: String,
- content: Option<String>,
- from_file: Option<String>,
- append: bool,
- wait: bool,
- timeout: Option<f64>,
- ctx: CliContext,
-) -> Result<()> {
- let client = ctx.get_client();
- let payload = match (content, from_file) {
- (Some(value), None) => value,
- (None, Some(path)) => std::fs::read_to_string(path)
- .map_err(|e| Error::Client(format!("Failed to read --from-file: {}", e)))?,
- _ => {
- return Err(Error::Client(
- "Specify exactly one of --content or --from-file".into(),
- ));
- }
- };
- commands::content::write(
- &client,
- &uri,
- &payload,
- append,
- wait,
- timeout,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_reindex(uri: String, regenerate: bool, wait: bool, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::content::reindex(
- &client,
- &uri,
- regenerate,
- wait,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_get(uri: String, local_path: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::content::get(&client, &uri, &local_path).await
-}
-
-async fn handle_find(
- query: String,
- uri: String,
- node_limit: i32,
- threshold: Option<f64>,
- after: Option<String>,
- before: Option<String>,
- ctx: CliContext,
-) -> Result<()> {
- let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
- if let Some(t) = threshold {
- params.push(format!("--threshold {}", t));
- }
- append_time_filter_params(&mut params, after.as_deref(), before.as_deref());
- params.push(format!("\"{}\"", query));
- print_command_echo("ov find", &params.join(" "), ctx.config.echo_command);
- let client = ctx.get_client();
- commands::search::find(
- &client,
- &query,
- &uri,
- node_limit,
- threshold,
- after.as_deref(),
- before.as_deref(),
- None,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_search(
- query: String,
- uri: String,
- session_id: Option<String>,
- node_limit: i32,
- threshold: Option<f64>,
- after: Option<String>,
- before: Option<String>,
- ctx: CliContext,
-) -> Result<()> {
- let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
- if let Some(s) = &session_id {
- params.push(format!("--session-id {}", s));
- }
- if let Some(t) = threshold {
- params.push(format!("--threshold {}", t));
- }
- append_time_filter_params(&mut params, after.as_deref(), before.as_deref());
- params.push(format!("\"{}\"", query));
- print_command_echo("ov search", &params.join(" "), ctx.config.echo_command);
- let client = ctx.get_client();
- commands::search::search(
- &client,
- &query,
- &uri,
- session_id,
- node_limit,
- threshold,
- after.as_deref(),
- before.as_deref(),
- None,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-fn append_time_filter_params(
- params: &mut Vec<String>,
- after: Option<&str>,
- before: Option<&str>,
-) {
- if let Some(value) = after {
- params.push(format!("--after {}", value));
- }
- if let Some(value) = before {
- params.push(format!("--before {}", value));
- }
-}
-
-/// Print command with specified parameters for debugging
-fn print_command_echo(command: &str, params: &str, echo_enabled: bool) {
- if echo_enabled {
- println!("cmd: {} {}", command, params);
- }
-}
-
-async fn handle_ls(
- uri: String,
- simple: bool,
- recursive: bool,
- abs_limit: i32,
- show_all_hidden: bool,
- node_limit: i32,
- ctx: CliContext,
-) -> Result<()> {
- let mut params = vec![
- uri.clone(),
- format!("-l {}", abs_limit),
- format!("-n {}", node_limit),
- ];
- if simple {
- params.push("-s".to_string());
- }
- if recursive {
- params.push("-r".to_string());
- }
- if show_all_hidden {
- params.push("-a".to_string());
- }
- print_command_echo("ov ls", &params.join(" "), ctx.config.echo_command);
-
- let client = ctx.get_client();
- let api_output = if ctx.compact { "agent" } else { "original" };
- commands::filesystem::ls(
- &client,
- &uri,
- simple,
- recursive,
- api_output,
- abs_limit,
- show_all_hidden,
- node_limit,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_tree(
- uri: String,
- abs_limit: i32,
- show_all_hidden: bool,
- node_limit: i32,
- level_limit: i32,
- ctx: CliContext,
-) -> Result<()> {
- let mut params = vec![
- uri.clone(),
- format!("-l {}", abs_limit),
- format!("-n {}", node_limit),
- format!("-L {}", level_limit),
- ];
- if show_all_hidden {
- params.push("-a".to_string());
- }
- print_command_echo("ov tree", &params.join(" "), ctx.config.echo_command);
-
- let client = ctx.get_client();
- let api_output = if ctx.compact { "agent" } else { "original" };
- commands::filesystem::tree(
- &client,
- &uri,
- api_output,
- abs_limit,
- show_all_hidden,
- node_limit,
- level_limit,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_mkdir(uri: String, description: Option<String>, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::filesystem::mkdir(
- &client,
- &uri,
- description.as_deref(),
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_rm(uri: String, recursive: bool, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::filesystem::rm(&client, &uri, recursive, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_mv(from_uri: String, to_uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::filesystem::mv(&client, &from_uri, &to_uri, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_stat(uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- commands::filesystem::stat(&client, &uri, ctx.output_format, ctx.compact).await
-}
-
-async fn handle_grep(
- uri: String,
- exclude_uri: Option<String>,
- pattern: String,
- ignore_case: bool,
- node_limit: i32,
- level_limit: i32,
- ctx: CliContext,
-) -> Result<()> {
- // Prevent grep from root directory to avoid excessive server load and timeouts
- if uri == "viking://" || uri == "viking:///" {
- eprintln!(
- "Error: Cannot grep from root directory 'viking://'.\n\
- Grep from root would search across all scopes (resources, user, agent, session, queue, temp),\n\
- which may cause server timeout or excessive load.\n\
- Please specify a more specific scope, e.g.:\n\
- ov grep --uri=viking://resources '{}'\n\
- ov grep --uri=viking://user '{}'",
- pattern, pattern
- );
- std::process::exit(1);
- }
-
- let mut params = vec![
- format!("--uri={}", uri),
- format!("-n {}", node_limit),
- format!("-L {}", level_limit),
- ];
- if let Some(excluded) = &exclude_uri {
- params.push(format!("-x {}", excluded));
- }
- if ignore_case {
- params.push("-i".to_string());
- }
- params.push(format!("\"{}\"", pattern));
- print_command_echo("ov grep", &params.join(" "), ctx.config.echo_command);
- let client = ctx.get_client();
- commands::search::grep(
- &client,
- &uri,
- exclude_uri,
- &pattern,
- ignore_case,
- node_limit,
- level_limit,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_glob(pattern: String, uri: String, node_limit: i32, ctx: CliContext) -> Result<()> {
- let params = vec![
- format!("--uri={}", uri),
- format!("-n {}", node_limit),
- format!("\"{}\"", pattern),
- ];
- print_command_echo("ov glob", &params.join(" "), ctx.config.echo_command);
- let client = ctx.get_client();
- commands::search::glob(
- &client,
- &pattern,
- &uri,
- node_limit,
- ctx.output_format,
- ctx.compact,
- )
- .await
-}
-
-async fn handle_health(ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
-
- // Reuse the system health command
- let _ = commands::system::health(&client, ctx.output_format, ctx.compact).await?;
-
- Ok(())
-}
-
-async fn handle_tui(uri: String, ctx: CliContext) -> Result<()> {
- let client = ctx.get_client();
- tui::run_tui(client, &uri).await
-}
-
#[cfg(test)]
mod tests {
use super::{Cli, CliContext};
use crate::config::Config;
+ use crate::handlers;
use crate::output::OutputFormat;
use clap::Parser;
@@ -1703,7 +976,7 @@ mod tests {
let after = Some("7d".to_string());
let before = Some("2026-03-12".to_string());
- super::append_time_filter_params(&mut params, after.as_deref(), before.as_deref());
+ handlers::append_time_filter_params(&mut params, after.as_deref(), before.as_deref());
assert_eq!(params, vec!["--after 7d", "--before 2026-03-12"]);
}
diff --git a/docs/en/concepts/10-encryption.md b/docs/en/concepts/10-encryption.md
index a00ef3122..bece3ec16 100644
--- a/docs/en/concepts/10-encryption.md
+++ b/docs/en/concepts/10-encryption.md
@@ -85,7 +85,7 @@ Suitable for development and single-node deployments:
**Initialization command**:
```bash
-ov crypto init-key --output ~/.openviking/master.key
+ov system crypto init-key --output ~/.openviking/master.key
```
### Vault (HashiCorp Vault)
diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.md
index 8adb5ccd6..5e0428952 100644
--- a/docs/en/guides/04-authentication.md
+++ b/docs/en/guides/04-authentication.md
@@ -1,6 +1,6 @@
# Authentication
-OpenViking Server supports two authentication modes with role-based access control: `api_key` and `trusted`. The default mode is `api_key`.
+OpenViking Server supports three authentication modes with role-based access control: `api_key`, `trusted`, and `dev`. The mode is auto-detected if not explicitly configured.
## Overview
@@ -19,8 +19,13 @@ All API keys are plain random tokens with no embedded identity. The server resol
|------|--------------------|-----------------|-------------|
| API key mode | `"api_key"` | API key, with optional tenant headers for root requests | Standard multi-tenant deployment |
| Trusted mode | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / optional `X-OpenViking-Agent` headers, plus `root_api_key` on non-localhost deployments | Behind a trusted gateway or internal network boundary |
+| Dev mode | `"dev"` | No authentication, always ROOT | Local development only |
-`api_key` is the default and standard production mode. `trusted` is an alternative mode for deployments where an upstream gateway or trusted internal caller injects identity headers on every request. In `trusted` mode, running without `root_api_key` is allowed only when the server binds to localhost; non-localhost `trusted` deployments must configure `root_api_key`.
+If `auth_mode` is not explicitly configured:
+- If `root_api_key` is set (non-empty): auto-selects `api_key` mode
+- If `root_api_key` is not set: auto-selects `dev` mode
+
+> **Note:** Setting `root_api_key` to an empty string `""` is invalid. Either set a non-empty value or remove the setting entirely.
## Setting Up (Server Side)
@@ -201,25 +206,25 @@ client = ov.SyncHTTPClient(
)
```
-## Roles and Permissions
-
-| Role | Scope | Capabilities |
-|------|-------|-------------|
-| ROOT | Global | All operations + Admin API (create/delete accounts, manage users) |
-| ADMIN | Own account | Regular operations + manage users in own account |
-| USER | Own account | Regular operations (ls, read, find, sessions, etc.) |
-
-In `trusted` mode, requests are resolved as `USER`, so the usual ROOT/ADMIN registration flow does not apply to ordinary traffic.
+## Dev Mode
-## Development Mode
+When `auth_mode = "dev"` (or auto-detected when no `root_api_key` is configured), authentication is disabled. All requests are accepted as ROOT with the default account. **This is only allowed when the server binds to localhost** (`127.0.0.1`, `localhost`, or `::1`). If `host` is set to a non-loopback address (e.g. `0.0.0.0`) in `dev` mode, the server will refuse to start.
-When `auth_mode = "api_key"` and no `root_api_key` is configured, authentication is disabled. All requests are accepted as ROOT with the default account. **This is only allowed when the server binds to localhost** (`127.0.0.1`, `localhost`, or `::1`). If `host` is set to a non-loopback address (e.g. `0.0.0.0`) without a `root_api_key`, the server will refuse to start.
+```json
+{
+ "server": {
+ "host": "127.0.0.1",
+ "port": 1933
+ }
+}
+```
-Development mode only exists in `api_key` mode. `trusted` mode never falls back to development mode.
+Or explicitly:
```json
{
"server": {
+ "auth_mode": "dev",
"host": "127.0.0.1",
"port": 1933
}
@@ -228,6 +233,16 @@ Development mode only exists in `api_key` mode. `trusted` mode never falls back
> **Security note:** The default `host` is `127.0.0.1`. If you need to expose the server on the network, you **must** configure `root_api_key`.
+## Roles and Permissions
+
+| Role | Scope | Capabilities |
+|------|-------|-------------|
+| ROOT | Global | All operations + Admin API (create/delete accounts, manage users) |
+| ADMIN | Own account | Regular operations + manage users in own account |
+| USER | Own account | Regular operations (ls, read, find, sessions, etc.) |
+
+In `trusted` mode, requests are resolved as `USER`, so the usual ROOT/ADMIN registration flow does not apply to ordinary traffic.
+
## Unauthenticated Endpoints
The `/health` endpoint never requires authentication. This allows load balancers and monitoring tools to check server health.
diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.md
index 40e6d3a1a..d1e1d80e1 100644
--- a/docs/zh/guides/04-authentication.md
+++ b/docs/zh/guides/04-authentication.md
@@ -1,6 +1,6 @@
# 认证
-OpenViking Server 支持两种认证模式,并带有基于角色的访问控制:`api_key` 和 `trusted`。默认模式是 `api_key`。
+OpenViking Server 支持三种认证模式,并带有基于角色的访问控制:`api_key`、`trusted` 和 `dev`。如果未显式配置,模式会自动推导。
## 概述
@@ -19,8 +19,13 @@ OpenViking 使用两层 API Key 体系:
|------|--------------------|----------|--------------|
| API Key 模式 | `"api_key"` | API Key,root 请求可附带租户请求头 | 标准多租户部署 |
| Trusted 模式 | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / 可选 `X-OpenViking-Agent` 请求头;非 localhost 部署还必须配置 `root_api_key` | 部署在受信网关或内网边界之后 |
+| Dev 模式 | `"dev"` | 无认证,始终为 ROOT | 仅限本地开发 |
-`api_key` 是默认模式,也是标准生产部署方式。`trusted` 是替代模式,适合由上游网关或受信内网调用方在每个请求里显式注入身份头。在 `trusted` 模式下,只有服务绑定到 localhost 时才允许不配置 `root_api_key`;只要是非 localhost 部署,就必须配置 `root_api_key`。
+如果未显式配置 `auth_mode`:
+- 如果设置了 `root_api_key`(非空):自动选择 `api_key` 模式
+- 如果未设置 `root_api_key`:自动选择 `dev` 模式
+
+> **注意:** 将 `root_api_key` 设置为空字符串 `""` 是非法的。请要么设置一个非空值,要么完全移除该配置项。
## 服务端配置
@@ -201,25 +206,25 @@ client = ov.SyncHTTPClient(
)
```
-## 角色与权限
-
-| 角色 | 作用域 | 能力 |
-|------|--------|------|
-| ROOT | 全局 | 全部操作 + Admin API(创建/删除工作区、管理用户) |
-| ADMIN | 所属 account | 常规操作 + 管理所属 account 的用户 |
-| USER | 所属 account | 常规操作(ls、read、find、sessions 等) |
-
-在 `trusted` 模式下,请求角色会解析为 `USER`,因此普通流量不适用 ROOT/ADMIN 的注册式管理语义。
+## Dev 模式
-## 开发模式
+当 `auth_mode = "dev"`(或未配置 `root_api_key` 时自动推导)时,认证禁用,所有请求以 ROOT 身份访问 default account。**此模式仅允许在服务器绑定 localhost 时使用**(`127.0.0.1`、`localhost` 或 `::1`)。如果 `host` 设置为非回环地址(如 `0.0.0.0`)且使用 `dev` 模式,服务器将拒绝启动。
-当 `auth_mode = "api_key"` 且未配置 `root_api_key` 时,认证禁用,所有请求以 ROOT 身份访问 default account。**此模式仅允许在服务器绑定 localhost 时使用**(`127.0.0.1`、`localhost` 或 `::1`)。如果 `host` 设置为非回环地址(如 `0.0.0.0`)且未配置 `root_api_key`,服务器将拒绝启动。
+```json
+{
+ "server": {
+ "host": "127.0.0.1",
+ "port": 1933
+ }
+}
+```
-开发模式只存在于 `api_key` 模式中;`trusted` 不会退化成开发模式。
+或显式配置:
```json
{
"server": {
+ "auth_mode": "dev",
"host": "127.0.0.1",
"port": 1933
}
@@ -228,6 +233,16 @@ client = ov.SyncHTTPClient(
> **安全提示:** 默认 `host` 为 `127.0.0.1`。如需将服务暴露到网络,**必须**配置 `root_api_key`。
+## 角色与权限
+
+| 角色 | 作用域 | 能力 |
+|------|--------|------|
+| ROOT | 全局 | 全部操作 + Admin API(创建/删除工作区、管理用户) |
+| ADMIN | 所属 account | 常规操作 + 管理所属 account 的用户 |
+| USER | 所属 account | 常规操作(ls、read、find、sessions 等) |
+
+在 `trusted` 模式下,请求角色会解析为 `USER`,因此普通流量不适用 ROOT/ADMIN 的注册式管理语义。
+
## 无需认证的端点
`/health` 端点始终不需要认证,用于负载均衡器和监控工具检查服务健康状态。
diff --git a/openviking/crypto/config.py b/openviking/crypto/config.py
index 9bcfbf8cf..1824c8345 100644
--- a/openviking/crypto/config.py
+++ b/openviking/crypto/config.py
@@ -138,7 +138,7 @@ async def bootstrap_encryption(config: Dict[str, Any]) -> Optional[FileEncryptor
"""
encryption_config = config.get("encryption", {})
if not encryption_config.get("enabled", False):
- logger.info("Encryption is disabled")
+ logger.debug("Encryption is disabled")
return None
# Validate configuration
diff --git a/openviking/server/app.py b/openviking/server/app.py
index b85eb672d..32b0fb597 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -15,6 +15,7 @@ from openviking.server.api_keys import APIKeyManager
from openviking.server.config import ServerConfig, load_server_config, validate_server_config
from openviking.server.dependencies import set_service
from openviking.server.error_mapping import map_exception
+from openviking.server.identity import AuthMode
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
from openviking.server.routers import (
admin_router,
@@ -22,6 +23,7 @@ from openviking.server.routers import (
content_router,
debug_router,
filesystem_router,
+ maintenance_router,
metrics_router,
observer_router,
pack_router,
@@ -68,13 +70,17 @@ def create_app(
if owns_service:
service = OpenVikingService()
await service.initialize()
- logger.info("OpenVikingService initialized")
assert service is not None
set_service(service)
# Initialize APIKeyManager after service (needs VikingFS)
- if config.auth_mode == "api_key" and config.root_api_key:
+ effective_auth_mode = config.get_effective_auth_mode()
+ if (
+ effective_auth_mode == AuthMode.API_KEY
+ and config.root_api_key
+ and config.root_api_key != ""
+ ):
api_key_manager = APIKeyManager(
root_key=config.root_api_key,
viking_fs=service.viking_fs,
@@ -86,9 +92,9 @@ def create_app(
"APIKeyManager initialized with encryption_enabled=%s",
config.encryption_enabled,
)
- elif config.auth_mode == "trusted":
+ elif effective_auth_mode == AuthMode.TRUSTED:
app.state.api_key_manager = None
- if config.root_api_key:
+ if config.root_api_key and config.root_api_key != "":
logger.info(
"Trusted mode enabled: authentication trusts X-OpenViking-Account/User/Agent "
"headers and requires the configured server API key on each request. "
@@ -103,14 +109,8 @@ def create_app(
"identity-injecting gateway after configuring server.root_api_key."
)
else:
+ # AuthMode.DEV - logging already handled in validate_server_config
app.state.api_key_manager = None
- logger.warning(
- "Dev mode: no root_api_key configured, authentication disabled. "
- "This is allowed because the server is bound to localhost (%s). "
- "Do NOT expose this server to the network without configuring "
- "server.root_api_key in ov.conf.",
- config.host,
- )
from openviking.metrics.global_api import (
init_metrics_from_server_config,
@@ -256,6 +256,7 @@ def create_app(
app.include_router(metrics_router)
app.include_router(tasks_router)
app.include_router(webdav_router)
+ app.include_router(maintenance_router)
app.include_router(bot_router, prefix="/bot/v1")
return app
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index ac868aed3..ec4b6f021 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -8,7 +8,7 @@ from typing import Optional
from fastapi import Depends, Header, Request
from openviking.metrics.account_context import set_metric_account_context
-from openviking.server.identity import RequestContext, ResolvedIdentity, Role
+from openviking.server.identity import AuthMode, RequestContext, ResolvedIdentity, Role
from openviking_cli.exceptions import (
InvalidArgumentError,
PermissionDeniedError,
@@ -27,9 +27,11 @@ _ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES = (
)
-def _auth_mode(request: Request) -> str:
+def _auth_mode(request: Request) -> AuthMode:
config = getattr(request.app.state, "config", None)
- return getattr(config, "auth_mode", "api_key")
+ if config is not None and hasattr(config, "get_effective_auth_mode"):
+ return config.get_effective_auth_mode()
+ return AuthMode.API_KEY
def _root_request_requires_explicit_tenant(path: str) -> bool:
@@ -48,7 +50,8 @@ def _root_request_requires_explicit_tenant(path: str) -> bool:
def _configured_root_api_key(request: Request) -> Optional[str]:
config = getattr(request.app.state, "config", None)
- return getattr(config, "root_api_key", None)
+ key = getattr(config, "root_api_key", None)
+ return key if key != "" else None
def _extract_api_key(x_api_key: Optional[str], authorization: Optional[str]) -> Optional[str]:
@@ -74,15 +77,24 @@ async def resolve_identity(
"""Resolve API key to identity.
Strategy:
+ - dev mode: no authentication, return implicit ROOT/default identity
- trusted mode: trust explicit account/user headers and return USER identity
- - api_key mode without manager: dev mode, return implicit ROOT/default identity
- - api_key mode with manager: resolve via APIKeyManager (root key first, then user key index)
+ - api_key mode: resolve via APIKeyManager (root key first, then user key index)
"""
auth_mode = _auth_mode(request)
api_key_manager = getattr(request.app.state, "api_key_manager", None)
api_key = _extract_api_key(x_api_key, authorization)
- if auth_mode == "trusted":
+ if auth_mode == AuthMode.DEV:
+ # Dev mode: no authentication, always return ROOT
+ return ResolvedIdentity(
+ role=Role.ROOT,
+ account_id=x_openviking_account or "default",
+ user_id=x_openviking_user or "default",
+ agent_id=x_openviking_agent or "default",
+ )
+
+ if auth_mode == AuthMode.TRUSTED:
configured_root_api_key = _configured_root_api_key(request)
if configured_root_api_key:
if not api_key:
@@ -104,13 +116,10 @@ async def resolve_identity(
agent_id=x_openviking_agent or "default",
)
+ # AuthMode.API_KEY
if api_key_manager is None:
- return ResolvedIdentity(
- role=Role.ROOT,
- account_id=x_openviking_account or "default",
- user_id=x_openviking_user or "default",
- agent_id=x_openviking_agent or "default",
- )
+ # This should not happen due to validate_server_config
+ raise RuntimeError("api_key_manager not initialized in api_key mode")
if not api_key:
raise UnauthenticatedError("Missing API Key when resolving identity.")
@@ -152,7 +161,7 @@ async def get_request_context(
auth_mode = _auth_mode(request)
api_key_manager = getattr(request.app.state, "api_key_manager", None)
if (
- auth_mode == "api_key"
+ auth_mode == AuthMode.API_KEY
and api_key_manager is not None
and identity.role == Role.ROOT
and _root_request_requires_explicit_tenant(path)
@@ -165,9 +174,9 @@ async def get_request_context(
"and X-OpenViking-User headers. Use a user key for regular data access."
)
- if auth_mode == "trusted" and not identity.account_id:
+ if auth_mode == AuthMode.TRUSTED and not identity.account_id:
raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-Account.")
- if auth_mode == "trusted" and not identity.user_id:
+ if auth_mode == AuthMode.TRUSTED and not identity.user_id:
raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-User.")
ctx = RequestContext(
@@ -205,3 +214,136 @@ def require_role(*allowed_roles: Role):
return ctx
return Depends(_check)
+
+
+# Convenience dependency factories for common role requirements
+require_root = require_role(Role.ROOT)
+require_admin = require_role(Role.ADMIN)
+require_user = require_role(Role.USER)
+
+
+_TRUSTED_MODE_ADMIN_API_MESSAGE = (
+ "Admin API is unavailable in trusted mode. In trusted mode, each request is resolved as USER "
+ "from X-OpenViking-Account/X-OpenViking-User headers and does not use user-key "
+ "registration. Switch to api_key mode with root_api_key for account and user management."
+)
+
+_DEV_MODE_ADMIN_API_MESSAGE = (
+ "Admin API requires api_key mode with root_api_key configured. Development mode does not "
+ "support account or user management."
+)
+
+
+def require_auth_role(*allowed_roles: Role):
+ """Decorator for Admin API routes with mode-aware errors.
+
+ Usage:
+ @router.post("/admin/accounts")
+ @require_auth_role(Role.ROOT)
+ async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):
+ ...
+ """
+ from functools import wraps
+
+ def decorator(func):
+ @wraps(func)
+ async def wrapper(*args, **kwargs):
+ # Extract request and ctx from kwargs or args
+ request = kwargs.get("request")
+ ctx = kwargs.get("ctx")
+
+ # Find request and ctx in args if not in kwargs
+ if request is None or ctx is None:
+ import inspect
+
+ sig = inspect.signature(func)
+ bound_args = sig.bind(*args, **kwargs)
+ bound_args.apply_defaults()
+ request = bound_args.arguments.get("request")
+ ctx = bound_args.arguments.get("ctx")
+
+ if request is None:
+ raise RuntimeError("require_auth_role decorator requires 'request' parameter")
+ if ctx is None:
+ raise RuntimeError("require_auth_role decorator requires 'ctx' parameter")
+
+ config = getattr(request.app.state, "config", None)
+ auth_mode = getattr(config, "auth_mode", AuthMode.API_KEY)
+ if auth_mode == AuthMode.TRUSTED:
+ raise PermissionDeniedError(_TRUSTED_MODE_ADMIN_API_MESSAGE)
+
+ manager = getattr(request.app.state, "api_key_manager", None)
+ if manager is None:
+ raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)
+
+ if ctx.role not in allowed_roles:
+ raise PermissionDeniedError(
+ f"Requires role: {', '.join(r.value for r in allowed_roles)}"
+ )
+
+ return await func(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
+
+
+# Convenience decorators for common admin role requirements
+def require_auth_root(func):
+ """Decorator to require ROOT role for Admin API.
+
+ Usage:
+ @router.post("/admin/accounts")
+ @require_auth_root
+ async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):
+ ...
+ """
+ return require_auth_role(Role.ROOT)(func)
+
+
+def require_auth_admin(func):
+ """Decorator to require ADMIN role for Admin API.
+
+ Usage:
+ @router.post("/admin/accounts")
+ @require_auth_admin
+ async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):
+ ...
+ """
+ return require_auth_role(Role.ADMIN)(func)
+
+
+def require_auth_user(func):
+ """Decorator to require USER role for Admin API.
+
+ Usage:
+ @router.post("/admin/accounts")
+ @require_auth_user
+ async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):
+ ...
+ """
+ return require_auth_role(Role.USER)(func)
+
+
+def require_auth_root_or_admin(func):
+ """Decorator to require ROOT or ADMIN role for Admin API.
+
+ Usage:
+ @router.post("/admin/accounts")
+ @require_auth_root_or_admin
+ async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):
+ ...
+ """
+ return require_auth_role(Role.ROOT, Role.ADMIN)(func)
+
+
+def get_api_key_manager_or_raise(request: Request):
+ """Get APIKeyManager from app state or raise appropriate error.
+
+ Raises:
+ PermissionDeniedError: In dev mode without API key manager.
+ """
+ manager = getattr(request.app.state, "api_key_manager", None)
+ if manager is None:
+ raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)
+ return manager
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 9808ba816..6a6b96f7d 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -7,6 +7,7 @@ from typing import List, Optional
from pydantic import BaseModel, Field, ValidationError
+from openviking.server.identity import AuthMode
from openviking_cli.utils import get_logger
from openviking_cli.utils.config.config_loader import (
load_json_config,
@@ -57,7 +58,7 @@ class ServerConfig(BaseModel):
host: str = "127.0.0.1"
port: int = 1933
workers: int = 1
- auth_mode: str = "api_key"
+ auth_mode: Optional[AuthMode] = None # If None, auto-detect based on root_api_key
root_api_key: Optional[str] = None
cors_origins: List[str] = Field(default_factory=lambda: ["*"])
with_bot: bool = False # Enable Bot API proxy to Vikingbot
@@ -67,6 +68,18 @@ class ServerConfig(BaseModel):
model_config = {"extra": "forbid"}
+ def get_effective_auth_mode(self) -> AuthMode:
+ """Get effective auth mode, auto-detecting if not explicitly set.
+
+ - If root_api_key is configured (non-empty) and auth_mode is None: API_KEY
+ - If root_api_key is not configured and auth_mode is None: DEV
+ """
+ if self.auth_mode is not None:
+ return self.auth_mode
+ if self.root_api_key is not None and self.root_api_key != "":
+ return AuthMode.API_KEY
+ return AuthMode.DEV
+
def load_server_config(config_path: Optional[str] = None) -> ServerConfig:
"""Load server configuration from ov.conf.
@@ -106,6 +119,17 @@ def load_server_config(config_path: Optional[str] = None) -> ServerConfig:
if not isinstance(server_data, dict):
raise ValueError("Invalid server config: 'server' section must be an object")
+ # Convert auth_mode string to enum if present
+ if "auth_mode" in server_data and isinstance(server_data["auth_mode"], str):
+ try:
+ server_data["auth_mode"] = AuthMode(server_data["auth_mode"])
+ except ValueError as e:
+ valid_modes = ", ".join(repr(m.value) for m in AuthMode)
+ raise ValueError(
+ f"Invalid server.auth_mode={server_data['auth_mode']!r}. "
+ f"Expected one of: {valid_modes}."
+ ) from e
+
# Get encryption enabled from config data directly (for test compatibility)
encryption_enabled = data.get("encryption", {}).get("enabled", False)
@@ -131,25 +155,71 @@ def _is_localhost(host: str) -> bool:
def validate_server_config(config: ServerConfig) -> None:
"""Validate server config for safe startup.
- In ``api_key`` mode, when ``root_api_key`` is not set, authentication is
- disabled (dev mode). This is only acceptable when the server binds to
- localhost. Binding to a non-loopback address without authentication
- exposes an unauthenticated ROOT endpoint to the network.
+ - **dev mode**: No authentication required, always returns ROOT identity.
+ Only acceptable when binding to localhost.
+ - **api_key mode**: Authenticates via root_api_key or user keys.
+ Requires root_api_key to be configured.
+ - **trusted mode**: Trusts X-OpenViking-Account/User/Agent headers.
+ Requires root_api_key when binding to non-localhost.
+
+ If auth_mode is not explicitly configured:
+ - If root_api_key is configured (non-empty): auto-select API_KEY mode
+ - If root_api_key is not configured: auto-select DEV mode
Raises:
SystemExit: If the configuration is unsafe.
"""
- if config.auth_mode not in {"api_key", "trusted"}:
+ # Check for empty root_api_key
+ if config.root_api_key == "":
logger.error(
- "Invalid server.auth_mode=%r. Expected one of: 'api_key', 'trusted'.",
- config.auth_mode,
+ "Invalid server.root_api_key: empty string is not allowed. "
+ "Either set a non-empty root_api_key or remove the setting entirely."
)
sys.exit(1)
- if config.auth_mode == "trusted":
- if config.root_api_key:
+ effective_auth_mode = config.get_effective_auth_mode()
+
+ if effective_auth_mode == AuthMode.DEV:
+ # Dev mode: no authentication, only allowed on localhost
+ if _is_localhost(config.host):
+ if config.auth_mode is None:
+ logger.warning(
+ "Dev mode (auto-detected): authentication disabled. "
+ "This is allowed because the server is bound to localhost (%s). "
+ "Do NOT expose this server to the network.",
+ config.host,
+ )
+ else:
+ logger.warning(
+ "Dev mode: authentication disabled. This is allowed because the "
+ "server is bound to localhost (%s). Do NOT expose this server "
+ "to the network.",
+ config.host,
+ )
+ return
+ logger.error(
+ "SECURITY: server.auth_mode='dev' requires server.host to be localhost, "
+ "but it is set to '%s'. Dev mode exposes an unauthenticated ROOT "
+ "endpoint and must not be exposed to the network.",
+ config.host,
+ )
+ logger.error(
+ "To fix, either:\n"
+ ' 1. Set server.auth_mode="api_key" and configure server.root_api_key, or\n'
+ ' 2. Bind dev mode to localhost (server.host = "127.0.0.1")'
+ )
+ sys.exit(1)
+
+ if effective_auth_mode == AuthMode.TRUSTED:
+ if config.root_api_key and config.root_api_key != "":
return
if _is_localhost(config.host):
+ logger.warning(
+ "Trusted mode without API key: authentication trusts "
+ "X-OpenViking-Account/User/Agent headers. This is allowed because "
+ "the server is bound to localhost (%s).",
+ config.host,
+ )
return
logger.error(
"SECURITY: server.auth_mode='trusted' requires server.root_api_key when "
@@ -164,19 +234,28 @@ def validate_server_config(config: ServerConfig) -> None:
)
sys.exit(1)
- if config.root_api_key:
+ # AuthMode.API_KEY
+ if config.root_api_key and config.root_api_key != "":
+ if config.auth_mode is None:
+ logger.info("Api key mode (auto-detected): using root_api_key for authentication")
return
- if not _is_localhost(config.host):
+ # api_key mode without root_api_key is invalid - should use dev mode instead
+ if _is_localhost(config.host):
logger.error(
- "SECURITY: server.root_api_key is not configured and server.host "
- "is '%s' (non-localhost). This would expose an unauthenticated "
- "ROOT endpoint to the network.",
- config.host,
+ "server.auth_mode='api_key' requires server.root_api_key to be configured.\n"
+ 'To run without authentication on localhost, either set server.auth_mode="dev" '
+ "or simply remove the server.auth_mode setting to auto-detect."
)
+ else:
logger.error(
- "To fix, either:\n"
- " 1. Set server.root_api_key in ov.conf, or\n"
- ' 2. Bind to localhost (server.host = "127.0.0.1")'
+ "SECURITY: server.auth_mode='api_key' requires server.root_api_key "
+ "to be configured when server.host is '%s' (non-localhost).",
+ config.host,
)
- sys.exit(1)
+ logger.error(
+ "To fix, either:\n"
+ " 1. Set server.root_api_key in ov.conf, or\n"
+ ' 2. Use server.auth_mode="dev" (localhost only)'
+ )
+ sys.exit(1)
diff --git a/openviking/server/identity.py b/openviking/server/identity.py
index 6e35049ca..b56418d49 100644
--- a/openviking/server/identity.py
+++ b/openviking/server/identity.py
@@ -15,6 +15,14 @@ class Role(str, Enum):
USER = "user"
+class AuthMode(str, Enum):
+ """Authentication modes for OpenViking server."""
+
+ API_KEY = "api_key"
+ TRUSTED = "trusted"
+ DEV = "dev"
+
+
@dataclass(frozen=True)
class AccountNamespacePolicy:
"""Account-level namespace isolation policy."""
diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.py
index b303bf6da..95fe50a1b 100644
--- a/openviking/server/routers/__init__.py
+++ b/openviking/server/routers/__init__.py
@@ -7,6 +7,7 @@ from openviking.server.routers.bot import router as bot_router
from openviking.server.routers.content import router as content_router
from openviking.server.routers.debug import router as debug_router
from openviking.server.routers.filesystem import router as filesystem_router
+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
@@ -36,4 +37,5 @@ __all__ = [
"observer_router",
"tasks_router",
"webdav_router",
+ "maintenance_router",
]
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index 8f7fe3456..9cac4cbe7 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -5,7 +5,12 @@
from fastapi import APIRouter, Depends, Path, Request
from pydantic import BaseModel
-from openviking.server.auth import get_request_context
+from openviking.server.auth import (
+ get_api_key_manager_or_raise,
+ get_request_context,
+ require_auth_root,
+ require_auth_root_or_admin,
+)
from openviking.server.dependencies import get_service
from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role
from openviking.server.models import Response
@@ -18,17 +23,6 @@ logger = get_logger(__name__)
router = APIRouter(prefix="/api/v1/admin", tags=["admin"])
-_TRUSTED_MODE_ADMIN_API_MESSAGE = (
- "Admin API is unavailable in trusted mode. In trusted mode, each request is resolved as USER "
- "from X-OpenViking-Account/X-OpenViking-User headers and does not use user-key "
- "registration. Switch to api_key mode with root_api_key for account and user management."
-)
-
-_DEV_MODE_ADMIN_API_MESSAGE = (
- "Admin API requires api_key mode with root_api_key configured. Development mode does not "
- "support account or user management."
-)
-
class CreateAccountRequest(BaseModel):
account_id: str
@@ -48,35 +42,7 @@ class SetRoleRequest(BaseModel):
def _get_api_key_manager(request: Request):
"""Get APIKeyManager from app state."""
- manager = getattr(request.app.state, "api_key_manager", None)
- if manager is None:
- raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)
- return manager
-
-
-def require_admin_role(*allowed_roles: Role):
- """Dependency factory for Admin API routes with mode-aware errors."""
-
- async def _check(
- request: Request,
- ctx: RequestContext = Depends(get_request_context),
- ) -> RequestContext:
- config = getattr(request.app.state, "config", None)
- auth_mode = getattr(config, "auth_mode", "api_key")
- if auth_mode == "trusted":
- raise PermissionDeniedError(_TRUSTED_MODE_ADMIN_API_MESSAGE)
-
- manager = getattr(request.app.state, "api_key_manager", None)
- if manager is None:
- raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)
-
- if ctx.role not in allowed_roles:
- raise PermissionDeniedError(
- f"Requires role: {', '.join(r.value for r in allowed_roles)}"
- )
- return ctx
-
- return Depends(_check)
+ return get_api_key_manager_or_raise(request)
def _check_account_access(ctx: RequestContext, account_id: str) -> None:
@@ -89,10 +55,11 @@ def _check_account_access(ctx: RequestContext, account_id: str) -> None:
@router.post("/accounts")
+@require_auth_root
async def create_account(
body: CreateAccountRequest,
request: Request,
- ctx: RequestContext = require_admin_role(Role.ROOT),
+ ctx: RequestContext = Depends(get_request_context),
):
"""Create a new account (workspace) with its first admin user."""
manager = _get_api_key_manager(request)
@@ -125,9 +92,10 @@ async def create_account(
@router.get("/accounts")
+@require_auth_root
async def list_accounts(
request: Request,
- ctx: RequestContext = require_admin_role(Role.ROOT),
+ ctx: RequestContext = Depends(get_request_context),
):
"""List all accounts."""
manager = _get_api_key_manager(request)
@@ -136,10 +104,11 @@ async def list_accounts(
@router.delete("/accounts/{account_id}")
+@require_auth_root
async def delete_account(
request: Request,
account_id: str = Path(..., description="Account ID"),
- ctx: RequestContext = require_admin_role(Role.ROOT),
+ ctx: RequestContext = Depends(get_request_context),
):
"""Delete an account and cascade-clean its storage (AGFS + VectorDB)."""
manager = _get_api_key_manager(request)
@@ -182,11 +151,12 @@ async def delete_account(
@router.post("/accounts/{account_id}/users")
+@require_auth_root_or_admin
async def register_user(
body: RegisterUserRequest,
request: Request,
account_id: str = Path(..., description="Account ID"),
- ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),
+ ctx: RequestContext = Depends(get_request_context),
):
"""Register a new user in an account."""
_check_account_access(ctx, account_id)
@@ -210,10 +180,11 @@ async def register_user(
@router.get("/accounts/{account_id}/users")
+@require_auth_root_or_admin
async def list_users(
request: Request,
account_id: str = Path(..., description="Account ID"),
- ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),
+ ctx: RequestContext = Depends(get_request_context),
):
"""List all users in an account."""
_check_account_access(ctx, account_id)
@@ -223,11 +194,12 @@ async def list_users(
@router.delete("/accounts/{account_id}/users/{user_id}")
+@require_auth_root_or_admin
async def remove_user(
request: Request,
account_id: str = Path(..., description="Account ID"),
user_id: str = Path(..., description="User ID"),
- ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),
+ ctx: RequestContext = Depends(get_request_context),
):
"""Remove a user from an account."""
_check_account_access(ctx, account_id)
@@ -237,12 +209,13 @@ async def remove_user(
@router.put("/accounts/{account_id}/users/{user_id}/role")
+@require_auth_root
async def set_user_role(
body: SetRoleRequest,
request: Request,
account_id: str = Path(..., description="Account ID"),
user_id: str = Path(..., description="User ID"),
- ctx: RequestContext = require_admin_role(Role.ROOT),
+ ctx: RequestContext = Depends(get_request_context),
):
"""Change a user's role (ROOT only)."""
manager = _get_api_key_manager(request)
@@ -258,11 +231,12 @@ async def set_user_role(
@router.post("/accounts/{account_id}/users/{user_id}/key")
+@require_auth_root_or_admin
async def regenerate_key(
request: Request,
account_id: str = Path(..., description="Account ID"),
user_id: str = Path(..., description="User ID"),
- ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),
+ ctx: RequestContext = Depends(get_request_context),
):
"""Regenerate a user's API key. Old key is immediately invalidated."""
_check_account_access(ctx, account_id)
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index 188166814..73a9de442 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -2,7 +2,6 @@
# SPDX-License-Identifier: AGPL-3.0
"""Content endpoints for OpenViking HTTP Server."""
-import asyncio
from urllib.parse import quote
from fastapi import APIRouter, Body, Depends, Query
@@ -13,7 +12,7 @@ from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
-from openviking.server.models import ErrorInfo, Response
+from openviking.server.models import Response
from openviking.server.telemetry import run_operation
from openviking.telemetry import TelemetryRequest
from openviking_cli.exceptions import NotFoundError
@@ -21,16 +20,6 @@ from openviking_cli.utils import get_logger
logger = get_logger(__name__)
-REINDEX_TASK_TYPE = "resource_reindex"
-
-
-class ReindexRequest(BaseModel):
- """Request to reindex content at a URI."""
-
- uri: str
- regenerate: bool = False
- wait: bool = True
-
class WriteContentRequest(BaseModel):
"""Request to write or append text content to an existing file."""
@@ -182,120 +171,3 @@ async def write(
result=execution.result,
telemetry=execution.telemetry,
).model_dump(exclude_none=True)
-
-
[email protected]("/reindex")
-async def reindex(
- request: ReindexRequest = Body(...),
- _ctx: RequestContext = Depends(get_request_context),
-):
- """Reindex content at a URI.
-
- Re-embeds existing .abstract.md/.overview.md content into the vector
- database. If regenerate=True, also regenerates L0/L1 summaries via LLM
- before re-embedding.
-
- Uses path locking to prevent concurrent reindexes on the same URI.
- Set wait=False to run in the background and track progress via task API.
- """
- from openviking.service.task_tracker import get_task_tracker
- from openviking.storage.viking_fs import get_viking_fs
-
- uri = request.uri
- viking_fs = get_viking_fs()
-
- # Validate URI exists
- if not await viking_fs.exists(uri, ctx=_ctx):
- return Response(
- status="error",
- error=ErrorInfo(code="NOT_FOUND", message=f"URI not found: {uri}"),
- )
-
- service = get_service()
- tracker = get_task_tracker()
-
- if request.wait:
- # Synchronous path: block until reindex completes
- if tracker.has_running(
- REINDEX_TASK_TYPE,
- uri,
- owner_account_id=_ctx.account_id,
- owner_user_id=_ctx.user.user_id,
- ):
- return Response(
- status="error",
- error=ErrorInfo(
- code="CONFLICT",
- message=f"URI {uri} already has a reindex in progress",
- ),
- )
- result = await _do_reindex(service, uri, request.regenerate, _ctx)
- return Response(status="ok", result=result)
- else:
- # Async path: run in background, return task_id for polling
- task = tracker.create_if_no_running(
- REINDEX_TASK_TYPE,
- uri,
- owner_account_id=_ctx.account_id,
- owner_user_id=_ctx.user.user_id,
- )
- if task is None:
- return Response(
- status="error",
- error=ErrorInfo(
- code="CONFLICT",
- message=f"URI {uri} already has a reindex in progress",
- ),
- )
- asyncio.create_task(
- _background_reindex_tracked(service, uri, request.regenerate, _ctx, task.task_id)
- )
- return Response(
- status="ok",
- result={
- "uri": uri,
- "status": "accepted",
- "task_id": task.task_id,
- "message": "Reindex is processing in the background",
- },
- )
-
-
-async def _do_reindex(
- service,
- uri: str,
- regenerate: bool,
- ctx: RequestContext,
-) -> dict:
- """Execute reindex within a lock scope."""
- from openviking.storage.transaction import LockContext, get_lock_manager
-
- viking_fs = service.viking_fs
- path = viking_fs._uri_to_path(uri, ctx=ctx)
-
- async with LockContext(get_lock_manager(), [path], lock_mode="point"):
- if regenerate:
- return await service.resources.summarize([uri], ctx=ctx)
- else:
- return await service.resources.build_index([uri], ctx=ctx)
-
-
-async def _background_reindex_tracked(
- service,
- uri: str,
- regenerate: bool,
- ctx: RequestContext,
- task_id: str,
-) -> None:
- """Run reindex in background with task tracking."""
- from openviking.service.task_tracker import get_task_tracker
-
- tracker = get_task_tracker()
- tracker.start(task_id)
- try:
- result = await _do_reindex(service, uri, regenerate, ctx)
- tracker.complete(task_id, {"uri": uri, **result})
- logger.info("Background reindex completed: uri=%s task=%s", uri, task_id)
- except Exception as exc:
- tracker.fail(task_id, str(exc))
- logger.exception("Background reindex failed: uri=%s task=%s", uri, task_id)
diff --git a/openviking/server/routers/maintenance.py b/openviking/server/routers/maintenance.py
new file mode 100644
index 000000000..d2fb37780
--- /dev/null
+++ b/openviking/server/routers/maintenance.py
@@ -0,0 +1,147 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Maintenance endpoints for OpenViking HTTP Server."""
+
+import asyncio
+
+from fastapi import APIRouter, Body, Depends
+from pydantic import BaseModel
+
+from openviking.server.auth import get_request_context, require_auth_root_or_admin
+from openviking.server.dependencies import get_service
+from openviking.server.identity import RequestContext
+from openviking.server.models import ErrorInfo, Response
+from openviking_cli.utils import get_logger
+
+logger = get_logger(__name__)
+
+REINDEX_TASK_TYPE = "resource_reindex"
+
+
+class ReindexRequest(BaseModel):
+ """Request to reindex content at a URI."""
+
+ uri: str
+ regenerate: bool = False
+ wait: bool = True
+
+
+router = APIRouter(prefix="/api/v1/maintenance", tags=["maintenance"])
+
+
[email protected]("/reindex")
+@require_auth_root_or_admin
+async def reindex(
+ request: ReindexRequest = Body(...),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Reindex content at a URI.
+
+ Re-embeds existing .abstract.md/.overview.md content into the vector
+ database. If regenerate=True, also regenerates L0/L1 summaries via LLM
+ before re-embedding.
+
+ Uses path locking to prevent concurrent reindexes on the same URI.
+ Set wait=False to run in the background and track progress via task API.
+ """
+ from openviking.service.task_tracker import get_task_tracker
+ from openviking.storage.viking_fs import get_viking_fs
+
+ uri = request.uri
+ viking_fs = get_viking_fs()
+
+ # Validate URI exists
+ if not await viking_fs.exists(uri, ctx=_ctx):
+ return Response(
+ status="error",
+ error=ErrorInfo(code="NOT_FOUND", message=f"URI not found: {uri}"),
+ )
+
+ service = get_service()
+ tracker = get_task_tracker()
+
+ if request.wait:
+ # Synchronous path: block until reindex completes
+ if tracker.has_running(
+ REINDEX_TASK_TYPE,
+ uri,
+ owner_account_id=_ctx.account_id,
+ owner_user_id=_ctx.user.user_id,
+ ):
+ return Response(
+ status="error",
+ error=ErrorInfo(
+ code="CONFLICT",
+ message=f"URI {uri} already has a reindex in progress",
+ ),
+ )
+ result = await _do_reindex(service, uri, request.regenerate, _ctx)
+ return Response(status="ok", result=result)
+ else:
+ # Async path: run in background, return task_id for polling
+ task = tracker.create_if_no_running(
+ REINDEX_TASK_TYPE,
+ uri,
+ owner_account_id=_ctx.account_id,
+ owner_user_id=_ctx.user.user_id,
+ )
+ if task is None:
+ return Response(
+ status="error",
+ error=ErrorInfo(
+ code="CONFLICT",
+ message=f"URI {uri} already has a reindex in progress",
+ ),
+ )
+ asyncio.create_task(
+ _background_reindex_tracked(service, uri, request.regenerate, _ctx, task.task_id)
+ )
+ return Response(
+ status="ok",
+ result={
+ "uri": uri,
+ "status": "accepted",
+ "task_id": task.task_id,
+ "message": "Reindex is processing in the background",
+ },
+ )
+
+
+async def _do_reindex(
+ service,
+ uri: str,
+ regenerate: bool,
+ ctx: RequestContext,
+) -> dict:
+ """Execute reindex within a lock scope."""
+ from openviking.storage.transaction import LockContext, get_lock_manager
+
+ viking_fs = service.viking_fs
+ path = viking_fs._uri_to_path(uri, ctx=ctx)
+
+ async with LockContext(get_lock_manager(), [path], lock_mode="point"):
+ if regenerate:
+ return await service.resources.summarize([uri], ctx=ctx)
+ else:
+ return await service.resources.build_index([uri], ctx=ctx)
+
+
+async def _background_reindex_tracked(
+ service,
+ uri: str,
+ regenerate: bool,
+ ctx: RequestContext,
+ task_id: str,
+) -> None:
+ """Run reindex in background with task tracking."""
+ from openviking.service.task_tracker import get_task_tracker
+
+ tracker = get_task_tracker()
+ tracker.start(task_id)
+ try:
+ result = await _do_reindex(service, uri, regenerate, ctx)
+ tracker.complete(task_id, {"uri": uri, **result})
+ logger.info("Background reindex completed: uri=%s task=%s", uri, task_id)
+ except Exception as exc:
+ tracker.fail(task_id, str(exc))
+ logger.exception("Background reindex failed: uri=%s task=%s", uri, task_id)
diff --git a/openviking/server/routers/pack.py b/openviking/server/routers/pack.py
index ca5ab16ee..523bf8cb1 100644
--- a/openviking/server/routers/pack.py
+++ b/openviking/server/routers/pack.py
@@ -5,12 +5,12 @@
import os
import tempfile
-from fastapi import APIRouter, Depends
+from fastapi import APIRouter, Depends, Request
from fastapi.responses import FileResponse
from pydantic import BaseModel, ConfigDict
from starlette.background import BackgroundTask
-from openviking.server.auth import get_request_context
+from openviking.server.auth import get_request_context, require_auth_root_or_admin
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
from openviking.server.local_input_guard import resolve_uploaded_temp_file_id
@@ -45,9 +45,11 @@ class ImportRequest(BaseModel):
@router.post("/export")
+@require_auth_root_or_admin
async def export_ovpack(
- request: ExportRequest,
- _ctx: RequestContext = Depends(get_request_context),
+ request: Request,
+ body: ExportRequest,
+ ctx: RequestContext = Depends(get_request_context),
):
"""Export context as .ovpack file and stream it to client."""
service = get_service()
@@ -58,10 +60,10 @@ async def export_ovpack(
try:
# Export to temp file
- await service.pack.export_ovpack(request.uri, temp_file, ctx=_ctx)
+ await service.pack.export_ovpack(body.uri, temp_file, ctx=ctx)
# Determine filename from URI
- base_name = request.uri.strip().rstrip("/").split("/")[-1]
+ base_name = body.uri.strip().rstrip("/").split("/")[-1]
if not base_name:
base_name = "export"
filename = f"{base_name}.ovpack"
@@ -86,21 +88,23 @@ async def export_ovpack(
@router.post("/import")
+@require_auth_root_or_admin
async def import_ovpack(
- request: ImportRequest,
- _ctx: RequestContext = Depends(get_request_context),
+ request: Request,
+ body: ImportRequest,
+ ctx: RequestContext = Depends(get_request_context),
):
"""Import .ovpack file."""
service = get_service()
upload_temp_dir = get_openviking_config().storage.get_upload_temp_dir()
- file_path, _ = resolve_uploaded_temp_file_id(request.temp_file_id, upload_temp_dir)
+ file_path, _ = resolve_uploaded_temp_file_id(body.temp_file_id, upload_temp_dir)
result = await service.pack.import_ovpack(
file_path,
- request.parent,
- ctx=_ctx,
- force=request.force,
- vectorize=request.vectorize,
+ body.parent,
+ ctx=ctx,
+ force=body.force,
+ vectorize=body.vectorize,
)
return Response(status="ok", result={"uri": result})
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index 0c7cecc63..6ea6b2d29 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -12,7 +12,7 @@ from pydantic import BaseModel, model_validator
from openviking.message.part import TextPart, part_from_dict
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
-from openviking.server.identity import RequestContext, Role
+from openviking.server.identity import AuthMode, RequestContext, Role
from openviking.server.models import ErrorInfo, Response
from openviking_cli.exceptions import InvalidArgumentError
@@ -101,9 +101,11 @@ def _to_jsonable(value: Any) -> Any:
return value
-def _request_auth_mode(request: Request) -> str:
+def _request_auth_mode(request: Request) -> AuthMode:
config = getattr(request.app.state, "config", None)
- return getattr(config, "auth_mode", "api_key")
+ if config is not None and hasattr(config, "get_effective_auth_mode"):
+ return config.get_effective_auth_mode()
+ return AuthMode.API_KEY
def _resolve_message_role_id(
@@ -115,7 +117,7 @@ def _resolve_message_role_id(
return request.role_id
role_id_provided = "role_id" in request.model_fields_set
- allow_explicit_role_id = _request_auth_mode(http_request) == "trusted" or ctx.role in {
+ allow_explicit_role_id = _request_auth_mode(http_request) == AuthMode.TRUSTED or ctx.role in {
Role.ROOT,
Role.ADMIN,
}
diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.py
index 3e571469b..49af89385 100644
--- a/openviking/server/routers/system.py
+++ b/openviking/server/routers/system.py
@@ -10,7 +10,7 @@ from pydantic import BaseModel
from openviking.server.auth import get_request_context, resolve_identity
from openviking.server.dependencies import get_service
-from openviking.server.identity import RequestContext
+from openviking.server.identity import AuthMode, RequestContext
from openviking.server.models import Response
from openviking.storage.viking_fs import get_viking_fs
from openviking_cli.utils import get_logger
@@ -27,35 +27,41 @@ async def health_check(request: Request):
result = {"status": "ok", "healthy": True, "version": __version__}
- # Try to get user identity if auth headers are present
+ # Try to get user identity
try:
# Extract headers manually
x_api_key = request.headers.get("X-API-Key")
authorization = request.headers.get("Authorization")
+ x_openviking_account = request.headers.get("X-OpenViking-Account")
x_openviking_user = request.headers.get("X-OpenViking-User")
-
- # Check if we have auth or in dev mode
- api_key_manager = getattr(request.app.state, "api_key_manager", None)
- if api_key_manager is None:
- # Dev mode - use default user
- result["user_id"] = x_openviking_user or "default"
- elif x_api_key or authorization:
- # Try to resolve identity
- try:
- identity = await resolve_identity(
- request,
- x_api_key=x_api_key,
- authorization=authorization,
- x_openviking_account=request.headers.get("X-OpenViking-Account"),
- x_openviking_user=x_openviking_user,
- x_openviking_agent=request.headers.get("X-OpenViking-Agent"),
- )
- if identity and identity.user_id:
- result["user_id"] = identity.user_id
- except Exception:
- pass
- except Exception:
- pass
+ x_openviking_agent = request.headers.get("X-OpenViking-Agent")
+
+ # Get effective auth mode from config
+ effective_auth_mode = AuthMode.API_KEY
+ config = getattr(request.app.state, "config", None)
+ if config is not None and hasattr(config, "get_effective_auth_mode"):
+ effective_auth_mode = config.get_effective_auth_mode()
+ result["auth_mode"] = effective_auth_mode.value
+
+ # Always try to resolve identity - resolve_identity handles all auth modes
+ try:
+ identity = await resolve_identity(
+ request,
+ x_api_key=x_api_key,
+ authorization=authorization,
+ x_openviking_account=x_openviking_account,
+ x_openviking_user=x_openviking_user,
+ x_openviking_agent=x_openviking_agent,
+ )
+ # Always set identity fields if available
+ result["account_id"] = str(identity.account_id)
+ result["user_id"] = str(identity.user_id)
+ result["agent_id"] = str(identity.agent_id)
+ result["role"] = identity.role.value
+ except Exception as e:
+ logger.warning(f"Failed to resolve identity: {e}")
+ except Exception as e:
+ logger.error(f"Failed to get health check: {e}")
return result
diff --git a/openviking/utils/agfs_utils.py b/openviking/utils/agfs_utils.py
index a8d7654a9..a31fe7650 100644
--- a/openviking/utils/agfs_utils.py
+++ b/openviking/utils/agfs_utils.py
@@ -101,7 +101,6 @@ def create_agfs_client(agfs_config: Any) -> Any:
)
client = RAGFSBindingClient()
- logger.warning("[RAGFS] Using Rust binding (ragfs-python)")
# Automatically mount backend for binding client
mount_agfs_backend(client, agfs_config)